-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathauth.controller.ts
More file actions
140 lines (126 loc) · 4.39 KB
/
auth.controller.ts
File metadata and controls
140 lines (126 loc) · 4.39 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
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
import {
BadRequestException,
Controller,
Get,
Query,
Req,
Res,
UseGuards,
Logger,
} from "@nestjs/common";
import { UserEntity } from "../user/entities/user.entity";
import { AuthGuard } from "@nestjs/passport";
import { Request, Response } from "express";
import { AuthService } from "./auth.service";
import { JwtAuthGuard } from "./jwt-auth.guard";
import { ConfigService } from "@nestjs/config";
import { UserService } from "../user/user.service";
import { UserId } from "../guards/UserGuard";
import * as CryptoJS from "crypto-js";
import { SocialAccountService } from "../user/social-account.service";
import { SocialPlatform } from "../user/entities/social-account.entity";
@Controller("auth")
export class AuthController {
private readonly logger = new Logger(AuthController.name);
constructor(
private readonly auth: AuthService,
private readonly configService: ConfigService,
private readonly userService: UserService,
private readonly socialAccountService: SocialAccountService,
) {}
@Get("/github/callback")
@UseGuards(AuthGuard("github"))
githubCallback(@Req() req: Request, @Res() res: Response) {
const user = req.user as UserEntity;
this.logger.log({ action: "github_login", userId: user.id });
const token = this.auth.signToken(user);
const redirectUrl = this.configService.getOrThrow<string>(
"OAUTH_SUCCESS_REDIRECT_URL",
);
if (redirectUrl) {
const cookieName =
this.configService.get<string>("AUTH_COOKIE_NAME") || "token";
const cookieDomain =
this.configService.get<string>("AUTH_COOKIE_DOMAIN") ||
(this.configService.get("NODE_ENV") === "development"
? "localhost"
: ".coregame.sh");
res.cookie(cookieName, token, {
httpOnly: true,
secure: true,
sameSite: "none",
domain: cookieDomain,
maxAge: 30 * 24 * 60 * 60 * 1000,
});
return res.redirect(redirectUrl);
}
return res.json({ token });
}
@Get("/42/getUrl")
@UseGuards(JwtAuthGuard)
getFortyTwoAuthUrl(@UserId() userId: string) {
const encryptedUserId = CryptoJS.AES.encrypt(
userId,
this.configService.getOrThrow<string>("API_SECRET_ENCRYPTION_KEY"),
).toString();
const base64EncodedEncryptedUserId =
Buffer.from(encryptedUserId).toString("base64");
return `https://api.intra.42.fr/oauth/authorize?client_id=${this.configService.getOrThrow<string>("FORTYTWO_CLIENT_ID")}&redirect_uri=${encodeURIComponent(this.configService.getOrThrow<string>("FORTYTWO_CALLBACK_URL"))}&response_type=code&state=${base64EncodedEncryptedUserId}`;
}
@Get("/42/callback")
@UseGuards(AuthGuard("42"))
async fortyTwoCallback(
@Req()
request: Request & {
user: {
fortyTwoAccount: {
platformUserId: string;
username: string;
email: string;
};
};
},
@Res() res: Response,
@Query("state") encryptedUserId: string,
) {
try {
const base64DecodedEncryptedUserId = Buffer.from(
encryptedUserId,
"base64",
).toString("utf-8");
const userId = CryptoJS.AES.decrypt(
base64DecodedEncryptedUserId,
this.configService.getOrThrow<string>("API_SECRET_ENCRYPTION_KEY"),
).toString(CryptoJS.enc.Utf8);
if (!userId) throw new BadRequestException("Invalid state parameter.");
await this.socialAccountService.upsertSocialAccountForUser({
userId,
platform: SocialPlatform.FORTYTWO,
platformUserId: request.user.fortyTwoAccount.platformUserId,
username: request.user.fortyTwoAccount.username,
});
this.logger.log({ action: "fortytwo_link", userId });
const redirectUrl = this.configService.getOrThrow<string>(
"OAUTH_42_SUCCESS_REDIRECT_URL",
);
return res.redirect(redirectUrl);
} catch (e) {
// Use a more detailed log, and preserve specific error messages for BadRequestException
this.logger.error("Error in FortyTwo callback:", e);
if (e instanceof BadRequestException) {
throw e;
}
throw new BadRequestException(
e && typeof e.message === "string"
? `Invalid state parameter: ${e.message}`
: "Invalid state parameter.",
);
}
}
@Get("/me")
@UseGuards(JwtAuthGuard)
me(@Req() req: Request) {
const user = req.user as UserEntity;
return this.userService.getUserById(user.id);
}
}