laravel passport custom value user_id in table oauth_access_tokens - laravel

I have master table user with name employee, So I wan't use that table not default table from laravel auth users. How to modify laravel passport so that I can use column from employee table?
this my login code
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('nApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}

In your config/auth.php you have providers and providers have drivers...
So the drivers make it to the model you want to use...
If you have some authentication process that use User model, then you can use helper function : auth('YOUR GUARD NAME')->user().
Your guard name is in config/auth.php too.

Related

Laravel make manual password reset

I am working in laravel,
I am stuck in reset password manually,
I verify the mail is exist in database or not if mail is exist than it will redirect to reset password page.
When user type the password and submit the form, at that time password is not update in mongoDb database.
here's my function...
class ForgotPasswordController extends Controller
{
public function confirmPassword(Request $request, $email)
{
$this->validate($request, [
'password' => 'required|string|min:6'
]);
$admin = AdminAuth::find($email);
$admin->password = $request->get('password');
$admin->save();
return view('auth.login');
}
}
Try
$admin->password = Hash::make($request->get('password'));
More details here. And remember: never save users passwords explicit in db.

i'm getting a null user id when i create a new artisan in a laravel and vue project

Here is my controller that holds the store function
public function store(Request $request)
{
$artisan = Artisan::create($request->all() + ['user_id' => Auth::user()]);
return $artisan;
}
Can figure out why Auth::user() is pushing a null value to the db instead of picking the current authenticated user id.
please help guys.
Auth::user() returns a instance of the User class (if the user is logged in).
You have to pick the id from it, like this:
$user_id = Auth::user()->id;
To get user data from Auth::user(), you have to follow this.
You have to use Auth class for login.
if (Auth::attempt(['email' => $email, 'password' => $password])) {}
You have to include all the routes under web middleware where you want to access authenticated user data.
Route::group(['middleware' => ['web']], function () {
Route::post('/dashboard', 'Controller#dashboard');
}
As the value comes from Session and web middleware has Session
activated.

redirect to different views in laravel logged in users based on role mentioned by using if condition in laravel controller

In laravel i have student,parent ,employee(Teacher,Librarian,warden) roles with different permissions...based on user role it should redirect to different blade files when user logged in..my problem is if user parent or student it is redirecting to different dashboards but whenever user is teacher or other it does not logged in but in users table already user exist.
below is my LoginController code
LoginController.php:
public function login(Request $request){
if(Auth::attempt([
'email'=>$request->email,
'username'=>$request->username,
'password'=>$request->password,
]))
{
$user=User::where('username',$request->username)->first();
$usertype=$user->user_type;
$username=$user->username;
$roles=DB::table('roles')->where('id','=',$usertype)->first();
$rolename=$roles->role_name;
if($rolename=="student"){
$student=DB::table('students')->where('stud_adm_id','=',$username)->first();
$classid=$student->class_id;
$sectionid=$student->section_id;
$class=DB::table('classtables')->where('id',$classid)->first();
$section=DB::table('sections')->where('id',$sectionid)->first();
return view('studentdashboard',compact('student','class','section'));
}elseif($rolename=="Teacher"){
$employeedetails=DB::table('employees')->where('employee_fname','=',$username)->first();
return view('teacherdashboard',compact('employeedetails'));
}
elseif($rolename=="parent"){
$parentdetails=DB::table('parents')->where('mother_phone','=',$username)->first();
$stateid=$parentdetails->state;
$state=DB::table('states')->where('state_id','=',$stateid)->first();
return view('parentdashboard',compact('parentdetails','state'));
}
}else{
return redirect()->back();
}
}
my roles are mentioned in role table and that id stored in users table
Thanks in advance...
You better create a middleware to check user role, and based on the role redirect user to different pages!
Run the command below to create a middleware that checks user's role.
php artisan make:middleware CheckRoleMiddleware
The command will create a file under App\Http\Middleware named CheckRoleMiddleware this class will come a predefined method handle() there you can place the logic that checks user's role and redirects them to different pages example:
<?php namespace App\Http\Middleware;
use Closure;
class CheckRoleMiddleware {
public function handle($request, Closure $next)
{
//User role is admin
if ( Auth::check() && Auth::user()->isAdmin() )
{
return $next($request);
}
//If user role is student
if(Auth::check() && auth()->user()->role === 'student')
{
return view('studentDashboard');
or route('routeName');
}
//If user role is teacher
if(Auth::check() && auth()->user()->role ==='teacher')
{
return view('teacherDashboard');
or route('routeName');
}
//default redirect
return redirect('home');
}
}
And don't forget to add CheckRoleMiddleware to App\Http\Kernel.php
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'user-role' => 'App\Http\Middleware\CheckRoleMiddleware', // this line right here
];
Lets just ignore everything about how this stuff should work and how it does by default and take what you have.
Do you see a problem here:
if ($rolename == "student")
elseif ($rolename == "Teacher")
elseif ($rolename == "parent")
If not, lets try it this way:
student
Teacher
parent
Which one is not like the others? And which one was the one that "was not working" correctly?
I would like to assume you have these roles named in a consistent fashion, so Teacher should be teacher.
You can do all of what you want to do with the default LoginController by overriding a method or two.
You should not be returning views from processing routes. POST REDIRECT GET. POST comes in, return a REDIRECT, that causes a GET request (which most likely is going to return a view).
For validating the login credentials:
protected function validateLogin(Request $request)
{
$this->validate($request, [
'email' => '...',
'username' => '...',
'password' => '...',
]);
}
For what credentials should be used from the request:
protected function credentials(Request $request)
{
return $request->only('email', 'username', 'password');
}
The response to return after successful authentication:
protected function authenticated(Request $request, $user)
{
// do your role checking here
// return a redirect response to where you want that particular user type to go
// return redirect()->route(...);
}
Everything related to building the views and gathering that data is its own route. All you have to do is return a redirect for the login flow. Where you redirect to is responsible for gathering the data needed to display a view.

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

Override login Authentication in laravel

my laravel version is 5.3. I'm using built-in Authentication in laravel to login users.
there is a column name in user table as status. when it is 0 it means the user cannot login.
now I don't know how to check this column before login method/user.
I don't want user can login when the status column is 0.
You can override authenticated() function:
protected function authenticated()
{
if (auth()->user()->status==0) {
auth()->logout();
return redirect('/');
}
}
You can also Manually authenticate users by overriding authenticate() function:
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password, 'status' => 1]))
{
// Authentication passed...
}
}

Resources