From 3f6c0e603772cf6ce27828906523023c16269f0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9rgio=20Salgado?= Date: Wed, 7 Apr 2021 02:16:16 +0100 Subject: [PATCH] fix: database constraint on auth_tokens --- lib/users.js | 6 +++--- migrations/1605181184453-users.js | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/lib/users.js b/lib/users.js index 054ea3f8..398be91e 100644 --- a/lib/users.js +++ b/lib/users.js @@ -86,7 +86,7 @@ function reset2FASecret (token, id, secret) { return db.tx(t => { const q1 = t.none('UPDATE users SET twofa_code=$1 WHERE id=$2', [secret, id]) const q2 = t.none(`DELETE FROM user_sessions WHERE sess -> 'user' ->> 'id'=$1`, [id]) - const q3 = t.none(`DELETE FROM auth_tokens WHERE token=$1 and type='reset_password'`, [token]) + const q3 = t.none(`DELETE FROM auth_tokens WHERE token=$1 and type='reset_twofa'`, [token]) return t.batch([q1, q2, q3]) }) }) @@ -94,7 +94,7 @@ function reset2FASecret (token, id, secret) { function createReset2FAToken (userID) { const token = crypto.randomBytes(32).toString('hex') - const sql = `INSERT INTO auth_tokens (token, type, user_id) VALUES ($1, 'reset_twofa', $2) ON CONFLICT (user_id) DO UPDATE SET token=$1, expire=now() + interval '30 minutes' RETURNING *` + const sql = `INSERT INTO auth_tokens (token, type, user_id) VALUES ($1, 'reset_twofa', $2) ON CONFLICT (user_id, type) DO UPDATE SET token=$1, expire=now() + interval '30 minutes' RETURNING *` return db.one(sql, [token, userID]) } @@ -123,7 +123,7 @@ function updatePassword (token, id, password) { function createResetPasswordToken (userID) { const token = crypto.randomBytes(32).toString('hex') - const sql = `INSERT INTO auth_tokens (token, type, user_id) VALUES ($1, 'reset_password', $2) ON CONFLICT (user_id) DO UPDATE SET token=$1, expire=now() + interval '30 minutes' RETURNING *` + const sql = `INSERT INTO auth_tokens (token, type, user_id) VALUES ($1, 'reset_password', $2) ON CONFLICT (user_id, type) DO UPDATE SET token=$1, expire=now() + interval '30 minutes' RETURNING *` return db.one(sql, [token, userID]) } diff --git a/migrations/1605181184453-users.js b/migrations/1605181184453-users.js index 4e1eeab7..b823d73c 100644 --- a/migrations/1605181184453-users.js +++ b/migrations/1605181184453-users.js @@ -25,8 +25,9 @@ exports.up = function (next) { `CREATE TABLE auth_tokens ( token TEXT NOT NULL PRIMARY KEY, type auth_token_type NOT NULL, - user_id UUID REFERENCES users(id) ON DELETE CASCADE UNIQUE, - expire TIMESTAMPTZ NOT NULL DEFAULT now() + interval '30 minutes' + user_id UUID REFERENCES users(id) ON DELETE CASCADE, + expire TIMESTAMPTZ NOT NULL DEFAULT now() + interval '30 minutes', + CONSTRAINT unique_userid_type UNIQUE (user_id, type) )`, `CREATE TABLE user_register_tokens ( token TEXT NOT NULL PRIMARY KEY,