221 lines
6.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Controller } = require('egg');
const { generateSalt, hashPassword } = require('../lib/password');
const { CODE_TTL, sendCode, verifyCode } = require('../lib/emailCode');
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
/**
* @controller AuthController 登录鉴权
*/
class AuthController extends Controller {
/**
* @summary 发送邮箱验证码
* @description 注册前置步骤:校验邮箱格式与唯一性后,发送 6 位验证码(10 分钟内有效);
* 受频率限制:同一邮箱 60 秒一次、每日上限 10 次,超限返回 429
* @router post /api/auth/email-code
* @request body sendEmailCodeRequest *body
* @response 200 baseResponse success
*/
async sendEmailCode() {
const { ctx, app } = this;
const { email } = ctx.request.body;
if (!email || !EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
return;
}
const exist = await ctx.model.User.findOne({ where: { email } });
if (exist) {
ctx.status = 400;
ctx.body = { code: 400, message: '邮箱已被注册' };
return;
}
const result = await sendCode(app, email, { ip: ctx.ip, scene: 'register' });
if (!result.ok) {
ctx.status = 429;
ctx.body = { code: 429, message: result.message };
return;
}
ctx.body = {
code: 0,
message: 'success',
data: { email, expires_in: CODE_TTL },
};
}
/**
* @summary 账号密码登录(支持用户名或邮箱)
* @description 校验登录账号或邮箱(account 字段)与加盐密码,成功后签发 JWT;token 载荷仅包含 user_id,不含敏感信息
* @router post /api/auth/login
* @request body loginRequest *body
* @response 200 loginResponse success
*/
async login() {
const { ctx, app } = this;
const { account, password } = ctx.request.body;
if (!account || !password) {
ctx.status = 400;
ctx.body = { code: 400, message: 'account 与 password 为必填项' };
return;
}
const user = await ctx.model.User.findOne({
where: {
[app.Sequelize.Op.or]: [{ username: account }, { email: account }],
},
});
if (!user) {
ctx.status = 401;
ctx.body = { code: 401, message: '账号或密码错误' };
return;
}
if (Number(user.status) !== 1) {
ctx.status = 403;
ctx.body = { code: 403, message: '账号已禁用' };
return;
}
if (hashPassword(password, user.salt) !== user.password) {
ctx.status = 401;
ctx.body = { code: 401, message: '账号或密码错误' };
return;
}
const expiresIn = app.config.jwt.expiresIn || '2h';
const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn });
await user.update({ last_login_at: new Date() });
ctx.body = {
code: 0,
message: 'success',
data: {
token,
user_id: user.id,
expires_in: this.parseExpiresIn(expiresIn),
},
};
}
/**
* @summary 用户注册
* @description 公开接口,无需登录;需先调用发送邮箱验证码接口完成邮箱认证,邮箱全局唯一;
* 密码加盐存储,注册成功后直接返回 token
* @router post /api/auth/register
* @request body registerRequest *body
* @response 200 loginResponse success
*/
async register() {
const { ctx, app } = this;
const { username, password, email, code, nickname, phone } = ctx.request.body;
if (!username || !password || !email || !code) {
ctx.status = 400;
ctx.body = { code: 400, message: 'username、password、email、code 为必填项' };
return;
}
if (String(password).length < 6) {
ctx.status = 400;
ctx.body = { code: 400, message: '密码长度不能少于 6 位' };
return;
}
if (!EMAIL_REGEX.test(email)) {
ctx.status = 400;
ctx.body = { code: 400, message: '请填写正确的邮箱地址' };
return;
}
const usernameExist = await ctx.model.User.findOne({ where: { username } });
if (usernameExist) {
ctx.status = 400;
ctx.body = { code: 400, message: '账号已存在' };
return;
}
const emailExist = await ctx.model.User.findOne({ where: { email } });
if (emailExist) {
ctx.status = 400;
ctx.body = { code: 400, message: '邮箱已被注册' };
return;
}
// 邮箱认证:校验验证码,通过后该验证码立即失效
const verified = await verifyCode(app, email, code);
if (!verified) {
ctx.status = 400;
ctx.body = { code: 400, message: '邮箱验证码错误或已过期' };
return;
}
const salt = generateSalt();
const user = await ctx.model.User.create({
username,
nickname: nickname || username,
email,
phone,
salt,
password: hashPassword(password, salt),
status: 1,
});
const expiresIn = app.config.jwt.expiresIn || '2h';
const token = app.jwt.sign({ user_id: user.id }, app.config.jwt.secret, { expiresIn });
ctx.body = {
code: 0,
message: 'success',
data: {
token,
user_id: user.id,
expires_in: this.parseExpiresIn(expiresIn),
},
};
}
/**
* @summary 当前登录用户信息
* @description 需要登录:请求头 Authorization: Bearer <token>
* @router get /api/auth/profile
* @apikey
* @response 200 baseResponse success
*/
async profile() {
const { ctx } = this;
const user = await ctx.model.User.findByPk(ctx.userId, {
attributes: { exclude: [ 'password', 'salt' ] },
});
if (!user) {
ctx.status = 404;
ctx.body = { code: 404, message: '用户不存在' };
return;
}
ctx.body = { code: 0, message: 'success', data: user };
}
/**
* 将有效期配置转换为秒数(如 2h => 7200)
* @param {String|Number} expiresIn 有效期,如 2h / 7200
* @return {Number} 有效秒数
*/
parseExpiresIn(expiresIn) {
if (typeof expiresIn === 'number') return expiresIn;
const matched = /^(\d+)([smhd])$/.exec(expiresIn);
if (!matched) return 0;
const units = { s: 1, m: 60, h: 3600, d: 86400 };
return Number(matched[1]) * units[matched[2]];
}
}
module.exports = AuthController;