Init Strategy in app.js and format user in verify callback
// app.js
const debug = require('debug')('egg-passport-twitter');
const assert = require('assert');
const Strategy = require('passport-twitter').Strategy;
module.exports = app => {
const config = app.config.passportTwitter;
// must set passReqToCallback to true
config.passReqToCallback = true;
assert(config.key, '[egg-passport-twitter] config.passportTwitter.key required');
assert(config.secret, '[egg-passport-twitter] config.passportTwitter.secret required');
// convert to consumerKey and consumerSecret
config.consumerKey = config.key;
config.consumerSecret = config.secret;
// register twitter strategy into `app.passport`
// must require `req` params
app.passport.use('twitter', new Strategy(config, (req, token, tokenSecret, params, profile, done) => {
// format user
const user = {
provider: 'twitter',
id: profile.id,
name: profile.username,
displayName: profile.displayName,
photo: profile.photos && profile.photos[0] && profile.photos[0].value,
token,
tokenSecret,
params,
profile,
};
debug('%s %s get user: %j', req.method, req.url, user);
// let passport do verify and call verify hook
app.passport.doVerify(req, user, done);
}));
};
That’s all!
APIs
extent application
app.passport.mount(strategy, options): Mount the login and the login callback routers to use the given strategy.
app.passport.authenticate(strategy, options): Create a middleware that will authorize a third-party account using the given strategy name, with optional options.
app.passport.verify(handler): Verify authenticated user
app.passport.serializeUser(handler): Serialize user before store into session
app.passport.deserializeUser(handler): Deserialize user after restore from session
extend context
ctx.user: get the current authenticated user
ctx.isAuthenticated(): Test if request is authenticated
* ctx.login(user[, options]): Initiate a login session for user.
ctx.logout(): Terminate an existing login session
Unit Tests
This plugin has includes some mock methods to helper you writing unit tests more conveniently.
app.mockUser([user]): Mock an authenticated user
const mm = require('egg-mock');
describe('mock user demo', () => {
let app;
before(() => {
app = mm.app();
return app.ready();
});
after(() => app.close());
afterEach(mm.restore);
it('should show authenticated user info', () => {
app.mockUser();
return request(app.callback())
.get('/')
.expect(/user name: mock_name/)
.expect(200);
});
});
app.mockUserContext([user]): Mock a context instance with authenticated user
it('should get authenticated user and call service', async () => {
const ctx = app.mockUserContext();
const result = await ctx.service.findUser({ id: ctx.user.id });
assert(result.user.id === ctx.user.id);
});
egg-passport
passport plugin for egg, base on passportjs.
Install
Usage
enable passport plugin
Using Github and Twitter strategy
Authenticate Requests
Use
app.passport.mount(strategy[, options]), specifying the'github'and'twitter'strategy, to authenticate requests.Verify and store user
Use
app.passport.verify(async (ctx, user) => {})hook:How to develop an
egg-passport-${provider}pluginSee example: egg-passport-twitter.
app.passportAPIs.Must use
keyandsecretinstead ofconsumerKey|clientIDandconsumerSecret|clientSecret.Strategyinapp.jsand format user inverify callbackAPIs
extent
applicationapp.passport.mount(strategy, options): Mount the login and the login callback routers to use the givenstrategy.app.passport.authenticate(strategy, options): Create a middleware that will authorize a third-party account using the givenstrategyname, with optionaloptions.app.passport.verify(handler): Verify authenticated userapp.passport.serializeUser(handler): Serialize user before store into sessionapp.passport.deserializeUser(handler): Deserialize user after restore from sessionextend
contextctx.user: get the current authenticated userctx.isAuthenticated(): Test if request is authenticated* ctx.login(user[, options]): Initiate a login session foruser.ctx.logout(): Terminate an existing login sessionUnit Tests
This plugin has includes some mock methods to helper you writing unit tests more conveniently.
app.mockUser([user]): Mock an authenticated userapp.mockUserContext([user]): Mock a context instance with authenticated userQuestions & Suggestions
Please open an issue here.
License
MIT