<?php
namespace Koselig\Auth;
use Illuminate\Auth\GuardHelpers;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Support\Facades\Request;
use Koselig\Models\User;
use Koselig\Support\Action;
use WP_Error;
class WordpressGuard implements StatefulGuard
{
use GuardHelpers;
private $lastAttempted = null;
public function check()
{
return is_user_logged_in();
}
public function user()
{
if (!is_null($this->user)) {
return $this->user;
}
return $this->user = ($this->check() ? User::find(get_current_user_id()) : null);
}
public function validate(array $credentials = [])
{
$user = wp_authenticate($credentials['username'], $credentials['password']);
$this->lastAttempted = User::find($user->ID);
return !($user instanceof WP_Error);
}
public function attempt(array $credentials = [], $remember = false, $login = true)
{
$validate = $this->validate($credentials);
if (!$login) {
return $validate;
}
$user = $this->lastAttempted;
wp_set_auth_cookie($user->ID, $credentials['remember'], Request::secure());
Action::trigger('wp_login', $user->user_login, $user);
$this->setUser($user);
return true;
}
public function once(array $credentials = [])
{
if ($this->validate($credentials)) {
$this->setUser($this->lastAttempted);
return true;
}
return false;
}
public function login(Authenticatable $user, $remember = false)
{
wp_set_auth_cookie($user->ID, $remember);
Action::trigger('wp_login', $user->user_login, get_userdata($user->ID));
wp_set_current_user($user->ID);
$this->user = $user;
}
public function loginUsingId($id, $remember = false)
{
$user = User::find($id);
if (!$user) {
return false;
}
wp_set_auth_cookie($user->ID, $remember);
Action::trigger('wp_login', $user->user_login, get_userdata($user->ID));
wp_set_current_user($user->ID);
return $this->user = $user;
}
public function onceUsingId($id)
{
$user = User::find($id);
if (!$user) {
return false;
}
wp_set_current_user($id);
return $this->user = $user;
}
public function viaRemember()
{
return Request::hasCookie(Request::secure() ? SECURE_AUTH_COOKIE : AUTH_COOKIE);
}
public function logout()
{
wp_logout();
$this->user = null;
}
public function setUser(Authenticatable $user)
{
wp_set_current_user($user->ID);
$this->user = $user;
return $this;
}
}