authorization.js 1.1 KB
/*
 * 添加passport验证登录权限方法
 */
module.exports = (app) => {
  app.passport.verify(async (ctx, user) => {
    const { provider = "" } = user;
    const { service = {} } = ctx;
    const { redirect_uri } = ctx.request.body;
    let result;
    switch (provider) {
      case "local":
        result = await service.login.localLogin(user);
        break;
      default:
        // console.log("error:", user)
        break;
    }
    if (result && result.code >= 300) {
      ctx.status = result.status;
      ctx.body = result.data;
      return false;
    }
    if (!result) {
      ctx.status = 500;
      ctx.body = {
        message: "用户或密码错误",
      };
      return false;
    }
    if (redirect_uri) {
      ctx.session.returnTo = `${redirect_uri}?ticket=${Math.random(10000)}`;
    }
    return result;
  });

  // 序列化与反序列化,序列化存储到session中只保存用户id
  app.passport.serializeUser(async (ctx, user) => {
    return user;
  });

  app.passport.deserializeUser(async (ctx, user) => {
    return user;
  });
};