Perform User Authentication if email provided exists in the database - php

In Laravel, is it possible to do a sign-in base on user email only - no password needed.
I'ved tried
public function postSignIn(){
$validator = Validator::make(Input::only('email') , array(
'email' => 'required',
));
if ($validator->fails()) {
return Redirect::to('/')->with('error', 'Please fill out your information ')->withErrors($validator)->withInput();
}
$email = strtolower(Input::get('email'));
$auth = Auth::attempt(array('email' => $email ));
if ($auth) {
return Redirect::to('/dashboard')->with('success', 'Hi '. Auth::user()->name .'! You have been successfully logged in.');
}
else {
return Redirect::to('/')->with('error', 'Username/Password Wrong')
->with('username', $username)
->withErrors($validator);
}
I keep getting : Undefined index: password
Do I need to modify the any kind of Auth driver for this to work ?
Any hints/ suggestions on this will be much appreciated !

You can do something like this:
public function postSignIn(){
$validator = Validator::make(Input::only('email') , array(
'email' => 'required',
));
if ($validator->fails()) {
return Redirect::to('/')->with('error', 'Please fill out your information ')->withErrors($validator)->withInput();
}
$email = strtolower(Input::get('email'));
try{
$user = User::where('email', $email)->firstOrFail();
Auth::login($user);
return Redirect::to('/dashboard')->with('success', 'Hi '. Auth::user()->name .'! You have been successfully logged in.');
}
catch(ModelNotFoundException $exception){
return Redirect::to('/')->with('error', 'Username/Password Wrong')
->with('username', $username)
->withErrors($validator);
}
}
You can check more info in here on how to manually login your users (you will have to scroll down a little bit)

Related

Logout user from all browser when password is reset in laravel 5.6

When the user changes their password, they get Logged Out from the browser. However, if they are logged into another browser at the same time they stay logged in on the other browser.
I want to log out the user from all browsers they are logged into when they reset their password.
Here login controller.
function checklogin(Request $request)
{
$this->validate($request, ['email' => 'required|email', 'password' => 'required|string|min:3']);
$user_data = array(
'email' => $request->get('email') ,
'password' => $request->get('password')
);
$remember_me = $request->has('remember') ? true : false;
if (Auth::attempt($user_data, $remember_me))
{
return redirect()->intended('dashboard');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
send mail function as below
function sendEmail(Request $request)
{
$this->validate($request, ['email' => 'required|exists:users']);
$email = $request->email;
$name = User::where('email', $email)->first();
$name = $name->name;
$token = Password::getRepository()->createNewToken();
$link = url("password/reset?email=$email&token=$token");
$value = Password_resets::where('email', $email)->first();
if (isset($value))
{
Password_resets::where('email', $email)->update(['email' => $email, 'token' => $token]);
}
else
{
Password_resets::insert(['email' => $email, 'token' => $token]);
}
Mail::to($email)->send(new \App\Mail\ResetPassword($link, $name));
return redirect()->back()->with('success', 'Please check your Email for Password Reset');
}
password reset function as below
function resetpasswordchange(Request $request)
{
$passwordtoken = $request->input('passwordtoken');
$email = $request->input('email');
$user_password = $request->input('user_password');
$users['user'] = Password_resets::where('token', $passwordtoken)->where('email', $email)->get();
if (empty($users['user'][0]))
{
$settoken = '0';
}
else
{
$settoken = $users['user'][0]->token;
}
if (($settoken) == $passwordtoken)
{
$update = array(
'password' => bcrypt($user_password) ,
);
User::where('email', $email)->update($update);
/* Auth::logout();
auth()->logoutOtherDevices(bcrypt($user_password),'password');*/
return redirect()->route('login')->with('success', 'Password has been Updated.');
}
else
{
return redirect()->back()->with('error', 'Token & Email Not Match!.');
}
}
How I can logout the user from all browsers who they are logged already ?
Open App\Http\Kernel and inside the protected $middlewareGroups property uncomment the \Illuminate\Session\Middleware\AuthenticateSession::class middleware. This compares the password hash of the user to see if the session is valid or not.

Laravel 5.7 Auth with email/username and password using tymon/jwt

I am using jwt-auth for my Laravel 5.7 app. Currently, I'm allowing the client to enter email and password as user credentials.
However, I also want to let the client to enter their username in place of their email. So they have 2 choices: email or username.
How can I do that in my code?
My UserController#authenticate
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
try {
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json([
'status' => 401,
'message' => 'invalid_credentials',
], 401);
}
} catch(JWTException $e) {
return response()->json([
'status' => 500,
'message' => 'token_creation_failed',
], 500);
}
return response()->json(compact('token'));
}
Thanks in advance
In your AuthController, add this to the login method;
public function login()
{
$loginField = request()->input('login');
$credentials = null;
if ($loginField !== null) {
$loginType = filter_var($loginField, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([ $loginType => $loginField ]);
$credentials = request([ $loginType, 'password' ]);
} else {
return $this->response->errorBadRequest('What do you think you\'re doing?');
}
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
This is how I handled mine where user can choose either email or phone to login.
public function login(Request $request)
{
//validate incoming request
$this->validate($request, [
'email_phone' => 'required|string',
'password' => 'required|string',
]);
try {
$login_type = filter_var( $request->email_phone, FILTER_VALIDATE_EMAIL ) ? 'email' : 'phone';
// return $login_type;
$credentials = [$login_type => $request->email_phone, 'password'=>$request->password];
if (! $token = Auth::attempt($credentials)) {
return response()->json($this->customResponse("failed", "Unauthorized"), 401);
}
return $this->respondWithToken($token);
} catch(JWTException $e) {
return response()->json($this->customResponse("failed", "An error occured, please contact support.", $user), 500);
}
}

custom Authentication on Laravel

I want to write a custom authentication on laravel, I want to know should I use default auth or should I write a new?
my auth workflow is:
Step 1- Show email form (in this step we will get just email address)
Step 1-2- check for email existence and if email exists we will go to Step 2 and if not exists I should redirect user to Step 3
Step 2- get the user password (validate password and if everything was OK user will login)
Step 3- show registration form and fill the email with entered user email address (validate form and register user)
What is your solution ?
//Login rules
public function user_login_rules(array $data)
{
$messages = [
'email.required' => 'Please enter your email'
];
$validator = Validator::make($data, [
'email' => 'required'
], $messages);
return $validator;
}
Your post method
public function postSignIn(Request $request)
{
$request_data = $request->all();
$validator = $this->user_login_rules($request_data);
if($validator->fails())
{
return redirect()->back()->withErrors($validator)->withInput();
}
else
{
$email = $request_data['email'];
$user_details = User::where('email', $email)->first();
if(count($user_details) > 0)
{
$credentials = array('email'=> $email ,'password'=> $request_data['password']);
if ($this->auth->attempt($credentials, $request->has('remember')))
{
//Login successful
return redirect()->to('/home');
}
else
{
$error = array('password' => 'Please enter a correct password');
return redirect()->back()->withErrors($error);
}
}
else
{
//Display register page with email
return view('register')->with('email', $email);
}
}
}

Storing user details in session but without login him yet in Laravel

Is it possible when user type his login username and password to store his details and redirect him to another page where I will query database for addition information which he provide before to log him? Consider this scenario:
User enter username/password
If they are correct store this user information and redirect to another page ( not logged yet )
Query database for addition information about this user
This is what I have so far
public function login() {
return View::make('site.users.login');
}
public function loginSubmit() {
$validatorRules = array(
'username' => 'required|alpha_dash',
'password' => 'required|min:6'
);
Input::merge(array_map('trim', Input::all()));
$validator = Validator::make(Input::all(), $validatorRules);
if ($validator->fails()) {
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
$user = User::where('username', Input::get('username'))->first();
if (!$user) {
$validator->messages()->add('username', 'Invalid login or password.');
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
if (!Hash::check(Input::get('password'), $user->password)) {
$validator->messages()->add('username', 'Invalid login or password.');
return Redirect::to('/users/login')->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
Session::put('user', ['user_id' => $user->user_id]);
return Redirect::to('/users/auth/' . $user->user_id . '?_token=' . csrf_token())->with('message_success', '.');
}
public function loginAuth() {
Session::get('user', ['user_id' => $user->user_id]);
$key = DB::table('users')->select('key')->where('user_id', '=', $data->user_id)->first();
return View::make('site.users.auth', [
'key' => $key
]);
}
Or there is another way to do this? This portion of source gave simple error
production.ERROR: exception 'ErrorException' with message 'Undefined variable: user'
On session get function
Session::get('user', ['user_id' => $user->user_id]);
You can fix your code like this:
public function loginAuth()
{
$data = Session::get('user');
$key = DB::table('users')->select('key')->where('user_id', '=', $data->user_id)->first();
return View::make('site.users.auth', [
'key' => $key
]);
}

Laravel - Confide - Save Change Password

I managed to save a new password or change a password for a logged in user.
public function saveNewPassword() {
$rules = array(
'old_password' => 'required',
'password' => 'required|confirmed|different:old_password',
'password_confirmation' => 'required|different:old_password|same:password_confirmation'
);
$user = User::findOrFail(Auth::user()->id);
// Validate the inputs
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
} else {
$password = Input::get( 'password' );
$passwordConfirmation = Input::get( 'password_confirmation' );
if(!empty($password)) {
if($password === $passwordConfirmation) {
$user->password = $password;
$user->password_confirmation = $passwordConfirmation;
}
} else {
unset($user->password);
unset($user->password_confirmation);
}
// Save if valid. Password field will be hashed before save
$user->save();
}
// Get validation errors (see Ardent package)
$error = $user->errors()->all();
if(empty($error)) {
Session::flash('message', 'Successfully saved!');
return Redirect::back();
} else {
Session::flash('error', $error);
return Redirect::back();
}
}
The problem I have is, how to check the Old Password, that is equal to the current password? Any Ideas? Does Confide has his own methods for changing passwords?
I use this sollution for changing the password. In your rules you have one error: password_confirmation should be the same as password not password_confirmation.
Here is the complete and tested function:
public function changePassword($id){
$rules = array(
'old_password' => 'required',
'new_password' => 'required|confirmed|different:old_password',
'new_password_confirmation' => 'required|different:old_password|same:new_password'
);
$user = User::find(Auth::user()->id);
$validator = Validator::make(Input::all(), $rules);
//Is the input valid? new_password confirmed and meets requirements
if ($validator->fails()) {
Session::flash('validationErrors', $validator->messages());
return Redirect::back()->withInput();
}
//Is the old password correct?
if(!Hash::check(Input::get('old_password'), $user->password)){
return Redirect::back()->withInput()->withError('Password is not correct.');
}
//Set new password to user
$user->password = Input::get('new_password');
$user->password_confirmation = Input::get('new_password_confirmation');
$user->touch();
$save = $user->save();
return Redirect::to('logout')->withMessage('Password has been changed.');
}
This also works if you dont work with Confide.
From the github of confide:
Integrated with the Laravel Auth and Reminders component/configs.
So I would guess using the Auth::validate() method will do the trick.

Categories