auth.ts 688 B

1234567891011121314151617181920212223242526
  1. import { Context, Next } from 'koa';
  2. import CODE from '@utils/code';
  3. interface InterfaceSession {
  4. user?: string
  5. }
  6. const noAuths = ['/api/login', '/api/register'];
  7. export default () => {
  8. return async (ctx: Context, next: Next): Promise<void> => {
  9. if (noAuths.includes(ctx.url)) {
  10. await next();
  11. return;
  12. }
  13. if (ctx.session) {
  14. const session: InterfaceSession = ctx.session.toJSON();
  15. if (!session.user) {
  16. ctx.session.user = null;
  17. ctx.body = ctx.$response(null, '未登录', false, CODE.NOT_LOGIN);
  18. return;
  19. }
  20. await next();
  21. } else {
  22. ctx.status = 500;
  23. ctx.throw(500, 'session获取失败');
  24. }
  25. };
  26. };