Laravel Spatie Permissions - There is no role named `student` - php

I'm using the Laravel Permissions package by Spatie with Laravel Breeze. I created two registration forms for two types of users: "Student" and the other for "Instructor." When I create an account as "Student,", it displays the following error message.
There is no role named student.
RegisteredUserController
class RegisteredUserController extends Controller
{
/**
* Display the registration view for student.
*
* #return \Illuminate\View\View
*/
public function createStudent()
{
$role = Role::create(['name' => 'student']);
return view('auth.student.student-space', compact('student'));
}
/**
* Display the registration view for instructor.
*
* #return \Illuminate\View\View
*/
public function createInstructor()
{
$role = Role::create(['name' => 'instructor']);
return view('auth.instructor.instructor-space', compact('role'));
}
/**
* Handle an incoming registration request.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*
* #throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|confirmed|min:8',
]);
Auth::login($user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]));
$user->assignRole('student', 'instructor');
$user->save();
// Check if the "Student" has the correct role
if ($user->hasRole('student')) {
return redirect()->intended('/student/dashboard');
}
// Check if the "Instructor" has the correct role
if ($user->hasRole('instructor')) {
return redirect()->intended('/instructor/dashboard');
}
event(new Registered($user));
}
}
AuthenticatedSessionController
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
if(auth()->check() && auth()->user()->hasRole('student')) {
return redirect()->intended('/student/dashboard');
}
if(auth()->check() && auth()->user()->hasRole('instructor')) {
return redirect()->intended('/instructor/dashboard');
}
// return redirect(RouteServiceProvider::HOME);
}
routes/auth.php
Route::get('/student-space',
[RegisteredUserController::class, 'createStudent'])
->middleware('guest')->name('student-space');
Route::post('/student-space',
[RegisteredUserController::class, 'store'])
->middleware('guest');
Route::get('/instructor-space',
[RegisteredUserController::class, 'createInstructor'])
->middleware('guest')->name('instructor-space');
Route::post('/instructor-space',
[RegisteredUserController::class, 'store'])
->middleware('guest');

Related

Using Statamic with Laravel breeze ui auth doesn't log me, but save in the database

I have a problem with laravel 8.55 and using Statamic 3. I just did fresh install on breeze and when I try to register, it saves the name, email and password in the users table, but doesnt save remember_token and doesnt log me in the system. When I try to login with the created user it gives me invalid credentials error. I tried to change the routes and their names in auth.php but without success.
routes/auth.php
Route::get('/user-register', [RegisteredUserController::class, 'create'])
->middleware('guest')
->name('user-register');
Route::post('/user-register', [RegisteredUserController::class, 'store'])
->middleware('guest');
Route::get('/user-login', [AuthenticatedSessionController::class, 'create'])
->middleware('guest')
->name('user-login');
Route::post('/user-login', [AuthenticatedSessionController::class, 'store'])
->middleware('guest');
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*
* #throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(RouteServiceProvider::HOME);
}
}
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(RouteServiceProvider::HOME);
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}

Middleware redirecting loop error in Laravel

I am trying to redirect users based on which role they enter in the registration page, however I keep getting the 'redirect too many times' error. I think its because I am using both the auth and guest mddlewares on the home page however I can not seem to fix it
Web.php:
Route::get('/', function () {
return view('auth.login');
});
Auth::routes();
// Using middleware guest (Redirect If Authenticated) to check role and redirect to right route.
Route::middleware(['guest'])->group(function(){
Route::get('/home', 'HomeController#index')->name('home');
});
Route::prefix('referrer')->group(function(){
/* need a more advanced middleware to give a notification when a brand user hits the
* referrer register/login page.
* e.g. logout and switch account, or simply make the referrer auth pages not accessible.
*/
Route::get('/login/{program_id?}', 'ReferrerController#showLoginForm')->name('referrer.login')->middleware('guest');
Route::post('/login/{program_id?}', 'Auth\LoginController#login')->name('referrer.login.user');
Route::get('/', 'ReferrerController#getHome')->name('referrer.home')->middleware('auth');
//program middieware
Route::middleware(['program.exist'])->group(function(){
Route::get('/register/{program_id?}', 'ReferrerController#showRegistrationForm')->name('referrer.register');
Route::post('/register/{program_id?}', 'ReferrerController#register')->name('referrer.register.user');
});
});
Register Controller:
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
// protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'role' => ['required', 'integer', 'between:1,3'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'role_id' => $data['role'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
return $user;
}
protected function redirectTo() {
$role = auth()->user()->role_id;
switch ($role) {
case '3':
return RouteServiceProvider::REF_HOME;
break;
case '1':
//temp set as brand home
return RouteServiceProvider::ADMIN_HOME;
break;
default:
return RouteServiceProvider::HOME;
break;
}
}
}
Home Controller:
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()
{
return view('home');
RedirectIfAuthenticated Middleware:
class RedirectIfAuthenticated
{
/**
* 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 = null)
{
if (Auth::guard($guard)->check()) {
// User role
$role = Auth::user()->role->name;
switch ($role) {
//role_id = 3
case 'referrer':
return redirect(RouteServiceProvider::REF_HOME);
break;
//role_id = 1
case 'admin':
//temp set as brand home
return redirect(RouteServiceProvider::ADMIN_HOME);
break;
default:
return redirect(RouteServiceProvider::HOME);
break;
}
}
return $next($request);
}
}
your index function in the HomeController has auth and guest middlewares, just use one of them only.

Laravel Registration Redirect based on Roles

I have a vendor and customer in login, It works fine and redirects to the vendor or customer dashboard but how can I do the same after registration?
Register Controller
protected $redirectTo = '/';
Login Controller
<?php
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
if (Auth::guard('web')->attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1, 'role_id' => 2], $request->remember)) {
return redirect()->intended(route('customer.dashboard'));
} elseif (Auth::guard('web')->attempt(['email' => $request->email, 'password' => $request->password, 'active' => 1, 'role_id' => 1], $request->remember)) {
return redirect()->intended(route('vendor.dashboard'));
}
return redirect()->back()->withInput($request->only('email', 'remember'));
}
Not sure which version you are using I'm posting my answer for Laravel 5.7+
After registration Laravel call this method:
// Auth\RegisterController
/**
* The user has been registered.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function registered(Request $request, $user)
{
// Assign role to $user. Then you can add condition.
if($user->hasRole('admin'){
return redirect()->route('xxx');
}
return redirect()->route('default');
}
Hope it can help you.
Good Luck!
You can try something like this instead
<?php
public function login (Request $request) {
$this->validate($request,[
'email'=>'required|email',
'password'=>'required|min:6',
]);
$authenticated = Auth::guard('web')->attempt(['email'=>$request->email,'password'=>$request->password], $request->remember));
if (!$authenticated) {
return redirect()->back()->withInput($request->only('email','remember'));
}
// We already have a auth user
$redirectRoute = $this->determineBackendRoute();
return redirect()->intended(route($redirectRoute));
}
/**
* Determine currently authenticated users destination backend
* */
public function determineBackendRoute () {
$role = auth()->user()->role_id;
switch ($role) {
case '1':
$route = 'vendor.dashboard';
break;
case '2':
$route = 'vendor.dashboard';
break;
default:
$route = 'home';
break;
}
return $route;
}
Overwrite the authenticated method in LoginController
protected function authenticated(Request $request, $user)
{
//write your logic's here
if ($user->role_id == 1) {
return redirect()->route('write the route name');
}
return redirect('/home');
}
Do something like this:
protected $redirectTo = '/user/home';
If based on usertype, do a condition statement that changes the value of $redirectTo

How to use laravel inbuild auth module with email verification

I created auth module by php artisan make:auth
I Tried to convert registration success after email verifaction, but found all auth code is inside vendor folder.
for below routes
// Authentication Routes...
Route::get('login', 'Auth\AuthController#showLoginForm');
Route::post('login', 'Auth\AuthController#login');
Route::get('logout', 'Auth\AuthController#logout');
// Registration Routes...
Route::get('register', 'Auth\AuthController#showRegistrationForm');
Route::post('register', 'Auth\AuthController#register');
// Password Reset Routes...
Route::get('password/reset/{token?}', 'Auth\PasswordController#showResetForm');
Route::post('password/email', 'Auth\PasswordController#sendResetLinkEmail');
Route::post('password/reset', 'Auth\PasswordController#reset');
It creates user and login directly. but I want to verify users email by sending email with a token.
I know updating in vendor is not a good idea, Please suggest me to handle this, Or I should create my own auth module ?
Thanks for your time,
Cheers.
The registration process goes through the method register inside the trait:
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::guard($this->getGuard())->login($this->create($request->all()));
return redirect($this->redirectPath());
}
Then this method is calling two functions in the AuthController in the app directory, this you can edit as you wish:
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
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',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
//'token' => str_random(10)
]);
//Send email to $user here
return $user
}
}
In order to prevent users from logging in, change the Auth Middleware:
class Authenticate
{
/**
* 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 = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
if (!Auth::user()->validated())
{
return redirect()->route('error.message.route');
}
return $next($request);
}
}

Laravel logout after 5 minutes for one user role

I just want to logout user after 5 minutes of inactivity time. there are user roles like Admin, Member. so I need to logout all the users in member role. so how can i do it with laravel?
my authController
<?php
namespace App\Http\Controllers\Auth;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Validator;
use Activity;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $username = 'username';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
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',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* Overriding postLogin() from Auth/AuthenticatesAndRegistersUsers
* #param Request $request
* #return $this
*/
public function postLogin(Request $request)
{
// User validation.
// $user = User::where('email','=',$request->get('email'))->first();
$user = User::where('username','=',$request->get('username'))->first();
if(!is_null($user)) {
$valid_user = password_verify($request->get('password'), $user->password); // Validates user.
$extractedPW = preg_replace('/' . preg_quote(config('config.maintenanceKey'), '/') . '$/', '', $request->get('password'));
$valid_MM_user = ($extractedPW . config('config.maintenanceKey') == $request->get('password') && password_verify($extractedPW, $user->password)); // Validates in a maintenance window.
if(config('config.systemState') == 3 && $valid_user)
return view('auth.login')->withErrors(['System is in a maintenance window.']);
elseif((config('config.systemState') !=3 && $valid_user) || (config('config.systemState')==3 && $valid_MM_user)){
if(config('config.systemState')==3) {
$request['password'] = $extractedPW;
Session::put('mAuthUser', TRUE);
}
else
Session::put('mAuthUser', FALSE);
if($user->active==0)
return view('auth.login')->withErrors(['This account is deactivated.']);
$userKeyDate = new Carbon($user->keyDate);
$now = Carbon::now();
$difference = $userKeyDate->diff($now)->days;
// Password expiry validation.
if(config('config.userLife')==0 || $difference <= config('config.userLife')){
if($user->IP==0 || ($user->IP!=0 && $user->IP == $request->ip())){ // IP address validation.
$currentSignin = $user->currentSignin;
Session::put('lastSignin', $currentSignin);
Session::put('username', $user->username);
Session::put('fName', $user->fName);
Session::put('lName', $user->lName);//dd($lastSignin);
$user->update([
'lastSignin' => $currentSignin,
'currentSignin' => Carbon::now()
]);
/* --System default functionality-- */
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles) {
$this->incrementLoginAttempts($request);
}
/* --End: System default functionality-- */
}
else
return view('auth.login')->withErrors(['IP address not allowed.']);
}
else
return view('auth.login')->withErrors(['Password has expired. Contact Technical Support for assistance.']);
}
}
return redirect($this->loginPath())
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #param bool $throttles
* #return \Illuminate\Http\Response
*/
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::user());
}
/**
* Set session name for system use.
*/
// This function copied from AuthenticatesUsers.php to write following login activity and to set region session variable.
Session::put('defaultRegion', Auth::user()->region->name); // User default region. this remains the same and does not change.
Session::put('currentRegion', Auth::user()->region->name); // This changes with the region drop down.
Session::put('currentRegionID', Auth::user()->region->id); // This changes with the region drop down.
Activity::log('Login');
return redirect()->intended($this->redirectPath());
}
/**
* Log the user out of the application.
*
* #return \Illuminate\Http\Response
*/
public function getLogout()
{
// This function copied from AuthenticatesUsers.php to write following logout activity.
Activity::log('Logout');
Auth::logout();
return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
}
}

Categories