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();
}
}
Related
I need to get Forgot Password functionality in my web app, so i am using laravel for this. When i click on the forgot password it shows me the a form that takes email on which i need to reset password when i click on the reset password button it sends a mail on the linked id, and when i click on the link in the mail it redirect me to the change password page that has password and confirm password field when i click on the reset password it redirects me to home link.
The issue is "first time it changes my password successfully", but when i tried for another account to reset password, when clicking on the link on the mail it redirects me to home other than the password change form and it happens for the all account now.
What is the problem that causes the above issue please explain and how to resolve this issue
Here is my password reset routes:
Route::post('password/email', 'Auth\ForgotPasswordController#sendResetLinkEmail');
Route::post('password/reset', 'Auth\PasswordController#reset')->name('password.reset');
Route::get('password/reset/{token?}', 'Auth\PasswordController#showResetForm')->name('password.request');
Here is the ResetsPasswords.php class
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Auth\Events\PasswordReset;
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
* #param string|null $token
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showResetForm(Request $request, $token = null)
{
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)
{
$this->validate($request, $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($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|min:6',
];
}
/**
* 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)
{
$user->password = Hash::make($password);
$user->setRememberToken(Str::random(60));
$user->save();
event(new PasswordReset($user));
$this->guard()->login($user);
}
/**
* Get the response for a successful password reset.
*
* #param string $response
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResetResponse($response)
{
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)
{
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();
}
}
and Here is the SendsResetEmails.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
trait SendsPasswordResetEmails
{
/**
* Display the form to request a password reset link.
*
* #return \Illuminate\Http\Response
*/
public function showLinkRequestForm()
{
return view('auth.passwords.email');
}
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function sendResetLinkEmail(Request $request)
{
$this->validateEmail($request);
// We will send the password reset link to this user. Once we have
attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = $this->broker()->sendResetLink(
$request->only('email')
);
return $response == Password::RESET_LINK_SENT
? $this->sendResetLinkResponse($response)
: $this->sendResetLinkFailedResponse($request, $response);
}
/**
* Validate the email for the given request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
}
/**
* Get the response for a successful password reset link.
*
* #param string $response
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResetLinkResponse($response)
{
return back()->with('status', trans($response));
}
/**
* Get the response for a failed password reset link.
*
* #param \Illuminate\Http\Request $request
* #param string $response
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResetLinkFailedResponse(Request $request, $response)
{
return back()->withErrors(
['email' => trans($response)]
);
}
/**
* Get the broker to be used during password reset.
*
* #return \Illuminate\Contracts\Auth\PasswordBroker
*/
public function broker()
{
return Password::broker();
}
}
You'll notice the in the ResetPasswordController we have:
protected function resetPassword($user, $password)
{
$user->password = Hash::make($password);
$user->setRememberToken(Str::random(60));
$user->save();
event(new PasswordReset($user));
$this->guard()->login($user);
}
After the password is reset, it logs the user in. However, we are also using the guest middleware in the same class:
public function __construct()
{
$this->middleware('guest');
}
Therefore if you try to visit the password reset page while logged in, you will be redirected. So just log out first.
I'm trying to modify the default authentication to tailor my needs. I have this requirements like a user should be able to login using either user name or email but it always returns invalid credentials error even if the given credentials are correct, please refer to the code below:
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
trait AuthenticatesUsers
{
use RedirectsUsers, ThrottlesLogins;
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('auth.login');
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
*/
public function login(Request $request)
{
$this->validateLogin($request);
// 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.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
// 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.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
/**
* Attempt to log the user into the application.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->has('remember')
);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(Request $request)
{
// return $request->only($this->username(), 'password');
if(filter_var($request->username_email, FILTER_VALIDATE_EMAIL) ){
return $request->only('email', 'password');
}else{
return $request->only('username', 'password');
}
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
//
return response()->json([ 'message' => 'authenticated']);
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => trans('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function username()
{
return 'username_email';
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/');
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard();
}
}
Inside credentials(), I check if its an username or email first and then return the corresponding database column, but it looks like it doesn't work at all. Any ideas, help please?
Your method:
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
With username() returning username_email seems incoherent. I think what you looking for is required_without_all:
protected function validateLogin(Request $request)
{
$this->validate($request, [
'username' => 'required_without_all:email|string',
'email' => 'required_without_all:username|string',
'password' => 'required|string',
]);
}
So username will be required when email is not present and vice versa.
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');
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);
}
}