diff --git a/src/handlers/create.ts b/src/handlers/create.ts index 1691932..b86fec9 100644 --- a/src/handlers/create.ts +++ b/src/handlers/create.ts @@ -11,13 +11,28 @@ export default async function create(c: Context) { if (!body.email || !body.token || !body.keyHash || !body.aes256Bit || !body.salt) { throw new HTTPException(401); } - //Maybe add some way of token verification later on - const emailPattern = /^[a-zA-Z]+\d{2}[a-zA-Z]{3}\d{1,3}@iiitkottayam\.ac\.in$/; + + let emailPattern = /^[a-zA-Z]+\d{2}[a-zA-Z]{3}\d{1,3}@iiitkottayam\.ac\.in$/; if (!emailPattern.test(body.email)) { throw new HTTPException(401); } - const stmt = `INSERT INTO users (email, token, keyHash, aes256Bit, salt) VALUES ($1, $2, $3, $4, $5)`; - const values = [body.email, body.token, body.keyHash, body.aes256Bit, body.salt]; + + let userToken = body.token; + let token_stmt = `SELECT email FROM users WHERE token = $1`; + let token_values = [userToken]; + let token_email; + + try { + let res = await c.env.DB.prepare.query(token_stmt, token_values); + token_email = res.rows[0].email; + } catch (e) { + throw new HTTPException(500); + } + if (token_email !== body.email) { + throw new HTTPException(401); + } + let stmt = `INSERT INTO users (email, token, keyHash, aes256Bit, salt) VALUES ($1, $2, $3, $4, $5)`; + let values = [body.email, body.token, body.keyHash, body.aes256Bit, body.salt]; try { await c.env.DB.prepare.query(stmt, values); } catch (e) { diff --git a/src/handlers/verify.ts b/src/handlers/verify.ts index ff965b3..dbefa98 100644 --- a/src/handlers/verify.ts +++ b/src/handlers/verify.ts @@ -22,11 +22,19 @@ export default async function verify(c: Context) { if (!otp || !otpPattern.test(otp) || !email || !emailPattern.test(email)) { throw new HTTPException(401); } - + const token = await createJWT(email); + const stmt = `INSERT INTO users (email, token) VALUES ($1, $2)`; + const values = [email, token]; + try { + await c.env.DB.prepare.query(stmt, values); + } catch (e) { + throw new HTTPException(500); + } + return c.json({ status: 'success', data: { - token: await createJWT(email), + token: token, }, }); }