Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/deploy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,7 @@ jobs:

DB_PASSWORD_PROD: ${{ secrets.PROD_DB_PASSWORD }}
REDIS_PASSWORD_PROD: ${{ secrets.PROD_REDIS_PASSWORD }}
JWT_SECRET_PROD: ${{ secrets.PROD_JWT_SECRET }}
DB_PASSWORD_DEV: ${{ secrets.DEV_DB_PASSWORD }}
REDIS_PASSWORD_DEV: ${{ secrets.DEV_REDIS_PASSWORD }}
REDIS_PASSWORD_DEV: ${{ secrets.DEV_REDIS_PASSWORD }}
JWT_SECRET_DEV: ${{ secrets.DEV_JWT_SECRET }}
82 changes: 82 additions & 0 deletions app/Http/Controllers/AuthController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\JwtService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
public function register(Request $request, JwtService $jwt)
{
$data = $request->validate([
'name' => ['required','string','max:120'],
'email' => ['required','email','max:190','unique:users,email'],
'password' => ['required','string','min:8','confirmed'],
]);

$user = User::query()->create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);

$token = $jwt->issueToken($user);

return response()->json([
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => (int) config('jwt.ttl'),
'user' => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
],
], 201);
}

public function login(Request $request, JwtService $jwt)
{
$data = $request->validate([
'email' => ['required','email'],
'password' => ['required','string'],
]);

$user = User::query()->where('email', $data['email'])->first();

if (!$user || !Hash::check($data['password'], $user->password)) {
throw ValidationException::withMessages([
'email' => ['Invalid credentials.'],
]);
}

$token = $jwt->issueToken($user);

return response()->json([
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => (int) config('jwt.ttl'),
'user' => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
],
]);
}

public function me(Request $request)
{
$user = $request->user();

return response()->json([
'user' => [
'id' => $user?->id,
'name' => $user?->name,
'email' => $user?->email,
],
]);
}
}
44 changes: 44 additions & 0 deletions app/Http/Middleware/JwtAuth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace App\Http\Middleware;

use App\Models\User;
use App\Services\JwtService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class JwtAuth
{
public function handle(Request $request, Closure $next)
{
$authHeader = (string) $request->header('Authorization', '');

if (!str_starts_with($authHeader, 'Bearer ')) {
return response()->json(['message' => 'Missing Bearer token'], 401);
}

$token = trim(substr($authHeader, 7));

try {
$claims = app(JwtService::class)->decode($token);

$userId = $claims['sub'] ?? null;
if (!$userId) {
return response()->json(['message' => 'Invalid token'], 401);
}

$user = User::query()->find($userId);
if (!$user) {
return response()->json(['message' => 'User not found'], 401);
}

Auth::setUser($user);
$request->attributes->set('jwt_claims', $claims);

return $next($request);
} catch (\Throwable $e) {
return response()->json(['message' => 'Invalid or expired token'], 401);
}
}
}
27 changes: 2 additions & 25 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,35 +9,12 @@

class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;

/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
protected $fillable = ['name', 'email', 'password'];

/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
protected $hidden = ['password', 'remember_token'];

/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
Expand Down
44 changes: 44 additions & 0 deletions app/Services/JwtService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace App\Services;

use App\Models\User;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Support\Carbon;

class JwtService
{
public function issueToken(User $user): string
{
$now = Carbon::now()->timestamp;
$ttl = (int) config('jwt.ttl');

$payload = [
'iss' => config('jwt.issuer'),
'aud' => config('jwt.audience'),
'iat' => $now,
'nbf' => $now,
'exp' => $now + $ttl,
'sub' => (string) $user->id,
'email' => $user->email,
];

return JWT::encode($payload, $this->secret(), 'HS256');
}

public function decode(string $token): array
{
$decoded = JWT::decode($token, new Key($this->secret(), 'HS256'));
return (array) $decoded;
}

private function secret(): string
{
$secret = (string) config('jwt.secret');
if ($secret === '') {
throw new \RuntimeException('JWT secret is not configured (JWT_SECRET).');
}
return $secret;
}
}
5 changes: 4 additions & 1 deletion bootstrap/app.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use App\Http\Middleware\JwtAuth;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
Expand All @@ -12,7 +13,9 @@
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
//
$middleware->alias([
'jwt' => JwtAuth::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"license": "MIT",
"require": {
"php": "^8.2",
"firebase/php-jwt": "^7.0",
"laravel/framework": "^12.0",
"laravel/tinker": "^2.10.1"
},
Expand Down
65 changes: 64 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions config/jwt.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

return [
'secret' => env('JWT_SECRET'),
'ttl' => (int) env('JWT_TTL_SECONDS', 3600),
'issuer' => env('JWT_ISSUER', 'cloudshopt-user-service'),
'audience' => env('JWT_AUDIENCE', 'cloudshopt'),
];
10 changes: 9 additions & 1 deletion routes/api.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
<?php

use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;

Route::get('/info', function () {
return response()->json([
'ok11' => true,
'ok' => true,
'service' => config('app.name'),
'sha' => env('IMAGE_SHA', null),
'time' => now()->toISOString(),
Expand Down Expand Up @@ -35,3 +36,10 @@
], 500);
}
});

Route::prefix('auth')->group(function () {
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
});

Route::middleware('jwt')->get('/me', [AuthController::class, 'me']);