import { createHash } from 'crypto';
import nextConnect from 'next-connect';
import { NextApiRequest, NextApiResponse, PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an49 from '@mmstudio/an000049';
import { sign } from 'jsonwebtoken';
import mmconf from '@mmstudio/config';
import an47 from '@mmstudio/an000047';
const logger = anylogger('pages/api/login');
const session = mmconf.session as {
secret: string;
expiresIn: string | number;
};
export type Result = boolean
export type Message = {
user: string;
psw: string;
}
const handler = nextConnect<NextApiRequest, NextApiResponse<Result>>();
handler.post(async (req, res) => {
logger.debug('msg body:', req.body);
const { user, psw } = req.body as Message;
const db = an49();
const tb1 = db<ITbuser>('user');
const val = md5(psw);
const u = await tb1.first('userid', 'role', 'name', 'phone', 'email').where({
userid: user,
psw: val
});
if (!u) {
const msg = '帐户名或密码错误';
res.statusMessage = encodeURIComponent(msg);
res.status(500).end(msg);
return;
}
const token = sign(u, session.secret, { expiresIn: session.expiresIn, algorithm: 'HS256' });
logger.debug('userlogin success', u, 'token', token);
an47(res, 'token', token, { sameSite: 'lax', httpOnly: true });
(() => {
const key = '01factory';
const options = {};
return an47(res, key, token, options);
})();
res.status(200).json(true);
});
export const config = {} as PageConfig;
export default handler;
function md5(value: string) {
return createHash('md5').update(value).digest('hex');
}