Laravel not creating authenticated session for user - laravel

I am doing user authentication using a custom table. I am able to login successfully as when I do in AuthController.php
public function authenticated(Request $request, $user)
{
dd($user);
}
I am getting the user details.
But when I access some other route and in the respective controller when I do
dd(Auth::user()) returns null
dd(session()->all()) returns _token
dd(Auth::check()) returns false
I am using public_users table for authentication and public_email , public_password fields for doing the authentication so I have changed the App\User.php file as follows:
class User extends Authenticatable
{
protected $table = 'public_users';
protected $primaryKey = 'public_users_id';
protected $fillable = [
'public_email',
'public_password'
];
protected $hidden = [
'public_password'
];
// Override required, Otherwise existing Authentication system will not match credentials
public function getAuthPassword()
{
return $this->public_password;
}
}
and in app/Http/Controllers/Auth/AuthController.php I have added the below code
public function loginUsername()
{
return property_exists($this, 'username') ? $this->username : 'public_email';
}
public function authenticated(Request $request, $user)
{
dd($user);
}
and my config/auth.php has
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
]
]
What am I doing wrong? How could I create user session?
Any help appreciated!

Try auth()->user() after login

Solved!
I removed dd($user) from app/Http/Controllers/Auth/AuthController.php which was closing the Request LifeCycle and creating a new token each time. All I needed was to redirect which is default in handleUserWasAuthenticated method in /vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
protected function authenticated(Request $request, $user)
{
return redirect()->intended($this->redirectPath());
}

Related

different login routes and login views for student and admin

Every laravel newbie struggles with multi auth, I am no exception
I am trying to make student management system. There will two different routs for admin admin/login and for student student/login.
The student can't register itself, but he will be registered by admin.
So a student has only access to student/dashboard, registration of students will be done by the admin on admin/dashboard.
Below is the detail what I have already done:
created migration for both admin and student.
created guard for both admin and student.
modified login controller and added adminLogin and studentLogin methods.
modified RedirectIfAuthenticated middleware
Config/auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'students' => [
'driver' => 'session',
'provider' => 'students',
],
'web-admin'=>[
'driver'=>'session',
'provider'=>'admin',
],
'api' => [
'driver' => 'token',
'provider' => 'students',
'hash' => false,
],
],
'providers' => [
'students' => [
'driver' => 'eloquent',
'model' => App\Student::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'passwords' => [
'students' => [
'provider' => 'students',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'table' => 'password_resets',
'expire' => 60,
],
],
LoginController.php
lass LoginController extends Controller
{
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:web-admin')->except('logout');
$this->middleware('guest:students')->except('logout');
}
public function showAdminLoginForm()
{
return view('admin.login', ['url' => 'admin']);
}
public function adminLogin(Request $request)
{
$this->validate($request, [
'admin_id' => 'required',
'password' => 'required|min:8'
]);
if (Auth::guard('admin')->attempt(['admin_id' => $request->adminid, 'password' => $request->password], $request->get('remember'))) {
return redirect()->intended('/admin/dashboard');
}
return back()->withInput($request->only('admin_id', 'remember'));
}
public function showStudentLoginForm()
{
return view('student.login', ['url' => 'student']);
}
public function studentLogin(Request $request)
{
$this->validate($request, [
'roll_no' => 'required',
'password' => 'required|min:8'
]);
if (Auth::guard('writer')->attempt(['roll_no' => $request->roll_no, 'password' => $request->password], $request->get('remember'))) {
return redirect()->intended('/student/dashboard');
}
return back()->withInput($request->only('roll_no', 'remember'));
}
}
RedirectAuthenticated.php
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if('web_admin'==='$guard'){
return redirect('/admin/dashboard');
}
return redirect('/admin/login');
}
if (Auth::guard($guard)->check()) {
if('students'==='$guard'){
return redirect('/student/dashboard');
}
return redirect('/student/login');
}
return $next($request);
}
}
I have created two folders in the view, student and admin. They both have two files. login.blade.php and dashboard.blade.php
What laravel does it it shows login, and register under auth folder.
I want to give two routes one for /admin/login which return admin.login view.
Same for student /student/login which return student.login view.
I want to remove /register route and make the link to available on admin dashboard , there will be no admin register link.
Also restrict the user from accessing admin area.
**I don't want the whole code, just help me steps and way that I should follow or changes I have to make **
Finally I solved it. I didn't use php artisan make:auth, instead I did it from scratch. Created a fresh project, deleted User.php and the migration.
Created models Student.php and Admin.php along with migrations and controllers.
php artisan make:model Student -mc
php artisan make:model Admin -mc
After than I created guards, I deleted default guard (I don't know It was right to do so, but I felt that if there is no need of default guard and also it was using users table so I deleted).
Here is config/auth.php
'guards' => [
'student'=>[
'driver'=>'session',
'provider'=>'students'
],
'admin'=>[
'driver'=>'session',
'provider'=>'admins'
],
],
'providers' => [
'students'=>[
'driver'=>'eloquent',
'model'=>App\Student::class,
],
'admins'=>[
'driver'=>'eloquent',
'model'=>App\Admin::class,
]
So I have two guards student and admin.
Here is the admin model Admin.php
class Admin extends Authenticatable
{
use Notifiable;
protected $fillable = [
'firstname', 'lastname','admin_id', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
and model Student Student.php
class Student extends Authenticatable
{
use Notifiable;
protected $fillable = [
'firstname', 'lastname','admin_id', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
After this I modified AdminController.php
class AdminsController extends Controller
{
use AuthenticatesUsers;
protected $guard = 'admin';
public function showLogin(){
return view('admin.login');
}
public function dashboard(){
return view('admin.dashboard');
}
public function login(Request $request){
$this->validate($request,[
'admin_id' => 'required',
'password'=>'required|min:8',
]);
if(Auth::guard('admin')->attempt(['admin_id'=>$request['admin_id'], 'password'=>$request['password']])){
return redirect('admin/dashboard');
}
return redirect('/admin');
}
}
Then I created routes Web.php
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin','AdminsController#showLogin');
Route::get('/student','StudentsController#showLogin');
Route::get('/admin/dashboard','AdminsController#dashboard');
Route::get('/student','StudentsController#showLogin');
Route::post('/admin/login','AdminsController#login');
Route::post('/student/login','StudentsController#login');
Now, at this time login works. I still need to do a lot. If any suggestion, I welcome that, please comment below.

custom auth of two different users using two tables. i don't want to use make:auth

The first auth system works very fine its code is below and needed to have to different users using two different tables am using laravel 5.5
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
class StudentController extends Controller
{
public function Register(Request $request)
{
$firstname = $request['firstname'];
$othername = $request['othername'];
$email = $request['email'];
$password = $request['password'];
$user = new User();
$user->firstname = $firstname;
$user->othername = $othername;
$user->email = $email;
$user->password = $password;
$user->save();
Auth::login($user);
return redirect()->route('studentDashboard');
}
public function Login(Request $request)
{
if(Auth::attempt(['email'=> $request['email'], 'password'=>
$request['password']]))
{
return redirect()->route('studentDashboard');
}
return redirect()->back();
}
}
i duplicated the above to create auth for a different user.The registration works but the login does not work even if the login data is right it returns the redirect back after the if statement
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employer;
use Illuminate\Support\Facades\Auth;
class EmployerController extends Controller
{
public function createEmployerAccount(Request $request)
{
$companyName = $request['companyname'];
$companyEmail = $request['email'];
$companyPasword = $request['password'];
$Employer = new Employer();
$Employer->companyname = $companyName;
$Employer->email = $companyEmail;
$Employer->password = $companyPasword;
$Employer->save();
Auth::login($Employer);
return redirect()->route('employersDashboard');
}
public function signInEmployer(Request $request)
{
if(Auth::attempt(['email'=>$request['email'],
'password'=>$request['password']]))
{
return redirect()->route('employersDashboard');
}
return redirect()->back();
}
}
when i try to change the 'email' to 'emails' an error is shown->the select query is from the users table not employers table that i need to get data from and also when i change 'password' to 'passwords' an error "undefined index password" is shown
this is the route file content
Route::get('/',function(){
return view('pages.index');
})->name('home');
Route::post('/signup',[
'uses'=>'StudentController#Register',
'as'=> 'signup'
]);
Route::post('/signin',[
'uses'=>'StudentController#Login',
'as'=>'signin'
]);
Route::get('/employers',[
'uses'=>'PageController#employersPage',
'as'=>'employers'
]);
Route::get('/studentDashboard',[
'uses'=>'PageController#getStudentDashboard',
'as'=> 'studentDashboard'
]);
Route::post('/createcompany',[
'uses'=>'EmployerController#createEmployerAccount',
'as'=>'createcompany'
]);
Route::post('/signInEmployer',[
'uses'=>'EmployerController#signInEmployer',
'as'=>'signInEmployer'
]);
Route::get('/employersDashboard',[
'uses'=>'PageController#getEmployersDashboard',
'as'=> 'employersDashboard',
'middleware'=>'auth:employer'
]);
Route::post('/createPost',[
'uses'=>'PostController#postCreatePost',
'as'=> 'createPost'
]);
You need to tell Auth to use different Guard for authentication at time of Employer login. To define guards for Employer change like this in your config/auth.php.
Look for guards section in auth.php and add your new guard
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'employer' => [
'driver' => 'session',
'provider' => 'employers',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Now in the same file there is a providers section. You need to add employers provider
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
//Employer provider
'employers' => [
'driver' => 'eloquent',
'model' => App\Employer::class,
],
],
Create a custom Auth middleware
namespace App\Http\Middleware;
use Closure;
use Auth;
class AuthenticateEmployer
{
public function handle($request, Closure $next)
{
//If request does not comes from logged in employer
//then he shall be redirected to employer Login page
if (!Auth::guard('employer')->check()) {
return redirect('/signInEmployer');
}
return $next($request);
}
}
Register custom auth middleware in Kernal.php in routeMiddleware
'employerAuth' => \App\Http\Middleware\AuthenticateEmployer::class,
Now we have setup our custom guard and custom middleware employerAuth
EmployerController
class EmployerController extends Controller
{
//either you have to define this or you can use `Auth::guard('employer')->attempt($credentials)` in login
protected function guard()
{
return Auth::guard('employer');
}
public function signInEmployer(Request $request)
{
if(Auth::attempt(['email'=>$request['email'],
'password'=>$request['password']]))
{
return redirect()->route('employersDashboard');
}
return redirect()->back();
}
}
For all the routes protected by Employer auth, you either need to add middleware employerAuth in routes or add employerAuth in each controller construct like this
public function __construct()
{
$this->middleware('employerAuth');
}
Hope it may help you. For details you can check this https://laravel.com/docs/5.6/authentication#authenticating-users
Check this nice sample app for multi auth application https://github.com/yskoverride/Various2.0/tree/master/app

Access authenticated user in a Laravel 5.4 Model

I'm building an app that has pricing. I would want to assign some special price to some specific users.
In the model that has the price, I'm trying to use an accessor to "tweak" the price like so:
public function getPriceAttribute($price)
{
dd(auth()->user()); //this returns null
if (auth()->check()) {
$user = auth()->user();
return $user->aDefinedRelationship()->first()->price;
}
return $price;
}
However auth()->user() always returns null.
I'm using the traditional Laravel authentication, no external library.
Please is there something I'm not doing right?
Any help would be appreciated.
More information:
auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Api\V1\Models\User::class,
],
],
];
ThePriceModel.php
namespace App\Api\V1\Models;
use Illuminate\Database\Eloquent\Model;
class ThePriceModel extends Model
{
protected $table = 'prices';
protected $fillable = ['code', 'price'];
public function getPriceAttribute($price)
{
dd(auth()->user()); //this returns null
if (auth()->check()) {
$user = auth()->user();
return $user->aDefinedRelationship()->first()->price;
}
return $price;
}
}
After every other thing failed, I resorted to using a global config variable.
in config/constants.php:
return [
...
'user' => []
];
somewhere in my controller:
config()->set('constants.user', auth()->user());
Then in the model:
...
public function getPriceAttribute($price)
{
$user = config()->get('constants.user');
...
}
I suppose you were using API and this is why it didn't work. You could check for the user using this. You need to check API guard.
$user = \Auth::user() ?? \Auth::guard("api")->user();

creating a custom authentication system in laravel

How can I build an authentication system for customer?
I have used laravel built in authentication system for my admin panel where built in user model and users table already used.
Now I want to build another authentication system for my customer where customer model and customers table will be used.
How can I do this in laravel 5.2 ?
How to implement Multi Auth in Larvel 5.2
As Mentioned above. Two table admin and users
Laravel 5.2 has a new artisan command.
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController e.g.,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
That's all needed to make it working and also to get json of authenticated admin use
Auth::guard('admin')->user()
Edit - 1
We can access authenticated user directly using
Auth::user() but if you have two authentication table then you have to use
Auth::guard('guard_name')->user()
for logout
Auth::guard('guard_name')->user()->logout()
for authenticated user json
Auth::guard('guard_name')->user()

How to Create Multi Auth in Laravel 5.2

I have made multi auth but i have problem with final code. I have code like this
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController e.g.,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
And what does this code mean Auth::guard('admin')->user() ? And where must i type that code?
And what does this code mean Auth::guard('admin')->user() ?
In simple word, Auth::guard('admin')->user() is used when you need to get details of logged in user. But, in multi auth system, there can be two logged in users (admin/client). So you need to specify that which user you want to get. So by guard('admin'), you tell to get user from admin table.
Where must i type that code?
As from answer, you can understand that where must you use it. But still I can explain with example. Suppose there are multiple admins. Each can approve users request (like post/comments etc). So when an admin approve any request, then to insert id of that admin into approved_by column of post, you must use this line.

Resources