简体   繁体   中英

Do auth login in Protected route

How can we do auth login in the protected route.

For example I have a protected where I allow user to connect their social media profiles once they are logged in.

Typically passport auth happens using href events ie <a href="base_url/auth/facebook"> Cick here to connect facebook </a>

Now, I am not sure how i can set cookie with my href (if this is the ideal way) if I want to connect user after they are logged in.

Here is what my middleware looks like

async verifyMiddleWare(req, res, next) {
    const token = req.cookies
    if (token) {
        try {
            const userToken = token.userToken
            const tokenVerficiation = await verifyToken(userToken)
            res.locals.userId = tokenVerficiation.userId
            res.locals.acessLevel = tokenVerficiation.acessLevel
            if (tokenVerficiation.acessLevel === this.routePermission) next()
            else
                res
                    .status(AUTH_ERRORS.INVALID_ACCESS_TOKEN.status)
                    .send(AUTH_ERRORS.INVALID_ACCESS_TOKEN.message)
        } catch (error) {
            return res
                .status(AUTH_ERRORS.UNAUTHORIZED_TO_VIEW.status)
                .send(AUTH_ERRORS.UNAUTHORIZED_TO_VIEW.message)
        }
    } else {
        return res
            .status(AUTH_ERRORS.MISSING_ACCESS_TOKEN.status)
            .send(AUTH_ERRORS.MISSING_ACCESS_TOKEN.message)
    }
}

and passport code (i am not serialising and de-serialising user)

const passport = require('passport')
const FacebookStrategy = require('passport-facebook').Strategy
const config = require('./../../config')

passport.use(
    new FacebookStrategy(
        {
            clientID: config.FACEBOOK_APP_ID,
            clientSecret: config.FACEBOOK_APP_SECRET,
            callbackURL: config.FACEBOOK_REDIRECT_URL,
            profileFields: ['id', 'displayName', 'email', 'gender']
        },
        async (accessToken, refreshToken, profile, done) => {
            return done(null, { accessToken, refreshToken, profile })
        }
    )
)

And I am setting cookie like this during auth

app.get(`/${serviceName}/callback`, passport.authorize(serviceName), async (req, res) => {
        const facebookDetials = req.account
        // the output from passport should mandatorily have email
        const userEmail = facebookDetials.profile.emails[0].value
        // Checking if user data exsists, corresponding to email id entered
        try {
            const userData = await getSelectedThingFromTable(
                SIGNUP_TABLES.userAuth,
                `email = "${userEmail}"`
            )
            if (userData.length > 0) {
                // Means email Exist
                const { userId, acessLevel } = userData[0] //
                    const createNewAccessToken = await JWT.generateToken({ userId, acessLevel })
                    //setting cookies
                    res.cookie('userToken', createNewAccessToken)
                    return res.redirect(config.BASE_CONFIG_URL)

What have I tried yet

  1. Pretty dumb way but login user in my browser (localhost:8000/auth/facebook) and then going to localhost:8000/social/twitter -> Here my token is coming to be undefined

I could easily be wrong but I'm guessing the cookie doesn't appear to be set because it's getting associated with the wrong domain name.

Try changing

res.cookie('userToken', createNewAccessToken)

to

res.cookie('userToken', createNewAccessToken, {domain: 'localhost:8000'})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM