This repository was archived by the owner on Sep 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsign_in_or_sign_up.ts
More file actions
56 lines (49 loc) · 1.78 KB
/
sign_in_or_sign_up.ts
File metadata and controls
56 lines (49 loc) · 1.78 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
import { ScriptContext } from "../module.gen.ts";
import { getUserId } from "../utils/db.ts";
import { IdentityDataInput, IdentityProviderInfo } from "../utils/types.ts";
export interface Request {
info: IdentityProviderInfo;
uniqueData: IdentityDataInput;
additionalData: IdentityDataInput;
username?: string;
}
export interface Response {
userToken: string;
userId: string;
}
export async function run(
ctx: ScriptContext,
req: Request,
): Promise<Response> {
return await ctx.db.$transaction(async tx => {
const userId = await getUserId(tx, req.info.identityType, req.info.identityId, req.uniqueData);
// If the identity provider is associated with a user, sign in
if (userId) {
// Generate a user token
const { token: { token } } = await ctx.modules.users.createToken({ userId });
return {
userToken: token,
userId,
};
} else {
// Otherwise, create a new user
const { user } = await ctx.modules.users.create({ username: req.username });
// Insert the identity data with the newly-created user
await tx.userIdentities.create({
data: {
userId: user.id,
identityType: req.info.identityType,
identityId: req.info.identityId,
uniqueData: req.uniqueData,
additionalData: req.additionalData,
},
});
// Generate a user token and return it
const { token: { token } } = await ctx.modules.users.createToken({ userId: user.id });
return {
userToken: token,
userId: user.id,
};
}
});
}