Laravel multi authetification with different users tables - laravel

I'm trying to build a multiple authentification in laravel with different tables (2 tables) for admin and user. The problème is that the registration and login forms work only with default auth login/register.
I've tried some examples form web tutorials but it didn't work.
HomeController.php:
public function __construct() {
$this->middleware('auth');
}
public function index() {
return view('home');
}
I have added createAdmin function in "Auth/RegisterController.php":
protected function createAdmin(array $data)
{
$this->validator($data->all())->validate();
$admin = Admin::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
return redirect()->intended('login/admin');
}
I have changed email validation rules to:
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'|'unique:admins']
And the route (web.php) is:
Route::post('/register/admin', 'Auth\RegisterController#createAdmin');
When I fill admin register credentials and click register button I get this message:
Symfony\Component\Debug\Exception\FatalThrowableError Too few arguments to function App\Http\Controllers\Auth\RegisterController::createAdmin(), 0 passed and exactly 1 expected

The error is coming from the array $data parameter in your createAdmin() controller method.
Usually, you want to use one of two types of parameters in your controller methods: route parameters or injected dependencies. The $data parameter isn't matching either of those, so Laravel doesn't know to provide it.
If you'd like to access the request (POST) data in the controller, you can either ask for an instance of Illuminate\Http\Request as a parameter:
// Import it at the top of your PHP file
use Illuminate\Http\Request;
// Then your updated method:
public function createAdmin(Request $request)
{
$data = $request->all();
// ...
}
Or, use the request() helper directly:
public function createAdmin()
{
$data = request()->all();
// ...
}

Related

How to remove Laravel Auth Hashing (to replace it by mysql hashing)?

I added registration, and I don't want to using laravels hash but mysql Hash (because I want existing users to still be able to connect).
So i do it step by step and for now I just try to register and then login without any hashing. The credentials are correct in my table but I get
"message":"The given data was invalid.","errors":{"email":["These credentials do not match our records."]}
I tried setting it in LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
public function username()
{
return 'email';
}
public function password()
{
return 'email';
}
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
public function Login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'pwd' => $request->password, 'password' => $request->password])){
$user = Auth::user();
$username = $user->nom;
return response()->json([
'status' => 'success',
'user' => $username,
]);
} else {
return response()->json([
'status' => 'error',
'user' => 'Unauthorized Access'
]);
}
}
}
I guess I should overwrite another function, but can't find out which one.
Could you please give me some help?
Altough what you're trying to achieve is considered unsecure, to remove Laravel's hashing for password, you need to add this to your User model :
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
and not in your controller, and be sure to remove the brcypt() methods in your RegisterController
To add your MySQL own hashing methods, update your controller to insert a RAW query while creating a user upon registration

Customise Reset Password Email and pass User Data in Laravel 5.3

I am using Laravel 5.3 and customizing the Password Reset Email Template. I have done the following changes to create my own html email for the notification using a custom Mailable class. This is my progress so far:
ForgotPasswordController:
public function postEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return Response::json(['status' => trans($response)], 200);
case Password::INVALID_USER:
return Response::json(['email' => trans($response)], 400);
}
}
User Model:
public function sendPasswordResetNotification($token)
{
Mail::queue(new ResetPassword($token));
}
ResetPassword Mailable Class:
protected $token;
public function __construct($token)
{
$this->token = $token;
}
public function build()
{
$userEmail = 'something'; // How to add User Email??
$userName = 'Donald Trump'; // How to find out User's Name??
$subject = 'Password Reset';
return $this->view('emails.password')
->to($userEmail)
->subject($subject)
->with([
'token' => $this->token
'userEmail' => $userEmail,
'userName' => $userName
]);
}
If you noticed above, I am not sure how do I pass the user's name and find out the user's email address. Do I need to send this data from the User Model or do I query it from the Mailable class? Can someone show me how I can do that please?
Usually you ask for the user email in order to send a reset password email, that email should come as a request parameter to your route controller.
By default, L5.3 uses post('password/email) route to handle a reset password request. This route execute sendResetLinkEmail method which is defined in the 'SendsPasswordResetEmails' trait used by the App\Http\Controllers\Auth\ForgotPasswordController.
From here you can take one of 2 options:
1st: You could overwrite the route to call another function in the same controller (or any other controller, in this case could be your postEmail function) which search for the user model by the email you received, then you can pass the user model as function parameter to the method which execute the queue mail action (this may or may not require to overwrite the SendsPasswordResetEmails, depends on how you handle your reset password method).
This solution would looks something like this:
In routes/web.php
post('password/email', 'Auth\ForgotPasswordController#postEmail')
in app/Mail/passwordNotification.php (for instance)
protected $token;
protected $userModel;
public function __construct($token, User $userModel)
{
$this->token = $token;
$this->userModel = $userModel;
}
public function build()
{
$userEmail = $this->userModel->email;
$userName = $this->userModel->email
$subject = 'Password Reset';
return $this->view('emails.password')
->to($userEmail)
->subject($subject)
->with([
'token' => $this->token
'userEmail' => $userEmail,
'userName' => $userName
]);
}
in app/Http/Controllers/Auth/ForgotPasswordController
public function postEmail(Request $request)
{
$this->validate($request, ['email' => 'required|email']);
$userModel = User::where('email', $request->only('email'))->first();
Mail::queue(new ResetPassword($token));
//Manage here your response
}
2nd: You could just overwirte the trait SendsPasswordResetEmails to search for the user model by the email and use your customized function in sendResetLinkEmail function. There you could use your function but notice that you still have to handle somehow an status to create a response as you already have it on ForgotPasswordController.
I hope it helps!

Login using laravel5.2

Hi I'm new to laravel and I'm using the laravel5.2 version.
Actually I have this registration form too. But no problem in registration.
My question is that I'm looking for a simple and understandable code in login. I've seen it somewhere while googling but I think that one is not laravel5.2.
I just get the reference code in some examples and test it into my login app. I'm using a repositories on it. I've got some errors. It says
Whoops, looks like something went wrong.
1/1 FatalErrorException in EloquentUserProvider.php line 126: Class '\App\User' not found
I'm not sure why the error says app user not found. Here is my code below
<?php
namespace App\Repositories;
use App\Repositories\Contracts\loginRepositoryInterface;
use Illuminate\Http\Request;
use App\Users;
use DB;
use Session;
use Auth;
class loginRepository implements loginRepositoryInterface{
protected $request;
//Initialize request instance
public function __construct(Request $request){
$this->request = $request;
}
public function loginAuth(){
//validate login
$validator = app('validator')->make($this->request->all(), [
'emailAddress' => 'email|required',
'password' => 'required']);
//if validator fails then return response error
if($validator->fails())
return redirect()->route('get.login')->withErrors($validator)->withInput();
try{
$pwd = $this->request->get('password');
$sha1 = sha1($pwd);
$userdata = array(
'emailAddress' =>$this->request->get('emailAddress'),
'password' =>$sha1
);
if(Auth::attempt($userdata)){
return redirect()->intended('get.dashboard');
}else{
return redirect()->route('get.login')->withErrors($validator)->withInput();
}
}catch(\Exception $e){
return redirect()->route('get.login')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
//postCreate
public function postCreate($screen){
switch($screen){
case 'auth':
return $this->loginAuth();
break;
}
}
//getLoginView
public function getCreate(){
return view('login');
}
}
In method public function loginAuth()
My routes
//postLogin
Route::post('/login/{screen}', [
'as' => 'post.login.auth',
'uses' => 'loginController#postCreate'
]);
//getLoginView
Route::get('/login', [
'as' => 'get.login',
'uses' => 'loginController#getCreate'
]);
Can some one help me on this?
Thanks.
Make sure you have the \App\User model in app/User.php from the looks of the code you posted above, you seem to have \App\Users not \App\User

Laravel 5 Auth - Change Login Route

I'm trying to redirect my user to 'homepage' after successful login.
I've been able to redirect after logout by adding the following to AuthController:
protected $redirectAfterLogout = 'homepage';
However, adding the following to AuthController does not work after login. It directs me to 'home."
protected $redirectPath = 'homepage';
I then changed the default redirect in the handle() function in RedirectIfAuthenticated to:
return redirect('homepage');
Not only does that not work, it gives me the following error:
This webpage has a redirect loop
ERR_TOO_MANY_REDIRECTS
Does anyone know how I can achieve redirecting to 'homepage' after login?
Edit - Adding Routes:
Route::get('/', function () {
return view('welcome');
});
Route::get('home', 'HomepageController#getIndex');
Route::get('homepage', 'HomepageController#getIndex');
Thanks for any guidance!
Dude the attribute should be named as $redirectTo:
$redirectTo = "homepage";
now if you got more than one rule like admin and user, stored within your user model as type field, you may override the value of this attribute within postLogin() function, override the function first then do your changes. i.e:
// AuthController.php
/**
* #param Request $request
* #return $this|\Illuminate\Http\RedirectResponse
*/
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if ($this->auth->attempt($credentials, $request->has('remember')))
{
$user=User::find($this->auth->user()->id);
if($user->type == "ADMIN")
$this->redirectTo = "/dashboard";
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
I got around this by simply modifying the existing Route::get('/') to the following:
Route::get('/', 'HomepageController#getIndex');
I really didn't need the Welcome View any longer, so this solution made the most sense.
Also, after modifying this Route, I was able to remove my previous 'home' and 'homepage' Routes.

Laravel 5.1 multiple authentication

How can you authenticate multiple types of users in Laravel 5.1 e.g. Jobseeker, Recruiter, Admin etc.
Some of you have suggested using a single users table to store only the password and email, creating profile tables to store user specific information (jobseeker_profile, recruiter_profile) and using roles to differentiate between the different types of users (i.e having a roles and role_user) table.
This is all very well but then what if the different types of users have different registration and login forms. How do you customize the default auth controller out of the box to display the correct view?
So if I have the following routes:
// Jobseeker Authentication routes...
Route::get('auth/login', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
// Jobseeker Registration routes...
Route::get('auth/register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
// Recruiter Authentication routes...
Route::get('recruiter/auth/login', 'Auth\AuthController#getLogin');
Route::post('recruiter/auth/login', 'Auth\AuthController#postLogin');
Route::get('recruiter/auth/logout', 'Auth\AuthController#getLogout');
// Recruiter Registration routes...
Route::get('recruiter/auth/register', 'Auth\AuthController#getRegister');
Route::post('recruiter/auth/register', 'Auth\AuthController#postRegister');
This is the default auth controller out of the box:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
traits used by the default out of the box auth controller:
trait AuthenticatesUsers
{
use RedirectsUsers;
public function getLogin()
{
return view('auth.login');
}
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email', 'password' => 'required',
]);
$credentials = $this->getCredentials($request);
if (Auth::attempt($credentials, $request->has('remember'))) {
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
}
public function loginPath()
{
return property_exists($this, 'loginPath') ? $this->loginPath : '/auth/login';
}
}
trait RegistersUsers
{
use RedirectsUsers;
public function getRegister()
{
return view('auth.register');
}
public function postRegister(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::login($this->create($request->all()));
return redirect($this->redirectPath());
}
}
I'm sure this is a very common requirement for many web applications but I can't find any helpful tutorials for Laravel specific implementations. All the tutorial simply focus on the out of the box implementation for some odd reason.
Any help on the above would be much appreciated.
This is not a solution to your question directly, but alternative way to solve your question problem with.
In stead of creating different username and password for different groups, make a central authentication that has roles. It called user and roles.
You can define groups with different roles, and each roles has specific access to respective area.
Regarding registration process you can make two differnet views but using the same controller, and for each view you can create a hidden field to indicate if it is jobseekers group or recruiter group.
Both will receive two different confirmation emails where they should fill the rest of the profile information, like recruiter should put company name and jobseeker should put his name etc. they might have two different tables for profile information, but still using the same login system.
By adding condition to middleware and correct route, if jobseeker tries to access recruiter area even if jobseeker is logged in the system, the jobseeker won't be able to access that area or the opposite way.
Since Laravel 5.1 has build in user login system, so you have few choices, build your own roles or use 3rd party.
I suggest you to build your own so you have control over your code and can further develop it as you wish with time. It might take you half day to get it run and understand how it works, but it is worth spending that time with the right approach in stead of the way you go in your Question OR using 3rd party is fine too, there is a lot of packages around you can search for. I have personally used Entrust (https://github.com/Zizaco/entrust) it is easy and nice way to provide roles and permissions to your project.
Here is also a link to video developed by Jeffrey Way at Laracast, it builds user and roles system from scratch for Laravel 4. but since you have user part, just follow roles part and with small modifications you will have a roles system to your Laravel 5.1, I have tried it and it works.
Regarding your question in the comments, when you follow the video you will understand the concept.
Link to the video: https://laracasts.com/lessons/users-and-roles
You might need to create account to see the video, most of videos are free.
Good practice
It is always also a good practice to illustrate what you want to achieve that makes things easier, I have just made an example for your project, but that is only example for learning:
I encourage you to read some of the topics regarding roles, here you will also find some inspiration to 3rd party acl systems to Laravel, there might be more articles but here is some:
Reading:
https://laracasts.com/discuss/channels/laravel/which-package-is-best-for-roles-permissions/?page=2
https://laracasts.com/discuss/channels/general-discussion/laravel-5-user-groups-management
https://laracasts.com/discuss/channels/general-discussion/roles-and-permissions-in-laravel-5
EDIT
Important Note
Laravel 5.1 has introduced Authorization, I have not found much documentation online yet but it is worth to spend some time learning it:
http://laravel.com/docs/5.1/authorization#policies
NEW UPDATE
There are some great videos solution for what you asking, follow ACL parts here
https://laracasts.com/series/whats-new-in-laravel-5-1
This might be very interesting too:
https://laracasts.com/lessons/email-verification-in-laravel
This will give you a complete own developed solution.
You can achieve multiple authentication easily by pulling up the sarav/laravel-multiauth package
composer require sarav/laravel-multiauth
I assume you have separate tables for Jobseeker, Recruiter, Admin.
Step 1 : Open app.php and replace
Illuminate\Auth\AuthServiceProvider::class
with
Sarav\Multiauth\MultiauthServiceProvider::class
Then, open up auth.php file and remove
<?php
return [
'driver' => 'eloquent',
'model' => 'App\User::class',
'table' => 'users',
'password' => [
'email' => 'emails.password',
'table' => 'password_resets',
'expire' => 60,
],
];
and add the following code
return [
'multi' => [
'jobseeker' => [
'driver' => 'eloquent',
'model' => App\Jobseeker::class, // Model Class
'table' => 'jobseeker' // jobseeker table
],
'recruiter' => [
'driver' => 'eloquent',
'model' => App\Recruiter::class, // Model Class
'table' => 'recruiter' //recruiter table
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class, // Model Class
'table' => 'admin' //admin table
],
],
'password' => [
'email' => 'emails.password',
'table' => 'password_resets',
'expire' => 60,
]
];
Thats it!
Now you can try login attempt by calling
\Auth::attempt('jobseeker', ['email'=> 'johndoe#example.com', 'password' => 'secret']);
\Auth::attempt('recruiter', ['email'=> 'johndoe#example.com', 'password' => 'secret']);
\Auth::attempt('admin', ['email'=> 'johndoe#example.com', 'password' => 'secret']);
Always remember first paramter should be your user parameter. Here I have given jobseeker for jobseeker login attempt, recruiter for recruiter attempt and admin for admin login attempt. Without the proper first parameter system will throw exception.
For more detailed information checkout this article
http://sarav.co/blog/multiple-authentication-in-laravel-continued/
Short Answer: Add user types to your users table with specific number.
TL;DR answer.
Long Answer:
If you have migrated your table, just run php artisan migrate:rollback.
Add following line to your migration table for users:
$table->integer("user_type")->default(0);
Here I am considering that user type zero is just a simple JobSeeker.
And in your form, you can add option with value zero and one such that people will be selecting what they want to be like recruiter. There is no need of other
As another solution, i can suggest you to use a polymorphic relation between User and Account, like
class User extends Eloquent {
...
public function account() {
return $this->morphTo();
}
}
class Account extends Eloquent {
...
public function user() {
return $this->morphOne(App\User::class, 'account');
}
}
class JobSeeker extends Account { ... }
class Recruiter extends Account { ... }
For different types of Account, you can use route prefixes and different auth controllers, specially for registration who differs for each account instances :
// Recruiter Authentication routes...
Route::group(['prefix' => 'recruiter'], function() {
Route::controller('auth', 'Auth\RecruiterAuthController');
});
At last, you can access the authenticated account directly from auth()->user()->account. it will return any instance of Account (Recruiter, Admin, ....)
hope it helps you ;)
I will try to explain how authentication is managed in Laravel 5.1
On application start AuthServiceProvider is called, which calls registerAuthenticator() function in which new AuthManager is created.
AuthServiceProvider -> registerAuthenticator() -> new AuthManager()
On manager create createNameDriver function will be called in which new nameProvider will be created, where name is your auth driver selected in auth config file. Then in that function new Guard will be created and nameProivder will be passed to its contractor. All auth functions in that Guard will use functions from that provider to manage auth. Provider implements UserProvider which has
retrieveById($identifier),
retrieveByToken($identifier, $token),
updateRememberToken(Authenticatable $user, $token),
retrieveByCredentials(array $credentials),
validateCredentials(Authenticatable $user, array $credentials)
functions.
Main idea of managing multi auth in Laravel 5.1 is to create new AutServiceProvider and on its boot pass app auth new AuthModelProvider which functions then will be used in same Guard. In AuthModelProvider you can manage all retrieve functions the way you need.
Here is all changed I've made to manage multi auth. My project name is APC, that's why I use it everywhere.
Add this function to your models
public function getAuthIdentifier()
{
return [self::MODULE_NAME => $this->getKey()];
}
Create AuthServiceProvider in Provider/YourProjectName directory. In boot function we extend auth from our new provider AuthModelProvider.
<?php
namespace App\Providers\Apc;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Hashing\BcryptHasher;
class AuthServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
self::getAuthModels();
$this->app['auth']->extend('apc', function() {
return new AuthModelProvider(self::getAuthModels(), new BcryptHasher());
});
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
}
public static function getAuthModels()
{
$configModels = config('auth.models');
$authModels = [];
foreach ($configModels as $key => $class) {
$authModel = new $class();
$authModels [$key]= $authModel;
}
return $authModels;
}
}
Create AuthModelProvider in same directory. Diff in my models is existence of login field in company table. But you can be more specific if you want. In retrieveByCridentials function I just look for existence of login and choose my model accordingly.
<?php
namespace App\Providers\Apc;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Support\Str;
class AuthModelProvider implements UserProvider
{
protected $users;
protected $hasher;
public function __construct($usersModels, HasherContract $hasher)
{
$this->users = $usersModels;
$this->hasher = $hasher;
}
/**
* Retrieve a user by their unique identifier.
*
* #param mixed $identifier
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveById($identifiers)
{
foreach ($identifiers as $key => $id) {
if (isset($this->users[$key])) {
return $this->users[$key]->where('id', $id)->active()->base()->first();
}
}
}
/**
* Retrieve a user by their unique identifier and "remember me" token.
*
* #param mixed $identifier
* #param string $token
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByToken($identifiers, $token)
{
return null;
$user = $this->getUserByIdentifier($identifiers);
if ($user) {
return $user->where($user->getRememberTokenName(), $token)->active()->first();
}
}
/**
* Update the "remember me" token for the given user in storage.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param string $token
* #return void
*/
public function updateRememberToken(Authenticatable $user, $token)
{
$user->setRememberToken($token);
$user->save();
}
/**
* Retrieve a user by the given credentials.
*
* #param array $credentials
* #return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials)) {
return null;
}
if (isset($credentials['login'])) {
$userModel = $this->users['company'];
} else {
$userModel = $this->users['user'];
}
$query = $userModel->newQuery();
foreach ($credentials as $key => $value) {
if (! Str::contains($key, 'password')) {
$query->where($key, $value);
}
}
return $query->first();
}
/**
* Validate a user against the given credentials.
*
* #param \Illuminate\Contracts\Auth\Authenticatable $user
* #param array $credentials
* #return bool
*/
public function validateCredentials(Authenticatable $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
private function getUserByIdentifier($identifiers)
{
if (!$identifiers) {
}
foreach ($identifiers as $namespace => $id) {
if (isset($this->users[$namespace])) {
return $this->users[$namespace];
}
}
return null;
}
}
Add AuthServiceProvider to app conf file.
\App\Providers\Apc\AuthServiceProvider::class,
Make this changes to auth conf file.
'driver' => 'apc',
'models' => [
\App\Apc\User\User::MODULE_NAME => \App\Apc\User\User::class,
\App\Apc\Company\Company::MODULE_NAME => \App\Apc\Company\Company::class
],
That's all. Hope it was helpful.

Resources