249 lines
7.5 KiB
PHP
249 lines
7.5 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\User;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Facades\Redis;
|
|
use Illuminate\Support\Facades\Validator;
|
|
|
|
/**
|
|
* @group Authentication
|
|
*
|
|
* Endpoints for JWT authentication and session lifecycle.
|
|
*/
|
|
class AuthController extends Controller
|
|
{
|
|
/**
|
|
* Login and get tokens
|
|
*
|
|
* Authenticate with email and password to receive an access token and refresh token.
|
|
*
|
|
* @bodyParam email string required User email address. Example: user@example.com
|
|
* @bodyParam password string required User password. Example: secret123
|
|
*
|
|
* @response 200 {
|
|
* "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
|
|
* "refresh_token": "abc123def456",
|
|
* "token_type": "bearer",
|
|
* "expires_in": 3600,
|
|
* "user": {
|
|
* "id": "550e8400-e29b-41d4-a716-446655440000",
|
|
* "name": "Alice Johnson",
|
|
* "email": "user@example.com",
|
|
* "role": "manager"
|
|
* }
|
|
* }
|
|
* @response 401 {"message":"Invalid credentials"}
|
|
* @response 403 {"message":"Account is inactive"}
|
|
* @response 422 {"errors":{"email":["The email field is required."],"password":["The password field is required."]}}
|
|
*/
|
|
public function login(Request $request): JsonResponse
|
|
{
|
|
$validator = Validator::make($request->all(), [
|
|
'email' => 'required|string|email',
|
|
'password' => 'required|string',
|
|
]);
|
|
|
|
if ($validator->fails()) {
|
|
return response()->json([
|
|
'errors' => $validator->errors(),
|
|
], 422);
|
|
}
|
|
|
|
$user = User::where('email', $request->email)->first();
|
|
|
|
if (! $user || ! Hash::check($request->password, $user->password)) {
|
|
return response()->json([
|
|
'message' => 'Invalid credentials',
|
|
], 401);
|
|
}
|
|
|
|
if (! $user->active) {
|
|
return response()->json([
|
|
'message' => 'Account is inactive',
|
|
], 403);
|
|
}
|
|
|
|
$accessToken = $this->generateAccessToken($user);
|
|
$refreshToken = $this->generateRefreshToken($user);
|
|
|
|
return response()->json([
|
|
'access_token' => $accessToken,
|
|
'refresh_token' => $refreshToken,
|
|
'token_type' => 'bearer',
|
|
'expires_in' => 3600,
|
|
'user' => [
|
|
'id' => $user->id,
|
|
'name' => $user->name,
|
|
'email' => $user->email,
|
|
'role' => $user->role,
|
|
],
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Refresh access token
|
|
*
|
|
* Exchange a valid refresh token for a new access token and refresh token pair.
|
|
*
|
|
* @authenticated
|
|
* @bodyParam refresh_token string required Refresh token returned by login. Example: abc123def456
|
|
*
|
|
* @response 200 {
|
|
* "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
|
|
* "refresh_token": "newtoken123",
|
|
* "token_type": "bearer",
|
|
* "expires_in": 3600
|
|
* }
|
|
* @response 401 {"message":"Invalid or expired refresh token"}
|
|
*/
|
|
public function refresh(Request $request): JsonResponse
|
|
{
|
|
$refreshToken = $request->input('refresh_token');
|
|
|
|
$userId = $this->getUserIdFromRefreshToken($refreshToken);
|
|
|
|
if (! $userId) {
|
|
return response()->json([
|
|
'message' => 'Invalid or expired refresh token',
|
|
], 401);
|
|
}
|
|
|
|
$user = User::find($userId);
|
|
|
|
if (! $user) {
|
|
return response()->json([
|
|
'message' => 'Invalid or expired refresh token',
|
|
], 401);
|
|
}
|
|
|
|
$this->invalidateRefreshToken($refreshToken, $userId);
|
|
|
|
$accessToken = $this->generateAccessToken($user);
|
|
$newRefreshToken = $this->generateRefreshToken($user);
|
|
|
|
return response()->json([
|
|
'access_token' => $accessToken,
|
|
'refresh_token' => $newRefreshToken,
|
|
'token_type' => 'bearer',
|
|
'expires_in' => 3600,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Logout current session
|
|
*
|
|
* Invalidate a refresh token and end the active authenticated session.
|
|
*
|
|
* @authenticated
|
|
* @bodyParam refresh_token string Optional refresh token to invalidate immediately. Example: abc123def456
|
|
*
|
|
* @response 200 {"message":"Logged out successfully"}
|
|
*/
|
|
public function logout(Request $request): JsonResponse
|
|
{
|
|
$user = $request->user();
|
|
$refreshToken = $request->input('refresh_token');
|
|
|
|
if ($refreshToken) {
|
|
$this->invalidateRefreshToken($refreshToken, $user->id);
|
|
}
|
|
|
|
return response()->json([
|
|
'message' => 'Logged out successfully',
|
|
]);
|
|
}
|
|
|
|
protected function generateAccessToken(User $user): string
|
|
{
|
|
$payload = [
|
|
'iss' => config('app.url', 'headroom'),
|
|
'sub' => $user->id,
|
|
'iat' => time(),
|
|
'exp' => time() + 3600,
|
|
'role' => $user->role,
|
|
'permissions' => $this->getPermissions($user->role),
|
|
'jti' => uniqid('token_', true),
|
|
];
|
|
|
|
return $this->encodeJWT($payload);
|
|
}
|
|
|
|
protected function generateRefreshToken(User $user): string
|
|
{
|
|
$token = bin2hex(random_bytes(32));
|
|
// Store with token as the key part for easy lookup
|
|
$key = "refresh_token:{$token}";
|
|
Redis::setex($key, 604800, $user->id);
|
|
|
|
return $token;
|
|
}
|
|
|
|
protected function getUserIdFromRefreshToken(string $token): ?string
|
|
{
|
|
return Redis::get("refresh_token:{$token}") ?: null;
|
|
}
|
|
|
|
protected function invalidateRefreshToken(string $token, string $userId): void
|
|
{
|
|
Redis::del("refresh_token:{$token}");
|
|
}
|
|
|
|
protected function getPermissions(string $role): array
|
|
{
|
|
return match ($role) {
|
|
'superuser' => [
|
|
'manage_users',
|
|
'manage_team_members',
|
|
'manage_projects',
|
|
'manage_allocations',
|
|
'manage_actuals',
|
|
'view_reports',
|
|
'configure_system',
|
|
'view_audit_logs',
|
|
],
|
|
'manager' => [
|
|
'manage_projects',
|
|
'manage_allocations',
|
|
'manage_actuals',
|
|
'view_reports',
|
|
'manage_team_members',
|
|
],
|
|
'developer' => [
|
|
'manage_actuals',
|
|
'view_own_allocations',
|
|
'view_own_actuals',
|
|
'log_hours',
|
|
],
|
|
'top_brass' => [
|
|
'view_reports',
|
|
'view_allocations',
|
|
'view_actuals',
|
|
'view_capacity',
|
|
],
|
|
default => [],
|
|
};
|
|
}
|
|
|
|
protected function encodeJWT(array $payload): string
|
|
{
|
|
$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
|
|
$header = base64_encode($header);
|
|
$header = str_replace(['+', '/', '='], ['-', '_', ''], $header);
|
|
|
|
$payload = json_encode($payload);
|
|
$payload = base64_encode($payload);
|
|
$payload = str_replace(['+', '/', '='], ['-', '_', ''], $payload);
|
|
|
|
$signature = hash_hmac('sha256', $header . '.' . $payload, config('app.key'), true);
|
|
$signature = base64_encode($signature);
|
|
$signature = str_replace(['+', '/', '='], ['-', '_', ''], $signature);
|
|
|
|
return $header . '.' . $payload . '.' . $signature;
|
|
}
|
|
}
|