From 05cfbf460f4d2993da93551ff92edef39a965cca Mon Sep 17 00:00:00 2001 From: Roland Bernard <rolbernard@unibz.it> Date: Sat, 17 Apr 2021 17:04:45 +0200 Subject: [PATCH] Fixed the CORS requests beeing blocked --- server/src/headers.ts | 13 ++++++++++++- server/src/v1/auth.ts | 6 +++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/server/src/headers.ts b/server/src/headers.ts index 308a05a..dd015a6 100644 --- a/server/src/headers.ts +++ b/server/src/headers.ts @@ -7,7 +7,18 @@ export function addDefaultHeaders(req: Request, res: Response, next: NextFunctio const origin = req.header('Origin'); if (allowedOrigins.includes('*') || origin && allowedOrigins.includes(origin)) { res.header('Access-Control-Allow-Origin', origin); + const headers = req.header('Access-Control-Request-Headers'); + if (headers) { + res.header('Access-Control-Allow-Headers', headers); + } + res.header('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE'); + res.header('Access-Control-Max-Age', '86400'); + } + if (req.method === 'OPTIONS') { + // Handle preflight requests + res.send(); + } else { + next(); } - next(); } diff --git a/server/src/v1/auth.ts b/server/src/v1/auth.ts index 01e3f0f..12f72c2 100644 --- a/server/src/v1/auth.ts +++ b/server/src/v1/auth.ts @@ -69,7 +69,7 @@ auth.post('/register', async (req, res) => { const token = await generateToken({ id: id }); await database('users').insert({ id: id, - user_name: body.username, + user_name: body.username.trim(), passwd_hash: passwdHash, email: body.email ?? null, real_name: body.realname ?? null, @@ -102,7 +102,7 @@ auth.post('/token', async (req, res) => { if (isOfType<TokenBody>(req.body, [['username', 'string'], ['password', 'string']])) { const body: TokenBody = req.body; try { - const user = await database('users').where({ user_name: body.username }); + const user = await database('users').where({ user_name: body.username.trim() }); if (user.length === 1) { if (await compare(body.password, user[0].passwd_hash)) { const token = await generateToken({ id: user[0].id }); @@ -165,7 +165,7 @@ auth.put("/username", async function (req, res) { const body: UsernameBody = req.body; try { await database('users').update({ - user_name: body.username, + user_name: body.username.trim(), }).where({ id: body.token.id, }); -- GitLab