-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.ts
More file actions
55 lines (47 loc) · 1.74 KB
/
auth.ts
File metadata and controls
55 lines (47 loc) · 1.74 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
import { NextApiRequest, NextApiResponse } from "next";
import { BaseClient, Issuer } from "openid-client";
import jwt from "jsonwebtoken";
import { prisma } from "./db";
import { IncomingMessage, ServerResponse } from "http";
import { NextApiRequestCookies } from "next/dist/server/api-utils";
// clientId: process.env.OAUTH_MS_CLIENT_ID!,
// clientSecret: process.env.OAUTH_MS_CLIENT_SECRET!,
// authority: process.env.OAUTH_MS_AUTHORITY!,
export let msOauth: BaseClient;
export async function setupOauth() {
if (!msOauth) {
let oauthIssuer = await Issuer.discover(process.env.OAUTH_MS_AUTHORITY!);
console.log("Setting up OAuth...");
msOauth = new oauthIssuer.Client({
client_id: process.env.OAUTH_MS_CLIENT_ID!,
client_secret: process.env.OAUTH_MS_CLIENT_SECRET!,
redirect_uris: [process.env.OAUTH_MS_REDIRECT_URL!],
response_types: ["code"],
});
console.log("Set up OAuth");
}
}
export async function getSessionUserId(req: IncomingMessage & { cookies: NextApiRequestCookies }, res: ServerResponse): Promise<number | null> {
let cookie = req.cookies["gpuserver"];
if (!cookie) {
return null;
}
let userId;
try {
userId = (jwt.verify(cookie, process.env.COOKIE_SECRET!) as any)?.userId;
} catch (ex) {
console.error("Could not verify jwt token", ex);
return null;
}
return userId;
}
export async function getSessionUser(req: IncomingMessage & { cookies: NextApiRequestCookies }, res: ServerResponse) {
let userId = await getSessionUserId(req, res);
if (!userId) return null;
let user = await prisma.user.findUnique({
where: {
id: userId,
},
});
return user;
}