From 180bf4ce1b6aabfe5d189762c8988f6d5e37cab6 Mon Sep 17 00:00:00 2001 From: toothless8392 Date: Wed, 13 Mar 2024 20:54:47 +0900 Subject: [PATCH 1/3] feat:add-authorization-and-authentication-and-change-studyapi-to-ts --- src/@types/index.d.ts | 18 +++++++-- src/app.ts | 11 +++++- src/controllers/adminStudy.ts | 55 ++++++++++++++++++++++++++ src/controllers/auth.ts | 71 +++++++++++++++++++++++----------- src/controllers/userStudy.ts | 70 +++++++++++++++++++++++++++++++++ src/middlewares/auth.ts | 16 ++------ src/middlewares/isAdmin.ts | 24 ++++++++++++ src/models/study.ts | 53 +++++++++++++++++++++++++ src/{schema => models}/user.ts | 5 +++ src/passport/index.ts | 17 +++++--- src/passport/localStrategy.ts | 15 +++---- src/routes/admin.ts | 22 +++++++++++ src/routes/auth.ts | 8 ++-- src/routes/study.ts | 18 +++++++++ 14 files changed, 347 insertions(+), 56 deletions(-) create mode 100644 src/controllers/adminStudy.ts create mode 100644 src/controllers/userStudy.ts create mode 100644 src/middlewares/isAdmin.ts create mode 100644 src/models/study.ts rename src/{schema => models}/user.ts (88%) create mode 100644 src/routes/admin.ts create mode 100644 src/routes/study.ts diff --git a/src/@types/index.d.ts b/src/@types/index.d.ts index 1923c92..b74f0f6 100644 --- a/src/@types/index.d.ts +++ b/src/@types/index.d.ts @@ -1,13 +1,25 @@ import { isExpression } from "typescript"; -import CoMitUser from "../schema/user"; +import CoMitUser from "../models/user"; declare global { namespace Express { interface User { - id?: number; + userName: string; + email: string; + id: number; + } + + interface Session { + user?: User; + } + } + + namespace session + { + interface Session { + user?: User; } - interface User extends CoMitUser {}; } } \ No newline at end of file diff --git a/src/app.ts b/src/app.ts index c117c46..1ffebfb 100644 --- a/src/app.ts +++ b/src/app.ts @@ -8,6 +8,10 @@ import * as path from "path"; import passportAuth from "./passport/index"; import authRouter from "./routes/auth"; +import studyRouter from "./routes/study"; +import adminRouter from "./routes/admin"; +import isAdmin from "./middlewares/isAdmin"; + dotenv.config(); passportAuth(); @@ -24,7 +28,8 @@ app.use((req: Request, res: Response, next: NextFunction) => { morgan("dev")(req, res, next); } -}) +}); +app.use(express.static(path.join(__dirname, "public"))); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser(process.env.COOKIE_SECRET)); @@ -48,6 +53,8 @@ app.get("/api", (req: Request, res: Response, next: NextFunction) => }); app.use("/auth", authRouter); +app.use("/study", studyRouter); +app.use("/admin", isAdmin, adminRouter); app.use((err: any, req: Request, res: Response, next: NextFunction) => @@ -55,7 +62,7 @@ app.use((err: any, req: Request, res: Response, next: NextFunction) => res.locals.message = err?.message; res.locals.error = process.env.NODE_ENV !== "production" ? err : {}; res.status(err?.status || 500); - return res.send("error"); + return res.send({ message: "error" }); }) app.listen("3000", () => diff --git a/src/controllers/adminStudy.ts b/src/controllers/adminStudy.ts new file mode 100644 index 0000000..b5daef8 --- /dev/null +++ b/src/controllers/adminStudy.ts @@ -0,0 +1,55 @@ +import express, { Request, Response, NextFunction } from "express"; +import moment from "moment"; +import Study from "../models/study"; +import connectDB from "../mongodb/connectDB"; + +export const getStudies = async (req: Request, res: Response, next: NextFunction) => { + try { + await connectDB(); + const studies = await Study.find(); + return res.status(200).json(studies); + } catch (error) { + console.error(error); + return res.status(500).json({ message: "Internal Server Error" }); + } +} + +export const getStudy = async (req: Request, res: Response, next: NextFunction) => { + try { + await connectDB(); + const studyId = req.params.id; + const study = await Study.findById(studyId); + return res.status(200).json(study); + } catch (error) { + console.error(error); + return res.status(500).json({ message: "Internal Server Error" }); + } +} + +export const editStudy = async (req: Request, res: Response, next: NextFunction) => { + try { + await connectDB(); + + const { id, imageSrc, title, mentor, day, startTime, endTime, level, stack, campus, description } = req.body; + const update = { imageSrc, title, mentor, day, startTime, endTime, level, stack, campus, description }; + const study = Study.findOneAndUpdate({ _id: id }, update, { new: true }); + + return res.status(200).json(study); + } catch (error) { + console.error(error); + return res.status(500).json({ message: "Internal Server Error" }); + } +} + +export const deleteStudy = async (req: Request, res: Response, next: NextFunction) => { + try { + const studyId = req.params.id; + await Study.findOneAndDelete({ _id: studyId }, {}); + + return res.status(200).json({ message: "Study is successfully deleted" }); + } catch (error) { + console.error(error); + return res.status(500).json({ message: "Internal Server Error" }); + } + +} \ No newline at end of file diff --git a/src/controllers/auth.ts b/src/controllers/auth.ts index f29cbe4..03ce376 100644 --- a/src/controllers/auth.ts +++ b/src/controllers/auth.ts @@ -1,9 +1,9 @@ import { RequestHandler, Request, Response, NextFunction } from "express"; import passport from "passport"; import bcrypt from "bcrypt"; -import CoMitUser from "../schema/user"; +import CoMitUser from "../models/user"; -const signIn: RequestHandler = async (req: Request, res: Response, next: NextFunction) => +const signup: RequestHandler = async (req: Request, res: Response, next: NextFunction) => { try { @@ -21,39 +21,66 @@ const signIn: RequestHandler = async (req: Request, res: Response, next: NextFun password: hashedPW, userName, studentID, + isAdmin: false, }); return res.status(201).json({ message: 0 }); } - catch (err) + catch (error) { - console.error(err); - return next(err); + console.error(error); + next(error); } } const login: RequestHandler = async (req: Request, res: Response, next: NextFunction) => { - passport.authenticate("local", (authError: Error|any, user: Express.User, info: any) => + try { + passport.authenticate("local", { failureRedirect: "/auth/login" }, (authError: Error|any, user: Express.User, info: any) => + { + console.log(info || "no info"); + if (authError) + { + console.error(authError); + next(authError); + } + if (!user) + { + return res.status(403); + } + return req.login(user, (loginError) => + { + if (loginError) + { + console.error(loginError); + next(loginError); + } + return; + }); + })(req, res, next); + } catch (error) { + console.error(error); + } +} + +const logout = (req: Request, res: Response, next: NextFunction) => +{ + req.logout((error) => { - if (authError) + if (error) { - console.error(authError); - return next(authError); + console.error(error); + next(error); } - if (!user) + }); + + req.session.save((error) => { + if (error) { - return res.status(403); + console.error(error); + next(error); } - return req.login(user, (loginError) => - { - if (loginError) - { - console.error(loginError); - return next(loginError); - } - return; - }); - })(req, res, next); + res.redirect("/"); + }); } -export { signIn, login }; \ No newline at end of file +export { signup, login, logout }; \ No newline at end of file diff --git a/src/controllers/userStudy.ts b/src/controllers/userStudy.ts new file mode 100644 index 0000000..085137e --- /dev/null +++ b/src/controllers/userStudy.ts @@ -0,0 +1,70 @@ +import express, { Request, Response, NextFunction } from "express"; +import moment from "moment"; +import Study from "../models/study"; +import connectDB from "../mongodb/connectDB"; + +export const getStudies = async (req: Request, res: Response, next: NextFunction) => { + try { + await connectDB(); + const studies = await Study.find(); + return res.status(200).json(studies); + } catch (error) { + console.error(error); + return res.status(500).json({ message: "Internal Server Error" }); + } +} + +export const getStudy = async (req: Request, res: Response, next: NextFunction) => { + try { + await connectDB(); + const studyId = req.params.id; + const study = await Study.findById(studyId); + return res.status(200).json(study); + } catch (error) { + console.error(error); + return res.status(500).json({ message: "Internal Server Error" }); + } +} + +export const addStudy = async (req: Request, res: Response, next: NextFunction) => { + try { + await connectDB(); + + const { imageSrc, title, mentor, day, startTime, endTime, level, stack, campus, description } = req.body; + const createDate = moment().format("YYYY-MM-DD HH:mm:ss"); + const newStudy = await Study.create({ + status: "reviewing", + imageSrc, + title, + mentor, + day, + startTime, + endTime, + level, + stack, + campus, + description, + createDate, + }); + + return res.status(200).json({ id: newStudy._id }); + } catch (error) { + console.error(error); + return res.status(500).json({ message: "Internal Server Error" }); + } +} + +export const editStudy = async (req: Request, res: Response, next: NextFunction) => { + try { + await connectDB(); + + const { id, imageSrc, title, mentor, day, startTime, endTime, level, stack, campus, description } = req.body; + const update = { imageSrc, title, mentor, day, startTime, endTime, level, stack, campus, description }; + const study = Study.findOneAndUpdate({ _id: id }, update, { new: true }); + + return res.status(200).json(study); + } catch (error) { + console.error(error); + return res.status(500).json({ message: "Internal Server Error" }); + } +} \ No newline at end of file diff --git a/src/middlewares/auth.ts b/src/middlewares/auth.ts index 4cfb69a..15f04c4 100644 --- a/src/middlewares/auth.ts +++ b/src/middlewares/auth.ts @@ -1,11 +1,6 @@ import { RequestHandler, Request, Response, NextFunction } from "express"; -const isLoggedIn: RequestHandler = -( - req: Request, - res: Response, - next: NextFunction -) => +const isLoggedIn: RequestHandler = (req: Request, res: Response, next: NextFunction) => { if (req.isAuthenticated()) { @@ -13,16 +8,11 @@ const isLoggedIn: RequestHandler = } else { - res.status(403).send("Log In required"); + res.status(403).json({ message: "Log In required" }); } } -const isNotLoggedIn: RequestHandler = -( - req: Request, - res: Response, - next: NextFunction -) => +const isNotLoggedIn: RequestHandler = (req: Request, res: Response, next: NextFunction) => { if (!req.isAuthenticated()) { diff --git a/src/middlewares/isAdmin.ts b/src/middlewares/isAdmin.ts new file mode 100644 index 0000000..f0de495 --- /dev/null +++ b/src/middlewares/isAdmin.ts @@ -0,0 +1,24 @@ +import { Request, Response, NextFunction } from "express"; +import connectDB from "../mongodb/connectDB"; +import CoMitUser from "../models/user"; + +const isAdmin = async (req: Request, res: Response, next: NextFunction) => { + try { + await connectDB(); + const { email } = req.params; + const user = await CoMitUser.findOne({ email }); + + if (user.isAdmin) { + res.locals.isAdmin = true; + next(); + } + else { + return res.status(403).json({ message: "Invalid access" }); + } + } catch (error) { + console.error(error); + return res.status(500).json({ message: "Internal server error" }); + } +} + +export default isAdmin; \ No newline at end of file diff --git a/src/models/study.ts b/src/models/study.ts new file mode 100644 index 0000000..8cfec6e --- /dev/null +++ b/src/models/study.ts @@ -0,0 +1,53 @@ +import mongoose, { Schema, models } from "mongoose"; + +const studySchema = new Schema({ + status: { + type: String, + }, + imageSrc: { + type: String + //required: true + }, + title: { + type: String + //required: true + }, + mentor: { + type: String + //required: true + }, + day: { + type: String + //required: true + }, + startTime: { + type: String + //required: true + }, + endTime: { + type: String + //required: true + }, + level: { + type: String + //required: true + }, + stack: { + type: Array, + }, + campus: { + type: String + //required: true + }, + description: { + String, + }, + createDate: { + type: String, + default: Date.now + } +}); + +const Study = models.Study || mongoose.model("Study", studySchema); + +export default Study; \ No newline at end of file diff --git a/src/schema/user.ts b/src/models/user.ts similarity index 88% rename from src/schema/user.ts rename to src/models/user.ts index 62c88d8..889fd00 100644 --- a/src/schema/user.ts +++ b/src/models/user.ts @@ -26,6 +26,11 @@ const CoMitUserSchema = new Schema({ { type: Number, required: true, + }, + isAdmin: + { + type: Boolean, + required: true, } }); diff --git a/src/passport/index.ts b/src/passport/index.ts index 039721d..7cde01c 100644 --- a/src/passport/index.ts +++ b/src/passport/index.ts @@ -1,20 +1,27 @@ import passport from "passport"; import local from "./localStrategy"; -import CoMitUser from "../schema/user"; +import CoMitUser from "../models/user"; +import connectDB from "../mongodb/connectDB"; const passportAuth = () => { passport.serializeUser((user: Express.User, done) => { - done(null, user.id); + done(null, user.email); }); - passport.deserializeUser(async (id: number, done) => + passport.deserializeUser(async (email: string, done) => { try { - const user = await CoMitUser.findOne({ id: id }); - done(null, user); + await connectDB(); + const user = await CoMitUser.findOne({ email }); + if (user) { + done(null, user); + } + else { + done(new Error("failed to find user"), false); + } } catch (err) { diff --git a/src/passport/localStrategy.ts b/src/passport/localStrategy.ts index 40610a6..5ccdb88 100644 --- a/src/passport/localStrategy.ts +++ b/src/passport/localStrategy.ts @@ -1,19 +1,20 @@ import passport from "passport"; import * as localStrategy from "passport-local" import bcrypt from "bcrypt"; - -import CoMitUser from "../schema/user"; +import connectDB from "../mongodb/connectDB"; +import CoMitUser from "../models/user"; const local = () => { passport.use(new localStrategy.Strategy({ usernameField: "email", - passwordField: "passwowrd", + passwordField: "password", passReqToCallback: false, }, async (email: string, password: string, done) => { try { + await connectDB(); const user = await CoMitUser.findOne({ email }); if (user) { @@ -32,12 +33,12 @@ const local = () => done(null, false, { message: "User not in database" }); } } - catch (err) + catch (error) { - console.error(err); - done(err); + console.error(error); + done(error); } - })) + })); } export default local; \ No newline at end of file diff --git a/src/routes/admin.ts b/src/routes/admin.ts new file mode 100644 index 0000000..ba73b00 --- /dev/null +++ b/src/routes/admin.ts @@ -0,0 +1,22 @@ +import express from "express"; + +import { getStudies, getStudy, editStudy, deleteStudy } from "../controllers/adminStudy"; + +const router = express.Router(); + +// study api for admin + +// /admin/study +router.get("/study", getStudies); + +// /admin/study/:id +router.get("/study/:id", getStudy); + +// /admin/study/:id +router.patch("/study/:id", editStudy); + +// /admin/study/:id +router.delete("/study/:id", deleteStudy); + + +export default router; \ No newline at end of file diff --git a/src/routes/auth.ts b/src/routes/auth.ts index 8966e58..d27b721 100644 --- a/src/routes/auth.ts +++ b/src/routes/auth.ts @@ -1,16 +1,16 @@ import express from "express"; import { isLoggedIn, isNotLoggedIn } from "../middlewares/auth"; -import { signIn, login } from "../controllers/auth"; +import { signup, login, logout } from "../controllers/auth"; const router = express.Router(); - // POST /auth/signup -router.post("/signup", isNotLoggedIn, signIn); +router.post("/signup", isNotLoggedIn, signup); // POST /auth/login router.post("/login", isNotLoggedIn, login); -router.get("/logout", isLoggedIn, ); +// POST /auth/login +router.post("/logout", isLoggedIn, logout); export default router; \ No newline at end of file diff --git a/src/routes/study.ts b/src/routes/study.ts new file mode 100644 index 0000000..8f173a3 --- /dev/null +++ b/src/routes/study.ts @@ -0,0 +1,18 @@ +import express from "express"; +import { getStudies, getStudy, addStudy, editStudy } from "../controllers/userStudy" + +const router = express.Router(); + +// Give all studies to front +router.get("/study", getStudies); + +// Give a particular study to front +router.get("/study/:id", getStudy); + +// Add a study +router.post("/study", addStudy); + +// Edit a study +router.patch("/study/:id", editStudy); + +export default router; \ No newline at end of file From b714ff55259a1d804e59fc4937b99a37fcb93791 Mon Sep 17 00:00:00 2001 From: toothless8392 Date: Wed, 13 Mar 2024 21:12:24 +0900 Subject: [PATCH 2/3] hotfix:remove-dist-folder --- dist/controllers/auth.js | 61 ------------------------------ dist/middlewares/auth.js | 22 ----------- dist/mongodb/connectDB.js | 48 ----------------------- dist/passport/index.js | 34 ----------------- dist/passport/localStrategy.js | 69 ---------------------------------- dist/routes/auth.js | 15 -------- dist/schema/user.js | 51 ------------------------- 7 files changed, 300 deletions(-) delete mode 100644 dist/controllers/auth.js delete mode 100644 dist/middlewares/auth.js delete mode 100644 dist/mongodb/connectDB.js delete mode 100644 dist/passport/index.js delete mode 100644 dist/passport/localStrategy.js delete mode 100644 dist/routes/auth.js delete mode 100644 dist/schema/user.js diff --git a/dist/controllers/auth.js b/dist/controllers/auth.js deleted file mode 100644 index ac908d7..0000000 --- a/dist/controllers/auth.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.login = exports.signIn = void 0; -const passport_1 = __importDefault(require("passport")); -const bcrypt_1 = __importDefault(require("bcrypt")); -const user_1 = __importDefault(require("../schema/user")); -const signIn = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { - try { - const user = yield user_1.default.findOne({ email: req.body.email }); - if (user) { - return res.status(403); - } - const { email, password, userName, studentID } = req.body; - const id = Date.now(); - const hashedPW = bcrypt_1.default.hash(password, 15); - yield user_1.default.create({ - id, - email, - password: hashedPW, - userName, - studentID, - }); - return res.status(201).json({ message: 0 }); - } - catch (err) { - console.error(err); - return next(err); - } -}); -exports.signIn = signIn; -const login = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () { - passport_1.default.authenticate("local", (authError, user, info) => { - if (authError) { - console.error(authError); - return next(authError); - } - if (!user) { - return res.status(403); - } - return req.login(user, (loginError) => { - if (loginError) { - console.error(loginError); - return next(loginError); - } - return; - }); - })(req, res, next); -}); -exports.login = login; diff --git a/dist/middlewares/auth.js b/dist/middlewares/auth.js deleted file mode 100644 index 1490c81..0000000 --- a/dist/middlewares/auth.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isNotLoggedIn = exports.isLoggedIn = void 0; -const isLoggedIn = (req, res, next) => { - if (req.isAuthenticated()) { - next(); - } - else { - res.status(403).send("Log In required"); - } -}; -exports.isLoggedIn = isLoggedIn; -const isNotLoggedIn = (req, res, next) => { - if (!req.isAuthenticated()) { - next(); - } - else { - const message = encodeURIComponent("Already logged in"); - res.redirect(`/?error=${message}`); - } -}; -exports.isNotLoggedIn = isNotLoggedIn; diff --git a/dist/mongodb/connectDB.js b/dist/mongodb/connectDB.js deleted file mode 100644 index 129c167..0000000 --- a/dist/mongodb/connectDB.js +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const mongoose_1 = __importDefault(require("mongoose")); -// declare global -// { -// var mongoose: -// { -// promise: Promise | null; -// connection: Mongoose | null; -// }; -// } -const URI = process.env.MONGODB_URL; -let cached = global.mongoose; -if (!cached) { - cached = global.mongoose = { connection: null, promise: null }; -} -const connectDB = () => __awaiter(void 0, void 0, void 0, function* () { - if (cached.connection) - return cached.connection; - try { - if (!cached.promise) { - cached.promise = mongoose_1.default - .set({ debug: true, strictQuery: false }) - .connect(`${URI}`) - .then((mongoose) => mongoose); - } - cached.connection = yield cached.promise; - console.log("Connected to MongoDB"); - return cached.connection; - } - catch (error) { - console.log("Failed to connect to MongoDB"); - console.error(error); - } -}); -exports.default = connectDB; diff --git a/dist/passport/index.js b/dist/passport/index.js deleted file mode 100644 index 8203296..0000000 --- a/dist/passport/index.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const passport_1 = __importDefault(require("passport")); -const localStrategy_1 = __importDefault(require("./localStrategy")); -const user_1 = __importDefault(require("../schema/user")); -const passportAuth = () => { - passport_1.default.serializeUser((user, done) => { - done(null, user.id); - }); - passport_1.default.deserializeUser((id, done) => __awaiter(void 0, void 0, void 0, function* () { - try { - const user = yield user_1.default.findOne({ id: id }); - done(null, user); - } - catch (err) { - console.error(err); - done(err); - } - })); - (0, localStrategy_1.default)(); -}; -exports.default = passportAuth; diff --git a/dist/passport/localStrategy.js b/dist/passport/localStrategy.js deleted file mode 100644 index a94ca60..0000000 --- a/dist/passport/localStrategy.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const passport_1 = __importDefault(require("passport")); -const localStrategy = __importStar(require("passport-local")); -const bcrypt_1 = __importDefault(require("bcrypt")); -const user_1 = __importDefault(require("../schema/user")); -const local = () => { - passport_1.default.use(new localStrategy.Strategy({ - usernameField: "email", - passwordField: "passwowrd", - passReqToCallback: false, - }, (email, password, done) => __awaiter(void 0, void 0, void 0, function* () { - try { - const user = yield user_1.default.findOne({ email }); - if (user) { - const compare = yield bcrypt_1.default.compare(password, user.password); - if (compare) { - done(null, user); - } - else { - done(null, false, { message: "Incorrect password" }); - } - } - else { - done(null, false, { message: "User not in database" }); - } - } - catch (err) { - console.error(err); - done(err); - } - }))); -}; -exports.default = local; diff --git a/dist/routes/auth.js b/dist/routes/auth.js deleted file mode 100644 index 4e5c3f6..0000000 --- a/dist/routes/auth.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const express_1 = __importDefault(require("express")); -const auth_1 = require("../middlewares/auth"); -const auth_2 = require("../controllers/auth"); -const router = express_1.default.Router(); -// POST /auth/signup -router.post("/signup", auth_1.isNotLoggedIn, auth_2.signIn); -// POST /auth/login -router.post("/login", auth_1.isNotLoggedIn, auth_2.login); -router.get("/logout", auth_1.isLoggedIn); -exports.default = router; diff --git a/dist/schema/user.js b/dist/schema/user.js deleted file mode 100644 index c722421..0000000 --- a/dist/schema/user.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const mongoose_1 = __importStar(require("mongoose")); -const CoMitUserSchema = new mongoose_1.Schema({ - id: { - type: Number, - required: true, - }, - email: { - type: String, - required: true, - unique: true, - }, - password: { - type: String, - required: true, - }, - name: { - type: String, - required: true, - }, - studentID: { - type: Number, - required: true, - } -}); -const CoMitUser = mongoose_1.models.CoMitUser || mongoose_1.default.model("CoMitUser", CoMitUserSchema); -exports.default = CoMitUser; From da372e7fa35d098ad388dd716fce03fee429d4d8 Mon Sep 17 00:00:00 2001 From: toothless8392 Date: Thu, 14 Mar 2024 13:14:27 +0900 Subject: [PATCH 3/3] feat:include-tsc-watch --- package-lock.json | 168 ++++++++++++++++++++++++++++++++++++++++++++++ package.json | 5 +- 2 files changed, 171 insertions(+), 2 deletions(-) diff --git a/package-lock.json b/package-lock.json index bed2a2b..8ae732e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -27,6 +27,7 @@ "morgan": "^1.10.0", "passport": "^0.7.0", "passport-local": "^1.0.0", + "tsc-watch": "^6.0.4", "typescript": "^5.3.3" }, "devDependencies": { @@ -651,6 +652,19 @@ "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", "dev": true }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/debug": { "version": "4.3.4", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", @@ -731,6 +745,11 @@ "url": "https://dotenvx.com" } }, + "node_modules/duplexer": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.2.tgz", + "integrity": "sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==" + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -770,6 +789,20 @@ "node": ">= 0.6" } }, + "node_modules/event-stream": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/event-stream/-/event-stream-3.3.4.tgz", + "integrity": "sha512-QHpkERcGsR0T7Qm3HNJSyXKEEj8AHNxkY3PK8TS2KJvQ7NiSHe3DDpwVKKtoYprL/AreyzFBeIkBIWChAqn60g==", + "dependencies": { + "duplexer": "~0.1.1", + "from": "~0", + "map-stream": "~0.1.0", + "pause-stream": "0.0.11", + "split": "0.3", + "stream-combiner": "~0.0.4", + "through": "~2.3.1" + } + }, "node_modules/express": { "version": "4.18.2", "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", @@ -926,6 +959,11 @@ "node": ">= 0.6" } }, + "node_modules/from": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/from/-/from-0.1.7.tgz", + "integrity": "sha512-twe20eF1OxVxp/ML/kq2p1uc6KvFK/+vs8WjEbeKmV2He22MKm7YF2ANIt+EOqhJ5L3K/SuuPhk0hWQDjOM23g==" + }, "node_modules/fs-minipass": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", @@ -1228,6 +1266,11 @@ "node": ">=0.12.0" } }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" + }, "node_modules/kareem": { "version": "2.5.1", "resolved": "https://registry.npmjs.org/kareem/-/kareem-2.5.1.tgz", @@ -1275,6 +1318,11 @@ "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", "dev": true }, + "node_modules/map-stream": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.1.0.tgz", + "integrity": "sha512-CkYQrPYZfWnu/DAmVCpTSX/xHpKZ80eKh2lAkyA6AJTef6bW+6JpbQZN5rofum7da+SyN1bi5ctTm+lTfcCW3g==" + }, "node_modules/media-typer": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", @@ -1540,6 +1588,11 @@ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz", "integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==" }, + "node_modules/node-cleanup": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/node-cleanup/-/node-cleanup-2.1.2.tgz", + "integrity": "sha512-qN8v/s2PAJwGUtr1/hYTpNKlD6Y9rc4p8KSmJXyGdYGZsDGKXrGThikLFP9OCHFeLeEpQzPwiAtdIvBLqm//Hw==" + }, "node_modules/node-fetch": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", @@ -1736,6 +1789,14 @@ "node": ">=0.10.0" } }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "engines": { + "node": ">=8" + } + }, "node_modules/path-to-regexp": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", @@ -1746,6 +1807,14 @@ "resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz", "integrity": "sha512-KG8UEiEVkR3wGEb4m5yZkVCzigAD+cVEJck2CzYZO37ZGJfctvVptVO192MwrtPhzONn6go8ylnOdMhKqi4nfg==" }, + "node_modules/pause-stream": { + "version": "0.0.11", + "resolved": "https://registry.npmjs.org/pause-stream/-/pause-stream-0.0.11.tgz", + "integrity": "sha512-e3FBlXLmN/D1S+zHzanP4E/4Z60oFAa3O051qt1pxa7DEJWKAyil6upYVXCWadEnuoqa4Pkc9oUx9zsxYeRv8A==", + "dependencies": { + "through": "~2.3" + } + }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", @@ -1770,6 +1839,20 @@ "node": ">= 0.10" } }, + "node_modules/ps-tree": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/ps-tree/-/ps-tree-1.2.0.tgz", + "integrity": "sha512-0VnamPPYHl4uaU/nSFeZZpR21QAWRz+sRv4iW9+v/GS/J5U5iZB5BNN6J0RMoOvdx2gWM2+ZFMIm58q24e4UYA==", + "dependencies": { + "event-stream": "=3.3.4" + }, + "bin": { + "ps-tree": "bin/ps-tree.js" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/pstree.remy": { "version": "1.1.8", "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", @@ -1986,6 +2069,25 @@ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "engines": { + "node": ">=8" + } + }, "node_modules/side-channel": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.5.tgz", @@ -2033,6 +2135,17 @@ "memory-pager": "^1.0.2" } }, + "node_modules/split": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/split/-/split-0.3.3.tgz", + "integrity": "sha512-wD2AeVmxXRBoX44wAycgjVpMhvbwdI2aZjCkvfNcH1YqHQvJVa1duWc73OyVGJUc05fhFaTZeQ/PYsrmyH0JVA==", + "dependencies": { + "through": "2" + }, + "engines": { + "node": "*" + } + }, "node_modules/statuses": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", @@ -2041,6 +2154,14 @@ "node": ">= 0.8" } }, + "node_modules/stream-combiner": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/stream-combiner/-/stream-combiner-0.0.4.tgz", + "integrity": "sha512-rT00SPnTVyRsaSz5zgSPma/aHSOic5U1prhYdRy5HS2kTZviFpmDgzilbtsJsxiroqACmayynDN/9VzIbX5DOw==", + "dependencies": { + "duplexer": "~0.1.1" + } + }, "node_modules/string_decoder": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", @@ -2049,6 +2170,14 @@ "safe-buffer": "~5.2.0" } }, + "node_modules/string-argv": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/string-argv/-/string-argv-0.3.2.tgz", + "integrity": "sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==", + "engines": { + "node": ">=0.6.19" + } + }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -2101,6 +2230,11 @@ "node": ">=10" } }, + "node_modules/through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==" + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -2187,6 +2321,26 @@ } } }, + "node_modules/tsc-watch": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/tsc-watch/-/tsc-watch-6.0.4.tgz", + "integrity": "sha512-cHvbvhjO86w2aGlaHgSCeQRl+Aqw6X6XN4sQMPZKF88GoP30O+oTuh5lRIJr5pgFWrRpF1AgXnJJ2DoFEIPHyg==", + "dependencies": { + "cross-spawn": "^7.0.3", + "node-cleanup": "^2.1.2", + "ps-tree": "^1.2.0", + "string-argv": "^0.3.1" + }, + "bin": { + "tsc-watch": "dist/lib/tsc-watch.js" + }, + "engines": { + "node": ">=12.12.0" + }, + "peerDependencies": { + "typescript": "*" + } + }, "node_modules/type-is": { "version": "1.6.18", "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", @@ -2288,6 +2442,20 @@ "node": ">=16" } }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, "node_modules/wide-align": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", diff --git a/package.json b/package.json index 3b7e572..d081f3e 100644 --- a/package.json +++ b/package.json @@ -2,10 +2,10 @@ "name": "comit-website-api", "version": "1.0.0", "description": "", - "main": "index.js", + "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", - "start": "nodemon dist/app.js" + "start": "tsc-watch --onSuccess \"nodemon dist/app.js\"" }, "author": "", "license": "ISC", @@ -32,6 +32,7 @@ "morgan": "^1.10.0", "passport": "^0.7.0", "passport-local": "^1.0.0", + "tsc-watch": "^6.0.4", "typescript": "^5.3.3" } }