passport.js
import routes from "./routes";
import passport from "passport";
import GithubStrategy from "passport-github";
import User from "./models/User";
import { githubLoginCallback } from "./controllers/userController";
passport.use(User.createStrategy());
passport.use(
new GithubStrategy({
clientID: process.env.GH_ID,
clientSecret: process.env.GH_SECRET,
callbackURL: `http://localhost:4000${routes.githubCallback}`
},
githubLoginCallback
)
);
...
User.js
import mongoose from "mongoose";
import passportLocalMongoose from "passport-local-mongoose";
const UserSchema = new mongoose.Schema({
name: String,
email:String,
avatarUrl: String,
facebookId: Number,
githubId: Number
});
UserSchema.plugin(passportLocalMongoose,
{usernameField:"email"},
);
const model = mongoose.model("User",UserSchema);
export default model;
routes.js
// Github
const GITHUB = "/auth/github";
const GITHUB_CALLBACK = "/auth/github/callback";
gitHub: GITHUB,
githubCallback: GITHUB_CALLBACK
...
globalRouter.js
import express from "express";
import passport from "passport";
import routes from "../routes";
import { postJoin, getLogin, logout, getJoin, postLogin, githubLogin, postGithubLogIn } from "../controllers/userController";
...
globalRouter.get(routes.gitHub, githubLogin);
globalRouter.get(
routes.githubCallback,
passport.authenticate("github", { failureRedirect: "/login" }),
postGithubLogIn
);
userController.js
import passport from "passport";
import routes from "../routes";
import User from "../models/User";
...
export const githubLogin = passport.authenticate("github");
export const githubLoginCallback = async (_, __, profile, cb) => {
...
};
export const postGithubLogIn = (req, res) => {
res.redirect(routes.home);
};
userController.js
...
export const githubLoginCallback = async (_, __, profile, cb) => {
const {
_json: { id, avatar_url, name, email }
} = profile;
try {
// 1
const user = await User.findOne({ email });
if (user) {
user.githubId = id;
user.save();
return cb(null, user);
}
// 2
const newUser = await User.create({
email,
name,
githubId: id,
avatarUrl: avatar_url
});
return cb(null, newUser);
} catch (error) {
return cb(error);
}
};
...
191114 - passport-kakao 를 이용해 카톡 로그인도 추가 완료