Laravel 5.2 - Auth::login not preserve when using new \App\User - laravel

I've used these code to authenticate username from external source without using database, but laravel 5.2 not save the authentication, and request the external source every time.
class Authenticate
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
$username = getFromExternalSource();
if($username==null){ redirect()->guest('auth/login'); }
$user = new \App\User(['username'=>'admin']);
Auth::login($user);
}
}
return $next($request);
}
}
But when I change Auth::login using $user model get from database it work, I don't know why:
$userDB = \App\User::where('username','=','admin')->first();
Auth::login($userDB);
My route (for example I want to access http://myApp/api)
Route::group(['middleware' => ['web']], function () {
Route::group(['middleware' => 'auth'], function () {
Route::get('api/', 'ApiController#index');
});
Route::group(['middleware' => ['csrf']], function () {
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
});
});

As far as I know for default authenticate method, you need to pass model that exists in database. In your example you created just object and assigned to it username property.
If you need to authenticate selected user, you should use:
Auth::loginUsingId($id);
(where in place of $id you should pass id of user you want to authenticate - in your case id of user with username admin)

Related

Call to a member function tokens() on null on Laravel Sanctum

I get this error when i am trying to logout the user
public function logout(Request $request)
{
$request->user()->tokens()->delete();
}
You need to include the API route inner the Sanctum Auth middleware like below:
Route::group(['middleware' => ['auth:sanctum']], function() {
Route::post('logout', [AuthController::class, 'logout']);
});
Auth::user()->token() is only valid by passing the Sanctum middleware.
Check this #1
Check this #2
This worked for me, Change this code in your Controller.php to,
public function logout(Request $request){
Auth::user()->tokens()->delete();
return [
'message' => 'logged out'
];
}
And make sure your Route POST request is protected in api.php, change the code to below
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
use token() instead of tokens()
$request->user()->token()->delete();
Or you can use it as below.
Auth::user()->tokens->each(function($token, $key) {
$token->delete();
});
by using revoke
$user = $request->user();
foreach ($user->tokens as $token) {
$token->revoke();
}

Laravel Protected Route With same Model

I changed the users table and put a field called "role" and was wondering if it is possible to use middleware to protect routes only by checking this field.
The table users:
I wnated something like this:
If user role == 0
Route::group(['middleware' => 'auth'], function () {});
If user role == 1
Route::group(['middleware' => 'auth:customers'], function () {});
However with the same table
Make a new middleware:
php artisan make:middleware CustomerMiddleware
The function handle in the new middleware:
public function handle($request, Closure $next)
{
if(Auth::check()){
if($request->user()->role != 0){
return redirect('/');
}
}
return $next($request);
}
The protected route in app/Http/Kernel.php
'CustomerMiddleware' => \App\Http\Middleware\CustomerMiddleware::class,
The group routes:
Route::group(['middleware' => 'CustomerMiddleware'], function () { });

Laravel middleware multi roles routing

I have problem to make routing with middleware multi roles
I have tried some in internet but still wont work
I have 3 roles, superadmin, admin and member
I want the superadmin and admin can access the add page
here is my code :
Route::group(['prefix' => 'staff', 'middleware' => 'auth'], function () {
Route::GET('/add', [
'uses' => 'StaffController#page_add',
'middleware' => 'rule:superadmin', ???
]);
});
I have tried to put 'middleware' => 'rule:superadmin|rule:admin'
but wont work
thank you
Create a middleware file eg Role.php
public function handle($request, Closure $next, ... $roles)
{
if (!Auth::check()) // I included this check because you have it, but it really should be part of your 'auth' middleware, most likely added as part of a route group.
return redirect('login');
$user = Auth::user();
if($user->isAdmin())
return $next($request);
foreach($roles as $role) {
// Check if user has the role This check will depend on how your roles are set up
if($user->hasRole($role))
return $next($request);
}
return redirect('login');
}
Finally in your web routes
Route::get('admin/scholen/overzicht', 'SchoolsController#overview')->middleware('role:editor,approver');
Route::get('admin/scholen/{id}/bewerken', 'SchoolsController#edit')->middleware('role:admin');
Check out this best answer for more details
Hey you can put a column named "role" in your users table then check it with a condition.
Route::get('/add', function() {
if (Auth::user()->role == 'superadmin' || Auth::user()->role == 'admin') {
return view('add-page');
}
else {
return view('error-page');
}
});

Laravel Guest Middleware and user authentication

I just created a simple login with guest middleware that allows the user to access one account at a time, but I am just worried if this is the right way to do it.
/** Routes **/
Route::group(['middleware' => 'guest'], function () {
Route::get('/', 'LoginController#index')->name('login');
Route::post('/', 'LoginController#post')->name('login.post');
});
/** login.post controller **/
public function post(Request $request){
$this->rules($request);
$rules = array(
'username' => $request->username,
'password' => $request->password,
);
if(Auth::attempt($rules)) {
if(Auth::user()->is_active == true){
/** IF THE USER IS CURRECTLY LOGIN **/
if(Auth::user()->is_login == true){
Auth::logout();
Session::flash('multilog', 'Your account is log-in to another device!!');
return redirect('/')->withInput();
}
$user = user::find(Auth::user()->id);
$user->is_login = true;
$user->save();
return redirect('admin/home');
}
Session::flash('unactivated', 'Your account is not activated!!');
return redirect('/')->withInput();
}
Session::flash('unmatch', 'Invalid username or password!!');
return redirect('/')->withInput();
}
/** **/
If you are not sure, you can use Laravel to create authentication. Write in command line:
php artisan make:auth
Then just look how the logic works in files.
More you can read here:
https://laravel.com/docs/5.5/authentication

How to logout a user from API using laravel Passport

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']);
}

Resources