Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
ankushchk committed Jul 23, 2024
0 parents commit f470398
Show file tree
Hide file tree
Showing 18 changed files with 812 additions and 0 deletions.
3 changes: 3 additions & 0 deletions server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
package-lock.json
.env
9 changes: 9 additions & 0 deletions server/dist/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"use strict";
var _a, _b, _c, _d;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = {
PORT: (_a = process.env.PORT) !== null && _a !== void 0 ? _a : "3000",
MONGODB_URI: (_b = process.env.MONGODB_URI) !== null && _b !== void 0 ? _b : "mongodb+srv://kush:[email protected]",
DB_NAME: (_c = process.env.DB_NAME) !== null && _c !== void 0 ? _c : "courses",
SECRET_KEY: (_d = process.env.SECRET_KEY) !== null && _d !== void 0 ? _d : "F7UVQlUTXZlXtO8uDURrOrxFa4cfuOrf",
};
32 changes: 32 additions & 0 deletions server/dist/db/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Course = exports.Admin = exports.User = void 0;
const mongoose_1 = __importDefault(require("mongoose"));
const userSchema = new mongoose_1.default.Schema({
username: { type: String },
password: String,
purchasedCourses: [{ type: mongoose_1.default.Schema.Types.ObjectId, ref: "Course" }],
});
const adminSchema = new mongoose_1.default.Schema({
username: String,
password: String,
});
const courseSchema = new mongoose_1.default.Schema({
title: String,
description: String,
price: Number,
imageLink: String,
published: String,
});
// Define mongoose models
exports.User = mongoose_1.default.model("User", userSchema);
exports.Admin = mongoose_1.default.model("Admin", adminSchema);
exports.Course = mongoose_1.default.model("Course", courseSchema);
// export default {
// User,
// Admin,
// Course,
// };
50 changes: 50 additions & 0 deletions server/dist/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const dotenv = __importStar(require("dotenv"));
dotenv.config();
const express_1 = __importDefault(require("express"));
const mongoose_1 = __importDefault(require("mongoose"));
const admin_1 = __importDefault(require("./routes/admin"));
const user_1 = __importDefault(require("./routes/user"));
const cors_1 = __importDefault(require("cors"));
const config_1 = __importDefault(require("./config"));
const app = (0, express_1.default)();
const port = config_1.default.PORT;
app.use((0, cors_1.default)());
app.use(express_1.default.json());
app.use("/admin", admin_1.default);
app.use("/users", user_1.default);
mongoose_1.default
.connect(config_1.default.MONGODB_URI, { dbName: config_1.default.DB_NAME })
.then(() => console.log("Connected to MongoDB"))
.catch((err) => console.error("Failed to connect to MongoDB:", err));
app.listen(port, () => {
console.log(`http://localhost:${port}`);
console.log("PORT:", config_1.default.PORT);
});
52 changes: 52 additions & 0 deletions server/dist/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"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 __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SECRET = exports.authenticateJwt = void 0;
const dotenv = __importStar(require("dotenv"));
dotenv.config();
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const config_1 = __importDefault(require("../config"));
const SECRET = config_1.default.SECRET_KEY; // This should be in an environment variable in a real application
exports.SECRET = SECRET;
const authenticateJwt = (req, res, next) => {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(" ")[1];
jsonwebtoken_1.default.verify(token, SECRET, (err, user) => {
if (err) {
return res.sendStatus(403);
}
req.user = user; // Set the user object directly
next();
});
}
else {
res.sendStatus(401);
}
};
exports.authenticateJwt = authenticateJwt;
130 changes: 130 additions & 0 deletions server/dist/routes/admin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"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 express_1 = __importDefault(require("express"));
const db_1 = require("../db");
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const auth_1 = require("../middleware/auth");
const auth_2 = require("../middleware/auth");
const dist_1 = require("@ankushch12/common/dist");
const router = express_1.default.Router();
router.get("/me", auth_2.authenticateJwt, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
try {
const admin = yield db_1.Admin.findOne({ username: req.user.username });
if (!admin) {
return res.status(403).json({ msg: "Admin doesn't exist" });
}
res.json({ username: admin.username });
}
catch (error) {
res.status(500).json({ message: "Internal Server Error" });
}
}));
router.post("/signup", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
const parsedInput = dist_1.signupInput.safeParse(req.body);
if (!parsedInput.success) {
const formattedErrors = parsedInput.error.issues
.map((issue) => {
return `${issue.path.join(".")} - ${issue.message}`;
})
.join(", ");
res.json({
error: formattedErrors,
});
return;
}
const { username, password } = parsedInput.data;
try {
const admin = yield db_1.Admin.findOne({ username });
if (admin) {
return res.status(403).json({ message: "Admin already exists" });
}
else {
const obj = { username, password };
const newAdmin = new db_1.Admin(obj);
yield newAdmin.save();
const token = jsonwebtoken_1.default.sign({ username, role: "admin" }, auth_1.SECRET, {
expiresIn: "1h",
});
res.json({ message: "Admin created successfully", token });
}
}
catch (error) {
res.status(500).json({ message: "Internal Server Error" });
}
}));
router.post("/login", (req, res) => __awaiter(void 0, void 0, void 0, function* () {
const parsedInput = dist_1.signupInput.safeParse(req.body);
if (!parsedInput.success) {
const formattedErrors = parsedInput.error.issues
.map((issue) => {
return `${issue.path.join(".")} - ${issue.message}`;
})
.join(", ");
res.json({
error: formattedErrors,
});
return;
}
const { username, password } = parsedInput.data;
try {
const admin = yield db_1.Admin.findOne({ username, password });
if (admin) {
const token = jsonwebtoken_1.default.sign({ username, role: "admin" }, auth_1.SECRET, {
expiresIn: "1h",
});
res.json({ message: "Logged in successfully", token });
}
else {
res.status(403).json({ message: "Invalid username or password" });
}
}
catch (error) {
res.status(500).json({ message: "Internal Server Error" });
}
}));
router.post("/courses", auth_2.authenticateJwt, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
try {
const course = new db_1.Course(req.body);
yield course.save();
res.json({ message: "Course created successfully", courseId: course.id });
}
catch (error) {
res.status(500).json({ message: "Internal Server Error" });
}
}));
router.put("/courses/:courseId", auth_2.authenticateJwt, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
try {
const course = yield db_1.Course.findByIdAndUpdate(req.params.courseId, req.body, { new: true });
if (course) {
res.json({ message: "Course updated successfully" });
}
else {
res.status(404).json({ message: "Course not found" });
}
}
catch (error) {
res.status(500).json({ message: "Internal Server Error" });
}
}));
router.get("/courses", auth_2.authenticateJwt, (req, res) => __awaiter(void 0, void 0, void 0, function* () {
try {
const courses = yield db_1.Course.find({});
res.json({ courses });
}
catch (error) {
res.status(500).json({ message: "Internal Server Error" });
}
}));
exports.default = router;
Loading

0 comments on commit f470398

Please sign in to comment.