|
|
@@ -71,6 +71,73 @@ export class UserController {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ async adminLogin(request: FastifyRequest<{ Body: LoginBody }>, reply: FastifyReply) {
|
|
|
+ try {
|
|
|
+ const { name, password } = request.body
|
|
|
+ if (!name || !password) {
|
|
|
+ return reply.code(400).send({ message: '请输入用户名和密码' })
|
|
|
+ }
|
|
|
+ const user = await this.userService.findByName(name)
|
|
|
+ if (!user) {
|
|
|
+ return reply.code(401).send({ message: '用户名或密码错误' })
|
|
|
+ }
|
|
|
+
|
|
|
+ // 验证角色必须是 admin
|
|
|
+ if (user.role !== UserRole.ADMIN) {
|
|
|
+ return reply.code(403).send({ message: '该账号无管理员权限' })
|
|
|
+ }
|
|
|
+
|
|
|
+ const isValidPassword = await this.userService.validatePassword(user, password)
|
|
|
+ if (!isValidPassword) {
|
|
|
+ return reply.code(401).send({ message: '用户名或密码错误' })
|
|
|
+ }
|
|
|
+
|
|
|
+ const token = await reply.jwtSign({ id: user.id, name: user.name, role: user.role })
|
|
|
+
|
|
|
+ return reply.send({
|
|
|
+ user: {
|
|
|
+ id: user.id,
|
|
|
+ name: user.name,
|
|
|
+ role: user.role
|
|
|
+ },
|
|
|
+ token
|
|
|
+ })
|
|
|
+ } catch (error) {
|
|
|
+ return reply.code(500).send(error)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async userLogin(request: FastifyRequest<{ Body: LoginBody }>, reply: FastifyReply) {
|
|
|
+ try {
|
|
|
+ const { name, password } = request.body
|
|
|
+ if (!name || !password) {
|
|
|
+ return reply.code(400).send({ message: '请输入用户名和密码' })
|
|
|
+ }
|
|
|
+ const user = await this.userService.findByName(name)
|
|
|
+ if (!user || user?.role !== UserRole.USER) {
|
|
|
+ return reply.code(401).send({ message: '用户名或密码错误' })
|
|
|
+ }
|
|
|
+
|
|
|
+ const isValidPassword = await this.userService.validatePassword(user, password)
|
|
|
+ if (!isValidPassword) {
|
|
|
+ return reply.code(401).send({ message: '用户名或密码错误' })
|
|
|
+ }
|
|
|
+
|
|
|
+ const token = await reply.jwtSign({ id: user.id, name: user.name, role: user.role })
|
|
|
+
|
|
|
+ return reply.send({
|
|
|
+ user: {
|
|
|
+ id: user.id,
|
|
|
+ name: user.name,
|
|
|
+ role: user.role
|
|
|
+ },
|
|
|
+ token
|
|
|
+ })
|
|
|
+ } catch (error) {
|
|
|
+ return reply.code(500).send(error)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
async profile(request: FastifyRequest, reply: FastifyReply) {
|
|
|
try {
|
|
|
const user = await this.userService.findById(request.user.id)
|