-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathuser.ts
48 lines (41 loc) · 1.03 KB
/
user.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
import { marshall, Status, unmarshall } from "../deps.ts";
import { DYNAMO_CLIENT } from "./clients.ts";
import { DYNAMO_USER_TABLE } from "./constants.ts";
import { generate } from "./token.ts";
export interface User {
id: number;
admin: boolean;
secret: string;
}
export async function getUser(id: number): Promise<User | undefined> {
const { Item: item } = await DYNAMO_CLIENT.getItem({
TableName: DYNAMO_USER_TABLE,
Key: marshall({ id }),
});
if (item) {
return unmarshall(item);
}
}
export async function createUser(
id: number,
admin = false,
): Promise<User | undefined> {
const secret = generate();
try {
await DYNAMO_CLIENT.putItem({
TableName: DYNAMO_USER_TABLE,
Item: marshall({ id, secret, admin }),
});
return { id, admin, secret };
} catch (e) {
// TODO
}
}
export async function authenticate(
id: number,
secret: string,
admin = false,
): Promise<boolean> {
const user = await getUser(id);
return !(user?.secret !== secret && (admin ? user?.admin : true));
}