I have two separated Auths for the project one for Doctors (Login, Register & Reset)[Accounts Table] and the other for Patients (clients) (Login, Register & Reset) [Patients table].
Each Patient can be registered with the same mail with any doctor (Account).
i have done all the stuff but my problem is when the patient resets his password inside specific doctor account. Laravel changes the password of the patient mail in patients table ..
My question is: how to add condition to resetPassword method
Ex: where mail = $mail and account_id = $account_id
i successed to override the sendRequestResetLinkMail method by
PatientAuth\ForgotPasswordController.php:
public function sendResetLinkEmail(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
]);
$response = $this->broker()->sendResetLink([
'email' => $request->input('email'),
'account_id' => Hashids::decode($request->segment(3)),
]);
return $response == Password::RESET_LINK_SENT
? $this->sendResetLinkResponse($response)
: $this->sendResetLinkFailedResponse($request, $response);
}
ResetPasswordController.php:
class ResetPasswordController extends Controller
{
public function __construct()
{
$this->middleware('lang');
}
//Client redirect path
protected function redirectTo(Request $request)
{
return route('WSG.view.home', $request->segments(3));
}
//trait for handling reset Password for patient / client
use ResetsPasswords;
//Show form to patient / client where they can reset password
public function showResetForm(Request $request, $id, $token = null)
{
$id = Hashids::decode($id);
$main_settings = WSGeneratorMainSetting::where('account_id', $id)->first();
return view('doctor_website.layouts.reset',
[
'token' => $token,
'email' => $request->email,
'main_settings' => $main_settings,
]
);
}
protected function credentials(Request $request)
{
return $request->only(
'email', 'password', 'password_confirmation', 'account_id' , 'token'
);
}
//returns Password broker of seller
public function broker()
{
return Password::broker('clients');
}
//returns authentication guard of seller
protected function guard()
{
return Auth::guard('client');
}
}
Related
I want to apply soft delete in laravel5.4 inbuilt reset password. Due to duplicate email of soft delete deleted email password is change but not the correct one. I am getting stuck to where apply deleted should be null instead of email checking only. that's why it fetches the deleted record insted of correct one. My reset password controller is given below. Please check my reset controller & suggest any solution please.
class ResetPasswordController extends Controller
{
use ResetsPasswords;
protected $redirectTo = 'member/welcome';
public function showResetForm(Request $request, $token = null)
{
return view('frontend.member.auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
public function reset(Request $request)
{
$this->validate($request, $this->rules(), $this->validationErrorMessages());
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
}
);
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->sendResetFailedResponse($request, $response);
}
protected function rules()
{
return [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:8|regex:/^.*(?=.{3,})(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[#!$#%^*()-_]).*$/',
];
}
/**
* Get the password reset validation error messages.
*
* #return array
*/
protected function validationErrorMessages()
{
return [
'password.regex' => 'The password must contain at least one uppercase, one lowercase, one number and one special(#!$#%...) character.'
];
}
protected function resetPassword($user, $password)
{
$password = app('hash')->needsRehash($password) ? Hash::make($password) : $password;
$user->forceFill([
'password' => $password,
'remember_token' => Str::random(60),
])->save();
$this->guard()->login($user);
}
public function broker()
{
return Password::broker('members');
}
protected function guard()
{
return Auth::guard('web_member');
}
}
Please help thanks in advance.I am new to laravel please help.
Just need to pass the correct user to resetPassword() function like
public function reset(Request $request)
{
$this->validate($request, $this->rules(), $this->validationErrorMessages());
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$user = User::where('email', $user->email)->whereNull('deleted_at')->first();
$this->resetPassword($user, $password);
}
);
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->sendResetFailedResponse($request, $response);
}
I'm trying to enable basic user authentication username, and password into my Lumen application.
In app.php file, the following has been uncommented as explained in https://lumen.laravel.com/docs/5.4/authentication
$app->withFacades();
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
$app->register(App\Providers\AuthServiceProvider::class);
My Route looks like this:
$app->post('auth/register', ['uses' => 'Auth\AuthController#postRegister']);
My Controller looks like this:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
use Auth;
use App\User;
class AuthController extends Controller {
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
}
public function postRegister(Request $request, UserRepository $userRepository)
{
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
$user = $userRepository->store($request);
Auth::login($user);
return ['result' => 'success'];
}
}
I have been getting a combination of weird and wonderful errors, currently I'm getting:
ReflectionException in BoundMethod.php line 155:
Class App\Repositories\UserRepository does not exist
I've done some extensive google searching, but there doesn't seem to be many documented uses of user auth in Lumen so looking for a pointer as to what I've missed here.
My initial error: I was looking for a method of logging in a user, what I should have been looking for was authentication. Thinking about what I actually needed to achieve I came up with the below functions:
Create user
Delete user
Verify user
With that in mind I ended up with something like the below:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
//Required to hash the password
use Illuminate\Support\Facades\Hash;
class AuthController extends Controller {
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
}
public function validateRequest(Request $request) {
$rules = [
'email' => 'required|email|unique:users',
'password' => 'required|min:6'
];
$this->validate($request, $rules);
}
//Get the input and create a user
public function store(Request $request) {
$this->validateRequest($request);
$user = User::create([
'email' => $request->get('email'),
'password'=> Hash::make($request->get('password'))
]);
return response()->json(['status' => "success", "user_id" => $user->id], 201);
}
//delete the user
public function destroy($id) {
$user = User::find($id);
if(!$user){
return response()->json(['message' => "The user with {$id} doesn't exist"], 404);
}
$user->delete();
return response()->json(['data' => "The user with with id {$id} has been deleted"], 200);
}
//Authenticate the user
public function verify(Request $request) {
$email = $request->get('email');
$password = $request->get('password');
$user = User::where('email', $email)->first();
if($user && Hash::check($password, $user->password)) {
return response()->json($user, 200);
}
return response()->json(['message' => "User details incorrect"], 404);
}
//Return the user
public function show($id) {
$user = User::find($id);
if(!$user) {
return response()->json(['status' => "invalid", "message" => "The userid {$id} does not exist"], 404);
}
return response()->json(['status' => "success", 'data' => $user], 200);
}
//Update the password
public function update(Request $request, $id) {
$user = User::find($id);
if(!$user){
return response()->json(['message' => "The user with {$id} doesn't exist"], 404);
}
$this->validateRequest($request);
$user->email = $request->get('email');
$user->password = Hash::make($request->get('password'));
$user->save();
return response()->json(['data' => "The user with with id {$user->id} has been updated"], 200);
}
}
I'm not really sure what you want to achieve with UserRepository and Auth.
Lumen is a stateless framework, meaning that Auth::login() never will have any effect. Also, as far as I'm concerned, UserRepository is a Laravel thing. Not a Lumen thing.
Create the user with App\User::create($request->all()) and access it through the Eloquent model. You can enable Eloquent in bootstrap/app.php
So I have two tables of users in my database with the name Mahasiswas and Users, and I want to override the resetPassword for Mahasiswas table, because every time I reset the password for the Mahasiswas table, it automatically logged into the Users dashboard.
I put this in my route :
Route::post('password/reset', 'MhsAuth\PasswordController#postMyReset');
And this is my passwordController :
namespace App\Http\Controllers\MhsAuth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
use ResetsPasswords;
protected $redirectPath = '/';
protected $getGuard = 'mahasiswa';
public function __construct()
{
$this->middleware('mahasiswa');
}
public function postMyReset(Request $request)
{
return $this->resetMe($request);
}
public function resetMe(Request $request)
{
$this->validate($request, [
'token' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed|min:6',
]);
$credentials = $request->only(
'email', 'password', 'password_confirmation', 'token'
);
$broker = $this->getBroker();
$response = Password::broker($broker)->reset($credentials, function ($user, $password) {
$this->resetMyPassword($user, $password);
});
switch ($response) {
case Password::PASSWORD_RESET:
return $this->getResetSuccessResponse($response);
default:
return $this->getResetFailureResponse($request, $response);
}
}
protected function resetMyPassword($user, $password)
{
$user->password = bcrypt($password);
$user->save();
//Auth::guard($this->getGuard())->login($user);
}
}
The problem is after reset the password for Mahasiswas table, it's perform auto login to Users Dashboard, it should be in Mahasiswas Dashboard, but I just want to disable the autologin and my passwordController doesn't work as I wanted. Thanks
I have a registration code:
public function postRegister(Request $request, AppMailer $mailer) {
$post = $request->all();
$rules = [
'email' => 'required|email|unique:users|confirmed|max:255',
'password' => 'required|confirmed|min:8|max:50',
];
$v = \Validator::make($post, $rules);
if($v->fails())
return "fail!";
$data = [
'email' => $post['email'],
'password' => \Hash::make($post['password'])
];
$user = User::create($data);
$mailer->sendEmailConfirmationTo($user);
return "account created!";
}
But, after the registration, laravel makes auto login.
How can i disable the auto login?
I think that the fastest way to do that is:
$user = User::create($data);
$mailer->sendEmailConfirmationTo($user);
Auth::logout(); //logout please!
return "account created!";
For the slower one, look at this question:
How to disable auto login on register in Laravel 5?
If you are using Laravel 5.2 try with this function inside your AuthController
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
$user = $this->create($request->all());
return redirect($this->redirectPath());
}
Make sure to add this to the top of your AuthController:
use Illuminate\Http\Request;
I use the included authentication of laravel 5.1.6 and want to know how I can extend it, to work like this:
if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
// The user is active, not suspended, and exists.
}
If the user is not "active", the login should not be possible. I have an 'active' column in the users table , with 0 or 1 as value. How can i do this while still using the built in authentication with login throtteling.
edit:
I don't have a postLogin function in the AuthController, only a use AuthenticatesAndRegistersUsers, ThrottlesLogins; , a __construct(), a validator() and a create() function. Do I have to change something in the trait in Illuminate\Foundation\Auth\.. or must I add the the postLogin() function in the AuthController ?
You can just override the getCredentials() method in your AuthController:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
public function getCredentials($request)
{
$credentials = $request->only($this->loginUsername(), 'password');
return array_add($credentials, 'active', '1');
}
}
This will add the active = 1 constraint when trying to authenticate a user.
EDIT: If you want a separate error message like BrokenBinary says, then Laravel allows you to define a method called authenticated that is called after a user has been authenticated, but before the redirect, allowing you to do any post-login processing. So you could utilise this by checking if the authenticated user is active, and throw an exception or display an error message if not:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
public function authenticated(Request $request, User $user)
{
if ($user->active) {
return redirect()->intended($this->redirectPath());
} else {
// Raise exception, or redirect with error saying account is not active
}
}
}
Don’t forget to import the Request class and User model class.
I have now changed the auth middleware /app/Http/Middleware/Authenticate.php (added the block below the comment):
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('auth/login');
}
}
#logout if user not active
if($this->auth->check() && $this->auth->user()->active !== 1){
$this->auth->logout();
return redirect('auth/login')->withErrors('sorry, this user account is deactivated');
}
return $next($request);
}
It seems, it also logs out inactive users if they were already logged in.
I would add following first thing in postLogin() function.
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
if ($this->auth->validate(['email' => $request->email, 'password' => $request->password, 'active' => 0])) {
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors('Your account is Inactive or not verified');
}
active is a flag in user table. 0 = Inactive, 1 = active. so whole function would look like following..
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
if ($this->auth->validate(['email' => $request->email, 'password' => $request->password, 'active' => 0])) {
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors('Your account is Inactive or not verified');
}
$credentials = array('email' => $request->email, 'password' => $request->password);
if ($this->auth->attempt($credentials, $request->has('remember'))){
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => 'Incorrect email address or password',
]);
}
Solved: this link ( tutorial) will help you : https://medium.com/#mshanak/solved-tutorial-laravel-5-3-disable-enable-block-user-login-web-passport-oauth-4bfb74b0c810
step1:
add new field to the User table called ‘status’ (1:enabled, 0:disabed)
step2:
to block the web login , in app/Http/Controllers/Auth/LoginController.php add the follwoing function:
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(\Illuminate\Http\Request $request)
{
$credentials = $request->only($this->username(), ‘password’);
return array_add($credentials, ‘status’, ‘1’);
}
Step3:
to block the user when using passport authentication ( token ) , in the User.php model add the following function :
public function findForPassport($identifier) {
return User::orWhere(‘email’, $identifier)->where(‘status’, 1)->first();
}
Done :)
On Laravel 5.3.* update app/Http/Controllers/Auth/LoginController
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function credentials(\Illuminate\Http\Request $request)
{
$credentials = $request->only($this->username(), 'password');
return array_add($credentials, 'active', '1');
}
// your code here