正在显示
4 个修改的文件
包含
104 行增加
和
2 行删除
examples/auth/google/auth.js
0 → 100644
1 | +/** | |
2 | + * Add following code to auth() function in | |
3 | + * ./config/auth.js | |
4 | + * | |
5 | + * It's better to keep 'returnURL' and 'realm' | |
6 | + * in settings. | |
7 | + */ | |
8 | + | |
9 | + | |
10 | +var GoogleStrategy = require('passport-google').Strategy | |
11 | + | |
12 | +passport.use( new GoogleStrategy({ | |
13 | + returnURL: 'http://localhost:3000/auth/google/callback', | |
14 | + realm: 'http://localhost:3000', | |
15 | + passReqToCallback: true | |
16 | + }, | |
17 | + function(req, identifier, profile, done) { | |
18 | + | |
19 | + var email = profile.emails[ 0 ].value | |
20 | + var User = lib.db.model('User') | |
21 | + | |
22 | + // save user | |
23 | + User.findOne({ | |
24 | + email: email | |
25 | + }, function( err, user ) { | |
26 | + | |
27 | + if (!user) { | |
28 | + User.create({ | |
29 | + email: email, | |
30 | + name: profile.displayName, | |
31 | + }, function(err, user) { | |
32 | + | |
33 | + // Update lastToken | |
34 | + user.lastToken = identifier | |
35 | + user.save() | |
36 | + return done( err, user ) | |
37 | + }); | |
38 | + | |
39 | + } else { | |
40 | + // Update lastToken | |
41 | + user.lastToken = identifier | |
42 | + user.save() | |
43 | + return done( err, user ) | |
44 | + } | |
45 | + | |
46 | + }); | |
47 | + } | |
48 | +)); | |
\ No newline at end of file | ... | ... |
examples/auth/google/routes.js
0 → 100644
1 | +/** | |
2 | + * Add following code to routes() function in | |
3 | + * your ./config/routes.js file. | |
4 | + */ | |
5 | + | |
6 | +var passport = require('passport') | |
7 | + | |
8 | +// auth route | |
9 | + | |
10 | +app.get('/auth/google', function(req,res,next) { | |
11 | + // add remember me details etc. here | |
12 | + next() | |
13 | + }, | |
14 | + passport.authenticate('google', { failureRedirect: '/', failureFlash: true }), | |
15 | + function(req, res) { | |
16 | + res.redirect('/') | |
17 | + }); | |
18 | + | |
19 | +// auth callback | |
20 | + | |
21 | +app.get('/auth/google/callback', | |
22 | + passport.authenticate( 'google', { | |
23 | + failureRedirect: '/' | |
24 | + }), | |
25 | + function(req, res, next) { | |
26 | + var redirectTo = req.session.redirectTo; | |
27 | + | |
28 | + // Successful authentication, redirect to dashboard page. | |
29 | + if ( redirectTo ) { | |
30 | + req.session.redirectTo = null | |
31 | + res.redirect(redirectTo) | |
32 | + } else { | |
33 | + res.redirect('/logged-in') | |
34 | + } | |
35 | + } | |
36 | +); | |
37 | + | |
38 | +// log out | |
39 | + | |
40 | +app.get('/logout', function(req, res){ | |
41 | + req.logout() | |
42 | + res.redirect('/') | |
43 | +}); | |
44 | + | |
45 | +// sample log-in message | |
46 | + | |
47 | +app.get('/logged-in', function(req, res){ | |
48 | + req.send(200, 'Hey!') | |
49 | +}); | |
\ No newline at end of file | ... | ... |
请
注册
或
登录
后发表评论