Skip to content

Commit 21082b6

Browse files
Create PassportOAuth2Middleware
1 parent 42ad8bc commit 21082b6

File tree

2 files changed

+101
-78
lines changed

2 files changed

+101
-78
lines changed

src/middleware.js

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import url from 'node:url';
2+
import passport from 'passport';
3+
import OAuth2Strategy from 'passport-oauth2';
4+
import { InternalOAuthError } from 'passport-oauth2';
5+
import { Router } from 'express';
6+
7+
passport.serializeUser(function(user, cb) {
8+
process.nextTick(function() {
9+
cb(null, { id: user.id, username: user.username, accessToken: user.accessToken });
10+
});
11+
});
12+
13+
passport.deserializeUser(function(user, cb) {
14+
process.nextTick(function() {
15+
return cb(null, user);
16+
});
17+
});
18+
19+
const PassportOAuth2Middleware = function (options) {
20+
const gitlabOAuth2Strategy = new OAuth2Strategy(
21+
{
22+
// configuration inspired from https://github.com/fh1ch/passport-gitlab2/blob/4238b67438c1f1a7050908556ac010bc319b734a/lib/strategy.js
23+
clientID: options.clientID,
24+
clientSecret: options.clientSecret,
25+
authorizationURL: options.authorizationURL,
26+
tokenURL: options.tokenURL,
27+
scope: options.scope,
28+
scopeSeparator: options.scopeSeparator,
29+
callbackURL: options.callbackURL
30+
},
31+
function(accessToken, refreshToken, profile, cb) {
32+
return cb(
33+
null,
34+
{
35+
id: profile.id,
36+
username: profile.username,
37+
accessToken: accessToken
38+
}
39+
);
40+
}
41+
);
42+
gitlabOAuth2Strategy.userProfile = function (accesstoken, done) {
43+
this._oauth2.get(
44+
url.resolve(process.env.GITLAB_BASEURL, 'api/v4/user'),
45+
accesstoken,
46+
(err, body) => {
47+
let json;
48+
if (err) {
49+
return done(new InternalOAuthError('Failed to fetch user profile', err));
50+
}
51+
52+
try {
53+
json = JSON.parse(body);
54+
} catch (ex) {
55+
return done(new Error('Failed to parse user profile'));
56+
}
57+
58+
const profile = {
59+
id: String(json.id),
60+
username: json.username,
61+
displayName: json.name,
62+
emails: [{value: json.email}],
63+
avatarUrl: json.avatar_url,
64+
profileUrl: json.web_url
65+
};
66+
67+
done(null, profile);
68+
}
69+
);
70+
};
71+
passport.use(gitlabOAuth2Strategy);
72+
const router = Router();
73+
74+
router.get(
75+
'/auth/gitlab',
76+
(req, res, next) => {
77+
passport.authenticate(
78+
'oauth2'
79+
)(req, res);
80+
}
81+
);
82+
83+
router.get(
84+
'/auth/gitlab/callback',
85+
passport.authenticate('oauth2', {
86+
failureRedirect: '/login'
87+
}),
88+
(req, res, next) => {
89+
console.log('Successful authentication, redirect home');
90+
res.redirect('/');
91+
}
92+
);
93+
return router;
94+
}
95+
96+
export default PassportOAuth2Middleware;

src/server.js

Lines changed: 5 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
import url from 'node:url';
22
import express from 'express';
3-
import passport from 'passport';
4-
import OAuth2Strategy from 'passport-oauth2';
5-
import { InternalOAuthError } from 'passport-oauth2';
63
import session from 'express-session';
4+
import PassportOAuth2Middleware from './middleware.js';
75

86
const app = express();
97
const port = 3000;
@@ -14,20 +12,10 @@ app.use(session({
1412
saveUninitialized: true
1513
}));
1614

17-
passport.serializeUser(function(user, cb) {
18-
process.nextTick(function() {
19-
cb(null, { id: user.id, username: user.username, accessToken: user.accessToken });
20-
});
21-
});
22-
23-
passport.deserializeUser(function(user, cb) {
24-
process.nextTick(function() {
25-
return cb(null, user);
26-
});
27-
});
2815

29-
const gitlabOAuth2Strategy = new OAuth2Strategy(
30-
{
16+
app.use(
17+
'/',
18+
PassportOAuth2Middleware({
3119
// configuration inspired from https://github.com/fh1ch/passport-gitlab2/blob/4238b67438c1f1a7050908556ac010bc319b734a/lib/strategy.js
3220
clientID: process.env.GITLAB_CLIENT_ID,
3321
clientSecret: process.env.GITLAB_CLIENT_SECRET,
@@ -36,51 +24,9 @@ const gitlabOAuth2Strategy = new OAuth2Strategy(
3624
scope: "api email profile",
3725
scopeSeparator: " ",
3826
callbackURL: 'http://127.0.0.1:3000/auth/gitlab/callback'
39-
},
40-
function(accessToken, refreshToken, profile, cb) {
41-
return cb(
42-
null,
43-
{
44-
id: profile.id,
45-
username: profile.username,
46-
accessToken: accessToken
47-
}
48-
);
49-
}
27+
})
5028
);
5129

52-
gitlabOAuth2Strategy.userProfile = function (accesstoken, done) {
53-
this._oauth2.get(
54-
url.resolve(process.env.GITLAB_BASEURL, 'api/v4/user'),
55-
accesstoken,
56-
(err, body) => {
57-
let json;
58-
if (err) {
59-
return done(new InternalOAuthError('Failed to fetch user profile', err));
60-
}
61-
62-
try {
63-
json = JSON.parse(body);
64-
} catch (ex) {
65-
return done(new Error('Failed to parse user profile'));
66-
}
67-
68-
const profile = {
69-
id: String(json.id),
70-
username: json.username,
71-
displayName: json.name,
72-
emails: [{value: json.email}],
73-
avatarUrl: json.avatar_url,
74-
profileUrl: json.web_url
75-
};
76-
77-
done(null, profile);
78-
}
79-
);
80-
};
81-
82-
passport.use(gitlabOAuth2Strategy);
83-
8430
app.get('/', (req, res) => {
8531
if (req.session?.passport?.user?.id) {
8632
res.send(`<ul>
@@ -96,25 +42,6 @@ app.get('/', (req, res) => {
9642
}
9743
});
9844

99-
app.get(
100-
'/auth/gitlab',
101-
passport.authenticate(
102-
'oauth2'
103-
)
104-
);
105-
106-
app.get(
107-
'/auth/gitlab/callback',
108-
passport.authenticate('oauth2', {
109-
failureRedirect: '/login'
110-
}),
111-
function(req, res) {
112-
// Successful authentication, redirect home.
113-
console.log('Successful authentication, redirect home');
114-
res.redirect('/');
115-
}
116-
);
117-
11845
app.get('/logout', (req, res) => {
11946
req.session.destroy(function(err) {
12047
res.redirect('/');

0 commit comments

Comments
 (0)