0

I am using nodejs api for doing twitter authentication. I have deployed nodejs api on firebase functions. I have also read documentation about IMA and set allUsers roles inside google cloud console. If I try to go with /hello endpoint then my code is working fine and I can see result on my screen. But when I am doing res.redirect() then I got error of

Error: Forbidden Your client does not have permission to get URL /twitter/login from this server.

const functions = require("firebase-functions");

var express = require('express');
var path = require('path');
// var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var Strategy = require('passport-twitter').Strategy;
var session = require('express-session');
const firebase = require('firebase');
const port = 3000

const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
};
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const Users = db.collection("users")

passport.use(new Strategy({
    consumerKey: '',
    consumerSecret: '',
    callbackURL: ''
}, function (token, tokenSecret, profile, callback) {
    return callback(null, profile);
}));

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

passport.deserializeUser(function (obj, callback) {
    callback(null, obj);
})

var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'whatever', resave: true, saveUninitialized: true }))

app.use(passport.initialize())
app.use(passport.session())



app.get('/', function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,PUT,PATCH,POST,DELETE");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    if (req.user == undefined) {
        // res.json({"message": "All ok"})
        res.redirect('/twitter/login')
    }
    else if (req.user != undefined) {
        return;
    }
})

app.get('/hello', function (req, res) {
    res.json({"message": "Hello"})
   
})

app.get('/twitter/login', passport.authenticate('twitter', {
    failureRedirect: '/'
}))

app.get('/twitter/sucess', function (req, res) {
    console.log("in twitter success")
    console.log(req.user.username);
    console.log(req.user);
    res.cookie("twitter_id", req.user.id, { expires: new Date(Date.now() + (7300 * 24 * 3600000)) });
    const userRef = db.collection("users").doc(req.user.id)
    userRef.get()
        .then((docSnapshot) => {
            if (docSnapshot.exists) {

            } else {
                userRef.set({"userName": req.user.username, "twitterId": req.user.id, "displayName": req.user.displayName, "crushCount": 0}) // create the document
            }
        });

    res.redirect("http://localhost:8000/add_crush");
    // res.status(200).json({"message": "Auth Successfull", "username": req.user.username})
})

app.get('/twitter/return', passport.authenticate('twitter', {
    failureRedirect: '/',
    successRedirect: '/twitter/sucess',
}), function (req, res) {
    
})

app.listen(port, () => console.log(`Listening on port ${port}`))

exports.app = functions.https.onRequest(app)

Here is my code, please suggest what to do?

Harsh Bhalala
  • 173
  • 1
  • 2
  • 9

1 Answers1

0

There can be multiple reasons behind the error you’re receiving.Usually, this is due to the way that you are authenticating on Firebase.

Considering that, I would recommend you to take a look at the following Community posts 1,2 &3 for more information, on alternatives to fix the error.

You can take a look at this documentation on Nodejs twitter login script with passport.js

Sathi Aiswarya
  • 2,068
  • 2
  • 11