I develop site with laravel 5.2 and use
https://github.com/mcamara/laravel-localization and
http://imrealashu.in/code/laravel/multi-auth-with-laravel-5-2-2/
i have followed everything in that link
my routes.php
Route::group([
'prefix' => LaravelLocalization::setLocale(),
'middleware' => ['web', 'localize', 'localeSessionRedirect', 'localizationRedirect']
], function () {
//Route::auth();
Route::get('login', 'UserAuthController#showLoginForm');
Route::post('login', 'UserAuthController#login');
Route::get('logout', 'UserAuthController#logout');
//user
Route::get('user/dashboard', ['as'=> 'user/dashboard', 'uses' => 'UsersController#index']);
});
Route::group(
['middleware' => 'web'], function () {
//Admin Login Routes...
Route::get('/admin/login','Admin\Auth\AuthController#showLoginForm');
Route::post('/admin/login','Admin\Auth\AuthController#login');
Route::get('/admin/logout','Admin\Auth\AuthController#logout');
Route::get('admin/dashboard', 'Admin\DashboardController#index');
Route::resource('admin/administrator', 'Admin\AdminController',['except' => 'show']);
UserAuthController.php
namespace App\Http\Controllers;
use Validator;
use Auth;
use Session;
use Illuminate\Http\Request;
use App\Http\Requests;
class UserAuthController extends Controller
{
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()){
// If validation falis redirect back to login.
return redirect('login')
->withErrors($validator)
->withInput();
}else {
$userdata = [
'email' => $request->email,
'password' => $request->password
];
// doing login.
if (Auth::guard('user')->validate($userdata)) {
if (Auth::guard('user')->attempt($userdata)) {
return redirect('/user/dashboard');
}
}
else {
// if any error send back with message.
Session::flash('error', 'Something went wrong');
return redirect('login');
}
}
}
public function logout()
{
Auth::guard('user')->logout();
return redirect('login');
}
}
UsersController.php
namespace App\Http\Controllers;
use Auth;
//use Session;
use App\User_Profile;
use Illuminate\Http\Request;
use App\Http\Requests;
class UsersController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
session()->put('uid',Auth::guard('user')->user()->id);
session()->put('username', Auth::guard('user')->user()->username);
session()->put('email', Auth::guard('user')->user()->email);
$uid = session()->get('uid');
$username = session()->get('username');
$profile = User_Profile::where('user_id', '=', $uid)->first();
return view('users.index', compact('username', 'profile'));
}
}
Admin\Auth\AuthController.php
namespace App\Http\Controllers\Admin\Auth;
use App\Admin;
use Validator;
use App\Http\Controllers\Admin\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
protected $redirectTo = 'admin/dashboard';
protected $guard = 'admin';
protected $redirectAfterLogout = 'admin/login';
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
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');
}
}
my kernel.php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
// \Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\View\Middleware\ShareErrorsFromSession::class,
// \App\Http\Middleware\VerifyCsrfToken::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
// 'auth' => [
// \App\Http\Middleware\Authenticate::class,
// \App\Http\Middleware\EncryptCookies::class,
// \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
// \Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\View\Middleware\ShareErrorsFromSession::class,
// \App\Http\Middleware\VerifyCsrfToken::class,
// ],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
'user' => \App\Http\Middleware\RedirectIfNotUser::class,
];
}
config/auth.php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'user',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| Here you may set the options for resetting passwords including the view
| that is your password reset e-mail. You may also set the name of the
| table that maintains all of the reset tokens for your application.
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
I have success in admin logged in and do anything to manage backend
but not in user, everytime logged in when i refresh keep redirect back to login page. it seems $this->middleware('auth') not working.
Can you help me, where did i miss ?
Thank you
Be sure to have the forms in your views (the login-form, registration-form, ...) post to the localized url's.
So in your blade-views use:
<form method="POST" action="{{ url(LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(), '/password/email')) }}">
...
</form>
The above scripts are alright.
I made a mistake in the view, I placed
Signout
logout function in the navigation view.
I have changed the link with usual logout link.
Signout
Now its working.
thanks
Related
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
When i am trying to change the table users, that is by default linked with the Auth in laravel my API always gives me "unauthorized user" response and when i use the default table user it works fine. I want to know why it is happening?
I have made all the changes that is required to switch the table from users to my choice table.
my table name is : apitable, Model_name: apitablemodel
changes in auth.php:
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'api',
'Passwords' => 'apitable', //if want to change the table attached with auth then make changes here
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'apitabel',
],
'api' => [
'driver' => 'passport',
'provider' => 'apitable',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'apitable' => [
'driver' => 'eloquent',
'model' => App\apitablemodel::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
'apitable' => [
'provider' => 'apitable',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Here is my model file
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
// use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class apitablemodel extends Authenticatable
{ use HasApiTokens, Notifiable;
//
protected $table='apitable';
protected $fillable = ['Email', 'Password','token'];
public $timestamps=false;
protected $hidden = [
'Password', 'token',
];
}
Here is my controller file
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\apitablemodel;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
// response()->json(['success' => $success], $this-> successStatus);
class product extends Controller
{ public $successStatus = 200;
public function login(Request $request){
if(Auth::check(['Email' => request('Email'), 'Password' => request('Password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
$user->token=$success['token'];
// $token->expires_at=Carbon::now()->addMinutes(1);
$user->save();
return response()->json(["token_expires in :"=>"2min","token"=>$user->token]);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
public function update(Request $req){
$obj= User::find($req->id);
$obj->email=$req->email;
if($obj->save()){
return response()->json(['success'=>'Updated']);
}
else{
return ["status:"=>"Unauthorized user, make sure your are login"];
}
}
}
I have two functions in my controller, one is for updating the data that is present in the "apitable" table and one for login so that only authenticated users can update the database table values.
When i hit my API in postman it gives me unauthorized response as for which i have write the condition in my controller. I want to know why if condition is failing.
I think you should use Auth::attempt() method for login.
public function login(Request $request){
$credentials = $request->only('Email', 'Password');
if(Auth::attempt($credentials)){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
$user->token=$success['token'];
// $token->expires_at=Carbon::now()->addMinutes(1);
$user->save();
return response()->json(["token_expires in :"=>"2min","token"=>$user->token]);
} else {
return response()->json(['error'=>'Unauthorised'], 401);
}
i'm on laravel and try to make a user verfication system but i have a probleme with the function Auth::attempt, it returns allways false even if i fix data.
this is my login function code in my controller
$request->validate([
'username' => 'string',
'password' => 'required|string',
]);
$credentials = ['username' =>$request->get('username'), 'password' =>$request->get('password')];
try {
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString()
]);
} catch(Exception $e){
echo $e;
}
this is my customerProvider for checking because i have in my database MD5 password
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
if(md5($plain) == $user->getAuthPassword()){
return true;
} else if($this->hasher->check($plain, $user->getAuthPassword())){
return true;
} else {
return false;
}
}
}
my user model
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'password'
];
/**
* 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',
];
}
this is my auth.php
<?php
use App\User;
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'customuserprovider',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Help me please to found a solution..
Seems like the config/auth.php has the api driver set to jwt and not passport as you posted for somewhat reason.
If you cache the configuration with php artisan optimize or php artisan config:cache you have to run php artisan optimize:clear to let your updated configuration has effect
I am trying to Auth Attempt for login in Laravel. and Successfully Logged . But can't Remember Auth Session.
My kernel.php file :
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
Auth.php file is:
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
HomeController.php Code is :
public function login(Request $request){
if($request->isMethod('post')){
$data = $request->all();
$any = array('email'=>$data['email'],'password'=>$data['password']);
if(auth()->attempt($any)){
dd("logged"); //This code is running when i try to login
//but after when i try to get Auth::check() then it return false
}
}
}
My web.php File :
<?php
Route::group(['middleware'=>'web'],function(){
Route::match(['get','post'],'/', 'HomeController#index');
Route::match(['get','post'],'/login', 'HomeController#login');
Route::group(['middleware'=>'auth'],function(){
});
});
?>
Did you tried to Authenticate users by calling so:
Auth::attempt($user_credentails);
instead of auth()
I solved this problem. Let's check my HomeController code
public function login(Request $request){
if($request->isMethod('post')){
$data = $request->all();
$any = array('email'=>$data['email'],'password'=>$data['password']);
if(auth()->attempt($any)){
dd("logged"); //This code is running when i try to login
//but after when i try to get Auth::check() then it return false
}
}
}
when auth attempt is successful then i stop code with dd("Logged"); if i stopped code then the auth attempt is not full completed. I removed dd("Logged"); then i make redirect to dashboard.
if(auth()->attempt($any)){
return Redirect('/dashboard');
}
Then i check auth with Auth::check() and it return true . Thanks Guys for Posting Your Valuable Comments and Answers . I really Appreciate it.
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.