Xboard/app/Services/AuthService.php

51 lines
1.2 KiB
PHP
Raw Normal View History

2023-11-17 01:44:01 -05:00
<?php
namespace App\Services;
use App\Models\User;
2025-01-06 12:20:11 -05:00
use App\Utils\CacheKey;
2023-11-17 01:44:01 -05:00
use Illuminate\Http\Request;
2025-01-06 12:20:11 -05:00
use Illuminate\Support\Facades\Cache;
use Laravel\Sanctum\NewAccessToken;
use Illuminate\Support\Str;
2023-11-17 01:44:01 -05:00
class AuthService
{
2025-01-06 12:20:11 -05:00
private User $user;
2023-11-17 01:44:01 -05:00
public function __construct(User $user)
{
$this->user = $user;
}
2025-01-06 12:20:11 -05:00
public function generateAuthData(): array
2023-11-17 01:44:01 -05:00
{
2025-01-06 12:20:11 -05:00
// Create a new Sanctum token with device info
$token = $this->user->createToken(
Str::random(20), // token name (device identifier)
['*'], // abilities
now()->addYear() // expiration
);
// Format token: remove ID prefix and add Bearer
$tokenParts = explode('|', $token->plainTextToken);
$formattedToken = 'Bearer ' . ($tokenParts[1] ?? $tokenParts[0]);
2023-11-17 01:44:01 -05:00
return [
2025-01-06 12:20:11 -05:00
'auth_data' => $formattedToken,
2023-11-17 01:44:01 -05:00
'is_admin' => $this->user->is_admin,
];
}
2025-01-06 12:20:11 -05:00
public function getSessions(): array
2023-11-17 01:44:01 -05:00
{
2025-01-06 12:20:11 -05:00
return $this->user->tokens()->get()->toArray();
2023-11-17 01:44:01 -05:00
}
2025-01-08 12:38:53 -05:00
public function removeSession(): bool
2023-11-17 01:44:01 -05:00
{
2025-01-06 12:20:11 -05:00
$this->user->tokens()->delete();
2023-11-17 01:44:01 -05:00
return true;
}
}