Spaces:
Running
Running
Download src/controllers/auth.controller.ts from its-seraj/auth-service: direct link, hf CLI and curl.
- Browser
- Download file 4.98 kB
-
https://huggingface.co/spaces/its-seraj/auth-service/resolve/main/src/controllers/auth.controller.ts
- Command line
-
hf download hf://spaces/its-seraj/auth-service/src/controllers/auth.controller.ts
-
curl -L -o auth.controller.ts https://huggingface.co/spaces/its-seraj/auth-service/resolve/main/src/controllers/auth.controller.ts
4.98 kB
| import { Request, Response, NextFunction, CookieOptions } from 'express'; | |
| import { authService } from '../services/auth.service'; | |
| import { tokenService } from '../services/token.service'; | |
| import { User } from '../models/user.model'; | |
| import { ApiError } from '../utils/apiError'; | |
| import { AuthenticatedRequest } from '../types'; | |
| import { env } from '../config/env'; | |
| const getCookieOptions = (): CookieOptions => ({ | |
| httpOnly: true, | |
| secure: env.NODE_ENV === 'production', | |
| sameSite: 'lax', | |
| maxAge: env.JWT_REFRESH_EXPIRATION_DAYS * 24 * 60 * 60 * 1000 | |
| }); | |
| export class AuthController { | |
| /** | |
| * POST /api/auth/google | |
| * Authenticate with Google ID Token. Open to any new Google user. | |
| */ | |
| async googleAuth(req: Request, res: Response, next: NextFunction): Promise<void> { | |
| try { | |
| const { idToken } = req.body; | |
| const metadata = { | |
| userAgent: req.headers['user-agent'], | |
| ipAddress: req.ip | |
| }; | |
| const result = await authService.authenticateWithGoogle(idToken, metadata); | |
| // Set secure HTTP-only refresh token cookie | |
| res.cookie('refreshToken', result.tokens.refreshToken, getCookieOptions()); | |
| res.status(result.isNewUser ? 201 : 200).json({ | |
| success: true, | |
| message: result.isNewUser ? 'User registered and authenticated' : 'Authenticated successfully', | |
| data: { | |
| user: result.user, | |
| accessToken: result.tokens.accessToken, | |
| refreshToken: result.tokens.refreshToken, | |
| expiresIn: result.tokens.expiresIn | |
| } | |
| }); | |
| } catch (error) { | |
| next(error); | |
| } | |
| } | |
| /** | |
| * POST /api/auth/refresh | |
| * Rotate refresh token and return fresh access token. | |
| */ | |
| async refresh(req: Request, res: Response, next: NextFunction): Promise<void> { | |
| try { | |
| const rawRefreshToken = req.body?.refreshToken || req.cookies?.refreshToken; | |
| if (!rawRefreshToken) { | |
| throw ApiError.unauthorized('Refresh token is required via cookie or request body'); | |
| } | |
| const metadata = { | |
| userAgent: req.headers['user-agent'], | |
| ipAddress: req.ip | |
| }; | |
| const { user, tokens } = await authService.refreshToken(rawRefreshToken, metadata); | |
| // Set new rotated refresh token in cookie | |
| res.cookie('refreshToken', tokens.refreshToken, getCookieOptions()); | |
| res.status(200).json({ | |
| success: true, | |
| message: 'Token refreshed successfully', | |
| data: { | |
| accessToken: tokens.accessToken, | |
| refreshToken: tokens.refreshToken, | |
| expiresIn: tokens.expiresIn, | |
| user | |
| } | |
| }); | |
| } catch (error) { | |
| next(error); | |
| } | |
| } | |
| /** | |
| * POST /api/auth/verify | |
| * Lightweight token validation endpoint for other microservices. | |
| */ | |
| async verifyToken(req: Request, res: Response, next: NextFunction): Promise<void> { | |
| try { | |
| let token: string | undefined; | |
| const authHeader = req.headers.authorization; | |
| if (authHeader && authHeader.startsWith('Bearer ')) { | |
| token = authHeader.split(' ')[1]; | |
| } else if (req.body?.token) { | |
| token = req.body.token; | |
| } | |
| if (!token) { | |
| throw ApiError.unauthorized('Token is required for verification (Bearer header or { token } in body)'); | |
| } | |
| const decoded = tokenService.verifyAccessToken(token); | |
| // Confirm user state in database | |
| const user = await User.findById(decoded.userId); | |
| if (!user || !user.isActive) { | |
| throw ApiError.unauthorized('User inactive or not found'); | |
| } | |
| res.status(200).json({ | |
| valid: true, | |
| user: { | |
| id: user.id, | |
| email: user.email, | |
| name: user.name, | |
| roles: user.roles | |
| } | |
| }); | |
| } catch (error) { | |
| next(error); | |
| } | |
| } | |
| /** | |
| * GET /api/auth/me | |
| * Return currently authenticated user profile. | |
| */ | |
| async getMe(req: AuthenticatedRequest, res: Response, next: NextFunction): Promise<void> { | |
| try { | |
| if (!req.user) { | |
| throw ApiError.unauthorized('Not authenticated'); | |
| } | |
| res.status(200).json({ | |
| success: true, | |
| data: { | |
| user: req.user | |
| } | |
| }); | |
| } catch (error) { | |
| next(error); | |
| } | |
| } | |
| /** | |
| * POST /api/auth/logout | |
| * Invalidate active session and clear cookie. | |
| */ | |
| async logout(req: Request, res: Response, next: NextFunction): Promise<void> { | |
| try { | |
| const rawRefreshToken = req.body?.refreshToken || req.cookies?.refreshToken; | |
| if (rawRefreshToken) { | |
| await authService.logout(rawRefreshToken); | |
| } | |
| // Clear refresh token cookie | |
| res.clearCookie('refreshToken', { | |
| httpOnly: true, | |
| secure: env.NODE_ENV === 'production', | |
| sameSite: 'lax' | |
| }); | |
| res.status(200).json({ | |
| success: true, | |
| message: 'Logged out successfully' | |
| }); | |
| } catch (error) { | |
| next(error); | |
| } | |
| } | |
| } | |
| export const authController = new AuthController(); | |