Register/Login implementation

This commit is contained in:
Florian Sylvain
2023-01-26 20:57:12 +01:00
parent 55f42008f6
commit 84d95d6f12
6 changed files with 765 additions and 19 deletions
+45 -5
View File
@@ -1,18 +1,58 @@
import { PrismaClient } from '@prisma/client'
import express from 'express'
import express, { RequestHandler } from 'express'
import userRouter from './routers/user.js'
import * as dotenv from 'dotenv'
import jwt from 'jsonwebtoken'
import cors from 'cors'
import cookieParser from 'cookie-parser'
import { getJwtSecret } from './utils/jwt.js'
dotenv.config()
function initEnvVariables() {
dotenv.config()
const varsToCheck = ['API_PORT', 'FRONT_ORIGIN']
varsToCheck.forEach(varName => {
const variable = process.env[varName]
if (variable == undefined || variable === '') {
console.error(`Missing '${varName}' in .env`)
process.exit()
}
})
}
initEnvVariables()
const app = express()
const prisma = new PrismaClient()
const appRouter = express.Router()
const port = process.env.API_PORT
app.use(cors({ origin: process.env.FRONT_ORIGIN, credentials: true }))
app.use(cookieParser())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.get('/v1/', async (req, res, next) => {
const authMiddleware: RequestHandler = function (req, res, next) {
const token = req.cookies.jwt
if (token == undefined) {
res.status(400).send({ message: 'Cannot find jwt auth cookie.' })
return;
}
try {
jwt.verify(token, getJwtSecret())
} catch (error) {
res.status(400).send({ message: 'Incorrect JWT.', error })
return;
}
next()
}
appRouter.get('/', authMiddleware, async (req, res, next) => {
res.send({ code: 200, message: "SnippetsManager v1.0" })
})
appRouter.use(userRouter)
app.use('/v1/', appRouter)
app.listen(port, () => console.log(`Listening on port ${port}`))
+96
View File
@@ -0,0 +1,96 @@
import { PrismaClient, User } from '@prisma/client'
import express from 'express'
import { z } from 'zod'
import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import { getJwtSecret } from '../utils/jwt.js'
interface LoginData {
email: string,
password: string
}
const userRouter = express.Router()
const prisma = new PrismaClient()
const LoginValidator = z.object({
email: z.string().email(),
password: z.string().min(4).max(20)
})
async function isUserValid(user: User | null, loginData: any): Promise<boolean> {
if (user == undefined) return false
return await bcrypt.compare(loginData.password, user.password)
}
async function isUserEmailAlreadyUsed(email: string): Promise<boolean> {
const user = await prisma.user.findFirst({ where: { email } })
return user != undefined
}
function parseLoginData(data: any): LoginData | undefined {
try {
const loginData: LoginData = LoginValidator.parse(data)
return loginData
} catch {
return undefined
}
}
userRouter.post("/login", async (req, res) => {
const loginData = parseLoginData(req.body)
if (loginData === undefined) {
res.status(400).json({ message: 'Incorrect credentials format.' })
return;
}
const user = await prisma.user.findFirst({
where: {
email: loginData.email
}
})
if (await isUserValid(user, loginData) === false) {
res.status(400).json({ message: 'Incorrect credentials.' })
return;
}
const jwtToken = jwt.sign({}, getJwtSecret(), { expiresIn: "1h" })
res.cookie('jwt', jwtToken, {
httpOnly: true,
secure: true,
sameSite: 'strict'
}).json({ message: "Logged in! httpOnly cookie set." })
})
userRouter.post("/register", async (req, res) => {
const loginData = parseLoginData(req.body)
if (loginData == undefined) {
res.status(400).json({ message: 'Incorrect credentials format.' })
return;
}
if (await isUserEmailAlreadyUsed(loginData.email)) {
res.status(400).json({ message: 'Email already linked to an account.' })
return;
}
const hashedPassword = await bcrypt.hash(loginData.password, 10)
await prisma.user.create({
data: {
email: loginData.email,
password: hashedPassword,
name: '',
picture_path: '',
created_at: new Date(),
updated_at: new Date()
},
})
res.json({ message: 'User successfully created!' })
})
export default userRouter
+7
View File
@@ -0,0 +1,7 @@
export function getJwtSecret(): string {
if (process.env["JWT_SECRET"] == undefined) {
console.error("WARNING! JWT secret is not set.")
process.exit()
}
return process.env["JWT_SECRET"]
}