Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Http\Controllers\Auth;
- use App\Http\Controllers\Controller;
- use App\Http\Requests\Auth\LoginRequest;
- use Illuminate\Http\Request;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Support\Facades\Auth;
- use Carbon\Carbon;
- use Symfony\Component\HttpFoundation\Cookie;
- use Illuminate\Validation\ValidationException;
- class AuthenticatedSessionController extends Controller
- {
- /**
- * Handle an incoming authentication request.
- */
- public function store(LoginRequest $request): JsonResponse
- {
- $request->validate([
- 'email' => ['required', 'string', 'email'],
- 'password' => ['required', 'string'],
- ]);
- // This will temporarily log the user in if credentials are correct.
- // It sets the session cookie for Sanctum SPA authentication.
- if (! Auth::attempt($request->only('email', 'password'), $request->boolean('remember'))) {
- throw ValidationException::withMessages([
- 'email' => trans('auth.failed'),
- ]);
- }
- // the user IS authenticated (temporarily)
- $user = Auth::user();
- // 3. Check if the user's email is verified.
- if (! $user->hasVerifiedEmail()) {
- Auth::guard('web')->logout();
- $request->session()->invalidate();
- $request->session()->regenerateToken();
- return response()->json([
- 'message' => 'Email is not verified. Please check your inbox or request a new verification link.'
- ], 403);
- }
- // Inject authenticated user's ID into session collection record when the user logs in
- $request->session()->put('user_id', $request->user()->id);
- // Create a new Personal Access Token for the user
- //$token = $user->createToken('api_token')->plainTextToken;
- $token = $user->createToken(
- 'api_token', // Name for the token
- ['*'], // Abilities
- Carbon::now()->addDays(30) // Token expires in 30 days
- );
- // Return the user and the new token as a JSON response
- return response()->json([
- 'user' => $user,
- 'token' => substr($token->plainTextToken, 1),
- ], 200)->withCookie(
- new Cookie(
- 'authToken',
- substr($token->plainTextToken, 1),
- Carbon::now()->addDays(30),
- '/',
- null,
- false,
- true, // HttpOnly
- false,
- false,
- 'Strict'
- )
- );
- }
- /**
- * Destroy an authenticated session.
- */
- public function destroy(Request $request): JsonResponse
- {
- $request->user()->currentAccessToken()->delete();
- // Return a successful, empty response
- return response()->json(null, 204);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment