<?php
namespace Extension;
 use TCMS\AuthExtension;
 use TCMS\TException;
 use Cookie;
 use Session;
 use Hash;
 class AdminAuthDefault extends AuthExtension {
 private $option = [ 'isRememberMe' => false ];
 public function __construct() {
 \Model::add('UserModel');
 $this->loginUrl = url('/login');
 }
 public function login(string $username, string $password, ?array $option = null) {
 copy_option($this->option, $option);
 $userModel = \Model::load('UserModel');
 if(!$userModel) {
 throw new TException('Không tìm thấy UserModel', 501);
 }
 $user = $userModel->select('id', 'name', 'password', 'group_id')->where('username', $username)->first();
 if($user) {
 include_library('Hash');
 if(Hash::verify($password, $user->password)) {
 unset($user->password);
 Session::set("__admin_LoginUser", $user);
 if($this->option['isRememberMe']) {
 $rememberKey = uniqid();
 if($userModel->where('id', $user->id)->update(['remember_key' => $rememberKey])) {
 include_library('Cookie');
 Cookie::set('__admin_LoginUser', $rememberKey, '30d', '/');
 }
 }
 return true;
 }
 }
 return false;
 }
 public function logout() {
 Session::remove('__admin_LoginUser');
 include_library('Cookie');
 Cookie::remove('__admin_LoginUser', '/');
 }
 public function auth() {
 if(Session::has('__admin_LoginUser')) {
 return Session::get('__admin_LoginUser');
 }
 include_library('Cookie');
 if(Cookie::has('__admin_LoginUser')) {
 $userModel = \Model::load('UserModel');
 if(!$userModel) {
 throw new TException('Không tìm thấy UserModel', 501);
 }
 $user = $userModel->select('id', 'name', 'group_id')->where('remember_key', Cookie::get('__admin_LoginUser'))->first();
 if($user) {
 Session::set('__admin_LoginUser', $user);
 $rememberKey = uniqid();
 if($userModel->where('id', $user->id)->update(['remember_key' => $rememberKey])) {
 Cookie::set('__admin_LoginUser', $rememberKey, '30d', '/');
 }
 return $user;
 }
 }
 return null;
 }
 public function hasRole($role) {
 return true;
 }
 public function getName() {
 $user = $this->auth();
 if($user) {
 return $user->name;
 }
 return 'Guest';
 }
 public function encodePass($password) {
 include_library('Hash');
 return Hash::encode($password);
 }
 public function updateUser($user) {
 if($user->password != $user->repassword) {
 $user->addModelError('repassword', 'Nhập lại mật khẩu sai!');
 return false;
 }
 else {
 if($user->password) {
 $user->password = $this->encodePass($user->password);
 }
 return $user->update();
 }
 }
 public function createUser($user) {
 $user->password = $this->encodePass($user->password);
 return $user->insert();
 }
 }
 ?>