Laravel 5 multiple authentication - authentication

How can you set up multiple authentication in Laravel 5. Out of the box you can only set up 1 authentication. What if I have a customers table and an admin table and wish to set up authentication for each - each authenticated type of user should be restricted from viewing or accessing admin pages and vis versa?
* UPDATE *
I've created a users table which holds information common to both a jobseeker and recruiter i.e. name, password etc.
I've created a roles and role_user table
I've created two separate tables to hold jobseeker_profile and recruiter_profile
How can you authenticate a user with a role of type jobseeker using the following routes?
Route::get('jobseeker/login', 'Auth\AuthController#getLogin');
Route::post('jobseeker/login', 'Auth\AuthController#postLogin');
Route::get('recruiter/login', 'Auth\AuthController#getLogin');
Route::post('recruiter/login', 'Auth\AuthController#postLogin');
And how can you secure routes once authenticated - in the following how is the middleware going to know the type of user:
Route::get('jobseeker/profile', ['middleware' => 'auth', 'uses' => 'JobseekerProfileController#show']);
Route::get('jobseeker/profile/update', ['middleware' => 'auth', 'uses' => 'JobseekerProfileController#updateProfile']);
class JobseekerProfileController extends Controller {
public function updateProfile()
{
if (Auth::user())
{
// Auth::user() returns an instance of the authenticated user...
}
}
}
Laravel 5 authentication controller uses the following trait -would you edit the trait with your answer or create a new authentication controller with your answer below?
trait AuthenticatesAndRegistersUsers {
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')))
{
return redirect()->intended($this->redirectPath());
}
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => 'These credentials do not match our records.',
]);
}
}

You may create a roles table in your db assign role to every user accordingly and then at the time of login check what role a user have and then you can redirect/show pages accordingly. No need to create separate tables for every type of user.
Edited answer
if(Auth::attempt(['email' => $request->email, 'password' => $request->password]))
{
//using role with an expectation that you have one relation method named role defined in User model
//and roles table stores user type as name
if(Auth::user()->role->name == 'admin')
{
return redirect()->to('/administrator/dashboard');
}
elseif(Auth::user()->role->name == 'jobseeker')
{
return redirect()->to('jobseeker/dashboard');
}
}

You can achieve multiple authentication by this package
https://packagist.org/packages/sarav/laravel-multiauth
For more detailed explaination check my previously return answer here
How to use authentication for multiple tables in Laravel 5

Related

How to send user login credentials after user registers

I am using laravel's default login and registration. I have successfully set up authentication, however I would like to send user's username and password to the emails they used during registration. How can I achieve this?
You can initiate a mail to user after you validated input received and before your create functions of your register controller present in
$email = new UserRegisterData(new User(['password' => $user->password, 'name' => $user->name]));
To do this you need to rewrite
protected function validator(array $data)
function in your register controller and modify that with this mail. as
protected function validator(array $data)
{
$email = new UserRegisterData(new User(['password' => $user->password, 'name' => $user->name]));
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:customers',
'password' => 'required|min:6|confirmed',
]);
}
once you hashed your password in create function, i think it can't be read. Also check if any security issue it may generate. Also you need to create mail as 'UserRegisterData' and add necessary code in it.

Get user details in Yii framework

I am new to Yii framework and I want to get the user details of current logged in user like userid, username & his avatar and want to add that data in the head tag. I am using basic version on Yii.
How can I get this details?
Yii handles user data in the session using the IdentityInterface.
Let's go step by step.
You can create a class, call it User, which implements IdentityInterface. If connected with the database you can extend it to ActiveRecord, totally up to your architecture.
class User extends ActiveRecord implements IdentityInterface
{
...
}
Add the configuration details into the config file, main.php. I work on advance template, thus its located into fronted/config. Check it for the basic one.
'components' => [
...
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
....
];
This tells the app to get the user session details form the common\model\User class. Its in common as I use the same class for backend and the frontend, which is not the case in the basic template.
Make user login into the app
When you get the object of the User class, with valid username and password, use the following code to login the user.
Yii::$app->user->login($user);
To get the value of the user you have following sample
Yii::$app->user->isGuest - This tells you whether the user is logged in or not.
Yii::$app->user->id - Get the id of the user
Yii::$app->user->identity->name - Yii::$app->user->identity will give you access to the entire object of the User class. If you have any other attributes, use the identity and get those. Example, you can have 'avatar', which stores the avatar url, you can get it by Yii::$app->user->identity->avatar.
Finally to logout
Yii::$app->user->logout();
Use the setState method.
In your UserIdentity.php:
public function authenticate()
{
$user=User::model()->find('LOWER(username)=?',array(strtolower($this->username)));
if($user===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if(!$user->validatePassword($this->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id=$user->id;
$this->username=$user->username;
$this->setState("userid",$user->user_id);// set States like this
$this->setState("username",$user->username);
$this->setState("avatar",$user->avatar );
$this->errorCode=self::ERROR_NONE;
}
return $this->errorCode;
}
Now anywhere get these like:
$userid = Yii::app()->user->getState('userid');

allow both username and email in login laravel 5

I use laravel's 5 built in authentication for login. im spending hours finding where is the database query located at that has been use when login, I want to both allow email and username is the email box. Anyone knows where that database query located at? anyone knows how to allow both username and password on the authentication.
PS: to sharpen the details, I just want the user to allow them to login both username and email.
PS: again! Im running on laravel 5 not 4!
Define both a login and an password input in your form then the request should look like :
public function authorize() {
return true;
}
public function rules()
{
return [
'login' => 'required',
'password' => 'required'
];
}
Then your login function should look like :
public function login(LoginRequest $request)
{
$field = filter_var($request->input('login'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input('login')]);
if ($this->auth->attempt($request->only($field, 'password')))
{
return redirect('/');
}
return redirect('/login')->withErrors([
'error' => 'You email/username or password combination is wrong.',
]);
}
This is an optimized version because instead of doing 2 attemps to verify the credentials for both : if is a username or if is a password, laravel will do the work with verifying if the given data points to an email login or username.

How to do a Sign Up with OAuth (facebook, twitter, google)?

I use Laravel (5) as my php framework, it recently added a library for social authentication (facebook, google, twitter and github).
I've been wondering how would you do a Sign Up with OAuth, a login can easily be done by getting the user's email via OAuth, checking if it exists in your DB, and if it does, then log in that user. But how would you do the Sign Up?
Mathius - I've recently been working on a site doing something similar to what you've described and this is what has worked for me:
public function syncUserDetails($userData)
{
// First I check to see if there is a user in the DB
// with the oAuth email address
if ( $user = $this->user->where('email', $userData->email)->first() )
{
// If there is a user, I simply update their local info
// with what is on their oAuth account
$user->token = $userData->token;
$user->google_id = $userData->id;
$user->name = $userData->name;
$user->avatar = $userData->avatar;
$user->first_name = $userData->user['given_name'];
$user->last_name = $userData->user['family_name'];
$user->save();
return $user;
}
// Otherwise, if the user doesn't already exist,
// I create them in my local user's DB
return $this->user->firstOrCreate([
'email' => $userData->email,
'token' => $userData->token,
'google_id' => $userData->id,
'name' => $userData->name,
'avatar' => $userData->avatar,
'first_name' => $userData->user['given_name'],
'last_name' => $userData->user['family_name']
]);
}
This is what I'm using to log in a user. However, you could just as easily run this alongside your regular Laravel login method.

Use joomla user table with cakephp

i have working joomla project (domain.kz).
and i need to build new independent project on subdomain (newapp.domain.kz)
but i want to use joomla user table. (to let user auth with joomla logins)
can i declare in user model the joomla jos_users fields
is it possible to use 2 DB (old one for auth, the new one for new app)
Create a new database config in app/config/database.php, then create your model as normal:
var $joomla_connection = array('driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => 'password!',
'database' => 'joomla_db',
'prefix' => 'jos_'); // I think this is correct
class User extends AppModel {
var $name = 'User';
var $useDbConfig = 'joomla_connection';
//your code here
//....
}
you will might experience problems with Auth when you login with the "security_salt" and "cipher" from cake against the user login data, that are created through joomla.
if Joomla saves md5 encrypted passwords you can modify cakestandard encryption with this:
change hash function - cake cookbook