-
Notifications
You must be signed in to change notification settings - Fork 0
/
signup.ts
50 lines (45 loc) ยท 1.53 KB
/
signup.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
import { APIGatewayEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
import { getUser, signup } from './mongo-modules';
import * as jwt from 'jsonwebtoken';
interface Claims {
sub: string | undefined;
iat: number;
exp: number;
}
export const handler = async (event: APIGatewayEvent, context: Context): Promise<APIGatewayProxyResult> => {
try {
const { username, password } = event.queryStringParameters || {};
const userData = await getUser(username);
if (userData !== null && userData?.username === username) {
return {
statusCode : 400,
body : JSON.stringify({
message : 'Invalid username',
result : false,
}),
};
}
await signup(username, password);
const claims: Claims = {
sub : username,
iat : Math.floor(Date.now() / 1000),
exp : Math.floor(Date.now() / 1000) + (60 * 60) // Expires in 1 hour
};
const token = jwt.sign(claims, process.env.JWT_SECRET);
console.log(token);
// result(JSON.stringify({ token }));
return {
statusCode : 200,
body : JSON.stringify({
message : 'Created successfully.',
token : token
})
};
} catch (err) {
console.error(err);
return {
statusCode : 500,
body : JSON.stringify({ message : err instanceof Error ? err.message : err }),
};
}
};