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.
Related
I am working with an inherited site based on the Laravel Framework which I upgraded from 5.6 to 8.0. I most aspects the site works great, but I occasionally sumble upon missing pieces. For example, I just discovered that the Reset Password feature does not work. Looking into it I find that there is a route for this:
Route::post('password/reset/{token}', ['as' => 'app.password.reset.post', 'uses' => 'App\Auth\ResetPasswordController#reset']);
Yet there is no 'reset()' method in the ResetPasswordController. Additionally, the ResetPasswordController uses the trait 'ResetsPassword', yet there is no such trait located under
Illuminate\Foundation\Auth\ResetsPasswords;
I tried checking the github repo for the Laravel framework, but these pieces were not there. I also looked under laravel-ui and didn't see them. According to the documentation,
"Laravel includes Auth\ForgotPasswordController and Auth\ResetPasswordController classes that contains the logic necessary to e-mail password reset links and reset user passwords. All of the routes needed to perform password resets may be generated using the laravel/ui Composer package"
I'm a little nervous about doing a general update as all other pieces are in place and working so I was looking for a way to obtain the individual pieces and have not found anything.
Here are my login routes:
Route::group(['prefix' => 'app'], function () {
//Auth::routes();
Route::get('login', ['as' => 'app.login', 'uses' => 'App\Auth\LoginController#showLoginForm']);
Route::post('login', ['as' => 'app.login.post', 'uses' => 'App\Auth\LoginController#login']);
Route::post('logout', ['as' => 'app.logout.post', 'uses' => 'App\Auth\LoginController#logout']);
Route::post('password/email', ['as' => 'app.password.email.post', 'uses' => 'App\Auth\ForgotPasswordController#sendResetLinkEmail']);
Route::get('password/reset', ['as' => 'app.password', 'uses' => 'App\Auth\ForgotPasswordController#showLinkRequestForm']);
Route::get('password/reset/{token}', ['as' => 'app.password.reset', 'uses' => 'App\Auth\ResetPasswordController#showResetForm']);
Route::post('password/reset/{token}', ['as' => 'app.password.reset.post', 'uses' => 'App\Auth\ResetPasswordController#reset']);
And this is what my ResetPasswordController looks like:
namespace App\Http\Controllers\App\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\ResetsPasswords;
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after password reset.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->redirectTo = route('app.dashboard');
$this->middleware('guest');
}
/**
* Display the password reset view for the given token.
*
* If no token is present, display the link request form.
*
* #param \Illuminate\Http\Request $request
* #param string|null $token
* #return \Illuminate\Http\Response
*/
public function showResetForm(Request $request, $token = null)
{
return view('app.auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
}
Also, from what I've read there is possibly an updated reset.blade.php. My question is what is my best approach to fix the reset password bug?
This is the trait for reseting passwords, that I found in my project, I hope it can help you somehow.
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;
trait ResetsPasswords
{
use RedirectsUsers;
/**
* Display the password reset view for the given token.
*
* If no token is present, display the link request form.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showResetForm(Request $request)
{
$token = $request->route()->parameter('token');
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function reset(Request $request)
{
$request->validate($this->rules(), $this->validationErrorMessages());
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($request, $response)
: $this->sendResetFailedResponse($request, $response);
}
/**
* Get the password reset validation rules.
*
* #return array
*/
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => ['required', 'confirmed', Rules\Password::defaults()],
];
}
/**
* Get the password reset validation error messages.
*
* #return array
*/
protected function validationErrorMessages()
{
return [];
}
/**
* Get the password reset credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
return $request->only(
'email', 'password', 'password_confirmation', 'token'
);
}
/**
* Reset the given user's password.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #param string $password
* #return void
*/
protected function resetPassword($user, $password)
{
$this->setUserPassword($user, $password);
$user->setRememberToken(Str::random(60));
$user->save();
event(new PasswordReset($user));
$this->guard()->login($user);
}
/**
* Set the user's password.
*
* #param \Illuminate\Contracts\Auth\CanResetPassword $user
* #param string $password
* #return void
*/
protected function setUserPassword($user, $password)
{
$user->password = Hash::make($password);
}
/**
* Get the response for a successful password reset.
*
* #param \Illuminate\Http\Request $request
* #param string $response
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResetResponse(Request $request, $response)
{
if ($request->wantsJson()) {
return new JsonResponse(['message' => trans($response)], 200);
}
return redirect($this->redirectPath())
->with('status', trans($response));
}
/**
* Get the response for a failed password reset.
*
* #param \Illuminate\Http\Request $request
* #param string $response
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResetFailedResponse(Request $request, $response)
{
if ($request->wantsJson()) {
throw ValidationException::withMessages([
'email' => [trans($response)],
]);
}
return redirect()->back()
->withInput($request->only('email'))
->withErrors(['email' => trans($response)]);
}
/**
* Get the broker to be used during password reset.
*
* #return \Illuminate\Contracts\Auth\PasswordBroker
*/
public function broker()
{
return Password::broker();
}
/**
* Get the guard to be used during password reset.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
}
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('/');
}
}
I have a problem with inserting Data into Database. Let's say I have a controller named HeroController and I want to create a new hero object and insert it to my database as a new hero.
My controller contains the following method:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// return response()->json([
// 'name' => 'Abigail',
// 'state' => 'CA'
// ]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6',
]);
}
public function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data[password]),
]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = $request->isMethod('put');
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
return response()->json($usere, 201);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
My routes.php file:
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/users/create', 'UserController#create');
This is the error that i got. Type error: Too few arguments to function App\Http\Controllers\UserController::attendance(), 0 passed and exactly 1 expected". I am new to laravel.
You are using a get request to call create function.
Route::get('/users/create', 'UserController#create');
So, you are not passing any data to that controller. Hence the error.
First, you'll want to change the visibility of create and validator:
protected function create(array $data)
And the validator method:
protected function validator(array $data)
Then you'll want to change your /users/create route to a post and to use the store method:
Route::post('/users/create', 'UserController#store');
In your UserController update your store method to:
public function store(Request $request)
{
// validate the request
$validator = $this->validator($request->all());
if ($validator->fails()) {
return response()
->json(422,$validator->errors()->messages());
}
$user = $this->create($request->all());
return response()->json($user, 201);
}
If you need some sort of form to register or create a user, add an additional method in your controller:
public function register()
{
return view('user.register');
}
Then define another get route:
Route::get('/users/register', 'UserController#register');
Route::delete('/file/{id}','FileController#destroy')->name('deletefile');
Hope it will be helpful
I am trying to make a custom login with multi auth. For the meantime, I am trying to do the login for admin. When an admin logs in, the login function handles it (it also just refreshes without the login function) Auth:attempt() seems to be always returning false, however (I have a different table name and fields). Aside from that, I can freely access the dashboard by just changing the url even if the user is not really logged in.
AuthController
/*
|--------------------------------------------------------------------------
| 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;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = 'admin/dashboard';
/**
* Where to redirect users after logout.
*
* #var string
*/
protected $redirectAfterLogout = 'admin/login';
/**
* Guard for admin
*
*
*/
protected $guard = 'admin';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* 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, [
'OUsername' => 'required|max:255|unique:users',
'OPassword' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return Admin::create([
'OUsername' => $data['OUsername'],
'OPassword' => bcrypt($data['OPassword']),
]);
}
/**
* Show login form.
*
*
*
*/
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('pages.admin.login');
}
/**
* Show registration form.
*
*
*
*/
public function showRegistrationForm()
{
return view('pages.admin.register');
}
public function login(Request $request)
{
//Get inputs
$username = $request->input('username');
$password = $request->input('password');
//Redirect accordingly
if (Auth::guard('admin')->attempt(array('OUsername' => $username, 'OPassword' => $password)))
{
return redirect()->intended('admin/dashboard');
}
else
{
//when echoing something here it is always displayed thus admin login is just refreshed.
return redirect('admin/login')->withInput()->with('message', 'Login Failed');
}
}
Admin Provider Model
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'account_officer_t';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'OUsername', 'OPassword',
];
public $timestamps = false;
/**
* Set primary key
*
* #var int
*/
protected $primaryKey = 'AccountOfficerID';
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'OPassword', 'remember_token',
];
public function getAuthPassword()
{
return $this->OPassword;
}
Routes
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::group(['namespace' => 'Admin', 'middleware' => 'guest'], function(){
//This uses the guest middleware with the class name RedirectIfAuthenticated
Route::auth();
//Route for admin dashboard view
Route::get('admin/dashboard', array('as' => 'dashboard', 'uses' => 'AdminController#showDashboard'));
});
Route::group(['middleware' => ['web']], function () {
//Route for login
Route::get('admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('admin/login','AdminAuth\AuthController#login');
Route::get('admin/logout','AdminAuth\AuthController#logout');
//Route for registration
Route::get('admin/ims-register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/ims-register', 'AdminAuth\AuthController#register');
});
RedirectIfAuthenticated (guest middleware)
/**
* 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('admin')->check()) {
return redirect('admin/dashboard');
}
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
I have just started learning the MVC framework and started using Laravel. Thank you for the help.
Notes
My passwords are stored using bcrypt() with column length of 255
I have tried checking if the hash from the table matches my input using Hash::check. It returns true. But when I do this:
dd( Auth::guard('admin')->attempt(array('OUsername' => $username, 'OPassword' => $password)));
It is false.
Tried checking the results based on the answer from this question especially # 7. Still the same.
The problem seems to be with this line
'OPassword' => $password
I changed it to
'password' => $password
It has to be password not OPassword. And then in my Admin model I specified
public function getAuthPassword()
{
return $this->OPassword;
}
I am using
Route::auth();
for making user login in Laravel.
There are multiple phones linked to a user and saved in table:phones.
Tables are
users : id,email,password
phones: id,user_id,phone_number
How to make user login with both Email/Phones and password
In App\Traits\Auth, create a file named LoginUser.php.
<?php
namespace App\Traits\Auth;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
trait LoginUser
{
/**
* Handle a Authenticates the User.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->attemptLogin($request)) {
return $this->successfulLogin($request);
}
return $this->failedLogin($request);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
'username' => 'required',
'password' => 'required',
]);
}
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
//Try with email AND username fields
if (Auth::attempt([
'phone' => $request['username'],
'password' => $request['password']
],$request->has('remember'))
|| Auth::attempt([
'email' => $request['username'],
'password' => $request['password']
],$request->has('remember'))){
return true;
}
return false;
}
/**
* This is executed when the user successfully logs in
*
* #var Request $request
* #return Reponse
*/
protected function successfulLogin(Request $request){
return redirect($this->redirectTo);
}
/**
* This is executed when the user fails to log in
*
* #var Request $request
* #return Reponse
*/
protected function failedLogin(Request $request){
return redirect()->back()->withErrors(['password' => 'You entered the wrong username or password']);
}
}
Then in
App\Http\Controllers\Auth
rewrite (or create) LoginController.php and paste this
<?php
namespace App\Http\Controllers\Auth;
use App\Traits\Auth\LoginUser;
use App\Http\Controllers\Controller;
class LoginController extends Controller
{
use LoginUser;
/**
* Where to redirect users after registration.
*
* #var string | URL
*/
protected $redirectTo = '/mPanel';
/**
* Displays login page
*
* #return \Illuminate\Http\Response
*/
public function show(){
return response()->view('LOGIN PAGE HERE');
}
}
Finally in your routes file, add these routes:
Route::get('login', 'Auth\LoginController#show');
Route::post('login', 'Auth\LoginController#login');