<?php
namespace Tlf\User;
trait UserManagement {
public function login($user){
$didLogin = $this->backend->login($user->model());
if ($didLogin===false)return false;
return true;
}
public function logoutUser(){
$this->backend->logoutUser();
}
/**
* Log a user in (sets cookies) & get that user object
*
* @param array $credentials must contain two keys 'email' and 'password' along with their values
* @return false|Tlf\User returns false if credentials are invalid in any way.
*/
public function logUserIn(array $credentials) {
list('email'=>$email, 'password'=>$password) = $credentials;
$email = $credentials['email'] ?? null;
$password = $credentials['password'] ?? null;
if ($email==null||$password==null)return false;
$model = $this->backend->authenticate($email, $password);
if ($model==null){
return;
}
$didLogin = $this->backend->login($model);
if (!$didLogin) return false;
return new \Tlf\User($model, $this->backend);
}
public function register($email, $name){
$password = $this->randomPassword();
$model = $this->backend->register($email, $name, $password);
if ($model==false)$model = null;
$user = new \Tlf\User($model, $this->backend);
return $user;
}
/**
* Sets the password for the given user. In the event of an error, removes the activation for the user & sets them a new, random password
*
* @param $user a Tlf User object
* @param string $newPassword a password that's already been checked to meet minimum requirements
* @return boolean false if the security-notification email fails to send. true otherwise
*/
public function setPassword($user, $newPassword){
$package = $this->package;
$this->backend->setPassword($user->model(), $newPassword);
// and send a security email to the user, informing them that their password has changed.
$date = date("F j, Y @ g:i a");
$url = $package->get('Site.url');
$name = $package->get('Site.name');
$message = "On {$date}, your password for <a href=\"{$url}\">{$name}</a> was changed.";
$sent = $this->sendEmail(
[ 'to'=> $user->email,
'to.name'=>$user->name,
'subject'=>"Password Changed",
'message'=>$message
]
);
if (!$sent){
$this->backend->removeActivation($user->model());
$this->backend->setPassword($model, $this->randomPassword());
return false;
}
return true;
}
}