Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules/
.DS_Store

config.env
dist/
116 changes: 116 additions & 0 deletions backend/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import express from "express";
import path from "path";
import morgan from "morgan";
import rateLimit from "express-rate-limit";
import helmet from "helmet";
import hpp from "hpp";
import cors from "cors";
import cookieParser from "cookie-parser";
import compression from "compression";

import AppError from "./utils/appError";
import globalErrorHandler from "./controllers/errorController";

import { userRouter } from "./routes/authRoutes";

function sanitizeValue(value: unknown): unknown {
if (typeof value === "string") {
return value.replace(/[<>$]/g, "");
}

if (Array.isArray(value)) {
return value.map(sanitizeValue);
}

if (value && typeof value === "object") {
return Object.fromEntries(
Object.entries(value).map(([key, nestedValue]) => [
key.replace(/[$.]/g, ""),
sanitizeValue(nestedValue),
]),
);
}

return value;
}

const app = express();
const frontendOrigin = process.env.FRONTEND_URL || "http://localhost:5173";
const publicDirectory = path.resolve(process.cwd(), "public");

app.set("trust proxy", process.env.NODE_ENV === "production" ? 1 : false);

app.set("view engine", "pug");
app.set("views", path.resolve(process.cwd(), "views"));

// Serving static files
app.use(express.static(publicDirectory));

// Set security HTTP headers
app.use(
cors({
origin: frontendOrigin,
credentials: true,
}),
);
app.options(
"/{*any}",
cors({
origin: frontendOrigin,
credentials: true,
}),
);

app.use(helmet());

// Development Logging
if (process.env.NODE_ENV === "development") {
app.use(morgan("dev"));
}

// Limit requests from same API
const limiter = rateLimit({
max: 100,
windowMs: 60 * 60 * 1000,
message: "Too many requests from this IP. Please try again in an hour!",
});

app.use("/api", limiter);

// Body parser, reading data from body into req.body
app.use(express.json({ limit: "10kb" }));
app.use(express.urlencoded({ extended: true, limit: "10kb" }));
app.use(cookieParser());

// Express 5 compatible request sanitization
app.use((req, _res, next) => {
req.body = sanitizeValue(req.body);
req.params = sanitizeValue(req.params) as typeof req.params;
next();
});

// Prevent parameter pollution
app.use(hpp());

app.use(compression());

// Test middleware
app.use((req: any, res, next) => {
// console.log('Hello from middleware :)');
req.requestTime = new Date().toISOString();
next();
});

// Routes
app.use("/api", userRouter);
app.all("/{*any}", (req, res, next) => {
// res.status(404).json({
// status: 'fail',
// message: `Can't find ${req.originalUrl} on this server!`,
// });
next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});

app.use(globalErrorHandler);

export default app;
242 changes: 242 additions & 0 deletions backend/controllers/authController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
import { Request, Response, NextFunction } from "express";
const { promisify } = require("util");
const jwt = require("jsonwebtoken");
import crypto from "crypto";

import User, { IUser } from "../models/userModel";
import AppError from "../utils/appError";
import asyncHandler from "../utils/asyncHandler";
import Email from "../utils/email";
import { createSendToken, getCookieOptions } from "../utils/generateToken";

export const signup = asyncHandler(async (req, res, next) => {
const newUser = await User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
passwordConfirm: req.body.passwordConfirm || req.body.password,
});

const url = `${req.protocol}://${req.get("host")}/`;
if (process.env.EMAIL_HOST) {
await new Email(newUser, url).sendWelcome();
}

createSendToken(newUser, 201, req, res);
});

export const login = asyncHandler(async (req, res, next) => {
const { email, password } = req.body;

// 1) Check if email and password exist
if (!email || !password) {
return next(
new AppError("Please enter both your email and password.", 400),
);
}
// 2) Check if user exists && password is correct
const user = await User.findOne({ email }).select("+password");

if (!user) {
return next(new AppError("No account found with that email address.", 404));
}

if (!(await user.correctPassword(password, user.password))) {
return next(new AppError("That password doesn't look right.", 401));
}

// 3) If everything ok, send token to client
createSendToken(user, 200, req, res);
});

export const logout = (req: Request, res: Response) => {
res.clearCookie("jwt", getCookieOptions(req, 0));
res.status(200).json({ status: "success" });
};

export const protect = asyncHandler(async (req, res, next) => {
// 1) Getting token and check of it's there
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
token = req.headers.authorization.split(" ")[1];
} else if (req.cookies.jwt) {
token = req.cookies.jwt;
}

if (!token) {
return next(
new AppError("You are not logged in! Please log in to get access.", 401),
);
}

// 2) Verification token
const decoded = await promisify(jwt.verify)(token, process.env.JWT_SECRET);

// 3) Check if user still exists
const currentUser = await User.findById(decoded.id);
if (!currentUser) {
return next(
new AppError(
"The user belonging to this token does no longer exist.",
401,
),
);
}

// 4) Check if user changed password after the token was issued
if (currentUser.changedPasswordAfter(decoded.iat)) {
return next(
new AppError("User recently changed password! Please log in again.", 401),
);
}

// GRANT ACCESS TO PROTECTED ROUTE
(req as any).user = currentUser;
res.locals.user = currentUser;
next();
});

// Only for rendered pages, no errors!
export const isLoggedIn = async (
req: Request,
res: Response,
next: NextFunction,
) => {
if (req.cookies.jwt) {
try {
// 1) Verify token
const decoded = await promisify(jwt.verify)(
req.cookies.jwt,
process.env.JWT_SECRET,
);

// 2) Check if user still exists
const currentUser = await User.findById(decoded.id);
if (!currentUser) {
return next();
}

// 3) Check if user changed password after the token was issued
if (currentUser.changedPasswordAfter(decoded.iat)) {
return next();
}

// THERE IS A LOGGED IN USER
res.locals.user = currentUser;
return next();
} catch (err) {
return next();
}
}
next();
};

export const restrictTo =
(...roles: string[]) =>
(req: any, res: Response, next: NextFunction) => {
// roles ['admin']. role='user'
if (!roles.includes(req.user.role)) {
return next(
new AppError("You do not have permission to perform this action", 403),
);
}
next();
};

export const forgotPassword = asyncHandler(async (req, res, next) => {
// 1) Get user based on posted email
const user = await User.findOne({ email: req.body.email });
if (!user) {
return next(new AppError("There is no user with email address", 404));
}

// 2) Generate the random reset token
const resetToken = user.createPasswordResetToken();
await user.save({ validateBeforeSave: false });

// 3) Send it to user's email
const frontendUrl =
process.env.FRONTEND_URL || `${req.protocol}://${req.get("host")}`;
const resetURL = `${frontendUrl}/reset-password/${resetToken}`;

// const message = `Forgot your password? Submit a PATCH request with your new password and passwordConfirm to: ${resetURL}.\nIf you didn't forget your password, please ignore this email!`;

try {
// await sendMail({
// email: user.email,
// subject: 'Your password reset token (valid for 10 mins)',
// message,
// });

if (!process.env.EMAIL_HOST) {
return res.status(200).json({
status: "success",
message: "Password reset flow is disabled until email config is set.",
});
}

await new Email(user, resetURL).sendPasswordReset();

res.status(200).json({
status: "success",
message: "Token sent to email",
});
} catch (err) {
user.passwordResetToken = undefined;
user.passwordResetExpires = undefined;
await user.save({ validateBeforeSave: false });

return next(
new AppError(
"There was an error sending the email. Try again later!",
500,
),
);
}
});

export const resetPassword = asyncHandler(async (req: any, res, next) => {
// 1) Get user based on token
const hashedToken = crypto
.createHash("sha256")
.update(req.params.token)
.digest("hex");

const user = await User.findOne({
passwordResetToken: hashedToken,
passwordResetExpires: { $gt: Date.now() },
});
// 2) If token has not expired, and there is user, set the new password
if (!user) {
return next(new AppError("Token is invalid or has expired", 400));
}
user.password = req.body.password;
user.passwordConfirm = req.body.passwordConfirm;
user.passwordResetToken = undefined;
user.passwordResetExpires = undefined;

await user.save();
// 3) Update changePasswordAt property for the user
// 4) Log the user in, send JWT
createSendToken(user, 200, req, res);
});

export const updatePassword = asyncHandler(async (req: any, res, next) => {
// 1) Get user from collection
const user: IUser = await User.findById(req.user.id).select("+password");

// 2) Check if POSTED current password is correct
if (!(await user.correctPassword(req.body.passwordCurrent, user.password))) {
return next(new AppError("Your current password is wrong.", 401));
}

// 3) If so, update password
user.password = req.body.password;
user.passwordConfirm = req.body.passwordConfirm;
await user.save();
// 4) Log user in, send JWT
createSendToken(user, 200, req, res);
});
Loading