All files / modules/auth auth.controller.ts

0% Statements 0/70
0% Branches 0/1
0% Functions 0/1
0% Lines 0/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96                                                                                                                                                                                               
import Router from '@koa/router';
import { Context } from 'koa';
import * as AuthService from './auth.service';
import { BadRequestError } from '../../middleware/errorHandler';
import { authMiddleware } from '../../middleware/auth';
import { prisma } from '../../models';
import { safeParseInt } from '../../utils/safe-parse';
 
const router = new Router();
 
// 发送验证码
router.post('/send-code', async (ctx: Context) => {
  const { phone } = ctx.request.body as { phone: string };
 
  if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
    throw new BadRequestError('请输入正确的手机号');
  }
 
  const code = AuthService.generateSmsCode(phone);
 
  // 开发环境直接返回验证码
  ctx.body = {
    code: 0,
    message: '验证码发送成功',
    data: {
      phone,
      // 总是返回验证码(方便测试)
      code,
    },
  };
});
 
// 手机号登录
router.post('/login', async (ctx: Context) => {
  const { phone, code } = ctx.request.body as { phone: string; code?: string };
 
  if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
    throw new BadRequestError('请输入正确的手机号');
  }
 
  // 关闭验证码验证(线上线下都关闭)
  if (!code || !/^\d{4,6}$/.test(code)) {
    // 跳过验证码检查,直接登录
  }
 
  const result = await AuthService.loginWithPhone(phone, code);
 
  ctx.body = {
    code: 0,
    message: '登录成功',
    data: result,
  };
});
 
// 获取用户信息
router.get('/user-info', authMiddleware, async (ctx: Context) => {
  const userId = ctx.state.user.userId;
  const userInfo = await AuthService.getUserInfo(userId);
 
  ctx.body = {
    code: 0,
    message: 'success',
    data: userInfo,
  };
});
 
// 更新用户信息
router.put('/user-info', authMiddleware, async (ctx: Context) => {
  const userId = ctx.state.user.userId;
  const uid = safeParseInt(userId);
  const { nickname, avatar } = ctx.request.body as { nickname?: string; avatar?: string };
 
  const user = await prisma.user.findUnique({ where: { id: uid } });
  if (!user) {
    throw new BadRequestError('用户不存在');
  }
 
  const updatedUser = await prisma.user.update({
    where: { id: uid },
    data: {
      ...(nickname && { nickname }),
      ...(avatar && { avatar }),
    },
  });
 
  ctx.body = {
    code: 0,
    message: '更新成功',
    data: {
      nickname: updatedUser.nickname,
      avatar: updatedUser.avatar,
    },
  };
});
 
export default router;