Laravel 5.6 Session takes newly created user after registration - php

In my application I made use of the php artisan make:auth command to provide some early on user login & registration scaffolding.
It has come to my attention that everytime I create a new user whilst being logged in as i.e. UserX, my user changes after submitting the registration to the newly created user.
Example below:
BEFORE REGISTRATION
Logged in as UserX
AFTER REGISTRATION
Logged in as UserZ (newly registered user)
=======
I am wondering how I can make it so that when I create a new user through registration, the system retains the user that was logged in instead of taking on the newly registered user.
Below is the register controller:
=======
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}

If you need to provide users the ability to add new users you should do so through a UsersController.
Now your new controller won't take on the behaviour of registration. This would also make logic in your application clearer since you are not registering a user, you are creating a new one.
To expand a little, the RegisterController executes the following code when you register a user (through use Auth\RegisteredUsers register method).
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
So in essence you must follow the approach I mention above unless you remove "use RegisteredUsers;" from the RegisterController which would not generally be recommended. Using your separate controller / behaviour allows you to create additional logic such as checking for user type (e.g. Admin User) before allowing to create a user etc. etc.

Related

Redirect to login page after a user is registered. laravel 5.5

How can I redirect to login page, after a user is registered on my web application with a message called "We have sent you a link on "user email". Please check your email to complete registration". By using laravel 5.5 version
Note: I have done the login and register by using Auth procress of laravel 5.5.
RegisterController
namespace App\Http\Controllers\Auth;
use App\Events\UserReferred;
use App\Profile;
use App\Reflink;
use App\Http\Controllers\Controller;
use App\Settings;
use App\User;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/verify/logout';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$settings = Settings::first();
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'admin'=>0,
'active'=>0,
'membership_id'=>1,
'membership_started'=>date('Y-m-d'),
'membership_expired'=>'2020-12-31',
'token'=>str_random(25),
]);
Profile::create([
'user_id'=>$user->id,
'avatar'=>'uploads/avatars/default.jpg',
'main_balance'=>$settings->signup_bonus,
]);
Reflink::create([
'user_id'=> $user->id,
'link'=> str_random(4).$user->id.str_random(4),
]);
$user->sendVerificationEmail();
event(new UserReferred(request()->cookie('ref'), $user));
session()->flash('message', 'Dear user your account create successful but not active. To active your account please check your email for verify code.');
Session::flash('type', 'warning');
Session::flash('title', 'Email Verify Required');
return $user;
}
}
After the user is successfully registered a Registered event is fired. So in your RegisterController you can override the registered method and log out the user from there:
protected function registered( Request $request, $user )
{
Auth::logout(); // don't forget to import the facade at the top of the class use Auth;
}
But a better approach is to use the verified middleware since you are using the verification option of Laravel.
So just surround your protected routes in a group:
Route::middleware([ 'auth', 'verified' ])->group(function () {
// your routes here.
});
So even if the user is directly logged in after registration he would not be able to access any routes until he verifies his email.
I'm going to suggest that seeing as you are using Laravel 5.X you should consider upgrading to 5.7 as it comes with a built in email verification system as can be seen here and with middleware functionalities to protect routes (middleware('verified');), events, views and post verification redirection.

Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() redirection on register does not work

I have this on my controller but the redirection does not work it says Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login(), I have tried this so far but nothing
<?php
namespace App\Http\Controllers\Auth;
use App\Events\NewUserWasRegistered;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Validator;
use Auth;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
*
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
$rules = [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'g-recaptcha-response' => 'required|captcha',
'allow_register' => 'required|accepted',
];
if (app()->environment('local') || app()->environment('testing')) {
unset($rules['g-recaptcha-response']);
}
$data['allow_register'] = config('root.app.allow_register', true);
$messages = [
'allow_register.accepted' => trans('app.allow_register'),
];
return Validator::make($data, $rules, $messages);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
*
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'username' => md5("{$data['name']}/{$data['email']}"),
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id' => $data['role'],
]);
event(new NewUserWasRegistered($user));
if($user){
if ($user->role_id == 0) {
Auth::login($user);
return redirect('user/businesses');
}else if($user->role_id == 1){
Auth::login($user);
return 'Working on..';
}
}
// return $user;
}
}
Can someone please help me I am stuck, I have tried so many things but I am new on coding so maybe you will understand If it is that I am asking too much
App\Models\User must implement the interface/contract Illuminate\Contracts\Auth\Authenticatable.
"If you need to log an existing user instance into your application, you may call the login method with the user instance. The given object must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract. Of course, the App\User model included with Laravel already implements this interface ..."
Laravel 5.7 Docs - Authentication - Manually Authenticating Users - Other Authentication Methods
Side Note:
The create method of that controller is only for taking an array of data and creating a new User and returning that User instance. Nothing else. The registration flow out of the box calls that method, only to create the user. It then does the login and everything else.

How to fix Laravel BadMethodCallException when using Entrust

Always getting the
[BadMethodCallException]
This cache store does not support tagging.
when ever i try to run a database command that include the save function it produce this error and i think is because of the Entrust.
On the RegisterController it displays the same error of
[BadMethodCallException]
This cache store does not support tagging.
but it still registers the user. all the same but any other part of the code is halt. How do i fix this error.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
register controller code
Set CACHE_DRIVER=array in your .env file.
Source
To Correct this I went entirely out of Entrust Package and Create a fresh
ROLE PERMISSION MODEL AND TABLE WITH THE SAME SCHEMA
as entrust run the database migration with and use tinker to fill the datas.
NEXT I EDITED THE MIDDLEWARE OF ENTRUST TO SEE MY ROLE, PERMISSION AS
STRINGS
after you create your model. Just to Zizaco\Entrust\Middleware\EntrustRole and just remove the explode function. to this for the other two middlewares

postLogin() method redirection after login in Laravel 5.2

I want my AuthController to check for few conditions and redirect to the respected routes accordingly. I want to check the if the logged in user's DB has particular columns are not empty. If its not empty i am redirecting to home page else I am redirecting to another route. I have used postLogin method. the issue here is its not checking the condition at all and directly redirecting to home even if the condtion fails. I tried to log in with new users whose details in DB are not filled , then also it redirected me to the home page and same happened with user who has his personal details filled in DB
here is the code of my AuthController
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
//protected $redirectTo = '/user-prof';
public function postLogin(Request $request)
{
$email = $request->email;
$user = \Auth::user();
if(($user->username && $user->phone && $user->bio && $user->dobday && $user->dobmonth && $user->dobyear && $user->firstname
&& $user->lastname && $user->topics && $user->nationality)!= NULL)
{
redirect('home');
}
else
{
redirect('/user-prof');
}
return $this->login($request);
}
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
I also want to know if i am checking the DB column data in the right way in IF condition inside the postLogin() method.
You probably mean to do those checks after the user has been 'authenticated' and logged in. You can define a authenticated method on your AuthController that will be called by handleUserWasAuthenticated after the user has been authenticated.
Something like this perhaps. (Get the user's attributes, only get the ones we want to check, use array_filter to remove the nulls, see if all the required fields are there).
protected function authenticated($request, $user)
{
$required = [
'username', 'phone', 'bio', 'dobday', 'dobmonth', 'dobyear',
'firstname', 'lastname', 'topics', 'nationality'
];
$userAtts = array_filter(array_only($user->toArray(), $required));
if (count($userAtts) != count($required)) {
return redirect('/user-prof');
}
return redirect('home');
}
This doesn't change any methods the AuthController already has via the traits, it just adds a method that handleUserWasAuthenticated will check to see if exists, and if so will call it.
Illuminate\Foundation\Auth\AuthenticatesUsers#login -> #handleUserWasAuthenticated
If you intend on 'caging' the user until these fields are filled in, then I would go with a middleware option similar to what #Ravi's answer is saying, but would have to be applied to a lot of routes.
Do not override the method in Authcontroller. Use an after-middleware on postLogin route to check the conditions and route accordingly.
https://laravel.com/docs/5.2/middleware
There is one other way to do it; however, I wouldn't suggest you do it. You may modify the RedirectsUsers trait. It is a Laravel file and will be defaulted back to original at every composer update. Although you can have a look at it to understand the redirection
https://github.com/laravel/framework/blob/5.1/src/Illuminate/Foundation/Auth/RedirectsUsers.php

how can I get email and password at the same time methop post laravel 5.2

I would like to get the email and password when I call AuthController#login method but there isn't in the controller.
My proyect : I want to save all activity from login , the bad passwords , bad email , how many time the user tried to enter to the system and the corrects logins of course .
My model UserActivity have this attributes: email,password,datetime .
I would like to create a new variable and save it userActivity->save(); when I call the POST method login.
I use
php artisan make:auth
but in the AuthController.php i only found that functions.
function __construct
function validator
function create
but i got that route with php artisan route:list command
POST | login | | App\Http\Controllers\Auth\AuthController#login | web,guest |
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
(I created laravel login this way because is easier, but i want to do only that diferent. Sorry my English is bad) .
There is method postLogin in Illuminate/Foundation/Auth/AuthenticatesUsers.php which can be overwritten.
Eg in AuthController add:
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
dd($request->all());
return parent::postLogin($request);
}

Categories