npm install passport passport-google-oauth20
구글 클라우드 접속하여서 가입을 하여 API GOOGLE_CLIENT_ID / GOOGLE_CLIENT_KEY 를 발급을 받는다.
app.get(
"/google",
passport.authenticate("google", {
scope: ["profile", "email"],
accessType: "offline", // 이 두 개 값은
prompt: "consent",
})
);
app.get(
"/google/callback",
passport.authenticate("google", {
successReturnToOrRedirect: "/",
failureRedirect: "/login",
})
);
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
import { prisma } from "../utils/prisma/index.js";
import "dotenv/config";
// req.login(user)
passport.serializeUser((user, done) => {
done(null, user.id);
});
// client => session => request
passport.deserializeUser((id, done) => {
prisma.users.findUnique({ where: { id: +id } }).then((user) => {
done(null, user);
});
});
const googleClientID = process.env.GOOGLE_CLIENT_ID;
const googleClientSecret = process.env.GOOGLE_CLIENT_SECRET;
const googleStrategyConfig = new GoogleStrategy(
{
clientID: googleClientID,
clientSecret: googleClientSecret,
callbackURL: "/google/callback",
},
async (accessToken, refreshToken, profile, done) => {
console.log(accessToken);
console.log(refreshToken);
console.log("google profile : ", profile);
const user = await prisma.users.findUnique({
where: { email: profile.emails[0].value },
});
if (user) {
done(null, user);
} else {
const newUser = {
email: profile.emails[0].value,
password: "google",
username: profile.displayName,
googleId: profile.id,
refreshToken: refreshToken,
};
const createUser = await prisma.users.create({
data: newUser,
});
console.log(createUser);
if (!createUser) {
return done(new Error());
}
done(null, user);
}
}
);
passport.use("google", googleStrategyConfig);
passport 를 통해 로그인 인증은 위임할 수 있다.