Skip to content

Instantly share code, notes, and snippets.

@dsantuc
Last active March 14, 2018 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsantuc/850d05c60800f4d7f424274a2d45bc81 to your computer and use it in GitHub Desktop.
Save dsantuc/850d05c60800f4d7f424274a2d45bc81 to your computer and use it in GitHub Desktop.
Pattern for reusing cookie-based authentication tokens in BeHat
// 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