11import { APIGatewayEvent } from "aws-lambda"
22import * as db from "simple-dynamodb"
33import sha256 from "crypto-js/sha256"
4+ import omit from "lodash.omit"
45
56function response ( statusCode : number , body : any ) {
6- return { statusCode, body : JSON . stringify ( body ) }
7+ return {
8+ statusCode,
9+ // permissive CORS headers
10+ headers : {
11+ "Access-Control-Allow-Headers" : "Content-Type" ,
12+ "Access-Control-Allow-Origin" : "*" ,
13+ "Access-Control-Allow-Methods" : "OPTIONS,POST,GET" ,
14+ } ,
15+ body : JSON . stringify ( body ) ,
16+ }
717}
818
919// Hashing your password before saving is critical
@@ -15,6 +25,21 @@ function hashPassword(username: string, password: string) {
1525 ) . toString ( )
1626}
1727
28+ async function createUser ( username : string , password : string ) {
29+ const result = await db . updateItem ( {
30+ TableName : process . env . USER_TABLE ! ,
31+ Key : {
32+ username,
33+ } ,
34+ UpdateExpression : `SET password = :password, createdAt = :createdAt` ,
35+ ExpressionAttributeValues : {
36+ ":password" : hashPassword ( username , password ) ,
37+ ":createdAt" : new Date ( ) . toISOString ( ) ,
38+ } ,
39+ } )
40+ return result . Attributes
41+ }
42+
1843// Logs you in based on username/password combo
1944// Creates user on first login
2045export const login = async ( event : APIGatewayEvent ) => {
@@ -27,30 +52,30 @@ export const login = async (event: APIGatewayEvent) => {
2752 } )
2853 }
2954
30- // username is the key, which means it must be unique
31- let user = await db . getItem ( {
55+ // find user in database
56+ let { Item : user } = await db . getItem ( {
3257 TableName : process . env . USER_TABLE ! ,
3358 Key : {
59+ // username is the key, which means it must be unique
3460 username,
3561 } ,
3662 } )
3763
3864 if ( ! user ) {
3965 // user was not found, create
40- user = await db . updateItem ( {
41- TableName : process . env . USER_TABLE ! ,
42- Key : {
43- username,
44- } ,
45- UpdateExpression : `SET password = :password, createdAt = :createdAt` ,
46- ExpressionAttributeValues : {
47- ":password" : hashPassword ( username , password ) ,
48- ":createdAt" : new Date ( ) . toISOString ( ) ,
49- } ,
50- } )
66+ user = await createUser ( username , password )
5167 } else {
5268 // check credentials
69+ if ( hashPassword ( username , password ) !== user . password ) {
70+ // 🚨
71+ return response ( 401 , {
72+ status : "error" ,
73+ error : "Bad username/password combination" ,
74+ } )
75+ }
5376 }
5477
55- return response ( 200 , user )
78+ // user was created or has valid credentials
79+
80+ return response ( 200 , omit ( user , "password" ) )
5681}
0 commit comments