Lee SeJin

login system update

......@@ -16,10 +16,15 @@
"@babel/node": "^7.13.13",
"@babel/preset-env": "^7.14.1",
"axios": "^0.21.1",
"connect-mongo": "^4.4.1",
"dotenv": "^9.0.2",
"express": "^4.17.1",
"express-session": "^1.17.1",
"mongoose": "^5.12.9",
"morgan": "^1.10.0",
"nodemon": "^2.0.7",
"passport": "^0.4.1",
"passport-github2": "^0.1.12",
"pug": "^3.0.2"
},
"devDependencies": {
......
import axios from "axios";
import passport from "passport";
import User from "../models/User";
const getQuote = async (req,res) =>{
......@@ -41,3 +42,40 @@ export const getLogin = (req,res)=>{
export const handleUsers = (req,res)=>{
res.render("users",{pageTitle:"Users"});
}
export const githubLogin = passport.authenticate("github", {scope: [ "user:email" ]});
export const githubLoginCallback = async (_, __, profile, done) =>{
const {_json: {id:githubId, login:githubName, avatar_url:avatarUrl, name, email}} = profile;
try{
const user = await User.findOne({email});
if(user){
user.githubId = githubId,
user.githubName = githubName
await user.save();
return done(null, user);
}else{
const newUser = await User.create({
githubId,
githubName,
avatarUrl,
name,
email
});
return done(null, newUser);
}
}catch(error){
return done(error);
}
};
export const postGithubLogin = (req,res)=>{
const userId = req.user.id;
res.redirect(`/users/${userId}`);
}
export const logout = (req,res)=>{
req.logout();
res.redirect("/");
}
\ No newline at end of file
......
import mongoose from "mongoose";
mongoose.connect("mongodb://127.0.0.1:27017/dev-profile",{
mongoose.connect(process.env.DB_URL,{
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
useUnifiedTopology: true,
useCreateIndex: true
}
);
......
import "dotenv/config";
import "./db";
import "./models/User";
import app from "./server";
......
export const localsMiddleware = (req,res,next) => {
res.locals.siteName = "Dev Profile";
res.locals.loggedUser = req.user || null;
next();
};
export const onlyPublic = (req, res, next) => {
if(req.user){
res.redirect("/");
} else {
next();
}
};
export const onlyPrivate = (req, res, next) => {
if(req.user){
next();
} else {
res.redirect("/");
}
};
\ No newline at end of file
......
......@@ -7,12 +7,14 @@ const UserSchema = new mongoose.Schema({
},
email: {
type: String,
trim: true
trim: true,
unique: true
},
avatarUrl: String,
githubId: {
type: Number,
required: "GitHub id is required"
required: "GitHub id is required",
unique: true
},
githubName: {
type: String,
......@@ -40,6 +42,13 @@ const UserSchema = new mongoose.Schema({
}
});
UserSchema.static("formatTech", function(tech){
return tech.split(",");
});
UserSchema.static("formatCareer",function(career){
return career.split(",");
});
const User = mongoose.model("User", UserSchema);
......
import passport from "passport";
import GithubStrategy from "passport-github2";
import { githubLoginCallback } from "./controllers/userController";
import User from "./models/User";
passport.use(new GithubStrategy(
{
clientID: process.env.GH_ID,
clientSecret: process.env.GH_SECRET,
callbackURL: `http://localhost:5500/auth/github/callback`
},
githubLoginCallback
)
);
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
\ No newline at end of file
import express from "express";
import { getJoin, getLogin, handleHome } from "../controllers/userController";
import passport from "passport";
import { getJoin, getLogin, githubLogin, handleHome, logout, postGithubLogin } from "../controllers/userController";
import { onlyPrivate, onlyPublic } from "../middlewares";
const globalRouter = express.Router();
globalRouter.get("/",handleHome);
globalRouter.get("/join", getJoin);
globalRouter.get("/login",getLogin);
globalRouter.get("/join", onlyPublic, getJoin);
globalRouter.get("/login", onlyPublic, getLogin);
globalRouter.get("/logout", onlyPrivate, logout);
globalRouter.get("/auth/github", githubLogin);
globalRouter.get(
"/auth/github/callback",
passport.authenticate("github",{failureRedirect: "/login"}),
postGithubLogin
);
export default globalRouter;
\ No newline at end of file
......
import express from "express";
import { getEditProfile, getUserDetail, handleUsers, postEditProfile } from "../controllers/userController";
import { onlyPrivate } from "../middlewares";
const userRouter = express.Router();
userRouter.get("/",handleUsers);
userRouter.get("/edit-profile", getEditProfile);
userRouter.post("/edit-profile", postEditProfile);
userRouter.get("/edit-profile", onlyPrivate, getEditProfile);
userRouter.post("/edit-profile", onlyPrivate, postEditProfile);
userRouter.get("/:id", getUserDetail);
......
import express from "express";
import path from "path";
import morgan from "morgan";
import session from "express-session";
import passport from "passport";
import MongoStore from "connect-mongo";
import globalRouter from "./routers/globalRouter";
import userRouter from "./routers/userRouter";
import { localsMiddleware } from "./middlewares";
import "./passport";
const app = express();
......@@ -16,7 +19,17 @@ app.use(express.static(path.join(__dirname, "static")));
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
session({
secret: process.env.COOKIE_SECRET,
resave: true,
saveUninitialized: false,
store: MongoStore.create({mongoUrl: process.env.DB_URL})
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(localsMiddleware);
app.use("/", globalRouter);
......
......@@ -4,7 +4,7 @@ block content
i.fas.fa-location-arrow
h3 Start with GitHub!
button.login-github
a(href="#")
a(href="/auth/github")
span
i.fab.fa-github
|Join with GitHub
......
......@@ -4,7 +4,7 @@ block content
i.fas.fa-location-arrow
h3 Login with GitHub!
button.login-github
a(href="#")
a(href="/auth/github")
span
i.fab.fa-github
|Login with GitHub
......
......@@ -2,11 +2,18 @@ header.header
.header__wrapper
.header__column
ul
li
a(href="/") Home
li
a(href="/join") Join
li
a(href="/login") Log In
li
a(href="/users/edit-profile") Edit Profile
\ No newline at end of file
if !loggedUser
li
a(href="/") Home
li
a(href="/join") Join
li
a(href="/login") Log In
else
li
a(href="/") Home
li
a(href="/users/edit-profile") Edit Profile
li
a(href="/logout") Log Out
\ No newline at end of file
......
......@@ -5,6 +5,7 @@ block content
.user-quote
h2=quote
h3=author
hr
.user-profile
.user-profile__column
img(src="#")
......@@ -20,6 +21,7 @@ block content
h3 TECH
h3 CAREER
h3 SELF-INTRODUCTION
hr
.user-status
.user-status__contributions
img(src="http://ghchart.rshah.org/lsj8706" alt="Name Your Github chart")
......