后台
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { getPrisma } from '../lib/prisma.js';
|
||||
import { env } from '../config/env.js';
|
||||
|
||||
export async function bootstrapAdmin() {
|
||||
const prisma = getPrisma();
|
||||
if ((await prisma.user.count()) === 0) {
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
username: env.ADMIN_USERNAME,
|
||||
passwordHash: await bcrypt.hash(env.ADMIN_PASSWORD, 10),
|
||||
},
|
||||
});
|
||||
console.log(`seeded admin "${env.ADMIN_USERNAME}"`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function login(username: string, password: string) {
|
||||
const prisma = getPrisma();
|
||||
const user = await prisma.user.findUnique({ where: { username } });
|
||||
if (!user || !(await bcrypt.compare(password, user.passwordHash)))
|
||||
throw Object.assign(new Error('invalid credentials'), { status: 401 });
|
||||
return {
|
||||
token: jwt.sign({ sub: String(user.id), u: user.username }, env.JWT_SECRET, {
|
||||
expiresIn: env.JWT_EXPIRES_IN,
|
||||
} as jwt.SignOptions),
|
||||
expiresIn: env.JWT_EXPIRES_IN,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user