Different Redirects depending on the situation Discord Passport strategy

Viewed 267

I'm a bit new to using Passport, but I was wondering if it was possible to change where the login redirects you to a different place depending on the situation. Since I can't access my res/req variables in the strategy file I was wondering if anybody had any suggestions on how to do this.

For example

Normal login

  • User clicks authorize (redirects to) -> ./profile

New User Login

  • User clicks authorize (redirects to) -> ./new-user

Here is my current router:

let express = require('express');
let router = express.Router();
const passport = require('passport');

router.get('/', passport.authenticate('discord'));


//Log out
router.get('/logout', ((req, res) => {
    req.logout();
    res.redirect('/')
}));

router.get('/redirect', passport.authenticate('discord', {
    failureRedirect: '/404',
}), ((req, res, next) => {
    console.log(req.ip + ' has logged in.')
    res.redirect('../profile')
}))



module.exports = router;

My strategy file:

const DiscordStrategy = require('passport-discord').Strategy;
const passport = require('passport');
const User = require('../schemas/User.js');
const axios = require("axios");
const MongoClient = require('mongodb').MongoClient;
const noblox = require('noblox.js');
const { getCollectionFromBotData } = require('../database');



passport.serializeUser((user, done) => {
    done(null, user.userID)
});

passport.deserializeUser(async (userID, done) => {
    let thisUser = await getCollectionFromBotData('userData').findOne({ userID })

    if (thisUser) {
        done(null, thisUser);
    }
})


passport.use(new DiscordStrategy({
    clientID: "Removed for privacy",
    clientSecret: "Removed for privacy",
    callbackURL: "/auth/redirect",
    scope: ['identify', 'guilds.join', 'email']
}, async (accessToken, refreshToken, profile, done) => {


    try {
        let user = await getCollectionFromBotData('userData').findOne( { userID: profile.id } )
        console.log(user);
        if (user) {
            console.log(`user exists`)
            let updateObj = {
                email: profile.email,
                userID: profile.id,
                discordAvatar: `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}`,
                discordUsername: profile.username,
                lastLoggedInAt: Date.now()
            }
            getCollectionFromBotData('userData').updateOne( { userID: profile.id }, {$set: updateObj })


            done(null, user);
        } else {
            console.log(`user doesnt exists`)

            User.email = profile.email;
            User.userID = profile.id;
            User.discordAvatar = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}`
            User.discordUsername = profile.username;
            User.caffeinatedAccountCreatedAt = Date.now();
            User.discordVerified = true;
            User.lastLoggedInAt = Date.now();


            axios.post('http://localhost:8000/verifyUser', {}, {
                headers: {
                    userID: profile.id
                }
            })
                .then((response) => {
                    if (response.data.code === 500) {
                            axios.put('https://discord.com/api/v8/guilds/737058844676587662/members/' + profile.id, { access_token: accessToken, roles: ['787536777312731136', '787536978320031775', '787536296523989012', '737609790905253918']}, {
                                headers: {
                                    Authorization: 'Removed for privacy',
                                }
                            })
                                .catch(err => {
                                    if (err.data.code === 40007) {
                                        console.log('user is banned');
                                    }
                                })
                    }
                    axios.get(`https://api.blox.link/v1/user/${profile.id}`)
                        .then(async r => {
                            if (r.data.status === 'ok') {
                                User.robloxData.robloxAvatar = `https://www.roblox.com/headshot-thumbnail/image?userId=${r.data.primaryAccount}&width=420&height=420&format=png`
                                User.robloxData.robloxID = r.data.primaryAccount;
                                User.robloxLinked = true;
                                User.robloxData.robloxUsername = await noblox.getUsernameFromId(Number(r.data.primaryAccount))

                                getCollectionFromBotData('userData').insertOne(User)
                                    .then(res => {
                                        done(null, res.ops[0]);
                                    })
                                    .catch((err) => {
                                        console.log(err);
                                    });
                            } else {

                                getCollectionFromBotData('userData').insertOne(User)
                                    .then(res => {
                                        done(null, res.ops[0]);
                                    })
                                    .catch((err) => {
                                        console.log(err);
                                    });
                            }
                        })
                        .catch(err => {
                            console.log(err);
                        })

                })
                .catch(err => {
                   console.log(err);
                });
        }
    }
    catch (e) {
        console.log(e)
    }

}));

i know its messy, but it works

If anybody could help me with how I could achieve this please let me know!

0 Answers
Related