I try to figure out this issue a days, please help me :( i dont know why this doesnt work.

IN MY LOCALHOST AND PRODUCTION MODE ITS WORKING FINE BUT WHEN I TRY TO MY REAL WEBSITE IN MODE PRODUCTION IS NOT WORKING

Iam using Express-session,express-mysql-session and iam using passport.js for authentication like google and facebook login.

I got some issue when user login with google and facebook. i cant write cookies to client and i cant store session. i dont know why, so far i check deserializeUser and serializeUser work fine, even after success login and check in my URL callback i got user data in req.user.

but i when redirect to my website this req.user is gone, i try to store it in cookie its not working and cookie doesnt appear.

HERE MY CODE

SERVER.JS

// SESSION
const MySQLStore = sess(session);
const optionSession = {
  host: keys.database.host,
  user: keys.database.user,
  password: keys.database.password,
  database: keys.database.database,
  clearExpired: true,
  checkExpirationInterval: 900000,
  expiration: 86400000,
  schema: {
    tableName: "session",
    columnNames: {
      session_id: "id",
      expires: "expires",
      data: "data"
    }
  }
};

var sessionStore = new MySQLStore(optionSession);

// Create our express app using the port optionally specified
const app = express();
const PORT = process.env.PORT || 5000;


if (process.env.NODE_ENV === 'production') {
  app.use(
    forceDomain({
      hostname: 'www.hammerstoutdenim.com',
      protocol: 'https'
    })
  );
}

app.use(cookieParser(keys.session.secret));

// Express Session
app.use(
  session({
    genid: function(req) {
      return uuidv4(); // use UUIDs for session IDs
    },
    name: keys.session.name,
    secret: keys.session.secret,
    resave: false,
    saveUninitialized: true,
    store: sessionStore,
    rolling: true,
    cookie: {
      secure: false,
      httpOnly: true,
      maxAge: keys.session.maxAge, // satu hari,
      // sameSite: true
    }
  })
);

// Passport
app.use(passport.initialize());
app.use(passport.session());

app.disable("x-powered-by");

app.use(cors({ origin: keys.origin.url, credentials: true }));

// Compress, parse, log, and raid the cookie jar


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(morgan("dev"));


if(process.env.NODE_ENV === 'production'){
  app.use(compression());
  app.use(csrf());
  app.use(function (err, req, res, next) {
    if (err.code !== 'EBADCSRFTOKEN') return next(err)

    // handle CSRF token errors here
    res.status(403)
    res.send('INVALID TOKEN')
  })
}

app.use("/v1/", [v1Routes]);

// Production Mode
if (process.env.NODE_ENV === "production") {
  // Set up homepage, static assets, and capture everything else
  app.use(express.Router().get("/", loader));
  app.use(express.static(path.resolve(__dirname, "../build")));
  app.use(loader);

  // We tell React Loadable to load all required assets and start listening - ROCK AND ROLL!
  Loadable.preloadAll().then(() => {
    app.listen(PORT, console.log(`App listening on port ${PORT}!`));
  });
}

REDIRECT URL

    export const googleRedirect = (req,res)=>{

        if(req.user){
              console.log('I CAN SEE HERE');
            if(req.session.carts){
                return res.redirect(keys.origin.redirect);
            }
            return res.redirect(keys.origin.redictProfile);
        }else{
            return res.status(400).json('INVALID');
        }
    }

    export const facebookRedirect = (req,res)=>{
        if (req.user) {
  console.log('I CAN SEE HERE');
            if (req.session.carts) {
                return res.redirect(keys.origin.redirect);
            }
            return res.redirect(keys.origin.redictProfile);
        }else{
            return res.status(400).json('INVALID');
        }
    }

PASSPORT SETUP

passport.serializeUser((user, done) => {

    let tokenValue = {
    }
    if (user.providerId) tokenValue.providerId = user.providerId;
    if (user.token) tokenValue.token = user.token;
    if (user.provider) tokenValue.provider = user.provider;
    if (user.id) tokenValue.user_id = user.id;

    if (user.email) tokenValue.email = user.email;

    done(null, tokenValue)
})
passport.deserializeUser((data, done) => {

    let querySelect = `SELECT 
    us.id,
    us.displayName,
    us.email,
    us.gender,
    up.providerId,
    up.token,
    up.provider,
    us.firstname,
    us.lastname,
    ui.birthday,
    ui.phone_number from user as us 
    left join user_provider as up on us.id = up.user_id 
    left join user_information as ui on us.id = ui.user_id
    where us.id = ? `;
    db.query(querySelect, [data.user_id], (err, ress) => {
        if (ress.length > 0) {
            done(null, ress[0])
        }

    })

})

passport.use('local-signup', new LocalStrategy(

    {
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true // allows us to pass back the entire request to the callback
    },
    function (req, email, password, done) {

        let queryFindUser = `SELECT email from user_account where email = ?;SELECT email from user where email = ? and is_provider = 1;`;
        db.query(queryFindUser, [req.body.email, req.body.email], (err, result) => {

            if (err) return done(null,false, { error: true, message: "ERROR FROM REGISTER" }); 
            if (result[0].length > 0) {
                return done(null, false,{ error: true, message: "Email is already registered" });

            }
            if (result[1].length > 0) {
                return done(null, false, { error: true, message: "Email is already registered using social media" }); 
            }
            if(result[0].length === 0 && result[1].length === 0){
                let queryInsert = 'INSERT into user set ?; INSERT into user_account set user_id = (select u.id from user as u order by u.id desc limit 1), ?;';
                // let querySelectUser = `INSERT `

                bcrypt.genSalt(10, (err, salt) => {
                    //10 adalah berapa banyak karakter
                    bcrypt.hash(req.body.password, salt, (err, hash) => {
                        if (err) {
                            throw err;
                        }
                        if (hash) {
                            db.query(queryInsert, [{ displayName: req.body.displayName, email: req.body.email }, { email: req.body.email, password: hash }], (err, result) => {
                                if (err) return done(null, false, { error: true, message: "ERROR FROM REGISTER" });
                                if (result) {
                                    let querySelect = `SELECT 
    us.id,
    us.displayName,
    us.email,
    us.gender,
    up.providerId,
    up.token,
    up.provider,
    us.firstname,
    us.lastname,
    ui.birthday,
    ui.phone_number from user as us 
    left join user_provider as up on us.id = up.user_id 
    left join user_information as ui on us.id = ui.user_id
    where us.id = ? `;
                                    db.query(querySelect, [result[0].insertId], (err, ress) => {
                                        if (ress.length > 0) {
                                            return done(null, ress[0])
                                        } else {
                                            return done(null, false, { error: true, message: "error from register" });
                                        }

                                    })
                                }
                            })
                        }

                    });
                });
            }
        })
    }

));

passport.use(new LocalStrategy(
    function (email, password, done) {


        let querySelect = `SELECT 
    us.id,
    us.displayName,
    us.gender,
    us.firstname,
    us.lastname,
    ui.birthday,
    ui.phone_number,
    ua.email,
    ua.password,
    ua.email_confirm_token
    from user as us 
    left join user_account as ua on us.id = ua.user_id
    left join user_information as ui on us.id = ui.user_id
    where ua.email = ?
    `
        db.query(querySelect, [email], (err, result) => {

            if (err) return done(err, null);
            if (result.length > 0) {
                let data = result[0];
                bcrypt.compare(password, data.password)
                    .then(isMatch => {
                        if (isMatch) {
                            return done(null, data);
                        } else {
                            return done(null, false, { message: 'Incorrect password.' });
                        }

                    })

            }
            if (result.length === 0) {
                return done(null, false, { message: 'Incorrect email.' });
            }


        })

    }
));

passport.use(
    new GoogleStrategy({
        //options for the google strategy
        callbackURL: keys.origin.redirectProvider + '/api/auth/google/redirect',
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret,
        userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
        passReqToCallback: true
    }, (req,accessToken, refreshToken, profile, done) => {

        req.session.dataUser = profile;
        console.log(req.session);
        let queryInsert = `INSERT INTO user set is_provider = 1, ?; INSERT INTO user_provider set user_id = (SELECT u.id from user as u order by id desc limit 1), ?;`;
        let queryUpdate = `update user_provider set token = ? where providerId = '${profile.id}'`;
        let queryFind = `SELECT 
        us.id,
        us.displayName,
        us.email,
        us.gender,
        up.providerId,
        up.token,
        up.provider,
        us.firstname,
        us.lastname,
        ui.birthday,
        ui.phone_number
        from user as us 
        left join user_provider as up on us.id = up.user_id 
        left join user_information as ui on us.id = ui.user_id
        where up.providerId = '${profile.id}' and up.provider = '${profile.provider}' and us.is_provider = 1`;

        let querySelect = `SELECT 
    us.id,
    us.displayName,
    us.email,
    us.gender,
    up.providerId,
    up.token,
    up.provider,
    us.firstname,
    us.lastname,
    ui.birthday,
    ui.phone_number from user as us 
    left join user_provider as up on us.id = up.user_id 
    left join user_information as ui on us.id = ui.user_id
    where us.id = ? and up.provider = ? and up.providerId = ?  and us.is_provider = 1`;
    const querySelectAfterUpdate = `SELECT 
    us.id,
    us.displayName,
    us.email,
    us.gender,
    up.providerId,
    up.token,
    up.provider,
    us.firstname,
    us.lastname,
    ui.birthday,
    ui.phone_number from user as us 
    left join user_provider as up on us.id = up.user_id 
    left join user_information as ui on us.id = ui.user_id
    where up.provider = ? and up.providerId = ?  and us.is_provider = 1`;
        let user = {
            email: profile.emails[0].value,
        }
        if (profile.gender) user.gender = profile.gender;
        if (profile.displayName) user.displayName = profile.displayName;
        if (Object.keys(profile.name).length > 0) {
            if (profile.name.familyName) user.lastname = profile.name.familyName;
            if (profile.name.givenName) user.firstname = profile.name.givenName;
        }

        let user_provider = {
            provider: profile.provider,
            providerId: profile.id,
            token: refreshToken ? refreshToken : accessToken
        }
        db.query(queryFind, (error, result) => {

            if (error) return done(error);
            if (result.length > 0) {
                console.log('user', result);

                db.query(queryUpdate, [user_provider.token], (err, ress)=>{
                    console.log('res',ress);
                    if (err) return done(err);
                    if (ress.affectedRows > 0) {
                        db.query(querySelectAfterUpdate, [profile.provider, profile.id], (err, ress) => {
                            if (err) return done(err);
                            if (ress.length > 0) {
                                return done(null, ress[0]);
                            }

                        })
                    }
                    if (ress.affectedRows === 0){
                        return done(null, result[0]);
                    }
                })

            } else {

                db.query(queryInsert, [user, user_provider], (err, ress, fields) => {
                    if (err) return done(err);
                    if (ress) {
                        db.query(querySelect, [ress[0].insertId, profile.provider, profile.id], (err, ress) => {
                            if (err) return done(err);
                            if (ress.length > 0) {
                                return done(null, ress[0]);
                            }

                        })
                    }
                })
            }
        })







    })

);



passport.use(new FacebookStrategy({
    clientID: keys.facebook.clientID,
    clientSecret: keys.facebook.clientSecret,
    callbackURL: keys.origin.redirectProvider + '/api/auth/facebook/redirect',
    profileFields: ['id', 'emails', 'name', 'birthday', 'location', 'gender', 'age_range', 'link', 'hometown']

}, (accessToken, refreshToken, profile, done) => {
    let payload = profile._json;
    let user = {
        email: payload.email
    }

    if (payload.gender) user.gender = payload.gender;
    if (payload.displayName) user.displayName = payload.displayName;
    if (payload.last_name) user.lastname = payload.last_name;
    if (payload.first_name) user.firstname = payload.first_name;

    let user_information = {};
    if (payload.birthday) user_information.birthday = payload.birthday;
    if (typeof payload.location !== "undefined" && typeof payload.location.name !== "undefined") {
        user_information.location = payload.location.name;

    }
    if (typeof payload.age_range !== "undefined" && typeof payload.age_range.min !== "undefined") {
        user_information.age = payload.age_range.min;
    }

    let user_provider = {
        provider: profile.provider,
        providerId: payload.id,
        token: accessToken
    }
    let queryInsert = `INSERT INTO user set is_provider = 1, ?; INSERT INTO user_provider set user_id = (SELECT u.id from user as u order by id desc limit 1), ?;
                       ${Object.keys(user_information).length > 0 ? `INSERT INTO user_information set user_id = (SELECT u.id from user as u order by id desc limit 1), ? ` : ''}`;
    let queryFind = `SELECT 
        us.id,
        us.displayName,
        us.email,
        us.gender,
        up.providerId,
        up.token,
        up.provider,
        us.firstname,
        us.lastname,
        ui.birthday,
        ui.phone_number
        from user as us 
        left join user_provider as up on us.id = up.user_id 
        left join user_information as ui on us.id = ui.user_id
        where up.providerId = '${profile.id}' and up.provider = '${profile.provider}' and us.is_provider = 1`;

    let querySelect = `SELECT 
    us.id,
    us.displayName,
    us.email,
    us.gender,
    up.providerId,
    up.token,
    up.provider,
    us.firstname,
    us.lastname,
    ui.birthday,
    ui.phone_number from user as us 
    left join user_provider as up on us.id = up.user_id 
    left join user_information as ui on us.id = ui.user_id
    where us.id = ? and up.provider = ? and up.providerId = ? and up.token = ? and us.is_provider = 1`;

    db.query(queryFind, (error, result) => {
        if (error) return done(error);
        if (result.length > 0) {
            return done(null, result[0]);
        } else {

            db.query(queryInsert, [user, user_provider, user_information], (err, ress, fields) => {
                if (err) return done(err);
                if (ress) {
                    db.query(querySelect, [ress[0].insertId, profile.provider, profile.id], (err, ress) => {
                        if (err) return done(err);
                        if (ress.length > 0) {
                            return done(null, ress[0]);
                        }

                    })
                }
            })
        }
    })
})

);

0 Answers