Friday 2 June 2017

How to save authenticated passport OAuth2 to express session

I have thoroughly hit my head against this as long as I would like.

I am trying to make it so that once the user has authenticated Slack that the express session saves the slack auth and refresh key so that slack becomes the login for the session.

Here is what I have so far.

const md5 = require("md5");
const express = require("express");
const session = require('express-session');
const passport = require('passport');
const SlackStrategy = require('passport-slack').Strategy;

const app = express();

app.set('view engine', 'ejs')

app.use(session({
    secret: "shhhh, don't tell nobody",
    cookie:{
        httpOnly: true
    }
}));
app.use(passport.initialize());
app.use(passport.session());

passport.serializeUser(function(user, done) {
    done(null, user);
});

passport.deserializeUser(function(user, done) {
    done(null, user);
});

passport.use(new SlackStrategy({
    clientID: SLACK_ID,
    clientSecret: SLACK_SECRET,
    callbackURL: SLACK_REDIRECT,
    skipUserProfile: true,
    scope: ['files:read', 'files:write:user']
    }, (accessToken, refreshToken, profile, done) => {
        console.log(accessToken, refreshToken, profile);
        done(null, accessToken);
    }
))

app.listen(80, () => {
    var time = new Date().toISOString();
    console.log(`[${time}] express site started`);
});

process.on('beforeExit', ()=>{
    var time = new Date().toISOString();
    console.log(`[${time}] express site stopped`);
});

process.on('SIGINT', ()=>{
    var time = new Date().toISOString();
    console.log(`[${time}] express site killed`);
    process.exit();
})

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect('/')
}
app.get('/auth/slack', passport.authenticate('slack'));

app.get('/auth/slack/callback', passport.authenticate('slack'),
    function(req, res) {
        console.log(res);
        res.redirect('/map');
    }
);
app.get('/logout', function(req, res){
    console.log('logging out');
    req.logout();
    res.redirect('/');
});
app.get('/map', ensureAuthenticated, (req, res)=>{
    console.log(res)
    res.render('map', {title: 'derp'})
})
app.get('/', function (req, res) {
    var html = "<ul>\
    <li><a href='/auth/slack'>Auth Slack</a></li>\
    <li><a href='/logout'>logout</a></li>\
    </ul>";

    res.send(html);
});
app.use(express.static('htdocs'));

What I cant get my head around when using passport.authenticate('slack'); is when its calling the callback or what I'm even able to do in the callback to stave to the session.

Thanks in advance!



via Sora3087

No comments:

Post a Comment