I created a custom login and custom middleware and
When I try to die dump anywhere it logouts the user what seems to be the problem?
Login Controller:
public function login(Request $request){
// flash::success('Succesfully login')->important();
$client = new Client();
try {
$res = $client->request('POST', 'http://api.fstbx.com/api/user/login', [
'headers' => [
'Accept' => 'application/json',
'Client-Key' => 'p947KVCgE7PyXLdZpfqOSIg4OwIla2BWdSPzdoqf'
],
'form_params' => [
'username' => $request->get('username'),
'password' => $request->get('password')
]
]);
} catch (\Exception $e) {
Flash::error('Invalid login credentials.');
return redirect('/login');
}
$info = json_decode((string) $res->getBody(), true);
$request->session()->put('authUser',$info['user']);
$request->session()->put('authToken',$info['access_token']);
$request->session()->put('authRole',['1','2']);
$role = [];
$role = ['1','2'];
$user = User::createAuth($info['user'],$info['access_token'],$role);
return redirect('/');
}
Custom Middleware
public function handle($request, Closure $next)
{
if(!empty(session('authUser'))){
// $user = $request->session()->get('authUser');
$user = session('authUser');
// $token = $request->session()->get('authToken');
$token = session('authToken');
// $role = $request->session()->get('authRole');
$role = session('authRole');
User::createAuth($user,$token,$role);
return $next($request);
}
return redirect('/login');
}
User Model
public static function createAuth($userData, $userToken,$userRole)
{
$user = new User();
$user->name = $userData['name'];
$user->email = $userData['email'];
$user->avatar = array_rand(User::get_avatar());
$user->token = $userToken;
$user->roles = $userRole;
Auth::login($user);
return $user;
}
adding this code on my custom middleware solved my problem
$request->session()->regenerate();
Related
I want to pass some parameters to an after middleware after the controller has finished running, this is in order to invalidate any password reset tokens if a new one is generated.
My code is:
Controller
public function resetPasswordRequest(Request $request)
{
$user = User::where('email', $request->email)->first();
if (!$user) {
throw ValidationException::withMessages([
'message' => 'invalid_email',
]);
}
$reset_request = Password_reset::create([
'user_email' => $request['email'],
'reset_token' => Helper::makeRandomString(8, true),
]);
$reset_token = $reset_request['reset_token'];
$user_email = $request['email'];
/*
Helper::sendEmail('pass_reset', $user_email = $request['email'], $reset_token);
*/
return response(array('message' => 'success', 'email' => $user_email, 'reset_token' => $reset_token, 'type' => 'reset'), status:200);
}
//Middleware
public function handle(Request $request, Closure $next)
{
$user_data = $next($request);
error_log($user_data);
$user_email = $user_data['email'];
$type = $user_data['reset'];
$tokens = null;
if ($type == 'reset') {
$tokens = Password_reset::where('user_email', '=', $user_email)->where('used', false)->get();
} else if ($type == 'confirmation') {
$tokens = EmailConfirm::where('user_email', '=', $user_email)->where('used', false)->get();
error_log('fffff');
}
error_log('gggg');
//Might not be optimum, need consultation
foreach ($tokens as $column) {
$column['used'] = true;
$column->save();
}
return $next($request);
}
The problem comes with the fact that I do not seem to be able to find a way to pass this data, if I try to access it via the content method the result will be an array of chars.
Any tips on this or another solution I can use?
You don't need middleware because resetting a password is almost never a protected resource.
How can you log in and go to a guarded resource if you forgot your password?
Middleware is to guard routes and its corresponding controllers.
In this case, there is a user, that is not logged in and wants to reset the password of its account.
Just process the request in the controller.
I'm trying to make login with google using laravel socialite and I have a problem.
Route that initiates login:
Route::get('/auth/login/google', 'AuthController#google');
Method in controller that initiates login:
public function google()
{
return Socialite::driver('google')->redirect();
}
Callback route:
Route::get('/auth/login/google/redirect', 'AuthController#googleRedirect');
Callback method in controller:
public function googleRedirect()
{
$googleUser = Socialite::driver('google')->user();
$email = $googleUser->getEmail();
$user = new User();
$user = $user->firstOrCreate(['email' => $email], ['email' => $email, 'password' =>
bcrypt(str_shuffle('abcdefgh45678')), 'email_verified' => 1]);
Auth::login($user, true);
}
And I'm getting ERR_EMPTY_RESPONSE every time I'm trying to redirect user after login.
Funny thing is that I can dump data with dd(Auth::user()->id) and I'm getting user's ID, but when I try to redirect user to the home page using return redirect('/') I'm getting empty response error and if I manually go to home page my user is not authenticated.
#Matej Petric blow code is working for me.
public function handleProviderCallback($provider) {
$user = Socialite::driver('google')->stateless()->user();
$authUser = $this->findOrCreateUser($user);
if ($authUser) {
Auth::login($authUser, true);
return redirect('/');
} else {
return redirect('/login')->withErrors(['msg', 'The Message']);
}
}
public function findOrCreateUser($user) {
$authUser = User::where('email', $user->email)->first();
if ($authUser) {
return $authUser;
}
$userN = User::create([
'name' => $user->name,
'email' => $user->email,
'password' => bcrypt(generateRandom()),
]);
return $userN;
}
I have been working on a reset system for mails registered in my application.
when the user receives the mail and clicks on the link, he will be guided to my page where I receive token and email and his new password and reset for him his password.
return view($view, ['strings'=>$strings, 'email'=>$passwordReset->email])->with('token', $token);
as you can see here is the view i load to show to the user the password input.
the problem is i do not know how to send this token to the view. suppose i want it to be in an hidden input in my view.
the method which passes the token and email to the form looks like this
public function getReset($token = null)
{
$view = 'auth.web.reset2';
if ( is_null( $token ) ) {
throw new NotFoundHttpException;
}
$passwordReset = PasswordReset::getEmailFromToken( $token );
if ( is_null( $passwordReset ) ) {
throw new NotFoundHttpException;
}
$user = User::getUserFromEmail( $passwordReset->email );
if ( is_null( $user ) ) {
throw new NotFoundHttpException;
}
if(User::isUserMobileClient($user)){
//$view = 'auth.reset';
}
$strings = array(
trans(Strings::PASSWORD_RESET_BLADE_01),
trans(Strings::PASSWORD_RESET_BLADE_02),
trans(Strings::PASSWORD_RESET_BLADE_03),
trans(Strings::PASSWORD_RESET_BLADE_04),
trans(Strings::PASSWORD_RESET_BLADE_05),
trans(Strings::PASSWORD_RESET_BLADE_06),
trans(Strings::PASSWORD_RESET_BLADE_051),
trans(Strings::PASSWORD_RESET_BLADE_07),
trans(Strings::PASSWORD_RESET_BLADE_08),
);
return view($view,['strings'=>$strings, 'email'=>$passwordReset->email, 'token' => $token]);
}
and the method which is called when the user press the submit button is like this:
public function postReset(Request $request)
{
$userFromMobile = false;
$this->validate($request, [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:6',
]);
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$response = Password::reset($credentials, function ($user, $password) {
$this->user;
$this->resetPassword($user, $password);
});
if(User::isUserMobileClient(User::getUserFromgEmail($request->email))){
$userFromMobile = true;
}
switch ($response) {
case Password::PASSWORD_RESET:
Input::flashonly('status');
return ($userFromMobile) ?
redirect('password/changed')->with('status', trans($response)) :
redirect($this->redirectPath())->with('status', trans($response));
default:
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
}
Why don't you just do this?
return view($view,['strings'=>$strings, 'email'=>$passwordReset->email, 'token' => $token]);
Is it possible with https://github.com/tymondesigns/jwt-auth
to get the current user? Because right now I can only generate a token (when a user sign in).
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
try {
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(compact('token'));
}
You don't need Auth::user();
You can use the toUser method of JWTAuth. Just pass the token as parameter and you will get back the user info:
$user = JWTAuth::toUser($token);
return response()->json(compact('token', 'user'));
For more info, this is the toUser method:
/**
* Find a user using the user identifier in the subject claim.
*
* #param bool|string $token
*
* #return mixed
*/
public function toUser($token = false)
{
$payload = $this->getPayload($token);
if (! $user = $this->user->getBy($this->identifier, $payload['sub'])) {
return false;
}
return $user;
}
You can get logged user data.
$credentials = $request->only('code', 'password', 'mobile');
try {
// verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token'], 500);
}
$currentUser = Auth::user();
print_r($currentUser);exit;
You can also use JWTAuth::user() method.
The user() method call is returned in the toUser() method, which itself is an alias for authenticate() method which authenticates a user via a token. If the user is already authenticated, there is no need to authenticate them again (which toUser() does), instead user() method can be used to get the authenticated user.
// $token = JWTAuth::attempt($credentials) was successful...
$user = JWTAuth::user();
return response()->json(compact('token', 'user'));
It works fine for me (laravel 5.7)
U must post token to me function and will return user
use Tymon\JWTAuth\Facades\JWTAuth;
public function me(Request $request)
{
$user = JWTAuth::user();
if (count((array)$user) > 0) {
return response()->json(['status' => 'success', 'user' => $user]);
} else {
return response()->json(['status' => 'fail'], 401);
}
}
try this (it works fine with laravel 5.6,5.7):
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
// code to generate token for user with email testuser#gmail.com
$user=User::where('email','=','testuser#gmail.com')->first();
if (!$userToken=JWTAuth::fromUser($user)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
return response()->json(compact('userToken'));
just need to return inside the specified route middleware
The route that you defined api route
Route::group(['middleware' => 'jwt.auth'], function () {
Route::post('/user', function (Request $request) {
try {
$user = \Illuminate\Support\Facades\Auth::user();
return $user;
} catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) {
return '$user';
}
});
});
You can get the current user related to token using :
$user = JWTAuth::setToken($token)->toUser();
In Laravel 7.2 if none of the above works use like this to retrive the user:
$credentials = request(['email', 'password']);
if (! $token = auth('api')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$user = auth('api')->user();
dd($user);
Solution for who are all struggle validate the user and token and then guard
Problems that i face
Jwt does not return any user even i put currect token
return null
$user = JWTAuth::user(); //getting null
return false
$user = JWTAuth::parseToken()->authenticate();
return false
auth()->user()
Solution to check
Before Going to solution middleware and your route guard is matter so keep in mind
Guard setting config/auth.php
'guards' => [
'website_admin' => [
'driver' => 'jwt',
'provider' => 'website_admin',
],
]
Provider
'providers' => [
'super_admin' => [
'driver' => 'eloquent',
'model' => App\Website_super_admin_auth::class,
],
]
Middleware (must)
<?php
namespace App\Http\Middleware;
use Closure;
use JWTAuth;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
class JwtMiddleware extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
try {
$user = JWTAuth::parseToken()->authenticate();
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
return response()->json(['status' => 'Token is Invalid']);
}else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
return response()->json(['status' => 'Token is Expired']);
}else{
return response()->json(['status' => 'Authorization Token not found']);
}
}
return $next($request);
}
}
Route(should specify middleware with guard)
Route::group(['prefix' => 'super_ad', 'middleware' => ['jwt.verify','auth:super_admin']], function()
{
Route::get('/test', function (){
// $user = JWTAuth::parseToken()->authenticate(); <-------check user here
$user=auth()->user();
// return $user;
});
})
$user = JWTAuth::setToken($token)->toUser();
Auth::login($user, $remember = true);
public function user(Request $request){
/// get user details from token
$user = JWTAuth::toUser($this->bearerToken($request));
// get payloads in the token
$payload = JWTAuth::getPayload($this->bearerToken($request));
}
public function bearerToken($request)
{
$header = $request->header('Authorization', '');
if (Str::startsWith($header, 'Bearer ')) {
return Str::substr($header, 7);
}
}
Hi help me,
login code
public function store()
{
$credentials = array(
'u_email' => Input::get('email'),
'password' => Input::get('password'));
if (Auth::attempt($credentials) ) {
$user = Auth::user()->toArray();
$userrole = with(new User)->get_user_role($user['u_id']);
$userobj['u_id'] = $user['u_id'];
$userobj['u_shortcode'] = $user['u_shortcode'];
$userobj['utype'] = $user['utype'];
$userobj['u_title'] = $user['u_title'];
$userobj['u_fname'] = $user['u_fname'];
$userobj['u_lname'] = $user['u_lname'];
$userobj['u_email'] = $user['u_email'];
$userobj['u_role'] = $userrole;
$userobj['id'] = Session::getId();
Session::put('admin', $userobj);
$value = Session::get('admin');
return Response::json([
'user' => $userobj ],
202
);
}else{
return Response::json([
'flash2' => 'Authentication failed'],
202
);
}
}
and my second controller is:
public function get_sessionobj()
{
var_dump(Session::all());
$value = Session::get('admin');
print_r($value);
exit();
}
when i am calling second controller after login then session data not printed. in login controller Session::get('admin') function returning data. and i am using file driver for session storage. I have seen my session file there was some data like this:
a:5:{s:6:"_token";s:40:"XrUgs7QLPlXvjvyzFaTdmDpqGL0aSZRzkJS0il9f";s:38:"login_82e5d2c56bdd0811318f0cf078b78bfc";s:1:"1";s:5:"admin";a:9:{s:4:"u_id";s:1:"1";s:11:"u_shortcode";s:5:"u1001";s:5:"utype";s:1:"1";s:7:"u_title";s:3:"Mr.";s:7:"u_fname";s:6:"Aristo";s:7:"u_lname";s:5:"Singh";s:7:"u_email";s:24:"chandan.singh#jetwave.in";s:6:"u_role";a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}s:2:"id";s:40:"cd074f7f61fcc88b3d92c482e57e8a12dc888958";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1410525787;s:1:"c";i:1410525787;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
Call a function get_sessionobj() in store function
Example:
public function store(){
$this->get_sessionobj();
}