mirror of
https://github.com/HeyPuter/puter.git
synced 2025-02-02 23:28:39 +08:00
Use jwt for email change confirmation
This commit is contained in:
parent
b944217410
commit
5b39e39e1f
@ -25,6 +25,8 @@ const { DB_READ, DB_WRITE } = require('../services/database/consts.js');
|
||||
|
||||
const config = require('../config.js');
|
||||
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const CHANGE_EMAIL_START = eggspress('/change_email/start', {
|
||||
subdomain: 'api',
|
||||
auth: true,
|
||||
@ -60,6 +62,10 @@ const CHANGE_EMAIL_START = eggspress('/change_email/start', {
|
||||
|
||||
// generate confirmation token
|
||||
const token = crypto.randomBytes(4).toString('hex');
|
||||
const jwt_token = jwt.sign({
|
||||
user_id: user.id,
|
||||
token,
|
||||
}, config.jwt_secret, { expiresIn: '24h' });
|
||||
|
||||
// send confirmation email
|
||||
const svc_email = req.services.get('email');
|
||||
@ -71,7 +77,7 @@ const CHANGE_EMAIL_START = eggspress('/change_email/start', {
|
||||
// update user
|
||||
await db.write(
|
||||
'UPDATE `user` SET `unconfirmed_change_email` = ?, `change_email_confirm_token` = ? WHERE `id` = ?',
|
||||
[new_email, token, user.id]
|
||||
[new_email, jwt_token, user.id]
|
||||
);
|
||||
|
||||
res.send({ success: true });
|
||||
@ -80,17 +86,18 @@ const CHANGE_EMAIL_START = eggspress('/change_email/start', {
|
||||
const CHANGE_EMAIL_CONFIRM = eggspress('/change_email/confirm', {
|
||||
allowedMethods: ['GET'],
|
||||
}, async (req, res, next) => {
|
||||
const user = req.user;
|
||||
const token = req.query.token;
|
||||
const jwt_token = req.query.token;
|
||||
|
||||
if ( ! token ) {
|
||||
if ( ! jwt_token ) {
|
||||
throw APIError.create('field_missing', null, { key: 'token' });
|
||||
}
|
||||
|
||||
const { token, user_id } = jwt.verify(jwt_token, config.jwt_secret);
|
||||
|
||||
const db = req.services.get('database').get(DB_WRITE, 'auth');
|
||||
const rows = await db.read(
|
||||
'SELECT `unconfirmed_change_email` FROM `user` WHERE `id` = ? AND `change_email_confirm_token` = ?',
|
||||
[user.id, token]
|
||||
[user_id, token]
|
||||
);
|
||||
if ( rows.length === 0 ) {
|
||||
throw APIError.create('token_invalid');
|
||||
@ -100,7 +107,7 @@ const CHANGE_EMAIL_CONFIRM = eggspress('/change_email/confirm', {
|
||||
|
||||
await db.write(
|
||||
'UPDATE `user` SET `email` = ?, `unconfirmed_change_email` = NULL, `change_email_confirm_token` = NULL WHERE `id` = ?',
|
||||
[new_email, user.id]
|
||||
[new_email, user_id]
|
||||
);
|
||||
|
||||
const h = `<p style="text-align:center; color:green;">Your email has been successfully confirmed.</p>`;
|
||||
|
Loading…
Reference in New Issue
Block a user