Implemented Jest tests

This commit is contained in:
Florian Sylvain
2023-01-27 12:21:41 +01:00
parent 8ec166e88e
commit 766b9ee9fb
9 changed files with 804 additions and 293 deletions
+33
View File
@@ -0,0 +1,33 @@
import { initServer } from '../app.js'
import request from 'supertest'
const app = initServer()
describe('GET /v1', () => {
it('returns status code 200 and api version message', async () => {
const res = await request(app)
.get('/v1')
expect(res.statusCode).toEqual(200)
expect(res.body).toHaveProperty('message')
})
})
describe('POST /v1/login', () => {
it('returns status code 200 and set httpOnly jwt token cookie', async () => {
const res = await request(app)
.post('/v1/login')
.set('Content-Type', 'application/json')
.send(JSON.stringify({
email: "a@a.com",
password: "aaaaaaaaaa"
}))
const jwtRegEx = /^jwt=.*Path=\/.*HttpOnly.*Secure.*SameSite=Strict.*$/
const jwtToken = res.get('Set-Cookie')
.filter(cookie => cookie.match(jwtRegEx))
expect(res.statusCode).toEqual(200)
expect(jwtToken).not.toBe(undefined)
})
})
+10 -8
View File
@@ -6,9 +6,6 @@ import cors from 'cors'
import cookieParser from 'cookie-parser'
import { getJwtSecret } from './utils/jwt.js'
const app = express()
const appRouter = express.Router()
const authMiddleware: RequestHandler = (req, res, next) => {
const token = req.cookies.jwt
if (token == undefined) {
@@ -30,7 +27,7 @@ const appRouterGet: RequestHandler = (req, res) => {
res.send({ code: 200, message: "SnippetsManager v1.0" })
}
function initEnvVariables() {
function initEnvVariables(): void {
dotenv.config()
const varsToCheck = ['API_PORT', 'FRONT_ORIGIN']
@@ -44,20 +41,25 @@ function initEnvVariables() {
})
}
function startServer(): void {
export function initServer(): express.Express {
initEnvVariables()
const app = express()
const appRouter = express.Router()
app.use(cors({ origin: process.env.FRONT_ORIGIN, credentials: true }))
app.use(cookieParser())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
appRouter.get('/', authMiddleware, appRouterGet)
appRouter.get('/', appRouterGet)
appRouter.use(userRouter)
app.use('/v1/', appRouter)
app.listen(process.env.API_PORT, () => console.log(`Listening on port ${process.env.API_PORT}`))
return app
}
startServer()
export function startServer(app: express.Express): void {
app.listen(process.env.API_PORT, () => console.log(`Listening on port ${process.env.API_PORT}`))
}
+4
View File
@@ -0,0 +1,4 @@
import { startServer, initServer } from "./app.js"
const app = initServer()
startServer(app)
+31 -22
View File
@@ -1,5 +1,5 @@
import { PrismaClient, User } from '@prisma/client'
import express from 'express'
import express, { RequestHandler } from 'express'
import { z } from 'zod'
import bcrypt from 'bcrypt'
@@ -29,6 +29,27 @@ async function isUserEmailAlreadyUsed(email: string): Promise<boolean> {
return user != undefined
}
async function createUser(email: string, password: string) {
await prisma.user.create({
data: {
email: email,
password: password,
name: '',
picture_path: '',
created_at: new Date(),
updated_at: new Date()
},
})
}
async function getUser(email: string): Promise<User | null> {
return await prisma.user.findFirst({
where: {
email: email
}
})
}
function parseLoginData(data: any): LoginData | undefined {
try {
const loginData: LoginData = LoginValidator.parse(data)
@@ -38,34 +59,28 @@ function parseLoginData(data: any): LoginData | undefined {
}
}
userRouter.post("/login", async (req, res) => {
const userRouterPostLogin: RequestHandler = 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
}
})
const user = await getUser(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 userRouterPostRegister: RequestHandler = async (req, res) => {
const loginData = parseLoginData(req.body)
if (loginData == undefined) {
res.status(400).json({ message: 'Incorrect credentials format.' })
@@ -79,18 +94,12 @@ userRouter.post("/register", async (req, res) => {
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()
},
})
createUser(loginData.email, hashedPassword)
res.json({ message: 'User successfully created!' })
})
}
userRouter.post("/login", userRouterPostLogin)
userRouter.post("/register", userRouterPostRegister)
export default userRouter