Created
November 28, 2020 15:06
-
-
Save mirsahib/4af0f135a5caeb1cf4b87a2eea6985d7 to your computer and use it in GitHub Desktop.
React_Serverless
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bcrypt from "bcryptjs"; | |
import { JsonWebTokenError } from "jsonwebtoken"; | |
import { createClient } from "../helpers/db-helper"; | |
import { createJwtCookie } from "../helpers/jwt-helper"; | |
export async function handler(event) { | |
const dbClient = createClient(); | |
let errorStatusCode = 500; | |
try { | |
await dbClient.connect(); | |
const users = dbClient.usersCollection(); | |
console.log(users); | |
const { email, password } = JSON.parse(event.body); | |
const existingUser = await users.findOne({ email }); | |
if (existingUser == null) { | |
errorStatusCode = 401; | |
throw new Error(`Invalid username and password`); | |
} | |
const isMatch = await bcrypt.compare(password, existingUser.password); | |
if (!isMatch) { | |
errorStatusCode = 401; | |
throw new Error(`Password do not match`); | |
} | |
const userId = existingUser._id; | |
const jwtCookie = createJwtCookie(userId, email); | |
return { | |
statusCode: 200, | |
headers: { | |
"Set-Cookie": jwtCookie, | |
"Content-Type": "application/json", | |
}, | |
body: JSON.stringify({ id: userId, email }), | |
}; | |
} catch (err) { | |
return { | |
statusCode: errorStatusCode, | |
body: JSON.stringify({ status: errorStatusCode, msg: err.message }), | |
}; | |
} finally { | |
dbClient.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment