49 lines
1.0 KiB
PHP
49 lines
1.0 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Services;
|
|
|
|
use App\Models\AuthenticationToken;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Str;
|
|
|
|
class AuthService
|
|
{
|
|
public function isAuthenticated()
|
|
{
|
|
$auth = request()->header('Authorization');
|
|
|
|
if ($auth === null) {
|
|
return false;
|
|
}
|
|
|
|
$authToken = AuthenticationToken::where('token', $auth)->where('valid_until', '>', Carbon::now())->first();
|
|
|
|
if ($authToken === null) {
|
|
return false;
|
|
}
|
|
|
|
return $authToken->authenticated;
|
|
}
|
|
|
|
public function generateToken()
|
|
{
|
|
return AuthenticationToken::create([
|
|
'token' => Hash::make(Str::random(32)),
|
|
'valid_until' => Carbon::now()->addDay(),
|
|
]);
|
|
}
|
|
|
|
public function authenticate(AuthenticationToken $token)
|
|
{
|
|
$token->authenticated = true;
|
|
$token->save();
|
|
}
|
|
|
|
public function logout(AuthenticationToken $token)
|
|
{
|
|
$token->authenticated = false;
|
|
$token->save();
|
|
}
|
|
}
|