Difficulties with 'Remember me' function in laravel - php

So, I'm trying to create a 'remember me' function in the login process in my laravel application. I created a basic form with email, password and remember me checkbox as input, as can be seen below:
<div class="col-xs-0 col-sm-6 col-md-6 col-md-offset-3 col-sm-offset-3 col-cs-offset-5" id="content">
{{ Form::open(['route' => 'sessions.store']) }}
<div>
{{ Form::label('email', 'Email:') }}
{{ Form::email('email') }}
</div>
<div>
{{ Form::label('password', 'Password:') }}
{{ Form::password('password') }}
</div>
<div>
{{ Form::label('remember', 'Remember me:') }}
{{ Form::checkbox('remember', 'Remember-me') }}
</div>
<div>{{ Form::submit('login') }}</div>
{{ Form::close() }}
</div>
This posts to the function below. But what happens right now, is that the user is always logged in with the true parameter. What am I doing wrong?
public function store()
{
$email = Input::get('email');
$password = Input::get('password');
$remember = Input::get('remember');
if ($remember == 'Remember-me') {
if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
return Redirect::intended('/');
}
return Redirect::back()->withInput();
} else {
if (Auth::attempt(array('email' => $email, 'password' => $password)))
{
return Redirect::intended('/');
}
return Redirect::back()->withInput();
}
}

Passing true as the third parameter of Auth::attempt will remember the login on success. Additionally your $remember check makes no sense because checkbox is supposed to represent a boolean value and Input::get returns it as either 1 or null which evaluates to true or false respectively.
What you probably want is this:
public function store()
{
$input = Input::only('email', 'password');
$remember = Input::get('remember');
if (Auth::attempt($input, $remember)
{
return Redirect::intended('/');
}
return Redirect::back()->withInput();
}

One of the reasons remember me is hard to do right (and there are many) is that the first time someone logs in with the box checked they need to login conventionally and that triggers the storage that you are going to do which allows them to log in without supplying their user name and password when they come back after their session has expired and they have closed their browser etc. So the initial authentication must be totally normal except for the addition of the step where the storage for future login happens. The remember me box being checked plays no role in that initial authentication. Assuming you are going to store the data in a cookie, checking the box means that after successful authentication the cookie is created and the other logic that will be needed for remember me authentication is implemented (and I won't go into the issues around that).
Later when they come back they shouldn't need to check the box or anything like that, they should just be logged in. That's when the remember me functionality comes into play however it is that you are implementing that.

This worked for me:
$remember = (Input::has('remember')) ? true : false;
The View looks like this:
<div class="field">
<input type="checkbox" name="remember" id="remember" />
<label for="remember">Remember me</label>
</div>
Off an old tutorial I don't know where I found, but it works.

Related

Laravel 7 - How to make 'Remember me' functionality work properly?

I am trying to implement the remember me functionality in my web site using Auth::viaRemember() but it always returns a value of false. what causes this and how to resolve this issue?
The remeber_token generates and stores it in database fine.
Here's the things i've tried:
Change the the value of 'expire_on_close' from false to true in config/session.php
Cleared the cookies and google chrome browser cache then restarted my browser
ran the php artisan config:cache and php artisan route:clear
Logged in with remember me checked then logged out (to see if the crendentials was saved).
Here's my login method code inside LoginController.php:
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
$remember = $request->has('remember') ? true : false;
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')], $remember))
{
if(Auth::viaRemember())
{
dd("remembered successfully");
}else{
dd("failed to remember");
}
return view('home');
}else{
return back()->with('error','your username and password are wrong.');
}
}
Here's my snippet code of login.blade.php file:
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
Here's the login page just in case:
There's no problem in logging in and successfully redirects to the home page. The only problem is that the credentials are not showing up or the log in form does not remember the credentials logged in before with remember me checked.
Had the same problem with this post and its references/posts included: Auth::viaRemember() doesnot work (means always return false even after successful login) in laravel 5.4 but unfortunately none of the provided solution works for me..
P.S.
I am using Laravel Framework 7.14.1 and latest google chrome version as of this moment (Version 83.0.4103.97 (Official Build) (64-bit))

Laravel: Show or hide content depending on a Session variable

I'm doing a view that has a password protection. Basically when you access that resource, you have a view that indicates that you need to put a password.
The correct behavior of this should be
You access the View
The user enters the password and sends the POST form
If the method redirects back with certain value, you must see the real content of the page.
So my blade code is the following:
#if ($passedPassword = Session::get('passedPassword'))
...here goes the real/true view content
#else
<section class="questionnaire-questions">
<div>
<form
action="{{ route('questionnaire.password', ['questionnaire' => $questionnaire->id]) }}"
method="POST">
{{ csrf_field() }}
<h3 class="text-center">#lang('questionnaire.password.advice')<h3>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="goal-input-group numeric">
<label>PASSWORD</label>
<input
style='visibility: visible;'
name="password"
type="password"
>
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="goal-btn goal-btn-lg goal-btn-artic-blue">#lang('questionnaire.password')</button>
</div>
</form>
</div>
</section>
#endif
That view is rendered with the following method:
public function show(Questionnaire $questionnaire) {
$data = [];
$data['questionnaire'] = $questionnaire;
\Session::flash('passedPassword', false);
return view('questionnaires.show', array('data' => $data));
}
In the previous method I'm passing the passedPassword, but I can't find a way to pass it as a flash variable. If there is a way to add data like
return back()->with(array(
'passedPassword' => false
));
But using the view method I'll really appreciate to know how.
Then, when the user clics the button I call the next function:
public function password(Request $request, Questionnaire $questionnaire) {
if (strcmp($questionnaire->password, $request->input('password')) == 0) {
return back()->with(array(
'passedPassword' => false
));
}
}
But even when the password is correct, I got the password view, the flash/session variable never arrived to the view.
Is there something I'm missing or doing wrong?
Thanks in advance.
As Dan told me in the comments, I was setting to false the value of the session variable.
So first I remove the \Session::flash('passedPassword', false); during the show method.
Then I modify my blade logic. In my case sometimes the password is needed and sometimes not.
#if (($passwordLength === 0) || ($passwordLength !== 0 && Session::has('passedPassword')))
With that, If the resource has no password we let the user pass. Or in the case it has a password and also we have the passedPassword variable, we also let the user see the content.

Laravel auth not working using correct username/password combination

For some reason, I'm unable to login with the correct username/password combination. I'm using flash messages to show when the login information is incorrect.
I've tried creating multiple accounts to make sure I wasn't actually entering the wrong login credentials, but after about an hour of fiddling it's still not working.
Any help would be greatly appreciated! Thank you!
Here's what I got.
UsersController.php (postCreate) - Function that creates my user account (working perfectly fine)
public function postCreate() {
$rules = array(
'username'=>'required|unique:users,username|alpha_dash|min:4',
'password'=>'required|min:8|confirmed',
'password_confirmation'=>'required|min:8',
'email'=>'required|email|unique:users,email'
);
$input = Input::only(
'username',
'password',
'password_confirmation',
'email'
);
$validator = Validator::make($input, $rules);
if($validator->fails())
{
return Redirect::to('register')->withErrors($validator)->withInput();
}
//$confirmation_code = str_random(30);
User::create(array(
'username'=>Input::get('username'),
'password'=>Hash::make(Input::get('password')),
'email'=>Input::get('email')
//'comfirmation_code' => $confirmation_code
));
// Mail::send('email.verify', function($message) {
// $message->to(Input::get('email'), Input::get('username'))
// ->subject('Verify your email address');
// });
// Flash::message('Thanks for signing up! Please check your email.');
return Redirect::to('login')->with('message', 'Thanks for signing up! Please check your email.');
}
UsersController.php (postLogin) - Function that logs me into account
public function postLogin() {
$user = array(
'email'=>Input::get('email'),
'password'=>Input::get('password')
);
if (Auth::attempt($user)){
return Redirect::intended('account')->with('message', 'Welcome back!');
} else {
return Redirect::to('login')
->with('message', 'Your username/password was incorrect')
->withInput();
}
}
Routes.php
Route::get('login', array('as'=>'login', 'uses'=>'UsersController#getLogin'));
Route::post('login', array('before'=>'csrf', 'uses'=>'UsersController#postLogin'));
login.blade.php - My login Page
#if($errors->has())
<p>The following errors have occured:</p>
<ul id="form-errors">
{{ $errors->first('username', '<li>:message</li>') }}
{{ $errors->first('password', '<li>:message</li>') }}
</ul>
#endif
#if (Session::has('message'))
<p>{{ Session::get('message') }}</p>
#endif
{{ Form::open(array('action'=>'login')) }}
<p>
{{ Form::label('username', 'Username') }}<br />
{{ Form::text('username', Input::old('username')) }}
</p>
<p>
{{ Form::label('password', 'Password') }}<br />
{{ Form::password('password') }}
</p>
<p>
{{ Form::submit('Login') }}
</p>
{{ Form::close() }}
In your
UsersController.php (postCreate) - : You are able to create using password with Hash 'password'=>Hash::make(Input::get('password')),
AND
UsersController.php (postLogin) : You are trying to login using 'password'=>Input::get('password') So this should replace with
'password'=>Hash::make(Input::get('password'))
Also hashed passwords required 64 charactters for database field. so check that too.
I found the issue to be with the amount of characters I was allowing to be entered into the password field of the database.
I had the password column set to: $table->string('password', 32); varchar(32) which wont work because hashed passwords in laravel require at least 64 characters.
Changing the password column in my database to varchar(64) fixed the issue.

How to make a Sign-in function in Laravel 4?

I have 3 user types :
Admin
Distributor
Internal
I have a problem sign in as user type. ( Internal )
I can sign in when my user type is Admin.
I can sign in when my user type is Distributor.
BUT I can’t sign in when my user type is internal. Wired ????
I look through every single line of my code in my sign-in functions in my AccountController.php.
I didn’t notice any bug there. If you guys notice any bugs there -- please kindly let me know.
That will be a huge help for me.
Here is my Sign-In Functions
GET
public function getSignIn(){
return View::make('account.signin');
}
POST
public function postSignIn() {
$validator = Validator::make( Input::only('username','password'),
array(
'username' =>'required',
'password' =>'required'
)
);
if ($validator->fails()) {
return Redirect::route('account-sign-in-post')
->with('error','Username/Password Wrong or account has not been activated !')
->withErrors($validator);
}
// Remember Me
$remember = (Input::has('remember')) ? true : false ;
$auth = Auth::attempt(array(
'username' => strtolower(Input::get('username')),
'password' => Input::get('password'),
'active' => 1),
$remember);
// Keep track on log-in information of the user.
if(Auth::check()){
$user = Auth::user();
$user->last_logged_in = Input::get('created_at');
$user->logged_in_count = $user->logged_in_count + 1 ;
$user->is_online = '1';
$user->save();
}
if($auth) {
return Redirect::to('/')
->with('success','You have been successfully logged in.')
;
}
else {
return Redirect::route('account-sign-in')
->with('error','Username/Password Wrong or account has not been activated !')
->withInput(Input::except('password'))
->withErrors($validator);
}
}
VIEW
#extends ('layouts.form')
#section('content')
<style type="text/css">
.signin{
text-align: center;
}
#forgetpassword{
/*color:#5cb85c;*/
color:silver;
}
</style>
<form class="form-horizontal" role="form" action=" {{ URL::route('account-sign-in-post')}}" method="post" >
#if ($errors->has('username')){{ $errors->first('username')}} #endif
<div class="form-group">
<label for=""> Email </label>
<input placeholder="Email" type="text" class="form-control" required name="username" {{ ( Input::old('username')) ? 'value="'.e(Input::old('username')).'"' : '' }}>
</div><br>
#if ($errors->has('password')){{ $errors->first('password')}} #endif
<div class="form-group">
<label for=""> Password </label>
<input placeholder="Password" type="password" class="form-control" required name="password">
</div><br>
<br>
<button type="submit" class="btn btn-success btn-sm btn-block ">Sign In </button>
{{ Form::token() }}
</form><br>
<div class="col-lg-12 text-center">
<a id="forgetpassword" href="{{ URL::route('account-forgot-password') }}"> Forget Password </a> <br>
</div>
#stop
I am sure that I typed in the right username and password because I double check with my database.
It keep redirecting me back to my sign-in page.
with('error','Username/Password Wrong or account has not been activated !')
Can someone please tell me, if I did anything that I’m not suppose to ?
In your situation, you should check your auth variable in your Sign_In Function.
According to your code,
$auth = Auth::attempt(array(
'username' => strtolower(Input::get('username')),
'password' => Input::get('password'),
'active' => 1),
$remember);
Keep in mind that, these are things need to make sure
username must match the database
password must match the database
user active must be 1
If any of these fail, therefore, it STOP you from signing in.
Since, you're so sure about username and password, what about user active ?
Did you check to if it's 1 ?
If Not
on your set-password function or anywhere, where you normally set your user active.
just do this :
$user->active = '1';
$user->save();
Let me know if this work!!

Keep modal open after validation redirect

i am currently working on a project where the login/register is handled through modal boxes (so i click the login button and a nice modal reveals with a form in).
Im using foundation 5's reveal modal to house my login form but when the form is submitted and theres a validation error the modal closes. The reason this is happening is because i am redirecting back to the route where the login form is and in that route a button needs to be clicked to fire the modal.
What i was wondering is, is there something i can set so that modal stays open if there is a validation error or exception (account not found etc.) So if there is a validation error the modal stays open.
looking for any type of solution. my code is shown below.
Login function
public function postLogin()
{
// Declare the rules for the form validation
$rules = array(
'email' => 'required|email',
'password' => 'required|between:3,32',
);
// Create a new validator instance from our validation rules
$validator = Validator::make(Input::all(), $rules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
try
{
// Try to log the user in
Sentry::authenticate(Input::only('email', 'password'), Input::get('remember-me', 0));
// Get the page we were before
$redirect = Session::get('loginRedirect', 'dashboard');
// Unset the page we were before from the session
Session::forget('loginRedirect');
// Redirect to the users page
return Redirect::to($redirect)->with('success', Lang::get('auth/message.signin.success'));
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_not_found'));
}
catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_not_activated'));
}
catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_suspended'));
}
catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_banned'));
}
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($this->messageBag);
}
Login modal
<div id="myModalLogin" class="reveal-modal small" data-reveal>
<h2>Login</h2>
<form method="post" action="{{ route('login') }}">
{{-- CSRF Token --}}
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
{{-- Email --}}
<label for="email"> Email
<input type="text" name="email" id="email" value="{{ Input::old('email') }}" />
</label>
{{ $errors->first('email', '<label class="error">:message</label>') }}
{{-- Password --}}
<label for="password"> Email
<input type="password" name="password" id="password" value=""/>
</label>
{{ $errors->first('password', '<label class="error">:message</label>') }}
{{-- Remember me --}}
<input name="remember-me" value="1" id="remember-me" type="checkbox"><label for="remember-me">Remember me</label>
<hr>
{{-- Form Actions --}}
<button type="submit" class="button">Sign in</button>
I forgot my password
<a class="close-reveal-modal">×</a>
</div>
You need to create a flag variable that you will pass to your view and set it true if you want the modal to auto open and set it false if you don't want to open it:
The problem with this is that ->with() doesn't work with Redirect::back() so we need a workaround: lets pass our flag variable as an input. For this you have to get all the old input and add the new flag variable to them. Make sure that the key (your flag variable name) doesn't already exist. You can check this with a var_dump(Input::all()).
$input = Input::all();//Get all the old input.
$input['autoOpenModal'] = 'true';//Add the auto open indicator flag as an input.
return Redirect::back()
->withErrors($this->messageBag)
->withInput($input);//Passing the old input and the flag.
Now in your view you have to print this "old" input into your JavaScript condition. If it exists it will print its value: true, otherwise it will print the second argument: false.
<script>
$(document).ready(function () {
if ({{ Input::old('autoOpenModal', 'false') }}) {
//JavaScript code that open up your modal.
}
});
</script>
You can return false; when you return the validations results.

Categories