Created
October 9, 2015 03:03
-
-
Save stones/6191fe378f7b0051a9da to your computer and use it in GitHub Desktop.
A login script for laravel 5.1 and behat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Encryption\Encrypter; | |
trait Auth | |
{ | |
/** | |
* @Given I am not not logged in | |
*/ | |
public function iAmNotNotLoggedIn() | |
{ | |
return \Auth::guest(); | |
} | |
/** | |
* | |
* @Given I am logged in as an :userLevel | |
*/ | |
public function iAmLoggedInAsAn( $userLevel ) | |
{ | |
$user = $this->getUserOfType( $userLevel ); | |
$this->logInUser( $user ); | |
} | |
/** | |
* @param $userLevel | |
* | |
* @TODO Allow this to be overridden | |
* @return mixed | |
*/ | |
private function getUserOfType( $userLevel ) | |
{ | |
switch (strtolower( $userLevel )) { | |
case 'admin': | |
$type_id = '0'; | |
break; | |
default: | |
$type_id = '100'; | |
} | |
//Get the user to login | |
return \User::where( 'account_type', $type_id )->first(); | |
} | |
/** | |
* Log a user in and set a cookie | |
* | |
* @param $user | |
*/ | |
private function logInUser( $user ) | |
{ | |
$name = $this->getAuthCookieName(); | |
$value = $this->getAuthCookieValue( $user ); | |
$this->getSession()->setCookie( $name, $value ); | |
} | |
/** | |
* Generate the cookie name as Laravel does in the Gaurd class | |
* | |
* @return string | |
*/ | |
private function getAuthCookieName() | |
{ | |
return 'remember_' . md5( 'Illuminate\Auth\Guard' ); | |
} | |
/** | |
* Get the laravel authentication cookie | |
* | |
* @param $user | |
* | |
* @return string | |
*/ | |
private function getAuthCookieValue( $user ) | |
{ | |
$key = \Config::get( 'app.key' ); | |
$cipher = \Config::get( 'app.cipher' ); | |
$encrypter = new Encrypter( $key, $cipher ); | |
//The remember token needs to be set for this to work | |
$token = $user->getRememberToken(); | |
//If you cannot afford a token, one will be provided for you :D | |
if (empty( $token )) { | |
$user->setRememberToken( str_random( 60 ) ); | |
$user->save(); | |
} | |
//The cookie value is the "user ID | Remember token" | |
$value = $user->getAuthIdentifier() . '|' . $user->getRememberToken(); | |
//return the encrypted value | |
return $encrypter->encrypt( $value ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment