create-oikko-mongo 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +275 -0
- package/bin/index.js +302 -0
- package/package.json +36 -0
- package/template/.env.example +82 -0
- package/template/_gitignore +6 -0
- package/template/package.json +50 -0
- package/template/src/app/config/env.ts +190 -0
- package/template/src/app/config/passport.ts +112 -0
- package/template/src/app/config/r2.config.ts +15 -0
- package/template/src/app/config/redis.config.ts +21 -0
- package/template/src/app/errorHelpers/AppError.ts +16 -0
- package/template/src/app/helpers/handleCastError.ts +10 -0
- package/template/src/app/helpers/handleDuplicateError.ts +12 -0
- package/template/src/app/helpers/handleValidationError.ts +19 -0
- package/template/src/app/helpers/handleZodError.ts +26 -0
- package/template/src/app/interfaces/error.Types.ts +10 -0
- package/template/src/app/interfaces/index.d.ts +8 -0
- package/template/src/app/middlewares/checkAuth.ts +54 -0
- package/template/src/app/middlewares/globalErrorHandler.ts +78 -0
- package/template/src/app/middlewares/notFound.ts +18 -0
- package/template/src/app/middlewares/requestLogger.ts +20 -0
- package/template/src/app/middlewares/validateRequest.ts +21 -0
- package/template/src/app/modules/auth/auth.controller.ts +184 -0
- package/template/src/app/modules/auth/auth.route.ts +27 -0
- package/template/src/app/modules/auth/auth.service.ts +136 -0
- package/template/src/app/modules/auth/auth.validation.ts +53 -0
- package/template/src/app/modules/auth/jwt.ts +16 -0
- package/template/src/app/modules/otp/otp.controller.ts +32 -0
- package/template/src/app/modules/otp/otp.route.ts +12 -0
- package/template/src/app/modules/otp/otp.service.ts +120 -0
- package/template/src/app/modules/otp/otp.validation.ts +27 -0
- package/template/src/app/modules/user/user.constant.ts +1 -0
- package/template/src/app/modules/user/user.controller.ts +55 -0
- package/template/src/app/modules/user/user.interface.ts +41 -0
- package/template/src/app/modules/user/user.model.ts +44 -0
- package/template/src/app/modules/user/user.route.ts +20 -0
- package/template/src/app/modules/user/user.service.ts +79 -0
- package/template/src/app/modules/user/user.validation.ts +77 -0
- package/template/src/app/routes/index.ts +25 -0
- package/template/src/app/utils/catchAsync.ts +10 -0
- package/template/src/app/utils/constants.ts +1 -0
- package/template/src/app/utils/logger.ts +68 -0
- package/template/src/app/utils/queryBuilder.ts +83 -0
- package/template/src/app/utils/sendEmail.ts +62 -0
- package/template/src/app/utils/sendResponse.ts +26 -0
- package/template/src/app/utils/setCookie.ts +34 -0
- package/template/src/app/utils/templates/forgetPassword.ejs +76 -0
- package/template/src/app/utils/templates/otp.ejs +76 -0
- package/template/src/app/utils/templates/resetPassword.ejs +121 -0
- package/template/src/app/utils/userTokens.ts +52 -0
- package/template/src/app.ts +44 -0
- package/template/src/server.ts +66 -0
- package/template/tsconfig.json +14 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import mongoose from "mongoose";
|
|
2
|
+
|
|
3
|
+
export enum Role {
|
|
4
|
+
USER = "user",
|
|
5
|
+
ADMIN = "admin",
|
|
6
|
+
SUPER_ADMIN = "super_admin"
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export enum IGender {
|
|
10
|
+
MALE = "male",
|
|
11
|
+
FEMALE = "female",
|
|
12
|
+
OTHER = "other",
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export enum IsActive {
|
|
16
|
+
ACTIVE = "active",
|
|
17
|
+
INACTIVE = "inactive",
|
|
18
|
+
BLOCKED = "blocked",
|
|
19
|
+
DELETED = "deleted"
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
export interface IAuthProvider {
|
|
24
|
+
provider: "google" | "credentials";
|
|
25
|
+
providerId: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface IUser {
|
|
29
|
+
_id?: mongoose.Types.ObjectId;
|
|
30
|
+
name: string;
|
|
31
|
+
email: string;
|
|
32
|
+
password: string;
|
|
33
|
+
photo: string | null;
|
|
34
|
+
gender: IGender | null;
|
|
35
|
+
isDeleted?: boolean;
|
|
36
|
+
isActive?: IsActive;
|
|
37
|
+
isVerified?: boolean;
|
|
38
|
+
role: Role;
|
|
39
|
+
auths: IAuthProvider[];
|
|
40
|
+
|
|
41
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { model, Schema } from "mongoose";
|
|
2
|
+
import { IAuthProvider, IGender, IsActive, IUser, Role } from "./user.interface";
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
const authProviderSchema = new Schema<IAuthProvider>({
|
|
6
|
+
provider: { type: String, required: true },
|
|
7
|
+
providerId: { type: String, required: true }
|
|
8
|
+
}, {
|
|
9
|
+
timestamps: false,
|
|
10
|
+
versionKey: false
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
const userSchema = new Schema<IUser>({
|
|
14
|
+
name: { type: String, required: true },
|
|
15
|
+
email: { type: String, required: true, unique: true },
|
|
16
|
+
password: { type: String },
|
|
17
|
+
photo: {
|
|
18
|
+
type: String,
|
|
19
|
+
default: null,
|
|
20
|
+
},
|
|
21
|
+
isDeleted: { type: Boolean },
|
|
22
|
+
isActive: {
|
|
23
|
+
type: String,
|
|
24
|
+
enum: Object.values(IsActive),
|
|
25
|
+
default: IsActive.ACTIVE
|
|
26
|
+
},
|
|
27
|
+
isVerified: { type: Boolean, default: false },
|
|
28
|
+
role: {
|
|
29
|
+
type: String,
|
|
30
|
+
enum: Object.values(Role),
|
|
31
|
+
default: Role.USER
|
|
32
|
+
},
|
|
33
|
+
gender: {
|
|
34
|
+
type: String,
|
|
35
|
+
enum: Object.values(IGender),
|
|
36
|
+
default: null,
|
|
37
|
+
},
|
|
38
|
+
auths: [authProviderSchema]
|
|
39
|
+
}, {
|
|
40
|
+
timestamps: true,
|
|
41
|
+
versionKey: false
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
export const User = model<IUser>("User", userSchema)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Router } from "express";
|
|
2
|
+
import { UserController } from "./user.controller";
|
|
3
|
+
import { createUserZodSchema } from "./user.validation";
|
|
4
|
+
import { validateRequest } from "../../middlewares/validateRequest";
|
|
5
|
+
import { Role } from "./user.interface";
|
|
6
|
+
import { checkAuth } from "../../middlewares/checkAuth";
|
|
7
|
+
|
|
8
|
+
const router = Router();
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
router.post("/register", validateRequest(createUserZodSchema), UserController.createUser);
|
|
14
|
+
router.get("/all-users", checkAuth(Role.ADMIN), UserController.getAllUsers);
|
|
15
|
+
// Get current user profile
|
|
16
|
+
router.get("/me",
|
|
17
|
+
checkAuth(...Object.values(Role)),
|
|
18
|
+
UserController.getMe)
|
|
19
|
+
|
|
20
|
+
export const UserRoutes = router;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import AppError from "../../errorHelpers/AppError";
|
|
2
|
+
import { IAuthProvider, IUser } from "./user.interface";
|
|
3
|
+
import { User } from "./user.model";
|
|
4
|
+
import httpStatus from "http-status-codes";
|
|
5
|
+
import bcrypt from "bcryptjs";
|
|
6
|
+
import { QueryBuilder } from "../../utils/queryBuilder";
|
|
7
|
+
import { userSearchableFields } from "./user.constant";
|
|
8
|
+
|
|
9
|
+
const createUserService = async (payload: Partial<IUser>) => {
|
|
10
|
+
const { email, password, ...rest } = payload;
|
|
11
|
+
|
|
12
|
+
const isUserExist = await User.findOne({ email });
|
|
13
|
+
|
|
14
|
+
if (isUserExist) {
|
|
15
|
+
throw new AppError(httpStatus.BAD_REQUEST, "User already exists with this email");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const hashedPassword = await bcrypt.hash(password as string, 10)
|
|
19
|
+
const authProvider: IAuthProvider = {
|
|
20
|
+
provider: "credentials",
|
|
21
|
+
providerId: email as string
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const user = await User.create({
|
|
25
|
+
email,
|
|
26
|
+
auths: [authProvider],
|
|
27
|
+
password: hashedPassword,
|
|
28
|
+
...rest
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
return user;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const getMe = async (userId: string) => {
|
|
35
|
+
const user = await User.findById(userId)
|
|
36
|
+
.select("-password")
|
|
37
|
+
|
|
38
|
+
if (!user) {
|
|
39
|
+
throw new AppError(httpStatus.NOT_FOUND, "User not found");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Format the response to include claimedRewards
|
|
43
|
+
const userData = user.toObject();
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
data: {
|
|
47
|
+
...userData
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const getAllUsers = async (query: Record<string, string>) => {
|
|
53
|
+
// Start with base query that excludes deleted users
|
|
54
|
+
const baseQuery = User.find({ isDeleted: { $ne: true } });
|
|
55
|
+
|
|
56
|
+
const queryBuilder = new QueryBuilder(baseQuery, query)
|
|
57
|
+
const usersData = queryBuilder
|
|
58
|
+
.filter()
|
|
59
|
+
.search(userSearchableFields)
|
|
60
|
+
.sort()
|
|
61
|
+
.fields()
|
|
62
|
+
.paginate();
|
|
63
|
+
|
|
64
|
+
const [data, meta] = await Promise.all([
|
|
65
|
+
usersData.build().select("-password"),
|
|
66
|
+
queryBuilder.getMeta()
|
|
67
|
+
])
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
data,
|
|
71
|
+
meta
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export const UserServices = {
|
|
76
|
+
createUserService,
|
|
77
|
+
getAllUsers,
|
|
78
|
+
getMe
|
|
79
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import z from "zod";
|
|
2
|
+
import { IsActive, Role } from "./user.interface";
|
|
3
|
+
export const createUserZodSchema = z.object({
|
|
4
|
+
body: z.object({
|
|
5
|
+
name: z
|
|
6
|
+
.string({
|
|
7
|
+
// Zod v4 uses a unified error callback
|
|
8
|
+
error: () => ({ message: "Name must be string" })
|
|
9
|
+
})
|
|
10
|
+
.trim()
|
|
11
|
+
.min(2, { message: "Name must be at least 2 characters long." })
|
|
12
|
+
.max(50, { message: "Name cannot exceed 50 characters." }),
|
|
13
|
+
|
|
14
|
+
email: z
|
|
15
|
+
.string({
|
|
16
|
+
error: () => ({ message: "Email must be string" })
|
|
17
|
+
})
|
|
18
|
+
.trim()
|
|
19
|
+
.email({ message: "Invalid email address format." })
|
|
20
|
+
.min(5, { message: "Email must be at least 5 characters long." })
|
|
21
|
+
.max(100, { message: "Email cannot exceed 100 characters." }),
|
|
22
|
+
|
|
23
|
+
password: z
|
|
24
|
+
.string({
|
|
25
|
+
error: () => ({ message: "Password must be string" })
|
|
26
|
+
})
|
|
27
|
+
.min(8, { message: "Password must be at least 8 characters long." })
|
|
28
|
+
.regex(/^(?=.*[A-Z])/, {
|
|
29
|
+
message: "Password must contain at least 1 uppercase letter.",
|
|
30
|
+
})
|
|
31
|
+
.regex(/^(?=.*[!@#$%^&*])/, {
|
|
32
|
+
message: "Password must contain at least 1 special character.",
|
|
33
|
+
})
|
|
34
|
+
.regex(/^(?=.*\d)/, {
|
|
35
|
+
message: "Password must contain at least 1 number.",
|
|
36
|
+
}),
|
|
37
|
+
}),
|
|
38
|
+
query: z.object({}).passthrough().optional(),
|
|
39
|
+
params: z.object({}).passthrough().optional(),
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
export const updateUserZodSchema = z.object({
|
|
43
|
+
body: z.object({
|
|
44
|
+
name: z
|
|
45
|
+
.string({
|
|
46
|
+
// Zod v4 uses a unified error callback
|
|
47
|
+
error: () => ({ message: "Name must be string" })
|
|
48
|
+
})
|
|
49
|
+
.trim()
|
|
50
|
+
.min(2, { message: "Name must be at least 2 characters long." })
|
|
51
|
+
.max(50, { message: "Name cannot exceed 50 characters." }).optional(),
|
|
52
|
+
password: z
|
|
53
|
+
.string({
|
|
54
|
+
error: () => ({ message: "Password must be string" })
|
|
55
|
+
})
|
|
56
|
+
.min(8, { message: "Password must be at least 8 characters long." })
|
|
57
|
+
.regex(/^(?=.*[A-Z])/, {
|
|
58
|
+
message: "Password must contain at least 1 uppercase letter.",
|
|
59
|
+
})
|
|
60
|
+
.regex(/^(?=.*[!@#$%^&*])/, {
|
|
61
|
+
message: "Password must contain at least 1 special character.",
|
|
62
|
+
})
|
|
63
|
+
.regex(/^(?=.*\d)/, {
|
|
64
|
+
message: "Password must contain at least 1 number.",
|
|
65
|
+
}).optional(),
|
|
66
|
+
role: z.enum(Object.values(Role) as [string]).optional(),
|
|
67
|
+
IsActive: z.enum(Object.values(IsActive) as [string]).optional(),
|
|
68
|
+
isDeleted: z.boolean({
|
|
69
|
+
error: () => ({ message: "isDeleted must be boolean" })
|
|
70
|
+
}).optional(),
|
|
71
|
+
isVerified: z.boolean({
|
|
72
|
+
error: () => ({ message: "isVerified must be boolean" })
|
|
73
|
+
}).optional(),
|
|
74
|
+
}),
|
|
75
|
+
query: z.object({}).passthrough().optional(),
|
|
76
|
+
params: z.object({}).passthrough().optional(),
|
|
77
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Router } from "express";
|
|
2
|
+
import { UserRoutes } from "../modules/user/user.route";
|
|
3
|
+
import { AuthRoutes } from "../modules/auth/auth.route";
|
|
4
|
+
import { OtpRoutes } from "../modules/otp/otp.route";
|
|
5
|
+
|
|
6
|
+
export const router = Router();
|
|
7
|
+
|
|
8
|
+
const moduleRoutes = [
|
|
9
|
+
{
|
|
10
|
+
path: "/user",
|
|
11
|
+
route: UserRoutes
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
path: "/auth",
|
|
15
|
+
route: AuthRoutes
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
path: "/otp",
|
|
19
|
+
route: OtpRoutes
|
|
20
|
+
}
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
moduleRoutes.forEach((route) => {
|
|
24
|
+
router.use(route.path, route.route)
|
|
25
|
+
})
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { NextFunction, Request, Response } from "express";
|
|
2
|
+
|
|
3
|
+
type AsyncHandler = (req: Request, res: Response, next: NextFunction) => Promise<void>;
|
|
4
|
+
|
|
5
|
+
export const catchAsync = (fn: AsyncHandler) => (req: Request, res: Response, next: NextFunction) => {
|
|
6
|
+
Promise.resolve(fn(req, res, next)).catch((err) => {
|
|
7
|
+
console.log(err);
|
|
8
|
+
next(err);
|
|
9
|
+
});
|
|
10
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const excludeField = ["searchTerm", "sort", "fields", "page", "limit"]
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import winston from "winston";
|
|
4
|
+
import { envVars } from "../config/env";
|
|
5
|
+
|
|
6
|
+
const logsDir = path.join(process.cwd(), "logs");
|
|
7
|
+
|
|
8
|
+
if (!fs.existsSync(logsDir)) {
|
|
9
|
+
fs.mkdirSync(logsDir, { recursive: true });
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const isProduction = envVars.NODE_ENV === "production";
|
|
13
|
+
|
|
14
|
+
const consoleFormat = winston.format.combine(
|
|
15
|
+
winston.format.colorize(),
|
|
16
|
+
winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
|
|
17
|
+
winston.format.printf(({ level, message, timestamp, stack, ...meta }) => {
|
|
18
|
+
const metaText = Object.keys(meta).length ? ` ${JSON.stringify(meta)}` : "";
|
|
19
|
+
const stackText = stack ? `\n${stack}` : "";
|
|
20
|
+
return `[${timestamp}] ${level}: ${message}${metaText}${stackText}`;
|
|
21
|
+
}),
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
const fileFormat = winston.format.combine(
|
|
25
|
+
winston.format.timestamp(),
|
|
26
|
+
winston.format.errors({ stack: true }),
|
|
27
|
+
winston.format.json(),
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
export const logger = winston.createLogger({
|
|
31
|
+
level: isProduction ? "info" : "debug",
|
|
32
|
+
defaultMeta: { service: "example-name" },
|
|
33
|
+
transports: [
|
|
34
|
+
new winston.transports.Console({
|
|
35
|
+
format: isProduction ? fileFormat : consoleFormat,
|
|
36
|
+
}),
|
|
37
|
+
new winston.transports.File({
|
|
38
|
+
filename: path.join(logsDir, "combined.log"),
|
|
39
|
+
format: fileFormat,
|
|
40
|
+
}),
|
|
41
|
+
new winston.transports.File({
|
|
42
|
+
filename: path.join(logsDir, "error.log"),
|
|
43
|
+
level: "error",
|
|
44
|
+
format: fileFormat,
|
|
45
|
+
}),
|
|
46
|
+
],
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
export const requestLogger = (message: string, meta?: Record<string, unknown>) => {
|
|
50
|
+
logger.info(message, meta);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export const errorLogger = (message: string, error?: unknown, meta?: Record<string, unknown>) => {
|
|
54
|
+
if (error instanceof Error) {
|
|
55
|
+
logger.error(message, {
|
|
56
|
+
...meta,
|
|
57
|
+
name: error.name,
|
|
58
|
+
stack: error.stack,
|
|
59
|
+
message: error.message,
|
|
60
|
+
});
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
logger.error(message, {
|
|
65
|
+
...meta,
|
|
66
|
+
error,
|
|
67
|
+
});
|
|
68
|
+
};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { Query } from "mongoose";
|
|
2
|
+
import { excludeField } from "./constants";
|
|
3
|
+
|
|
4
|
+
export class QueryBuilder<T> {
|
|
5
|
+
public modelQuery: Query<T[], T>;
|
|
6
|
+
public readonly query: Record<string, string>
|
|
7
|
+
|
|
8
|
+
constructor(modelQuery: Query<T[], T>, query: Record<string, string>) {
|
|
9
|
+
this.modelQuery = modelQuery;
|
|
10
|
+
this.query = query;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
filter(): this {
|
|
15
|
+
const filter = { ...this.query }
|
|
16
|
+
|
|
17
|
+
for (const field of excludeField) {
|
|
18
|
+
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
|
|
19
|
+
delete filter[field]
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (Object.keys(filter).length > 0) {
|
|
23
|
+
this.modelQuery = this.modelQuery.find(filter)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return this;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
search(searchableField: string[]): this {
|
|
30
|
+
const searchTerm = (this.query.searchTerm || "").trim();
|
|
31
|
+
if (searchTerm && searchableField.length > 0) {
|
|
32
|
+
const searchQuery = {
|
|
33
|
+
$or: searchableField.map(field => ({ [field]: { $regex: searchTerm, $options: "i" } }))
|
|
34
|
+
}
|
|
35
|
+
this.modelQuery = this.modelQuery.find(searchQuery)
|
|
36
|
+
}
|
|
37
|
+
return this
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
sort(): this {
|
|
41
|
+
|
|
42
|
+
const sort = this.query.sort || "-createdAt";
|
|
43
|
+
|
|
44
|
+
this.modelQuery = this.modelQuery.sort(sort)
|
|
45
|
+
|
|
46
|
+
return this;
|
|
47
|
+
}
|
|
48
|
+
fields(): this {
|
|
49
|
+
|
|
50
|
+
const fields = this.query.fields?.split(",").join(" ") || ""
|
|
51
|
+
|
|
52
|
+
this.modelQuery = this.modelQuery.select(fields)
|
|
53
|
+
|
|
54
|
+
return this;
|
|
55
|
+
}
|
|
56
|
+
paginate(): this {
|
|
57
|
+
|
|
58
|
+
const page = Number(this.query.page) || 1
|
|
59
|
+
const limit = Number(this.query.limit) || 10
|
|
60
|
+
const skip = (page - 1) * limit
|
|
61
|
+
|
|
62
|
+
this.modelQuery = this.modelQuery.skip(skip).limit(limit)
|
|
63
|
+
|
|
64
|
+
return this;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
build() {
|
|
68
|
+
return this.modelQuery
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async getMeta() {
|
|
72
|
+
// Get the filter from the current query to count matching documents
|
|
73
|
+
const filter = this.modelQuery.getFilter();
|
|
74
|
+
const totalDocuments = await this.modelQuery.model.countDocuments(filter);
|
|
75
|
+
|
|
76
|
+
const page = Number(this.query.page) || 1
|
|
77
|
+
const limit = Number(this.query.limit) || 10
|
|
78
|
+
|
|
79
|
+
const totalPage = Math.ceil(totalDocuments / limit)
|
|
80
|
+
|
|
81
|
+
return { page, limit, total: totalDocuments, totalPage }
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
import ejs from "ejs";
|
|
3
|
+
import nodemailer from "nodemailer";
|
|
4
|
+
import path from "path";
|
|
5
|
+
import AppError from "../errorHelpers/AppError";
|
|
6
|
+
import httpStatus from "http-status-codes";
|
|
7
|
+
import { envVars } from "../config/env";
|
|
8
|
+
const transporter = nodemailer.createTransport({
|
|
9
|
+
host: envVars.EMAIL_SENDER.SMTP_HOST,
|
|
10
|
+
port: Number(envVars.EMAIL_SENDER.SMTP_PORT),
|
|
11
|
+
secure: Number(envVars.EMAIL_SENDER.SMTP_PORT) === 465, // true for 465, false for other ports
|
|
12
|
+
auth: {
|
|
13
|
+
user: envVars.EMAIL_SENDER.SMTP_USER,
|
|
14
|
+
pass: envVars.EMAIL_SENDER.SMTP_PASS
|
|
15
|
+
},
|
|
16
|
+
tls: {
|
|
17
|
+
// Do not fail on invalid certs (for development)
|
|
18
|
+
rejectUnauthorized: false
|
|
19
|
+
}
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
interface SendEmailOptions {
|
|
23
|
+
to: string,
|
|
24
|
+
subject: string;
|
|
25
|
+
templateName: string;
|
|
26
|
+
templateData?: Record<string, any>
|
|
27
|
+
attachments?: {
|
|
28
|
+
filename: string,
|
|
29
|
+
content: Buffer | string,
|
|
30
|
+
contentType: string
|
|
31
|
+
}[]
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const sendEmail = async ({
|
|
35
|
+
to,
|
|
36
|
+
subject,
|
|
37
|
+
templateName,
|
|
38
|
+
templateData,
|
|
39
|
+
attachments
|
|
40
|
+
}: SendEmailOptions) => {
|
|
41
|
+
try {
|
|
42
|
+
const templatePath = path.join(process.cwd(), 'src', 'app', 'utils', 'templates', `${templateName}.ejs`);
|
|
43
|
+
|
|
44
|
+
const html = await ejs.renderFile(templatePath, templateData)
|
|
45
|
+
const info = await transporter.sendMail({
|
|
46
|
+
from: `"Example" <${envVars.EMAIL_SENDER.SMTP_FROM}>`,
|
|
47
|
+
to: to,
|
|
48
|
+
subject: subject,
|
|
49
|
+
html: html,
|
|
50
|
+
attachments: attachments?.map(attachment => ({
|
|
51
|
+
filename: attachment.filename,
|
|
52
|
+
content: attachment.content,
|
|
53
|
+
contentType: attachment.contentType
|
|
54
|
+
}))
|
|
55
|
+
})
|
|
56
|
+
console.log(`\u2709\uFE0F Email sent to ${to}: ${info.messageId}`);
|
|
57
|
+
} catch (error: any) {
|
|
58
|
+
console.log("email sending error", error.message);
|
|
59
|
+
throw new AppError(httpStatus.INTERNAL_SERVER_ERROR, "Failed to send email. Please try again later")
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Response } from "express";
|
|
2
|
+
|
|
3
|
+
interface TMeta {
|
|
4
|
+
page: number;
|
|
5
|
+
limit: number;
|
|
6
|
+
totalPage: number;
|
|
7
|
+
total?: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
interface TResponse<T> {
|
|
11
|
+
statusCode: number;
|
|
12
|
+
success: boolean;
|
|
13
|
+
message: string;
|
|
14
|
+
data: T;
|
|
15
|
+
meta?: TMeta
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const sendResponse = <T>(res: Response, data: TResponse<T>) => {
|
|
19
|
+
res.status(data.statusCode).json({
|
|
20
|
+
statusCode: data.statusCode,
|
|
21
|
+
success: data.success,
|
|
22
|
+
message: data.message,
|
|
23
|
+
meta: data.meta,
|
|
24
|
+
data: data.data
|
|
25
|
+
})
|
|
26
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Response } from "express";
|
|
2
|
+
import { envVars } from "../config/env";
|
|
3
|
+
|
|
4
|
+
export interface AuthTokens {
|
|
5
|
+
accessToken?: string;
|
|
6
|
+
refreshToken?: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const baseCookieOptions = {
|
|
10
|
+
httpOnly: true,
|
|
11
|
+
secure: envVars.NODE_ENV === "production",
|
|
12
|
+
sameSite: (envVars.NODE_ENV === "production" ? "none" : "lax") as "none" | "lax",
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export const setAuthCookie = (res: Response, tokenInfo: AuthTokens) => {
|
|
16
|
+
if (tokenInfo.accessToken) {
|
|
17
|
+
res.cookie("accessToken", tokenInfo.accessToken, {
|
|
18
|
+
...baseCookieOptions,
|
|
19
|
+
maxAge: 24 * 60 * 60 * 1000 // 1 day in milliseconds
|
|
20
|
+
})
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (tokenInfo.refreshToken) {
|
|
24
|
+
res.cookie("refreshToken", tokenInfo.refreshToken, {
|
|
25
|
+
...baseCookieOptions,
|
|
26
|
+
maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days in milliseconds
|
|
27
|
+
})
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const clearAuthCookie = (res: Response) => {
|
|
32
|
+
res.clearCookie("accessToken", baseCookieOptions)
|
|
33
|
+
res.clearCookie("refreshToken", baseCookieOptions)
|
|
34
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
|
|
4
|
+
<head>
|
|
5
|
+
<meta charset="UTF-8" />
|
|
6
|
+
<title>Your OTP Code</title>
|
|
7
|
+
<style>
|
|
8
|
+
body {
|
|
9
|
+
background-color: #f6f9fc;
|
|
10
|
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
|
11
|
+
margin: 0;
|
|
12
|
+
padding: 0;
|
|
13
|
+
color: #333;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
.container {
|
|
17
|
+
max-width: 600px;
|
|
18
|
+
margin: 40px auto;
|
|
19
|
+
background-color: #ffffff;
|
|
20
|
+
padding: 30px 40px;
|
|
21
|
+
border-radius: 10px;
|
|
22
|
+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
h2 {
|
|
26
|
+
color: #2c3e50;
|
|
27
|
+
font-weight: 600;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
.otp-box {
|
|
31
|
+
font-size: 28px;
|
|
32
|
+
font-weight: bold;
|
|
33
|
+
background: #f0f4f8;
|
|
34
|
+
padding: 15px 25px;
|
|
35
|
+
text-align: center;
|
|
36
|
+
border-radius: 8px;
|
|
37
|
+
margin: 20px 0;
|
|
38
|
+
letter-spacing: 2px;
|
|
39
|
+
color: #34495e;
|
|
40
|
+
border: 2px dashed #3498db;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
p {
|
|
44
|
+
font-size: 16px;
|
|
45
|
+
line-height: 1.6;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
.footer {
|
|
49
|
+
margin-top: 30px;
|
|
50
|
+
font-size: 13px;
|
|
51
|
+
text-align: center;
|
|
52
|
+
color: #999;
|
|
53
|
+
}
|
|
54
|
+
</style>
|
|
55
|
+
</head>
|
|
56
|
+
|
|
57
|
+
<body>
|
|
58
|
+
<div class="container">
|
|
59
|
+
<h2>Hello <%= name %>,</h2>
|
|
60
|
+
<p>Use the OTP code below to complete your verification:</p>
|
|
61
|
+
|
|
62
|
+
<div class="otp-box">
|
|
63
|
+
<%= otp %>
|
|
64
|
+
</div>
|
|
65
|
+
|
|
66
|
+
<p>This code is valid for <strong>2 minutes</strong>. Please do not share it with anyone.</p>
|
|
67
|
+
|
|
68
|
+
<p>If you didn’t request this, you can ignore this message.</p>
|
|
69
|
+
|
|
70
|
+
<div class="footer">
|
|
71
|
+
© <%= new Date().getFullYear() %> Gamify Learn. All rights reserved.
|
|
72
|
+
</div>
|
|
73
|
+
</div>
|
|
74
|
+
</body>
|
|
75
|
+
|
|
76
|
+
</html>
|