mirror of
https://github.com/Gimanh/taskview-community.git
synced 2026-09-11 13:29:17 +00:00
fix: login by code
This commit is contained in:
@@ -17,9 +17,12 @@ import {
|
||||
import { generateString, isEmail, time } from '../../utils/helpers';
|
||||
import EnEmailTemplate from './mail/confirm-email-en';
|
||||
import RuEmailTemplate from './mail/confirm-email-ru';
|
||||
import LoginCodeEmailTemplate from './mail/login-code-en';
|
||||
import type { ExternalAuthUser } from './strategies/external-auth.types';
|
||||
import { OrganizationRepository } from '../organizations/OrganizationRepository';
|
||||
|
||||
const LOGIN_CODE_TTL_MS = 5 * 60 * 1000;
|
||||
|
||||
export default class AuthController {
|
||||
private readonly jwtAlg: Algorithm = process.env.JWT_ALG as Algorithm;
|
||||
private readonly jwtExp: string = process.env.ACCESS_LIFE_TIME!;
|
||||
@@ -104,7 +107,8 @@ export default class AuthController {
|
||||
}
|
||||
|
||||
generateLoginCode() {
|
||||
return `${this.makeidLogin(12)}:${Date.now()}`.toLocaleLowerCase();
|
||||
const code = String(randomInt(100000, 1000000));
|
||||
return `${code}:${Date.now()}`;
|
||||
}
|
||||
/**
|
||||
* Register user by email and send login code to the email
|
||||
@@ -165,26 +169,36 @@ export default class AuthController {
|
||||
|
||||
const lastUpdate = userData.remember_token?.split(':')[1];
|
||||
const now = Date.now();
|
||||
const RESEND_COOLDOWN_MS = 60 * 1000;
|
||||
|
||||
if (!lastUpdate || (lastUpdate && now - +lastUpdate > 60 * 1000)) {
|
||||
$logger.info(`[AuthController:sendLoginCode] updating login code for user`);
|
||||
|
||||
await req.appUser.authManager.repository.updateLoginCode(code, email);
|
||||
|
||||
$logger.info(`[AuthController:sendLoginCode] sending code by email to`);
|
||||
|
||||
await this.sendCodeByEmail(code.split(':')[0], email);
|
||||
if (lastUpdate && now - +lastUpdate < RESEND_COOLDOWN_MS) {
|
||||
return res.status(429).send({
|
||||
message: 'Please wait before requesting another code.',
|
||||
retryAfter: Math.ceil((RESEND_COOLDOWN_MS - (now - +lastUpdate)) / 1000),
|
||||
});
|
||||
}
|
||||
|
||||
$logger.info(`[AuthController:sendLoginCode] updating login code for user`);
|
||||
await req.appUser.authManager.repository.updateLoginCode(code, email);
|
||||
$logger.info(`[AuthController:sendLoginCode] sending code by email to`);
|
||||
this.sendCodeByEmail(code.split(':')[0], email)
|
||||
.then((ok) => {
|
||||
if (!ok) $logger.error({ email }, 'Failed to send login code email');
|
||||
})
|
||||
.catch((err) => $logger.error({ err, email }, 'Failed to send login code email'));
|
||||
return res.status(200).end();
|
||||
};
|
||||
|
||||
async sendCodeByEmail(code: string, email: string) {
|
||||
const text = `Your TaskView verification code is ${code}\n\nUse this code to sign in. The code expires in 5 minutes.\n\nIf you didn't request this code, ignore this email.`;
|
||||
const html = LoginCodeEmailTemplate.replace('{code}', code);
|
||||
|
||||
return await Email.send({
|
||||
text: null,
|
||||
text,
|
||||
to: email,
|
||||
subject: 'Code',
|
||||
subject: `Your TaskView code: ${code}`,
|
||||
from: process.env.SMTP_FROM_EMAIL as string,
|
||||
attachment: [{ data: `<span>Code <strong>${code}</strong></span>`, alternative: true }],
|
||||
attachment: [{ data: html, alternative: true }],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -295,8 +309,8 @@ export default class AuthController {
|
||||
|
||||
loginByCode = async (req: Request, res: Response) => {
|
||||
const schema = z.object({
|
||||
email: z.string().email().toLowerCase(),
|
||||
code: z.string().min(12).toLowerCase(),
|
||||
email: z.string().trim().email().toLowerCase(),
|
||||
code: z.string().trim().regex(/^\d{6}$/, '6-digit code'),
|
||||
});
|
||||
|
||||
const data = schema.safeParse(req.body);
|
||||
@@ -323,7 +337,7 @@ export default class AuthController {
|
||||
return res.status(400).send({ message: 'Invalid code' });
|
||||
}
|
||||
|
||||
if (tokenFromDb[1] && Date.now() - +tokenFromDb[1] > 60 * 1000) {
|
||||
if (tokenFromDb[1] && Date.now() - +tokenFromDb[1] > LOGIN_CODE_TTL_MS) {
|
||||
await req.appUser.authManager.repository.updateLoginCode(null, userData.email);
|
||||
return res.status(400).send({ message: 'Code expired, get new code' });
|
||||
}
|
||||
@@ -538,9 +552,11 @@ export default class AuthController {
|
||||
subject: 'Remind password!',
|
||||
from: process.env.SMTP_FROM_EMAIL as string,
|
||||
attachment: [{ data: remindPasswordBody, alternative: true }],
|
||||
}).catch((err) => {
|
||||
$logger.error({ err, to: userData.email }, 'Failed to send remind password email');
|
||||
});
|
||||
})
|
||||
.then((ok) => {
|
||||
if (!ok) $logger.error({ to: userData.email }, 'Failed to send remind password email');
|
||||
})
|
||||
.catch((err) => $logger.error({ err, to: userData.email }, 'Failed to send remind password email'));
|
||||
|
||||
return respond();
|
||||
};
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
export default `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="format-detection" content="telephone=no" />
|
||||
<meta name="color-scheme" content="only" />
|
||||
<title>TaskView verification code</title>
|
||||
</head>
|
||||
<body style="margin: 0; padding: 0; background-color: #f5f7fa; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color: #f5f7fa;">
|
||||
<tr>
|
||||
<td align="center" style="padding: 40px 16px;">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width: 480px; background-color: #ffffff; border-radius: 12px; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);">
|
||||
<tr>
|
||||
<td style="padding: 40px 32px 24px; text-align: center;">
|
||||
<div style="font-size: 18px; font-weight: 600; color: #000000; letter-spacing: 0.5px;">TaskView</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 0 32px 16px; text-align: center;">
|
||||
<h1 style="margin: 0; font-size: 20px; font-weight: 600; color: #18181b;">Your verification code</h1>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 0 32px 24px; text-align: center;">
|
||||
<p style="margin: 0; font-size: 14px; line-height: 1.5; color: #71717a;">Use the code below to sign in. It expires in 5 minutes.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" style="padding: 0 32px 32px;">
|
||||
<div style="display: inline-block; padding: 20px 28px; background-color: #f4f4f5; border-radius: 10px; font-family: 'SF Mono', Menlo, Consolas, monospace; font-size: 36px; font-weight: 600; letter-spacing: 8px; color: #18181b;">{code}</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 0 32px 40px; text-align: center;">
|
||||
<p style="margin: 0; font-size: 13px; line-height: 1.5; color: #a1a1aa;">If you didn't request this code, you can safely ignore this email.</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p style="margin: 24px 0 0; font-size: 12px; color: #a1a1aa; text-align: center;">© TaskView</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`
|
||||
Reference in New Issue
Block a user