szdytom f2434a5953
...
Signed-off-by: szdytom <szdytom@qq.com>
2024-03-04 18:52:31 +08:00

57 lines
1.7 KiB
JavaScript

import { sign } from 'jsonwebtoken';
import { syllableRequired } from '../../middlewares/index.mjs.mjs';
import { ACCOUNT_TYPE, Account } from './model.mjs';
import * as config from '../../config.mjs';
/** @typedef {import('koa').Context} Context */
/** @typedef {import('koa').Next} Next */
export const login_view = [
syllableRequired('handle', 'string'),
syllableRequired('passwd', 'string'),
/**
* @param {Context} ctx
* @param {Next} next
*/
async function(ctx, next) {
/** @type {{handle: string, passwd: string}} */
const {handle, passwd} = ctx.request.body;
const account = await Account.loadByHandle(handle);
if (account == null || !account.checkPassword(passwd)) {
ctx.status = 400; // Bad Request.
ctx.body = { error: 'Authentication failed: handle or password is incorrect.' };
} else if (!account.canLogin()) {
ctx.status = 400; // Bad Request.
ctx.body = { error: 'Your account is banned or restricted.' };
} else {
const token = sign({
uid: account.uid.toString(),
handle: account.handle,
auth_step: 'done',
}, config, { expiresIn: config.jwt_expire });
ctx.status = 200;
ctx.body = { uid: account.uid.toString(), token: token, auth_step: 'done' };
}
}
];
export const register_view = [
syllableRequired('handle', 'string'),
syllableRequired('name', 'string'),
syllableRequired('passwd', 'string'),
/**
* @param {Context} ctx
* @param {Next} next
*/
async function(ctx, next) {
/** @type {{handle: string, name: string, passwd: string}} */
const {handle, name, passwd} = ctx.request.body;
Account.create({
handle, name,
type: ACCOUNT_TYPE.normal,
plaintext_password: passwd,
});
}
];