-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.ts
More file actions
65 lines (54 loc) · 1.76 KB
/
index.ts
File metadata and controls
65 lines (54 loc) · 1.76 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
import type { Request, Response, NextFunction } from "express";
import type { AuthType } from "@oko-wallet/oko-types/auth";
import { validateOAuthToken } from "@oko-wallet-tss-api/middleware/google_auth/validate";
import { GOOGLE_CLIENT_ID } from "@oko-wallet-tss-api/middleware/google_auth/client_id";
import type { OAuthLocals } from "@oko-wallet-tss-api/middleware/types";
export interface GoogleAuthenticatedRequest<T = any> extends Request {
body: T;
}
export async function googleAuthMiddleware(
req: GoogleAuthenticatedRequest,
res: Response<unknown, OAuthLocals>,
next: NextFunction,
) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
res
.status(401)
.json({ error: "Authorization header with Bearer token required" });
return;
}
const idToken = authHeader.substring(7); // skip "Bearer "
try {
const result = await validateOAuthToken(idToken, GOOGLE_CLIENT_ID);
if (!result.success) {
res.status(401).json({ error: result.err });
return;
}
if (!result.data) {
res.status(500).json({
error: "Internal server error: Token info missing after validation",
});
return;
}
if (!result.data.sub || !result.data.email) {
res.status(401).json({
error: "Can't get sub or email from Google token",
});
return;
}
res.locals.oauth_user = {
type: "google" as AuthType,
// in google, use google sub as email with prefix
email: `google_${result.data.sub}`,
name: result.data.email,
};
next();
return;
} catch (error) {
res.status(500).json({
error: `Token validation failed: ${error instanceof Error ? error.message : String(error)}`,
});
return;
}
}