v0.1.0
This commit is contained in:
49
backend/api/common/Service/Auth.php
Normal file
49
backend/api/common/Service/Auth.php
Normal file
@ -0,0 +1,49 @@
|
||||
<?php
|
||||
namespace ProVM\Crypto\Common\Service;
|
||||
|
||||
use Carbon\Carbon;
|
||||
use ProVM\Common\Factory\Model as ModelFactory;
|
||||
use ProVM\Crypt\User;
|
||||
use ProVM\Crypt\Login;
|
||||
|
||||
class Auth {
|
||||
protected $login_time;
|
||||
public function __construct(int $login_time) {
|
||||
$this->login_time = $login_time;
|
||||
}
|
||||
protected $factory;
|
||||
public function setFactory(ModelFactory $factory) {
|
||||
$this->factory = $factory;
|
||||
}
|
||||
protected function createToken() {
|
||||
return password_hash(random_bytes(100), \PASSWORD_BCRYPT);
|
||||
}
|
||||
public function login(string $username, string $password) {
|
||||
$user = $this->factory->find(User::class)->where([['name', $username]])->one();
|
||||
if (!$user) {
|
||||
return false;
|
||||
}
|
||||
if (!password_verify($password, $user->password)) {
|
||||
return false;
|
||||
}
|
||||
$now = Carbon::now();
|
||||
$login = $this->factory->find(Login::class)->where([['user_id', $user->id], ['date_time', $now->copy()->subSeconds($this->login_time), '>=']])->one();
|
||||
if (!$login) {
|
||||
$token = $this->createToken();
|
||||
$data = [
|
||||
'user_id' => $user->id,
|
||||
'token' => $token,
|
||||
'date_time' => $now->format('Y-m-d H:i:s')
|
||||
];
|
||||
$login = $this->factory->create(Login::class, $data);
|
||||
} else {
|
||||
$login->date($now);
|
||||
}
|
||||
$login->save();
|
||||
return $token;
|
||||
}
|
||||
public function isLoggedIn($token) {
|
||||
$login = $this->factory->find(Login::class)->where([['token', $token]])->one();
|
||||
return $login->user();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user