Coder Social home page Coder Social logo

Comments (8)

vcwen avatar vcwen commented on August 19, 2024

你用loopback-passport-component的话,已经在providers写了ballback URL,loopback会处理callbak,而且calbakURL,/auth/wechat/callback,默认成功就是到/account。你可以在providers.json里设置successRedirect为你想要成功后的跳转。server.js不应该在写authenticate方法了

from passport-wechat-public.

JoeShi avatar JoeShi commented on August 19, 2024

谢谢 @wenwei1202 , 我需要实现动态回调, callbackURL 不是固定的,所以看来我不能写在providers.json里了。我按照 这里的做法模仿写了一个。 每次都会重定向到 /error

passport.use("wechat", new WechatStrategy({
  appId: app.get('wechat').appId,
  appSecret: app.get('wechat').secret,
  state: "state",
  scope: "snsapi_userinfo",
  agent: "wechat"
},
  function (accessToken, refreshToken, profile, done) {
    console.log("profile....");
    console.log(profile);
    var User = app.models.user;
    var UserIdentity = app.models.userIdentity;
    UserIdentity.findOrCreate(
      {
        provider: "wechat",
        externalId: profile.unionid
      },
      {
        provider: "wechat",
        externalId: profile.unionid,
        profile: profile,
        created: new Date(),
        authScheme: "OAuth 2.0"
      },
      function (error, userIdentity, created) {
        if (error) {
          done(error);
          return;
        }
        // Check If the UserIdentity is newly created.
        if (created) {
          User.create({
            created: new Date(),
            username: "wechat." + userIdentity.externalId,
            password: "saltyegg",
            email: userIdentity.externalId+"@loopback.wechat.com"
          }, function (error, user) {
            console.log('creating user.........');
            if (!error) {
              userIdentity.updateAttributes(
                {
                  userId: user.id
                }, function (error, instance) {
                  if (error) {
                    console.error(error);
                    done(error);
                  }
                }
              )
            } else {
              console.error(error);
              done(error);
              return;
            }
            console.log("user created.......");
            console.log(user)
          })
        } else {
          // The UserIdentity already exists.
          console.log("user exists........");
          userIdentity.user(function (error, user) {
            done(error, user);
          });
        }
      }
    )
}));


app.get("/auth/wechat/event/:id", function(req, res, next) {
  passport.authenticate("wechat",
    {
      callbackURL: "/auth/wechat/callback/event/" + req.params.id
    })(req, res, next);
});

app.get("/auth/wechat/callback/event/:id", function (req, res, next) {
  passport.authenticate("wechat", {
    callbackURL: "/auth/wechat/callback/event/" + req.params.id,
    successRedirect: "/event/" + req.params.id,
    failureRedirect: "/error"
  })(req, res, next);
});

from passport-wechat-public.

JoeShi avatar JoeShi commented on August 19, 2024

我有多个网页需要authentication. 我的基本想法是:

/event/:id 如果未登陆就发送到 /auth/wechat/event/:id 进行authentication.
/calendar/:id 发送到 /auth/wechat/calendar/:id 进行authentication.

但是我觉得 authenticate 的方式都应该是一个, 不知道对不对。如:

passport.use("wechat", new WechatStrategy({})  //这里的callbackURL 不写,或者下面可以重写。

app.get("/auth/wechat/event/:id", function(req, res, next) {
  passport.authenticate("wechat",
    {
      callbackURL: "/auth/wechat/callback/event/" + req.params.id
    })(req, res, next);
});

app.get("/auth/wechat/calendar/:id", function(req, res, next) {
  passport.authenticate("wechat",
    {
      callbackURL: "/auth/wechat/callback/calendar/" + req.params.id
    })(req, res, next);
});

from passport-wechat-public.

vcwen avatar vcwen commented on August 19, 2024

我觉得你需要的是connect-ensure-login这个模块, 例如auth path是/auth/wechat, callbck path是/auth/wechat/callback, success redirect是/auth/wechat/account,
app.get("/calendar/:id",ensureLoggedIn('/auth/wechat'),function(req, res) {...})
app.get("/event/:id",ensureLoggedIn('/auth/wechat'),function(req, res) {...})

app.get("/auth/wechat/account",function(req, res) {
if(req.session.returnTo) {
  req.redirect(req.session.returnTo)
} else {
//default handler
}

})

from passport-wechat-public.

JoeShi avatar JoeShi commented on August 19, 2024

你好 @wenwei1202

代码实现如下, 每次运行会,会被定向到 /account, 但是会报错,

TypeError: Cannot read property 'returnTo' of undefined
    at /Users/Joe/Developer/Wechat/server/server.js:79:26
passport.use("wechat",new WechatStrategy({
    appId: app.get('wechat').appId,
    appSecret: app.get('wechat').secret,
    callbackURL: "/auth/wechat/callback",
    state: "state",
    scope: "snsapi_base",
    agent: "wechat"
  },
  function(accessToken, refreshToken, profile, done) {
    done(null, profile);
  }
));

app.get('/auth/wechat',
  passport.authenticate('wechat'));

app.get('/auth/wechat/callback',
  passport.authenticate('wechat', { failureRedirect: '/login', successReturnToOrRedirect: '/account'}));

app.get('/account', function(req, res) {
  console.log('/account');
  console.log(req.session.returnTo);
  if (req.session.returnTo) {
    res.redirect(req.session.returnTo);
  }
});

app.get('/event/:id', ensureLoggedIn('/auth/wechat'), function(req, res) {
  res.redirect('/event/' + req.params.id);
});

from passport-wechat-public.

vcwen avatar vcwen commented on August 19, 2024

TypeError: Cannot read property 'returnTo' of undefined, 说明session没有设置,你有设置session吗?

from passport-wechat-public.

JoeShi avatar JoeShi commented on August 19, 2024

如果我加上下面这段代码,那么当我 GET /event/123 的时候,就出现无限去请求微信授权的情况,但是我 'GET /auth/wechat' 正常。

代码是模仿 loopback-passport-example写的。

app.middleware('session:before', loopback.cookieParser(app.get('cookieSecret')));
app.middleware('session', loopback.session({
  secret: 'kitty',
  saveUninitialized: true,
  resave: false
}));

from passport-wechat-public.

vcwen avatar vcwen commented on August 19, 2024

app.get('/event/:id', ensureLoggedIn('/auth/wechat'), function(req, res) {
res.redirect('/event/' + req.params.id);
});

这个本身就是个死循环

from passport-wechat-public.

Related Issues (3)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.