I'm using entrust package to manage roles and I have used passport for authentication since it is API's.
Actually what I need is want to check user has a role,
I have tried with below code but it doesn't work
public function Adminlogin()
{
if(Auth::attempt(['email' => request('email'), 'password' => request('password')]))
{
$user = Auth::user();
if($user->hasRole('admin'));
{
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
return response()->json(['error'=>'Abort'], 403);
}
else
{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
I want to generate access token only if user has admin role,If user has no role admin then show abort message.
if(Auth::user()->hasRole('admin'))
should work.
But you don't explain what is not working in your case so...
Related
In laravel 9 with breeze 1.11 I need to add additive checks on field if user is admin.
In app/Http/Requests/Auth/LoginRequest.php I add lines :
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
\Log::info(varDump(Auth::user()->is_admin, ' -1 Auth::user()->is_admin::')); // I see data of logged user
if(!Auth::user()->is_admin) {
\Log::info(varDump(-13, 'RAISE ERROR')); // I see this log line
throw ValidationException::withMessages([
'email' => trans('You have no admin credentials'),
]);
}
RateLimiter::clear($this->throttleKey());
}
But anyway user is logged into dashboard.
Which method is correct for this task ?
Thanks!
I fixed this issue with manual logout method :
if(!Auth::user()->is_admin) {
Auth::guard('web')->logout();
throw ValidationException::withMessages([
'email' => 'You have no admin credentials',
]);
}
I'm using Auth::attempt($credentials) to authenticate login data from users.
$credentials = [
'user_name' => $request->user_name,
'password' => $request->password,
];
if (Auth::attempt($credentials)) {
return redirect()->route('admin.dashboard');
} else {
return redirect()->back()->with('status', 'Invalid credentials!');
}
If a user types the wrong password or wrong username, I throw an invalid credentials error. But I want if a user does not exist in the database, I can throw an error that the user does not exist.
My Auth::attempt($credentials) returns true or false, so I don't know how to do this. Can you help?
$user = User::where('user_name',$request->user_name)->first();
if($user) {
$credentials = [
'user_name' => $request->user_name,
'password' => $request->password,
];
if (Auth::attempt($credentials)) {
return redirect()->route('admin.dashboard');
} else {
return redirect()->back()->with('status', 'Invalid credentials!');
}
} else {
return redirect()->back()->with('status', 'Not found!');
}
It would be an security issue sir as #fubar said, but the simple logic is
Find at users table if email is exists.
if exists then go to auth attempt like the way you implement already.
if not exists throw 404.
So I made Authentication using passport, everything worked fine until I logged user out. My paths are protected via auth:api guard so after logging out I can't access any functions, however my frontend is rendered via react based on Auth:check() value and it stays true after logging out. Therefore I am able to get into admin dashboard without any permissions, which is a bug and I can't find a solution to fix it.
This is my log out function:
public function logout()
{
if (Auth::check()) {
DB::table('oauth_access_tokens')
->where('user_id', Auth::user()->id)
->update([
'revoked' => true
]);
return response(['check' => Auth::check()]); // I get true after logging out
}
return response(['check' => Auth::check()]);
}
This is my login and register functions:
public function register(Request $request){
$validatedData = $request->validate([
'name' => 'required|max:55|unique:users',
'password' => 'required'
]);
$validatedData['password'] = bcrypt($request->password);
$user = User::create($validatedData);
$accessToken = $user->createToken('authToken')->accessToken;
return response()
}
public function login(Request $request)
{
$loginData = $request->validate([
'name' => 'required',
'password' => 'required'
]);
$a = auth()->attempt($loginData, true);
if(!$a) {
return response(['message'=>'Invalid credentials');
}
$accessToken = auth()->user()->createToken('authToken')->accessToken;
return response()->json($accessToken);
}
What have I missed?
The reason that Auth::check() returns true is the user is set on the auth service. You are only revoking the access token, meaning that the user will be logged out from the next request.
You can solve this one of two ways
1) Assume that the any call to the logout route will result in the user being logged out, irrespective of the logic performed. For example, you could make the call and then clear the access token in your frontend (or perform whatever other logout logic).
2) You can call Auth::logout() in your code, which will set the current user on the authentication service to null resulting in Auth::check() returning false.
I am using lumen for API development. I have an issue in Lumen Custom Authentication.
I want to login a user when his credentials and account_name matches with stored record. In the credentials filed there is not username and password type data.
here my login method
public function login(Request $request)
{
$this->validate($request,[
'data.credentials' => 'required',
'data.account_name' => 'required',
]);
try {
$credentials=$request->data['credentials'];
$account_name=$request->data['account_name'];
$user=User::where('account_name',$account_name)->where('credentials',$credentials)->first();
if($user){
// storing the authenticated user to the guard session
$auth_token=Hash::make($account_name . ":" . $credentials);
// update user auth token
$user->auth_token=$auth_token;
$user->update();
$data="Some Data";
return response()->json([
"auth_token"=> $auth_token,
"data"=>$data,
"request_id"=> uniqid(),
"status"=> "success"
]);
}
} catch (\Exception $e) {
return response()->json(array(
'error' => $e->getMessage(),
'status' => 'failed',
'status_code' => 500
));
}
}
I authenticated user with credentials I want to store that user in guard that can be default guard or custom and want to return auth_token from every response. if I use following code it give me an error.
Auth::guard()->attempt(['credentials'=>$credentials,'account_name'=>$account_name]);
It give an error that attempt_undefined_method. and If I use the following code
Auth::guard()->check(['credentials'=>$credentials,'account_name'=>$account]);
it returns the false value and do not store user in guard. I want such type of response from every request where I applied auth middleware
return response()->json([
"auth_token"=> auth()->user()->auth_token,
"data"=>$data,
"request_id"=> uniqid(),
"status"=> "success
]);
following is my AuthMiddleware.php code
$header=$request->header('Auth-Token');
if(Auth::guard('api')){
// we can use $user variable for further :)
return $next($request);
}
I'm practicing manual authentication in Laravel for learning purposes, following along laracasts.com and reading the manual user authentication related documentation here - https://laravel.com/docs/5.4/authentication#authenticating-users
My login controller code is as follows:
public function loginSubmit() {
$email = request('email');
$password = request('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return 'logged in';
} else {
return 'not logged in';
}
Albeit the password not being hashed, I am using the Auth::attempt with the correct email and password information but am not able to return 'logged in'. How can I get the login to work with Auth::attempt ?
You need to hash the password
use Illuminate\Support\Facades\Hash;
$password = Hash::make($request->password);