custom Authentication on Laravel - php

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);
}
}
}

Related

Laravel Input Validaiton Exists with username or email

how to make correct validation if i have input from where i can sign in with username or email, i want to if user will text username in field, it check if this username doesnt exist, then fail, also if he will choose to use email to sign in, then it will check if email doesnt exist then fail. (login form have only 2 inputs, login and password, in login u can text username or email)
my rule =
public function rules()
{
return [
'user' => 'required|min:3|exists:users,username,email]',
'password' => 'required',
];
}
You can use custom login as :
public function login(Request $request)
{
$request->validate([
'user' => 'required|min:3]',
'password' => 'required',
]);
}
$userName_or_Email = $request->user;
$password = $request->password;
$user = User::where('username',$userName_or_Email)->first();
if(empty($user)){
$user = User::where('email',$userName_or_Email)->first();
}
if(empty($user)){
return new Response()->with('error','Username or email not available in database');
}
if(Hash::check($password, $user->password)){
// Login successful code
}else{
return new Response()->with('error','Username or email not available in database');
}

Private account by a attribute in laravel

I have a proplem with this function.
My attribute 'sv_trangThai'=2 , of course. i can log in. and if sv_trangThai=1, this account won't log in because of being locked.
Ok. 2:can log in and 1: being locked and can't log in.
Absolutely my code is running well but when i typed the wrong password or username, i got "username or password is not true!".That's first case. Fine.
In case 2th, when i typed true password and username, i got the same "username or password is not true".
I wanna ask to how i should write to Show MessageBag:"This account is being locked" when i use case 2. instead of "username or password is not true".enter code here
public function login(Request $request)
{
$rules = [
'sv_ma' =>'required',
'password' => 'required|min:6',
];
$messages = [
'sv_ma.required' => 'Please type code',
'password.required' => 'please type password here',
'password.min' => 'password is the least at**strong text** 6!!!!',
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
else
{
if (Auth::guard('sinhvien')->attempt(['sv_ma'=>$request->sv_ma,'password'=>$request->password,'sv_trangThai'=>2],$request->remember))
{
return redirect()->intended('/trangchu');
}
else
{
$errors = new MessageBag(['errorlogin' => 'username or password is not true!']);
return redirect()->back()->withInput($request->only('sv_ma','remember'))->withErrors($errors);
}
}
}
$credentials = $request->only('sv_ma','password');
if(Auth::guard('sinhvien')->attempt($credentials, $request->remember)){
$user = Auth:user();
if($user->sv_trangThai == 1 ){
//account locked
Auth::logout();
$errors = new MessageBag(['errorlogin' => 'Account Locked']);
return redirect()->back()->withInput($request->only('sv_ma','remember'))->withErrors($errors);
}
}else{
$errors = new MessageBag(['errorlogin' => 'username or password is not true!']);
return redirect()->back()->withInput($request->only('sv_ma','remember'))->withErrors($errors);
}
First you must check the sv_ma and password what's return with this
dd($request->sv_ma .' '.$request->password );
Second go to your database and check your password if is hashed or not if is not hashed you must add a new account but the password should be hashed using bcrypt.

Perform User Authentication if email provided exists in the database

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)

update profile password laravel 5

I am working in laravel 5.1 and my update profile was working but will not encrypted and not working now.
When I try to update the user table will also password_confirmation field and causes a conflict in the database. I do not understand.
In the form says successfully but the database does not update any
Code
public function updatePassword() {
$passwordData = Input::except('_token');
$validation = Validator::make($passwordData, User::$passwordData);
if ($validation->passes()) {
array_forget($passwordData,'password_confirmation');
User::where(array(
'password' => Hash::make(Input::get('password'))
));
Session::flash('password', 'Perfil editado com sucesso');
return Redirect::to('backend/perfil/password');
} else {
return Redirect::to('backend/perfil/password')->withInput()->withErrors($validation);
}
}
user
public static $passwordData = array(
'password' => 'required|confirmed',
'password_confirmation' => 'required'
);
Follow this simple steps to get rid of anything
Step 1 : Get the password from the form
$PasswordData = Input::all();
Step 2 : Validate your password
Validator::extend('pwdvalidation', function($field, $value, $parameters) {
return Hash::check($value, Auth::user()->password);
});
Step 3 : Define the validation rule in your User Model
public static $rulespwd = array('OldPassword' => 'required|pwdvalidation',
'NewPassword' => 'required|confirmed|alphaNum|min:5|max:10',
'NewPassword_confirmation' => 'required',
);
Note : You shall define your own rule according to your need
Step 4 : If the rule is passed, then update else throw error messages to your view
$validator = Validator::make($PasswordData, User::$rulespwd, $messages);
if ($validator->passes()) {
$user = User::find(Auth::user()->id);
$user->password = Input::get('NewPassword');
$user->save();
return Redirect::to(Session::get('urlpath') . '/changepassword')->withInput()->with('Messages', 'The Password Information was Updated');
} else {
return Redirect::to(Session::get('urlpath') . '/changepassword')->withInput()->withErrors($validator);
}

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