Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Laravel's Auth user

Tags:

laravel-4

I'm using Laravel's Auth class to authenticate users on my site, basic Auth::attempt(...) stuff.

Recently there has been a new requirement (yay stakeholders!) and now there's a need for users to create new users (secondary users). Since the login of the main users goes through a third party system, there's no way I can store the secondary users with the main users (and re-use the current authentication system).

What I thought of was to somehow tell the Auth class to login and forcefully set the user on the Auth::user() method.

Is there a way to do this?

like image 355
Ben Avatar asked Jul 03 '14 20:07

Ben


1 Answers

EDIT

In order to do so you have to use in your secondary user's model the UserInterface class

use Illuminate\Auth\UserInterface;

Then you need to implement the 5 required methods: getAuthIdentifier, getAuthPassword, getRememberToken, setRememberToken and getRememberTokenName.

Since apparently config > auth can't be changed on run time, you'll have to check the user's credentials manually, get the instance and do Auth::login($secondaryUser).

<?php

use Illuminate\Auth\UserInterface;

class SecondaryUser extends Eloquent implements UserInterface {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'secondary_users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password');

    /**
     * Get the unique identifier for the secondary user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Get the password for the secondary user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->password;
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken()
    {
        return $this->remember_token;
    }

    /**
     * Set the token value for the "remember me" session.
     *
     * @param  string  $value
     * @return void
     */
    public function setRememberToken($value)
    {
        $this->remember_token = $value;
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName()
    {
        return 'remember_token';
    }

    public function mainUser()
    {
        return $this->belongsTo('User');
    }

}

ORIGINAL ANSWER

I'm not sure to have understood what you wanted, but maybe this can help: http://laravel.com/docs/security#manually

$user = User::find(1);
Auth::login($user);

And if you have 2 user models, I think it should work as long as they extend the main User class

like image 154
punkeel Avatar answered Oct 20 '22 05:10

punkeel