Laravel Remember Me, running with Auth::attempt? - php

So I have this code:
public function postLogin() {
// validate the info, create rules for the inputs
$rules = array(
'username' => 'required', // make sure the email is an actual email
'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::route('login')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
$remember = (Input::has('remember')) ? true : false;
// create our user data for the authentication
$userdata = (array(
'username' => Input::get('username'),
'password' => Input::get('password')
), $remember);
// attempt to do the login
if (Auth::attempt($userdata)) {
// validation successful!
// redirect them to the secure section or whatever
// return Redirect::to('secure');
// for now we'll just echo success (even though echoing in a controller is bad)
echo 'SUCCESS!';
} else {
// validation not successful, send back to form
return Redirect::route('login')
->with('global', 'Incorrect username or password. Please try again.');
}
}
}
When it runs I get: syntax error, unexpected ','. Basically it isn't expecting the $remember to be passed there. Where is it meant to be? I've tried putting it here: Auth::attempt($userdate), $remember) { } but that didn't work either. It had the same error. Not sure what's going on. Any help would be appreciated.

You can use Auth::viaRemember() in your Authcontroller, to check if a user was already logged:
if (Auth::check() || Auth::viaRemember()) {...
And change your login-check as follows:
//Assuming, the remember-input is a checkbox and its value is 'on'
if (Auth::attempt($userData, (Input::get('remember') == 'on') ? true : false)) {...

Related

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.

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

Laravel Routing returns blank page

to make it a bit short. I just made a registration form fully working with a controller, the routes and the view. Now I know it's common sense to use a Model for it and in the controller only call the method in the model. So i thought okay lets fix that. Now when I register an account I get a blank page. I bet the redirect is going wrong but I can't fix it maybe you can?
RegisterController.php
public function doRegister(){
$user = new User();
$user->doRegister();
}
User.php (model)
public function doRegister()
{
// process the form here
// create the validation rules ------------------------
$rules = array(
'username' => 'required|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|min:5',
'serial_key' => 'required|exists:serial_keys,serial_key|unique:users'
);
// create custom validation messages ------------------
$messages = array(
'required' => 'The :attribute is important.',
'email' => 'The :attribute is not a legit e-mail.',
'unique' => 'The :attribute is already taken!'
);
// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make(Input::all(), $rules);
// check if the validator failed -----------------------
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
// redirect our user back to the form with the errors from the validator
return Redirect::to('/register')
->withErrors($validator)
->withInput(Input::except('password', 'password_confirm'));
} else {
// validation successful ---------------------------
// our duck has passed all tests!
// let him enter the database
// create the data for our duck
$duck = new User;
$duck->username = Input::get('username');
$duck->email = Input::get('email');
$duck->password = Hash::make(Input::get('password'));
$duck->serial_key = Input::get('serial_key');
// save our user
$duck->save();
// redirect with username ----------------------------------------
return Redirect::to('/registered')->withInput(Input::old('username'));
}
}
you need to make $user->doRegister(); a return statement
in your RegisterController you have to do
public function doRegister(){
$user = new User();
return $user->doRegister();
}
try this
return Redirect::to('/registered')
->with('bill_no', Input::get('username'));
in the '/registered' controller,..
use this
$username = Session::get("username");
above worked for me,...

Input validation in laravel?

I have a Input validation to change user password, when i tried to submit the form i got always an error that the new password and confirm password are not matched even, this is my post action :
public function doChangePassword()
{
if(Auth::check())
{
$validator = Validator::make(Input::all(), User::$updatePasswordRules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('change-password')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();
} else {
// store
$user = User::find(Auth::user()->id);
if(Auth::user()->password==Input::get('new_password')){
$user->password = Hash::make(Input::get('new_password'));
$user->save();
}
else{
return Redirect::to('change-password')->with('message', 'The password is not correct');
}
// redirect
Session::flash('message', 'Successfully updated password!');
return Redirect::to('login');
}
}
else{
return Redirect::to('login');
}
}
this is my rules :
public static $updatePasswordRules = array(
'password'=>'required|alpha_num|between:6,12',
'new_password'=>'required|alpha_num|between:6,12|confirmed',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
so please if someone has an idea i will be very appreciative
It's because Laravel expects (for your specific case) confirmed field to be named new_password_confirmation
From doc "The field under validation must have a matching field of foo_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input."
Thus rules should look like (also change input name in form):
public static $updatePasswordRules = array(
'password'=>'required|alpha_num|between:6,12',
'new_password'=>'required|alpha_num|between:6,12|confirmed',
'new_password_confirmation'=>'required|alpha_num|between:6,12'
);
Or you can do it with same validation rule (if don't want to update form inputs):
public static $updatePasswordRules = array(
'password'=>'required|alpha_num|between:6,12',
'new_password'=>'required|alpha_num|between:6,12|same:password_confirmation',
'password_confirmation'=>'required|alpha_num|between:6,12'
);

Posting data from two different forms in laravel?

I have a log in and register form that I'd like to set up on the same page.
The log in form works just fine, with dummy data already inputted in to the database that i'm using.
The issue I'm having is that I'm getting a method calling error (assumedly because I have the same post function call to two different functions.
Currently in my routes.php file I have
// route to process the form
Route::post('/', array('uses' => 'HomeController#doLogin'));
Route::post('/', array('uses' => 'HomeController#doRegister'));
And my controller file looks like this (sorry it's a little long, I thought it'd be better to provide everything instead of assuming someone can understand my question from just my explanation alone)
public function doRegister() {
$v = User::validate(Input::all());
if ( $v->passes() ) {
User::create(array(
'name'=> Input::get('name'),
'email'=> Input::get('email'),
'password'=> Hash::make(Input::get('password')),
));
return 'Thanks for registering!';
} else {
return Redirect::to('/')->withErrors($v->getMessages());
}
}
public function doLogin()
{
// validate the info, create rules for the inputs
$rules = array(
'email' => 'required|email', // make sure the email is an actual email
'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// if the validator fails, redirect back to the form
if ($validator->fails()) {
return Redirect::to('/')
->withErrors($validator) // send back all errors to the login form
->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {
// create our user data for the authentication
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userdata)) {
// validation successful!
// redirect them to the secure section or whatever
// return Redirect::to('secure');
// for now we'll just echo success (even though echoing in a controller is bad)
echo 'SUCCESS!';
} else {
// validation not successful, send back to form
return Redirect::to('/');
}
}
}
As far as I'm aware this is because I'm not setting which function to use correctly for my registration form.
Hopefully I've done an ok job at explaining my issue, any solution please? (rather new to laravel)
One form would post to login and the other to register
Route::post('login', array('uses' => 'HomeController#doLogin'));
Route::post('register', array('uses' => 'HomeController#doRegister'));
And then you would open the form like:
{{ Form::open(array('url' => 'login')) }}
and
{{ Form::open(array('url' => 'register')) }}
Edit:
And the forms would just be placed inside your home view for example, and then you would just redirect from the login and register methods, and not show a view.

Categories