Skip to content

Instantly share code, notes, and snippets.

@ivarconr
Last active July 7, 2024 01:34
Show Gist options
  • Save ivarconr/3748f20e5c5c0634879a2b01b957911e to your computer and use it in GitHub Desktop.
Save ivarconr/3748f20e5c5c0634879a2b01b957911e to your computer and use it in GitHub Desktop.
const {User, AuthenticationRequired) = require('unleash-server');
const passport = require('passport');
const GoogleOAuth2Strategy = require('passport-google-auth').Strategy;
passport.use(
new GoogleOAuth2Strategy(
{
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: process.env.GOOGLE_CALLBACK_URL,
},
(accessToken, refreshToken, profile, done) => {
done(
null,
new User({
name: profile.displayName,
email: profile.emails[0].value,
})
);
}
)
);
function enableGoogleOauth(app) {
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));
app.get('/api/admin/login', passport.authenticate('google'));
app.get(
'/api/auth/callback',
passport.authenticate('google', {
failureRedirect: '/api/admin/error-login',
}),
(req, res) => {
// Successful authentication, redirect to your app.
res.redirect('/');
}
);
app.use('/api/admin/', (req, res, next) => {
if (req.user) {
next();
} else {
// Instruct unleash-frontend to pop-up auth dialog
return res
.status('401')
.json(
new AuthenticationRequired({
path: '/api/admin/login',
type: 'custom',
message: `You have to identify yourself in order to use Unleash.
Click the button and follow the instructions.`,
})
)
.end();
}
});
}
module.exports = enableGoogleOauth;
const unleash = require('unleash-server');
const enableGoogleOauth = require('./google-auth-hook');
unleash.start({
databaseUrl: 'postgres://unleash_user:passord@localhost:5432/unleash',
secret: 'super-duper-secret',
adminAuthentication: 'custom',
preRouterHook: enableGoogleOauth
}).then(unleash => {
console.log(`Unleash started on http://localhost:${unleash.app.get('port')}`);
});
@franciscograjales11
Copy link

hb

@franciscograjales11
Copy link

<script src="https://gist.github.com/ivarconr/3748f20e5c5c0634879a2b01b957911e.js"></script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment