jaredhanson / passport-google-oauth2

Google authentication strategy for Passport and Node.js.
https://www.passportjs.org/packages/passport-google-oauth20/?utm_source=github&utm_medium=referral&utm_campaign=passport-google-oauth20&utm_content=about
MIT License
812 stars 154 forks source link

syntax error at or near "AND" #97

Open parimal-10 opened 9 months ago

parimal-10 commented 9 months ago

This is my code

I am using postgresql, I am able to register as a new user but the login process throws this error?? What to do??

passport.use(new GoogleStrategy({
    clientID: process.env["CLIENT_ID"],
    clientSecret: process.env["CLIENT_SECRET"],
    callbackURL: "http://localhost:3000/oauth2/redirect/google",
    scope: ["profile"],
    state: true
}, function verify(accessToken, refreshToken, profile, cb) {
    db.query(
        "SELECT * FROM federated_credentials WHERE provider = ? AND subject = ?", [
        "https://accounts.google.com",
        profile.id
    ], function (err, cred) {
        if (err) { return cb(err); }

        console.log(profile);

        if (!cred) {
        // The account at Google has not logged in to this app before.  Create a
        // new user record and associate it with the Google account.
        db.run("INSERT INTO users (name) VALUES (?)", [
            profile.displayName
        ], function (err) {
            if (err) { return cb(err); }

            var id = this.lastID;
            db.run("INSERT INTO federated_credentials (user_id, provider, subject) VALUES (?, ?, ?)", [
                id,
                "https://accounts.google.com",
                profile.id
            ], function (err) {
                if (err) { return cb(err); }

                var user = {
                    id: id,
                    name: profile.displayName
                };
                return cb(null, user);
            });
        });
    } else {
        // The account at Google has previously logged in to the app.  Get the
        // user record associated with the Google account and log the user in.
        db.query("SELECT * FROM users WHERE id = ?", [cred.user_id], function (err, user) {
            if (err) { return cb(err); }
            if (!user) { return cb(null, false); }
            return cb(null, user);
        });
    }
});

} ));

This is my rest of the code for reference

import dotenv from "dotenv" dotenv.config()

import express from "express" import bodyParser from "body-parser" import pg from "pg" import bcrypt from "bcrypt" import session from "express-session" import passport from "passport" import { Strategy as LocalStrategy } from "passport-local" import GoogleStrategy from "passport-google-oauth20"

const app = express(); const port = 3000; const saltRounds = 10; initialize(passport);

const db = new pg.Client({ user: "postgres", host: "localhost", database: "auth", password: "Parimal_10", port: 5432, }); db.connect()

function initialize(passport) { async function authenticateUser(username, password, done) {

    try {
        const response = await db.query(
            "SELECT * FROM users WHERE username = $1",
            [username]
        );

        const user = response.rows[0];

        bcrypt.compare(password, user.password, function (err, result) {
            if (err) {
                throw err;
            }

            if (result) {
                return done(null, user);
            } else {
                return done(null, false, { message: "Password is not correct" });
            }
        })
    } catch (err) {
        return done(null, false, { message: "The username is not registered" })
    }
}

passport.use(
    new LocalStrategy({
        usernameField: "username",
        passwordField: "password",
    }, authenticateUser)
);

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

passport.deserializeUser(async (id, done) => {
    const result = await db.query(
        "SELECT * FROM users WHERE id = $1",
        [id]
    );

    return done(null, result.rows[0]);
})

}

//Middlewares app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static("public")); app.set("view engine", "ejs");

app.use(session({ secret: "Harry Potter", resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session());

passport.use(new GoogleStrategy({ clientID: process.env["CLIENT_ID"], clientSecret: process.env["CLIENT_SECRET"], callbackURL: "http://localhost:3000/oauth2/redirect/google", scope: ["profile"], state: true }, function verify(accessToken, refreshToken, profile, cb) { db.query( "SELECT * FROM federated_credentials WHERE provider = ? AND subject = ?", [ "https://accounts.google.com", profile.id ], function (err, cred) { if (err) { return cb(err); }

    console.log(profile);

    if (!cred) {
        // The account at Google has not logged in to this app before.  Create a
        // new user record and associate it with the Google account.
        db.run("INSERT INTO users (name) VALUES (?)", [
            profile.displayName
        ], function (err) {
            if (err) { return cb(err); }

            var id = this.lastID;
            db.run("INSERT INTO federated_credentials (user_id, provider, subject) VALUES (?, ?, ?)", [
                id,
                "https://accounts.google.com",
                profile.id
            ], function (err) {
                if (err) { return cb(err); }

                var user = {
                    id: id,
                    name: profile.displayName
                };
                return cb(null, user);
            });
        });
    } else {
        // The account at Google has previously logged in to the app.  Get the
        // user record associated with the Google account and log the user in.
        db.query("SELECT * FROM users WHERE id = ?", [cred.user_id], function (err, user) {
            if (err) { return cb(err); }
            if (!user) { return cb(null, false); }
            return cb(null, user);
        });
    }
});

} ));

app.get("/", (req, res) => { res.render("home"); });

app.get("/login", (req, res) => { res.render("login"); });

app.get("/register", (req, res) => { res.render("register"); });

app.get("/secrets", function (req, res) { if (req.isAuthenticated()) { res.render("secrets"); } else { res.redirect("/login") } });

app.get("/login/google", passport.authenticate("google"));

app.get("/oauth2/redirect/google", passport.authenticate("google", { failureRedirect: "/login", failureMessage: true }), function (req, res) { res.render("secrets"); } );

app.post("/register", async (req, res) => { const username = req.body.username; const password = req.body.password;

try {
    bcrypt.hash(password, saltRounds, async function (err, hash) {
        // Store hash in your password DB.
        try {
            await db.query(
                "INSERT INTO users (username, password) VALUES ($1, $2)",
                [username, hash]
            )

            res.redirect("login")
        } catch (err) {
            console.log(err.message);
            res.send("Username already exists")
        }
    });
} catch (err) {
    console.log(err.message);
    res.send("Username already exists")
}

});

app.post("/login", passport.authenticate("local", { successRedirect: "/secrets", // Redirect to the secrets page upon successful login failureRedirect: "/login", // Redirect back to the login page if authentication fails
}));

app.get("/logout", function (req, res) { req.logout(function(err) { if (err) { return next(err); } res.redirect("/"); }); });

app.listen(port, () => { console.log(The port ${port} is up and running); });