-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathauth.controller.ts
More file actions
61 lines (47 loc) · 2 KB
/
Copy pathauth.controller.ts
File metadata and controls
61 lines (47 loc) · 2 KB
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
import { randomBytes } from "crypto";
import { Request, Response } from "express";
import type { OAuthProvider } from "../types/auth.types.js";
import { AuthCallbackParamsSchema } from "../types/auth.types.js";
import { AuthService } from "./auth.service.js";
export class AuthController {
constructor(private readonly authService: AuthService) {}
async getUrl(req: Request, res: Response) {
const provider = req.params.provider as OAuthProvider;
const state = randomBytes(16).toString("hex");
(req.session as { oauth_state?: string }).oauth_state = state;
await req.session.save();
const url = await this.authService.getAuthUrl(provider, state);
return res.json({ url });
}
async callback(req: Request, res: Response) {
const frontendUrl = process.env.FRONTEND_URL || "http://localhost:5173";
try {
const callbackUrl = `${process.env.APP_URL}/auth/${req.params.provider}/callback?${new URLSearchParams(req.query as Record<string, string>).toString()}`;
const params = AuthCallbackParamsSchema.parse({
provider: req.params.provider,
code: req.query.code,
state: req.query.state,
callbackUrl,
});
const oauthState = (req.session as { oauth_state?: string }).oauth_state;
if (!oauthState) {
return res.redirect(`${frontendUrl}/login?error=oauth_state_missing`);
}
if (oauthState !== params.state) {
return res.redirect(`${frontendUrl}/login?error=oauth_state_invalid`);
}
delete (req.session as { oauth_state?: string }).oauth_state;
const result = await this.authService.handleCallback({
...params,
callbackUrl,
});
req.session.userId = result.session.userId;
req.session.role = result.session.role;
await req.session.save();
return res.redirect(`${frontendUrl}/auth/callback`);
} catch (error) {
console.error("OAuth callback error:", error);
return res.redirect(`${frontendUrl}/login?error=oauth_failed`);
}
}
}