Spaces:
Running
Running
File size: 4,975 Bytes
b480ef7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | 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();
|