-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathauth.ts
53 lines (42 loc) · 1.3 KB
/
auth.ts
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
import { createClerkClient, verifyToken } from "@clerk/backend";
import { APIError, Gateway, Header } from "encore.dev/api";
import { authHandler } from "encore.dev/auth";
import { secret } from "encore.dev/config";
import log from "encore.dev/log";
import { AUTHORIZED_PARTIES } from "./config";
const clerkSecretKey = secret("ClerkSecretKey");
const clerkClient = createClerkClient({
secretKey: clerkSecretKey(),
});
interface AuthParams {
authorization: Header<"Authorization">;
}
interface AuthData {
userID: string;
imageUrl: string;
emailAddress: string | null;
}
const myAuthHandler = authHandler(async (params: AuthParams): Promise<
AuthData
> => {
const token = params.authorization.replace("Bearer ", "");
if (!token) {
throw APIError.unauthenticated("no token provided");
}
try {
const result = await verifyToken(token, {
authorizedParties: AUTHORIZED_PARTIES,
secretKey: clerkSecretKey(),
});
const user = await clerkClient.users.getUser(result.sub);
return {
userID: user.id,
imageUrl: user.imageUrl,
emailAddress: user.emailAddresses[0].emailAddress || null,
};
} catch (e) {
log.error(e);
throw APIError.unauthenticated("invalid token", e as Error);
}
});
export const mygw = new Gateway({ authHandler: myAuthHandler });