cakephp flash error not working - validation

i've created a login in system where an activated user can log in but a user who's account hasnt been activated wont be able to log in. The problem is that no flash message is outputted when the user tries to log in with a deactivated account, so a user wouldn't know why the page keeps refreshing on the login page.
heres my login function
if ($this->request->is('post')){
if ($this->request->data['User']['password'] == 'qazwsx'){
if ($this->Auth->login()){
$username = $this->request->data['User']['username'];
if (0 === $this->User->find('count',array('conditions'=>array('activated'=>1,'username'=> $username)))) {
$this->Session->setFlash('Sorry, your account is not validated yet.');
$this->redirect($this->referer());
}
$this->Auth->user('id');
$this->redirect($this->Auth->redirect('eboxs/home'));
}
}
else {
$this->Session->setFlash('Username or password is incorrect');
}
}else{
$this->Session->setFlash('Welcome, please login');
}
}
I havent included my view cause so far with flash messages i havent had to call them

Weird Authentification way you're doing there.
Like you've been already told in the comments, check, wherever the user is redirected ($this->redirect), there is a
<?php echo $this->Session->flash(); ?>
in that view.
Also with that method, the user is logged in anyway. You've to manually log out that user again, before you show him the flash message / redirect him.
You can also just write:
<?php
...
$this->Auth->scope = array('User.activated' => 1);
if ($this->Auth->login()) {
// logged-in logic
} else {
// not logged-in logic
}
?>
This would save you some lines of code.

Related

Laravel stuck on email/verify

I just applied the laravel email-verification and wanted to make sure my users are verified, before entering page behind the login.
I added the follwing code:
class User extends Authenticatable implements MustVerifyEmail
...
Auth::routes(['verify' => true]);
...
Route::get('management', function () {
// Only verified users may enter...
})->middleware('verified');
If a user registers he gets a note and an email to verify his mail. He clicks the button in the mail, gets verified and everything works perfectly well.
But I discovered another case:
If the user registers and won't verify his mail, he will always get redirected to email/verify.
For example if accidentally having entered a wrong email, he can't even visit the register page, because even on mypage.com/register he gets redirected to mypage.com/email/verify!
Is this done on purpose by Laravel? Did I miss something? Do I have to / is it possible to exclude the login/register pages from verification?
Thank you in advance
I have this issue before, I have this way to resolve that, if you want to customize it you can consider this way.
In LoginController.php you can add this a little bit code, I overwriting the default login method:
public function login(Request $request)
{
$this->validateLogin($request);
$user = User::where($this->username(), $request->{$this->username()})->first();
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($user->hasVerifiedEmail()) {
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
})
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
You can overwrite and add a new parameter to the sendFailedLoginResponse too to let the method know when to redirect to email/verify page or just add else in $user->hasVerifiedEmail() if block to redirect him to email/verify page
EDIT:
You can delete $this->middleware('guest') in LoginController and RegisterController to make logged in user can go to register and login page, but it will be weird if someone who already logged in can login or register again.
I had the same problem and I solved it very user friendly... (I think!)
First: Inside View/Auth/verify.blade.php put a link to the new route that will clear the cookie:
My mail was wrong, I want to try another one
Second: On your routes/web.php file add a route that will clear the session cookie:
// Clear session exception
Route::get('/clear-session', function(){
Cookie::queue(Cookie::forget(strtolower(config('app.name')) . '_session'));
return redirect('/');
});
This will clear the cookie if the user press the button, and redirect to home page.
If this doesn't work, just make sure that the cookie name you are trying to forget is correct. (Use your chrome console to inspect: Application -> cookies)
For example:
Cookie::queue(Cookie::forget('myapp_session'));

How can I logout user after delete with Laravel?

What is the correct way to logout user after I delete his data in Laravel? I would not like to delete him before, in case of delete process goes with errors.
When I am having this code:
if($this->userManipulator->softDeleteUser(Auth::user())){
Auth::logout();
return redirect(url('login'));
}
it works fine in the app, but does not work correctly during testing.
As I mentioned in the comments, you must log the user out of your application first since once deleted Eloquent won't be able to locate/logout the user.
Below is a solution that addresses your concern about what to do if the delete fails. It might need adjustment depending on how you have things setup, but this concept will work:
// Get the user
$user = Auth::user();
// Log the user out
Auth::logout();
// Delete the user (note that softDeleteUser() should return a boolean for below)
$deleted = $this->userManipulator->softDeleteUser($user);
if ($deleted) {
// User was deleted successfully, redirect to login
return redirect(url('login'));
} else {
// User was NOT deleted successfully, so log them back into your application! Could also use: Auth::loginUsingId($user->id);
Auth::login($user);
// Redirect them back with some data letting them know it failed (or handle however you need depending on your setup)
return back()->with('status', 'Failed to delete your profile');
}
This is not possible, Auth won't be able to located them because Eloquent treats them as deleted.
Solution: You should logout user before delete.
$user = \User::find(Auth::user()->id);
Auth::logout();
if ($user->delete()) {
return Redirect::route('home');
}

user already logged in but it try to open login link then how to redirect specified path in laravel

http://localhost/admin/login
I have logged in then I am redirecting to
localhost/admin/
Now I am open localhost/admin/login
then I want to redirect on
localhost/admin/dashboard not on
localhost/admin/
You need to put it in your auth controller.
protected $redirectTo = '/admin/dashboard';
You can use like this,
header('Location: http://www.example.com/');
You have to check if the user is logged :
if (Auth::check()) {
return Redirect::to('localhost/admin/');
}else{
log-in part
}
You have to simply check for the that particular user is logged into system using below code -
if (Auth::check()) {
return Redirect::to('admin/dashboard');
}else{
return Redirect::to('login/admin');
}
If user is logged in then redirect to dashboard of admin &
If user isn't logged in then redirect to login blade of the project.

Laravel - Redirect after login

Im a bit of a newbie when it comes to Laravel so i was hoping someone could help out.
Im using the standard authentication and login stuff that ships with Laravel so theres nothing fancy going on, but what i want to do is check in the DB to see if a few fields are completed ( name, address, postcode ) .... If they are, then the user gets redirected to the dashboard, but if they aren't, the user will get redirected to the profile page to fill out the rest of their information.
Im guessing i should put something in my routes.php file in the
Route::post('login', function
part, but how do i check for the fields?
Any help would be greatly appreciated.
Cheers,
Once you have authenticated the user using Auth::check you'll be able to grab the authenticated user with Auth::user.
if (Auth::attempt($credentials))
{
$user = Auth::user();
if ($user->email == '' || $user->address == '')
{
return Redirect::to('user/profile');
}
return Redirect::to('home');
}
You just need to check the fields you want on the user to make sure they are there. If they're not then redirect them to the profile page. If they are redirect them to the home page or somewhere else.
You can also do it this way
if (Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password')))) {
return Redirect::to('users/dashboard');
} else {
return Redirect::to('users/profile');
}
You can use this code
if (Auth::guest())
{
//user is not authenticated or logged in;
return Redirect::to('login');
}else{
//user is authenticated and logged in;
return Redirect::to('profile');
}

CakePHP 2.0 Automatic Login after Account Activation

I'm just working on the user management-component of our new project.
The plan is:
User registers on the page with minimal amount of account data (username, pass, email)
User gets an email with an activation link to activate the account
User clicks on the link and activates his account
The system logs in the user after automatically after activation and redirects him to kind of a dashboard with account information (last login, hi "username", etc.)
But there are some problems with the auto login. this is the part of the code i use:
<?php
...
// set userstatus to "active" and delete meta information "activation_key"
// then automatically login
$this->User->id = $id;
$this->User->saveField('modified', date('Y-m-d H:i:s') );
$this->User->saveField('status', 1 );
// $this->User->deleteActivationKey ....
$this->Auth->login($this->User->read());
$this->Session->setFlash(__('Successfully activated account. You are now logged in.'));
$this->User->saveField('last_login', date('Y-m-d H:i:s') );
$this->redirect(array('controller' => 'pages'));
...
This works so far, until you want to get information about the logged in user with the user() function of the Auth Component.
We're using this in AppController->beforeRender, to have user information application wide:
$this->set('auth', $this->Auth->user());
but after that auto login action, i'm getting undefined index notices. (e.g. by accessing $auth['id'] in a view). print_r() shows me only the username and hashed password of the current user.
If you login manually, everything works fine. it must be something with the automatic login after the account activation.
Seems to be a problem with the session? What am i doing wrong?
Found a solution after testing many variations.
Works now with:
$user = $this->User->findById($id);
$user = $user['User'];
$this->Auth->login($user);
Don't know why, i thought i tried this way already and that did not work.
Have you tried this? (CakePHP 2.x)
public function signup() {
if (!empty($this->request->data)) {
// Registration stuff
// Auto login
if ($this->Auth->login()) {
$this->redirect('/');
}
}
}
That simple!

Resources