laravel custom auth - attempt(), session - laravel

I'm learning how to create custom auth system. I created own guard Player. On my test function I'm usimg attempt() to authenticate user. Checking is passed. Then I created test2 method which is accesible only for logged user.
My Route is:
Route::get('test', 'MyController#test');
Route::get('test2', 'MyController#test2')->middleware('auth');
My Controller is:
class MyController extends Controller
{
public function test()
{
$cr = ['name' => 'pl', 'password' => 'pl'];
if (Auth::guard('player')->attempt($cr)) {
$user = Auth::guard('player')->user();
return 'ok';
}
return 'not found';
}
public function test2()
{
return 'test2';
}
}
My guard config is:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'player' => [
'driver' => 'session',
'provider' => 'player',
],
'club' => [
'driver' => 'session',
'provider' => 'club',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'player' => [
'driver' => 'eloquent',
'model' => App\Player::class,
],
'club' => [
'driver' => 'eloquent',
'model' => App\Club::class,
],
],
I want to get access to test2 route by hand (not by redirecting) after performing test function but I can't. I'm receiving Auth default login form.
Should I write my own middleware or set session manually? Please help.

You need to write you own middleware,
<?php
namespace App\Http\Middleware;
use Closure;
class RedirectIfNotPlayer
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'player')
{
if(!auth()->guard($guard)->check()) {
return redirect(url('/player/login'));
}
return $next($request);
}
}
add this middleware to your kernel.php file, inside routeMiddleware,
'player' => \App\Http\Middleware\RedirectIfNotPlayer::class,
Then You can use your middleware in route,
Route::get('test2', 'MyController#test2')->middleware('player');

I suggest you to do like this may be this work out!
public function test()
{
$cr = ['name' => 'pl', 'password' => 'pl'];
if (Auth::guard('player')->attempt($cr)) {
$user = Auth::guard('player')->user();
return 'ok';
redirect("test2(view)");
}

You need to redirect to somewhere after login is successful to have the session persist.

make auth middleware use your guard:
Route::get('test2', 'MyController#test2')->middleware('auth:player');

Related

Laravel middleware not redirecting to custom login page

I have two middlewares set up for admin and one for customer
class AuthenticateCustomer
{
public function handle($request, Closure $next)
{
if (! Auth::guard('customer')->check()) {
return redirect(route('customer.login'));
}
return $next($request);
}
}
And that of the admin is
class AuthenticateAdmin
{
public function handle($request, Closure $next)
{
if (! Auth::guard('admin')->check()) {
return redirect(route('admin.login'));
}
return $next($request);
}
}
However I still get directed to the Laravel built in log in page auth.login. It appears my middlewares are not being used.
You should add an alias for you middleware in app\http\Kernel.php like below:
protected $routeMiddleware = [
'customerAuth' => \App\Http\Middleware\AuthenticateCustomer::class,
'adminAuth' => \App\Http\Middleware\AuthenticateAdmin::class,
]
Then use it on your routes like below as group:
// For customer
Route::group(['middleware' => 'customerAuth'],function (){
Route::get('test',function (){
});
});
// For admin
Route::group(['middleware' => 'adminAuth'],function (){
Route::get('test',function (){
});
});
did you config auth.php? if not then config auth.php. Open config/auth.php and add the new guards edit as follows:
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
*/
//For User
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
//For Admin
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|-----------------------------------------------------------------------
*/
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
You can also modify LoginController if you want to use same controller, then opent the Login Controller in app/Http/Controllers/Auth and edit as follows:
class LoginController extends Controller
{
[...]
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:admin')->except('logout');
}
[...]
}

unable to login as admin in laravel 5.8

I have multi-authentication set up in my laravel app. I am trying to create multiple authentication using default authentication laravel 5.8. I have two tables one is users and other is admins. I have configured the guards for admin. User login works fine, no issues but when I try to login the admin, it doesn't work even if I login with correct credentials. Password field validation works if I use less then 6 character. Please help me to solve this problem.enter code here
My Admin model is
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable {
use Notifiable;
protected $guard = 'admin';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'title',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Guard setting is
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
],
AdminLoginController is
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Http\Request;
class AdminLoginController extends Controller {
public function __construct() {
$this->middleware('guest:admin')->except('logout');
}
public function showLoginForm() {
return view('auth.admin-login');
}
protected function guard() {
return Auth::guard('admin');
}
public function login(Request $request) {
//validate the form
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
//attemp to login
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
//Authentication passed...
return 'success';
//return redirect()
//->intended(route('admin.dashboardsdsdsd'));
//if login success then redirect to page
// if not success then redirect to back
}
return redirect()->back()->withInput($request->only('email', 'remember'));
}
}
Route is
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('admin', 'AdminController#index')->name('admin.dashboard');
Route::get('admin/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('admin/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Please help me to resolve this issue, so that admin can login.
There are two main reasons:
First one: your hash password is not correct, so open this website ( which is MD5 Hash Generator) then put any number that you like, take it and create a new admin account directly from database and paste the password then try
Second one: Clear your cache and view :
php artisan view:clear
php artisan cache:clear

Laravel: Multiple auth with same routes

I have a Laravel(5.8) application where I have 2 roles Super Admin and Admin which are saved in two different tables admins & users. They each have their own access levels respectively. However, about 95% of the routes in the entire application are same for each of them but restricted or modified according to their access levels.
For example:
Admin can only update his own profile and has the permission to Create & View.
Super Admin can play with the list of admins and has the permission of create/update/view & delete.
Therefore I have two guards users(default) = users table and admins = admins table. But when I am adding both or the guards in a same controller it just keep redirecting and display that the page is not redirecting properly
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'member' => [
'driver' => 'session',
'provider' => 'member',
],
...
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'member' => [
'driver' => 'eloquent',
'model' => App\Member::class,
],
],
User.php
class User extends Authenticatable
{
...
public function _login($request)
{
if(\Auth::attempt([
'email' => $request->email,
'password' => $request->password
]))
{
return [
'success' => true
];
}
else
{
return [
'success' => false
];
}
}
}
Member.php
class Member extends Authenticatable
{
...
public function _login($request)
{
if(\Auth::guard('member')->attempt([
'email' => $request->email,
'password' => $request->password
]))
{
return [
'success' => true
];
}
else
{
return [
'success' => false
];
}
}
}
HomeController.php
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
echo "<pre>";
if(\Auth::user())
{
print_r(\Auth::user());
}
else if(\Auth::guard('member')->user())
{
print_r(\Auth::guard('member')->user());
}
echo "</pre>";
}
}
If I comment the auth middleware in the __construct() then it works and displays the data of the logged in user but if keep redirecting and shows the page is not redirecting properly error.
You probably want to use $this->middleware('auth:web') or $this->middleware('auth:member') so your middleware knows which guard to use.
Anything after the : is passed to the Middleware's handle() function as arguments.

Laravel - Multiple Authentication

i need to create three authentication: user, admin, restUser.
I managed to create multiple login for user and admin but when try to add login for restUser it returns user form...
this is my code:
app/Teretaneusers.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Teretaneusers extends Authenticatable
{
use Notifiable;
protected $guard = 'teretaneuser';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
and I create table in MySQL database teretaneusers with column: name, email, password
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
'teretaneuser' => [
'driver' => 'session',
'provider' => 'teretaneusers',
],
'teretaneuser-api' => [
'driver' => 'token',
'provider' => 'teretaneusers',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admins::class,
],
'teretaneusers' => [
'driver' => 'eloquent',
'model' => App\Teretaneusers::class,
],
],
Controllers/UserGymController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserGymController extends Controller
{
public function __construct()
{
$this->middleware('auth:teretaneuser');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('teretaneuser');
}
}
Controllers\Auth\UserGymLoginController.php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
class UserGymLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:teretaneuser');
}
public function showLoginForm(){
return view('auth.teretaneuser-login');
}
public function login(Request $request){
//validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]
);
//attempt to log user in
if(Auth::guard('teretaneuser')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
return redirect()->intended(route('userGym.dashboard'));
}
return redirect()->back()->withInput($request->only('email','remember'));
}
}
auth/teretaneuser-login.blade.php
form class="form-horizontal" method="POST" action="{{
route('userGym.login.submit') }}"
and web.php
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::prefix('admin')->group( function() {
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminController#index')->name('admin.dashboard');
});
Route::prefix('userGym')->group( function() {
Route::get('/login', 'Auth\UserGymLoginController#showLoginForm')->name('userGym.login');
Route::post('/login', 'Auth\UserGymLoginController#login')->name('userGym.login.submit');
Route::get('/', 'UserGymController#index')->name('userGym.dashboard');
});
Can somebody tell me where I'm wrong? When I try login from adress http://localhost/logovanje/public/userGym/login
it redirest me to http://localhost/logovanje/public/home
I use Laravel 5.4
I did the same for the admin and it worked.
Most likely you still have a valid session and you got a middleware (possibly RedirectIfAuthenticated) that is coming into play.
I think you could use Sentinel for this as it has an authentication package called roles and permissions
Here's a link for its documentation.

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