I'm following a tutorial for login.
I wrote all the code step by step but at the end I am not able to log in, even when I provide the correct credentials.
Below is my code:
LoginController
public function getLogin()
{
if (Auth::guard('web')->check())
{
return redirect()->route('dashboard');
}
return view('login');
}
public function postLogin(Request $request)
{
$auth = Auth::guard('web')->attempt(['username'=>$request->username,
'password'=>$request->password,'active'=> 1]);
if($auth)
{
return redirect()->route('dashboard');
}
return redirect()->back()->with(['error' =>'Wrong Credentials']);
}
public function getLogout()
{
Auth::guard('web')->logout();
return redirect()->route('/');
}
DashboardController
public function __construct()
{
$this->middleware('auth');
}
public function dashboard()
{
return view('layouts.app');
}code here
Middleware (VisitorsMiddleware.php)
public function handle($request, Closure $next, $guard = 'web')
{
if(!Auth::guard($guard)->check()){
return redirect()->route('dashboard');
}
return $next($request);
}
CheckRole.php
epublic function handle($request, Closure $next)
{
$roles = $this->getRequiredRoleForRoute($request->route());
if($request->user()->hasRole($roles)|| !$roles)
{
return $next($request);
}
return redirect()->route('/noPermission');
}
private function getRequiredRoleForRoute($route)
{
$actions = $route->getAction();
return isset($actions['roles']) ? $actions['roles']: null;
}
web.php
Route::group(['middleware'=>['visitors','roles']],function (){
Route::get('/logout', ['as' => 'logout', 'uses' => 'LoginController#getLogout']);
Route::get('/dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController#dashboard']);});
Route::get('/', ['as' => '/', 'uses' => 'LoginController#getLogin']);
Route::post('/login', ['as' => 'login', 'uses' => 'LoginController#postLogin']);
Related
I'm building a Laravel application from start with user login/registration function.
Below is some code of it:
// web.php
Route::middleware(['guest'])->group(function () {
Route::get('/register', 'UserController#register');
Route::post('/register', 'UserController#doRegister')->middleware('throttle:10,1');
Route::get('/login', 'UserController#login')->name('login');
Route::post('/login', 'UserController#doLogin')->middleware('throttle:15,1');
});
Route::get('/logout', 'UserController#logout');
// UserController.php
class UserController extends Controller
{
public function register()
{
return view('user.register');
}
public function doRegister(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:App\User',
'password' => 'required|confirmed'
]);
$userData = $request->only(['name', 'email']);
$userData['password'] = Hash::make($request->input('password'));
$user = User::create($userData);
auth()->login($user);
return redirect("/");
}
use ThrottlesLogins;
protected $maxAttempts=5;
protected $decayMinutes=1;
public function login()
{
return view('user.login');
}
public function doLogin(Request $request)
{
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$this->validate($request, [
'email' => 'required|email',
'password' => 'required'
]);
if (auth()->attempt($request->only(['email', 'password']), $request->boolean('remember_password')) == false) {
$this->incrementLoginAttempts($request);
return back()->withErrors([
'message' => __('auth.failed')
])->with('email', $request->input('email'));
}
$this->clearLoginAttempts($request);
return redirect()->to('/');
}
protected function username()
{
return 'email';
}
public function logout()
{
auth()->logout();
return redirect()->to('/');
}
}
The web page seem working.
When I enable middleware \Illuminate\Session\Middleware\AuthenticateSession::classin Kernel.php (for trial function "Invalidating Sessions On Other Devices" later), following error happen:
After creating new user success and redirect to home page with redirect("/"), Illuminate\Auth\AuthenticationException: Unauthenticated will happen and redirect again to login page (expected must go to home page with logged user).
Stacktrace:
E:\Web\movie-resumer\vendor\laravel\framework\src\Illuminate\Session\Middleware\AuthenticateSession.php:94
Stack trace:
#0 E:\Web\movie-resumer\vendor\laravel\framework\src\Illuminate\Session\Middleware\AuthenticateSession.php(55): Illuminate\Session\Middleware\AuthenticateSession->logout(Object(Illuminate\Http\Request))
This trace refer to following code in AuthenticateSession.php:
class AuthenticateSession
{
public function handle($request, Closure $next)
{
...
if ($request->session()->get('password_hash') !== $request->user()->getAuthPassword()) {
$this->logout($request);
}
...
}
}
I just try with other replacement as below in UserController#doRegister method:
Change auth()->login($user); to use auth()->attempt($request->only(['email', 'password'])); then Exception will not occur
Or: change return redirect("/"); to use return view('home'); then Exception will not occur (the URL http://localhost/register will show the home page with logged user)
Or: change/remove the route name 'login' (Route::get('/login', 'UserController#login')->name('login123');) then Exception will not occur.
Do my first implement has any mistake, so that it cannot working with AuthenticateSession middleware?
I have 2 two users (Admin and operators) for my system and i want to authenticate them to their various pages based on their roles. I am using the Authenticated.php middleware to achieve this job like below
but i get an error when trying to login with any of the users as
Call to undefined method Illuminate\Contracts\Auth\Factory::check()
What am i doing wrong please?
Authenticated.php
public function handle($request, Closure $next, ...$guards)
{
if(Auth::check()) {
if(Auth::user()->hasRole('administrator')) {
return redirect('/');
} else if (Auth::user()->hasRole('operator')) {
return redirect('client/dashboard');
}
}
// $this->authenticate($guards);
return $next($request);
}
Route.php
Route::group(['middleware' => ['auth']], function () {
Route::get('/', 'PagesController#dashboard');
});
Route::group(array('prefix' => 'client', 'namespace' => 'User', 'middleware' => ['auth']), function () {
Route::get('/dashboard', 'DashboardController#create');
});
Aren't you messing up with your if condition? Try the below code in your RedirectIfAuthenticated.php file in App\Http\Middleware. Hope that will resolve your problem.
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if(Auth::user()->hasRole('administrator'))
{
return redirect('/');
}
else
{
return redirect('client/dashboard');
}
}
return $next($request);
}
And Are you using Entrust for handling roles?
i have a middleware, i want it to pass $role to the route.php
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
$role= "normal";
$user_roles = AssignedRoles::join('roles','role_user.role_id','=','roles.id')
->where('user_id', $this->auth->user()->id)->select('roles.is_admin', 'roles.is_vendor')->get();
foreach($user_roles as $item)
{
//var_dump($item->is_vendor);
//die();
if($item->is_admin==1)
{
$role = "admin";
}
if($item->is_vendor==1)
{
$role = "vendor";
}
}
if($role=="normal"){
return $this->response->redirectTo('/');
}
//$request->attributes->add(['admin' => $admin, 'vendor' => $vendor]);
$request->attributes->add(['role' => $role]);
View::share ('role', $role);
return $next($request);
}
return $this->response->redirectTo('/');
}
is there any way to do that?
My route:
Route::group(['prefix' => 'admin', 'middleware' => ['auth']], function() {
Route::auth();
Route::pattern('id', '[0-9]+');
Route::pattern('id2', '[0-9]+');
#Admin Dashboard
Route::get('dashboard', 'Admin\DashboardController#index');
Route::get('vendor/{id}/edit', 'Admin\VendorController#getEdit');
Route::post('vendor/{id}/edit', 'Admin\VendorController#postEdit');
});
You can do something like this:
// In your middleware
$request->offsetSet('role', $role);
Then in the routes.php:
use Illuminate\Http\Request;
Route::get('test', ['middleware' => 'auth', function(Request $request) {
dd($request->get('role'));
}]);
Don't working authentication. I create authentication manually.
My AdminController:
class AdminController extends Controller
{
public function signin() {
return view('admin.signin');
}
public function index(Request $request) {
dd(Auth::check());
if (Auth::check())
return view('admin.index.index', ['login' => Auth::user()->name]);
else
return redirect()->action('AdminController#signin');
}
public function login() {
$data = Input::all();
if (Auth::attempt(['name' => $data['login'], 'password' => $data['password']])) {
return redirect()->intended('/admin');
} else {
return redirect()->intended('/admin/signin');
}
}
public function logout() {
if (Auth::logout() ) {
return Redirect::to('/admin');
}
}
}
My routes.php file:
//GET
Route::get('/', 'IndexController#index');
Route::get('/admin/signin', 'AdminController#signin');
Route::get('/admin', 'AdminController#index');
Route::get('/admin/logout', 'AdminController#logout');
//POST
Route::post('/admin/auth', 'AdminController#login');
dd(Auth::check()); returned false
What I doing wrong?
In Laravel 5.2 you need to define routes using web middleware to make sessions work, so your routes.php file should look like this:
Route::group(['middleware' => ['web']], function () {
//GET
Route::get('/', 'IndexController#index');
Route::get('/admin/signin', 'AdminController#signin');
Route::get('/admin', 'AdminController#index');
Route::get('/admin/logout', 'AdminController#logout');
//POST
Route::post('/admin/auth', 'AdminController#login');
});
I trying to make a login and admin script, the problem is that I have a redirect loop I dont know why.
I want the login users and can be in the / path not /home.
If change return new RedirectResponse(url('/')); to return new RedirectResponse(url('/anotherpage')); it works but I want to be /
Routes:
Route::get('/', [
'as' => 'home', 'uses' => 'HomeController#index'
]);
// Tutorials Routes
Route::get('/tutorials', 'HomeController#tutorials');
Route::get('/tutorials/{category?}', 'HomeController#tutorialsCategory');
Route::get('/tutorials/{category?}/{lesson?}', 'HomeController#tutorialsLesson');
// Courses and Series Routes
Route::get('/courses-and-series', 'HomeController#coursesandseries');
// Admin Routes
Route::group(['middleware' => 'App\Http\Middleware\AdminMiddleware'], function()
{
Route::get('/admin', function()
{
return 'Is admin';
});
});
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Admin middleware:
public function handle($request, Closure $next)
{
if (Auth::user()->type != 'Admin')
{
return abort(404);
}
return $next($request);
}
RedirectIfAuthenticated:
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
return new RedirectResponse(url('/'));
}
return $next($request);
}
Home Controller:
class HomeController extends Controller {
public function __construct()
{
$this->middleware('guest');
}
public function index()
{
return view('home');
}
public function tutorials()
{
return view('pages.tutorials');
}
public function tutorialsCategory()
{
return view('pages.tutorials');
}
public function tutorialsLesson()
{
return view('pages.single');
}
public function coursesandseries()
{
return view('pages.coursesandseries');
}
public function single()
{
return view('pages.single');
}
}
You are having these redirection loops because all the methods in HomeController are protected by Guest Middleware.
Since you wish to redirect authenticated users to HomeController#index
Remove $this->middleware('guest'); from HomeController
or
Modify the Guest Middleware to ignore index method
$this->middleware('guest', ['only' => ['tutorials','tutorialsCategory']])
List other methods you wish to protect with Guest Middleware excluding Index method