-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathauth.controller.ts
More file actions
197 lines (163 loc) · 5.57 KB
/
auth.controller.ts
File metadata and controls
197 lines (163 loc) · 5.57 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
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import { Response } from "express";
import { GaxiosError } from "gaxios";
import { TokenPayload } from "google-auth-library";
import { ObjectId, WithId } from "mongodb";
import supertokens from "supertokens-node";
import { SessionRequest } from "supertokens-node/framework/express";
import Session from "supertokens-node/recipe/session";
import { BaseError } from "@core/errors/errors.base";
import { Logger } from "@core/logger/winston.logger";
import {
Result_Auth_Compass,
Result_VerifyGToken,
} from "@core/types/auth.types";
import { gCalendar } from "@core/types/gcal";
import { Schema_User } from "@core/types/user.types";
import { initGoogleClient } from "@backend/auth/services/auth.utils";
import compassAuthService from "@backend/auth/services/compass.auth.service";
import GoogleAuthService, {
getGAuthClientForUser,
} from "@backend/auth/services/google.auth.service";
import { error } from "@backend/common/errors/handlers/error.handler";
import { GcalError } from "@backend/common/errors/integration/gcal/gcal.errors";
import { SyncError } from "@backend/common/errors/sync/sync.errors";
import { isInvalidGoogleToken } from "@backend/common/services/gcal/gcal.utils";
import {
ReqBody,
Res_Promise,
SReqBody,
} from "@backend/common/types/express.types";
import syncService from "@backend/sync/services/sync.service";
import { updateGoogleRefreshToken } from "@backend/user/queries/user.queries";
import userService from "@backend/user/services/user.service";
const logger = Logger("app:auth.controller");
class AuthController {
createSession = async (
req: ReqBody<{ cUserId: string }>,
res: Res_Promise,
) => {
const { cUserId } = req.body;
if (!ObjectId.isValid(cUserId)) {
res.promise({ error: "Invalid user ID" });
return;
}
if (cUserId) {
const sessionData =
await compassAuthService.createSessionForUser(cUserId);
res.promise({
message: `User session created for ${cUserId}`,
accessToken: sessionData.accessToken,
});
} else {
res.promise({ error: "User doesn't exist" });
return;
}
};
getUserIdFromSession = (req: SessionRequest, res: Res_Promise) => {
const userId = req.session?.getUserId();
res.promise({ userId });
};
verifyGToken = async (req: SessionRequest, res: Res_Promise) => {
try {
const userId = req.session?.getUserId();
if (!userId) {
res.promise({ isValid: false, error: "No session found" });
return;
}
const gAuthClient = await getGAuthClientForUser({ _id: userId });
// Upon receiving an access token, we know the session is valid
await gAuthClient.getAccessToken();
const result: Result_VerifyGToken = { isValid: true };
res.promise(result);
} catch (error) {
const result: Result_VerifyGToken = {
isValid: false,
error: error as Error | BaseError,
};
res.promise(result);
}
};
loginOrSignup = async (req: SReqBody<{ code: string }>, res: Res_Promise) => {
try {
const { code } = req.body;
const gAuthClient = new GoogleAuthService();
const { tokens } = await gAuthClient.oauthClient.getToken(code);
const { gUser, gcalClient, gRefreshToken } = await initGoogleClient(
gAuthClient,
tokens,
);
const { authMethod, user } = await compassAuthService.determineAuthMethod(
gUser.sub,
);
const { cUserId, email } =
authMethod === "login"
? await this.login(
user as WithId<Schema_User>,
gcalClient,
gRefreshToken,
)
: await this.signup(gUser, gRefreshToken);
const sUserId = supertokens.convertToRecipeUserId(cUserId);
await Session.createNewSession(req, res, "public", sUserId, {
email,
});
const result: Result_Auth_Compass = {
cUserId,
isNewUser: authMethod === "signup",
email,
};
res.promise(result);
} catch (e) {
if (isInvalidGoogleToken(e as GaxiosError)) {
const invalidCodeErr = error(GcalError.CodeInvalid, "gAPI Auth Failed");
logger.error(invalidCodeErr);
res.promise({ error: invalidCodeErr });
return;
}
res.promise(Promise.reject(e));
}
};
login = async (
user: WithId<Schema_User>,
gcal: gCalendar,
gRefreshToken: string,
) => {
const cUserId = user._id.toString();
if (gRefreshToken !== user.google.gRefreshToken) {
await updateGoogleRefreshToken(cUserId, gRefreshToken);
}
try {
await syncService.importIncremental(cUserId, gcal);
} catch (e) {
if (
e instanceof Error &&
e.message === SyncError.NoSyncToken.description
) {
logger.info(
`Resyncing google data due to missing sync for user: ${cUserId}`,
);
userService.restartGoogleCalendarSync(cUserId);
}
}
await userService.saveTimeFor("lastLoggedInAt", cUserId);
return { cUserId, email: user.email };
};
revokeSessionsByUser = async (
req: SReqBody<{ userId?: string }>,
res: Response,
) => {
let userId;
if (req.body.userId) {
userId = req.body.userId;
} else {
userId = req.session?.getUserId() as string;
}
const revokeResult = await compassAuthService.revokeSessionsByUser(userId);
res.send(revokeResult);
};
signup = async (gUser: TokenPayload, gRefreshToken: string) => {
const user = await userService.initUserData(gUser, gRefreshToken);
return { cUserId: user.userId, email: user.email };
};
}
export default new AuthController();