如果使用Passport JS在本地数据库中不存在用户,如何将他们重定向到另一个页面

时间:2019-01-15 19:50:16

标签: mysql node.js passport.js

我最近在Google上尝试了Passport Js OAuth20,并试图创建一个简单的登录页面。当用户尝试登录时,该页面工作正常,因为它们位于我的本地数据库中。除非我的登录凭据不正确,否则我想尝试将其重定向到另一个页面。我可以在代码中的哪个位置执行此操作?还是更好,如果Google的回调URI失败,如何将用户重定向到另一个页面?

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20');
const keys = require('./keys');
const mysql = require('mysql');

const pool = mysql.createPool ({
    connectionLimit: 10,
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    port : '3306',
    database : 'seattle'
});

// connection
function getConnection() {
    return pool
}

passport.use(

    new GoogleStrategy({
    //options for google to start
    callbackURL: '/auth/google/redirect',
    clientID: keys.google.clientID,
    clientSecret: keys.google.clientSecret

}, (accessToken, refreshToken, profile, cb) =>{

    const queryString = 'SELECT * FROM admin WHERE google_id = ?';   

    getConnection().query(queryString, [profile.id], (err, rows, fields) => {

            if (rows.length) {

            console.log('admin already exists in the databse')
            console.log(rows[0].google_id)

            return cb(err, rows[0].google_id)

            } else {
                console.log('it occured here');
                // Here I create a user if they dont exist
                // But instead of creating a user 
                // I want to redirect them to another page saying you dont have the credentials to log in
                const insertQuery = 'INSERT INTO admin (google_id, display_name) VALUES (?,?)';

                    getConnection().query(insertQuery,[profile.id, profile.displayName],function(err, rows) {


                        const queryString = 'SELECT * FROM admin WHERE google_id = ?';   

                            getConnection().query(queryString, [profile.id], (err, rows, fields) => {

                                return cb(err, rows[0].google_id);

                            });

                });
            }    

        });      

    })
)

// used to serialize the user for the session
passport.serializeUser(function(user, cb) {
    cb(null, user);
});

// used to deserialize the user
passport.deserializeUser(function(user, cb) {
    getConnection().query("SELECT * FROM admin WHERE google_id = ? ",[user], function(err, rows){
        cb(null, user);
    });
});

0 个答案:

没有答案