Last active
March 14, 2018 21:53
-
-
Save dsantuc/850d05c60800f4d7f424274a2d45bc81 to your computer and use it in GitHub Desktop.
Pattern for reusing cookie-based authentication tokens in BeHat
This file contains 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
// in FeatureContext.php | |
// Store session tokens for reauthentication | |
private static $credentialStore = array(); | |
// ... other code ... | |
/** | |
* Authenticates a user with password from configuration. | |
* | |
* @Given /^I am logged in as "([^"]*)"$/ | |
*/ | |
public function iAmLoggedInAs($username) { | |
if ($authCookie = $this->getCredentials($username)) { | |
echo "Reusing authentication tokens for $username"; | |
$this->setAuthCookie($authCookie); | |
} | |
else { | |
$password = $this->fetchPassword($username); | |
$this->doLogin($username, $password); | |
} | |
} | |
public function doLogin ($username, $password) { | |
// Visit login page, enter credentials, submit login form... | |
// ... after successful login: | |
$this->storeCredentials($username); | |
} | |
public function storeCredentials ($username) { | |
if ($credential = $this->getAuthCookie()) { | |
self::$credentialStore[$username] = $credential; | |
} | |
} | |
public function getCredentials ($username) { | |
return array_key_exists($username, self::$credentialStore) ? self::$credentialStore[$username] : null; | |
} | |
public function getAuthCookie () { | |
// Return key=>value pair for session authentication token | |
} | |
public function setAuthCookie ($authCookie) { | |
$this->getSession()->setCookie($authCookie['name'], $authCookie['value']); | |
} | |
public function fetchPassword ($username) { | |
// Return user's password, looked up from configuration | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment