Skip to content

Instantly share code, notes, and snippets.

@thannaske
Created May 18, 2018 17:59
Show Gist options
  • Save thannaske/7598261602dc5a4b4c1f020d68172c24 to your computer and use it in GitHub Desktop.
Save thannaske/7598261602dc5a4b4c1f020d68172c24 to your computer and use it in GitHub Desktop.
<?php
// [...]
/**
* Generate a random hexadecimal token by hashing the current time in microseconds as float
*
* @return string Random 32-characters long hexadecimal token
*/
public static function generateToken() {
return md5(microtime(true));
}
/**
* Check if the confirmation_token field in the database is NULLed or not
*
* @return bool Whether the user has confirmed his e-mail address or not
*/
public function hasConfirmed() {
return $this->confirmation_token === null ? true : false;
}
/**
* Try to confirm the user's e-mail address using the provided token
*
* @param $token string The user-provided token
* @return bool Whether the confirmation succeed or not.
*/
public function confirm($token) {
// If the user has already confirmed we can't confirm him again.
if ($this->hasConfirmed()) return false;
if ($token === $this->confirmation_token) {
// User has confirmed his e-mail address.
$this->confirmation_token = null;
$this->confirmed_at = \Carbon\Carbon::now();
$this->save();
return true;
}
// Token was incorrect.
return false;
}
/**
* Try to unconfirm the user's e-mail address
*
* @return bool Whether the unconfirmation succeed or not.
*/
public function unconfirm() {
// If the user is not even confirmed we can't unconfirm him.
if (!$this->hasConfirmed()) return false;
// Reset token with a newly generated one and save the model.
$this->confirmation_token = User::generateToken();
$this->confirmed_at = null;
$this->save();
return true;
}
// [...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment