i am creating session for some purpose but when user logout the purpose value becomes null but i want to use it after user logout.. the scenario is the session is created by admin and i want use this session for normal user but when admin logout its session also become null..
this is the logout code of laravel
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return redirect('/');
}
Here's what you can do:
first get all the data you want to keep.
then delete all the session data.
then save the data in to the session.
then logout.
public function logout(Request $request)
{
// get the data first for example the user's name
$name = Auth::user()->name;
$this->guard()->logout();
$request->session()->invalidate();
// save the data into a new session
session(['name' => $name]);
return redirect('/');
}
then in your view you get the data like so:
#if(session('name'))
{{ session('name') }}
#endif
I want to redirect back user to entered url after authenticating user
Scenario is: User enter a url, in backend I check for user to be authenticated and if user does not authenticated redirect user to login url and after successful login redirect user back to first url that user entered
Users Controller:
public function index()
{
if(!Auth::check())
{
return View::make('adminLogin');
}
return Redirect::to('admin');
}
public function login()
{
$creds = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
if (Auth::attempt($creds))
return Redirect::back();
}
routes.php:
Route::resource('users', 'UsersController');
Route::post('login', 'UsersController#login');
filters.php:
Route::filter('logged', function($request)
{
if(!Auth::check())
return Redirect::to('users');
});
SettingController.php:
public function __construct()
{
$this->beforeFilter('logged', array('only' => array('index')));
}
public function index()
{
return View::make('setting');
}
Please help me.I'm a newbie in Laravel.
Use Redirect::intended('/'); instead of Redirect::back();.
PS: Also change
Route::filter('logged', function($request)
{
if(!Auth::check())
return Redirect::guest(URL::to('users')); //Your login form.
});
use the intended() method
The intended method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.
example : return Redirect::intended('/');
Is it possible to logout from a page and redirect to signin page without using auth as shown below.
Auth::logout();
You can use the session's regenerate or flush to purge all of the session:
request()->session()->regenerate(true);
request()->session()->flush();
// then redirect to login
return redirect()->route('login');
update
You have two return statements in your comment's code:
public function signout(Request $request) {
// don't return here
// return Auth::logout();
return redirect('/login');
}
Session::flush();
return redirect()->route('login');
//use session in your controller
I'm currently using 2 projects. 1 front end (with laravel backend to communicate with API) and another laravel project (the API).
Now I use Laravel Passport to authenticate users and to make sure every API call is an authorized call.
Now when I want to log out my user, I send a post request to my API (with Bearer token) and try to log him out of the API (and clear session, cookies,...)
Then on the client I also refresh my session so the token is no longer known. Now when I go back to the login page, it automatically logs in my user. (Or my user is just still logged in).
Can someone explain me how to properly log out a user with Laravel passport?
Make sure that in User model, you have this imported
use Laravel\Passport\HasApiTokens;
and you're using the trait HasApiTokens in the User model class using
use HasApiTokens
inside the user class.
Now you create the log out route and in the controller,
do this
$user = Auth::user()->token();
$user->revoke();
return 'logged out'; // modify as per your need
This will log the user out from the current device where he requested to log out. If you want to log out from all the devices where he's logged in. Then do this instead
$tokens = $user->tokens->pluck('id');
Token::whereIn('id', $tokens)
->update(['revoked'=> true]);
RefreshToken::whereIn('access_token_id', $tokens)->update(['revoked' => true]);
Make sure to import these two at the top
use Laravel\Passport\RefreshToken;
use Laravel\Passport\Token;
This will revoke all the access and refresh tokens issued to that user. This will log the user out from everywhere. This really comes into help when the user changes his password using reset password or forget password option and you have to log the user out from everywhere.
You need to delete the token from the database table oauth_access_tokens
you can do that by creating a new model like OauthAccessToken
Run the command php artisan make:model OauthAccessToken to create the model.
Then create a relation between the User model and the new created OauthAccessToken Model , in User.php add :
public function AauthAcessToken(){
return $this->hasMany('\App\OauthAccessToken');
}
in UserController.php , create a new function for logout:
public function logoutApi()
{
if (Auth::check()) {
Auth::user()->AauthAcessToken()->delete();
}
}
In api.php router , create new route :
Route::post('logout','UserController#logoutApi');
Now you can logout by calling posting to URL /api/logout
This is sample code i'm used for log out
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response()->json([
'message' => 'Successfully logged out'
]);
}
Create a route for logout:
$router->group(['middleware' => 'auth:api'], function () use ($router) {
Route::get('me/logout', 'UserController#logout');
});
Create a logout function in userController ( or as mentioned in your route)
public function logout() {
$accessToken = Auth::user()->token();
DB::table('oauth_refresh_tokens')
->where('access_token_id', $accessToken->id)
->update([
'revoked' => true
]);
$accessToken->revoke();
return response()->json(null, 204);
}
I am using Laravel 6.12.0, below function is working for me.
public function logout(Request $request){
$accessToken = Auth::user()->token();
$token= $request->user()->tokens->find($accessToken);
$token->revoke();
$response=array();
$response['status']=1;
$response['statuscode']=200;
$response['msg']="Successfully logout";
return response()->json($response)->header('Content-Type', 'application/json');
}
This is my first post.. and i find a clean solution (Laravel last Version)
/**
* Logout api
*
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
if (Auth::check()) {
$token = Auth::user()->token();
$token->revoke();
return $this->sendResponse(null, 'User is logout');
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised'] , Response::HTTP_UNAUTHORIZED);
}
}
Below is the simplest way I found to do it.
1. USE database SESSION INSTEAD OF file SESSION
Official documention
php artisan session:table
php artisan migrate
Replace SESSION_DRIVER=file by SESSION_DRIVER=database in your .env file.
2. DELETE USER SESSION RIGHT AFTER LOGIN
After a user is redirected to your frontend and logs in to finally get a token, you probably call a route in api/routes.php to get the user information, that's where I'm closing the user backend session before sending back user information to the frontend:
Route::middleware('auth:api')->get('/user', function (Request $request) {
// Close user session here
Illuminate\Support\Facades\DB::table('sessions')
->whereUserId($request->user()->id)
->delete();
return $request->user();
});
3. REVOKE TOKENS AT LOGOUT
Then, to "log out" (actually, revoke tokens) the user from the frontend, you just need to call another route to revoke the token and refresh_token:
Route::middleware('auth:api')->post('/logout', function (Request $request) {
// Revoke access token
// => Set oauth_access_tokens.revoked to TRUE (t)
$request->user()->token()->revoke();
// Revoke all of the token's refresh tokens
// => Set oauth_refresh_tokens.revoked to TRUE (t)
$refreshTokenRepository = app('Laravel\Passport\RefreshTokenRepository');
$refreshTokenRepository->revokeRefreshTokensByAccessTokenId($request->user()->token()->id);
return;
});
You may prefer to put these two closures in the UserController.
Hope help someone:
if (Auth::check()) {
$request->user()->tokens->each(function ($token, $key) {
$token->delete();
});
}
Good Luck.
I use this in my project to logout from multiple device.
public function logout(Request $request, $devices = FALSE)
{
$this->logoutMultiple(\Auth::user(), $devices);
return response()->json([], 204);
}
private function logoutMultiple(\App\Models\User $user, $devices = FALSE)
{
$accessTokens = $user->tokens();
if ($devices == 'all') {
} else if ($devices == 'other') {
$accessTokens->where('id', '!=', $user->token()->id);
} else {
$accessTokens->where('id', '=', $user->token()->id);
}
$accessTokens = $accessTokens->get();
foreach ($accessTokens as $accessToken) {
$refreshToken = \DB::table('oauth_refresh_tokens')
->where('access_token_id', $accessToken->id)
->update(['revoked' => TRUE]);
$accessToken->revoke();
}
}
Try this code to help you to logout from passport authentication.
Route::post('/logout', function(){
if (Auth::check()) {
Auth::user()->AauthAcessToken()->delete();
}
return response()->json([
'status' => 1,
'message' => 'User Logout',
], 200);
});
check whether your model contains OauthAccessToken which needs to connect with the database oauth_access_tokens. The access token is stored in the database table oauth_access_tokens. and makes a relation from users to oauth_access_tokens.
public function AauthAcessToken(){
return $this->hasMany(OauthAccessToken::class);
}
You can use following code to remove to token for logged in user.
$request->user()->token()->revoke();
If you want to learn about this in-depth then watch this tutorial:
https://www.youtube.com/watch?v=UKSQdg1uPbQ
public function logout(Request $request)
{
$request->user()->token()->revoke();
if ($request->everywhere) {
foreach ($request->user()->tokens()->whereRevoked(0)->get() as $token) {
$token->revoke();
}
}
return response()->json(['message' => 'success']);
}
I am using Laravel 5.3, I have a situation here...I'm on PAGE-2 and logged-out from there then redirected to Login Page. Now, what I am trying to achieve is to redirect back to PAGE-2 if the user logs-in again.
the Current situation is that, the user will be redirected to defaultAfterLogin page, which is not my desired login flow.
NOTE: Default page after-login is "DashBoard".
It is OKAY IF YOU WILL GO THE FIRST-TIME TO PAGE-2(not the default DashBoard page) and if you're not LOGGED-IN you will be redirected to LOGIN PAGE then IF YOU'll login again you will be redirected back to PAGE-2, which is fine.
BUT what is happening now is that, when you're in PAGE-2 then you LOGOUT then you will be REDIRECTED TO LOGIN-PAGE, if you LOGIN again you will be redirected to "DashBoard" which is not what I want. It should redirect back to PAGE-2
The flow should be,... users will be redirected after login no matter which PAGE they're previously working with.
Here's the a sample script I am using (it's actually from laravel i'am using its built-in Auth)
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
return redirect()->intended($this->redirectPath());
}
Any ideas, please? Thank you very Much for your help.
Try this
On auth middleware:app/http/middleware/RedirectIfAuthenticated
// redirect the user to your login page "/login"
public function handle($request, Closure $next)
{
if ($this->auth->check()) {
return redirect('/login');
}
return $next($request);
}
// This is your login method
public function postSignIn(Request $request)
{
$request_data = $request->all();
$email = $request_data['email'];
$user_details = User::where('email', $email)->first();
if(count($user_details) > 0)
{
$credentials = array('email'=> $email ,'password'=> $request_data['password']);
if ($this->auth->attempt($credentials, $request->has('remember')))
{
return redirect()->to('/dashboard'); //Here is your redirect url, redirect to dashbord
OR
return redirect()->to('/page2'); //Here is your redirect url, redirect to page2
}
else
{
$error = array('password' => 'Please enter a correct password');
return redirect()->back()->withErrors($error);
}
}
else
{
$error = array('password' => 'User not found');
return redirect()->back()->withErrors($error);
}
}
Open AuthController class : app/Http/Controllers/Auth/AuthController.php
Add below property to the class
protected $redirectAfterLogout = 'auth/login';
you can change auth/login with any url.
U CAN USE THIS CODE
return redirect()->back();
or
u can use route and in ur route u need to configure and in controller u can put the below code
// this is ur route
Route::get('/dashboard',[
'uses' => 'PostController#dashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
//put this in ur controller
return redirect()->route('dashboard');