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.
Files changed (53) hide show
  1. package/README.md +275 -0
  2. package/bin/index.js +302 -0
  3. package/package.json +36 -0
  4. package/template/.env.example +82 -0
  5. package/template/_gitignore +6 -0
  6. package/template/package.json +50 -0
  7. package/template/src/app/config/env.ts +190 -0
  8. package/template/src/app/config/passport.ts +112 -0
  9. package/template/src/app/config/r2.config.ts +15 -0
  10. package/template/src/app/config/redis.config.ts +21 -0
  11. package/template/src/app/errorHelpers/AppError.ts +16 -0
  12. package/template/src/app/helpers/handleCastError.ts +10 -0
  13. package/template/src/app/helpers/handleDuplicateError.ts +12 -0
  14. package/template/src/app/helpers/handleValidationError.ts +19 -0
  15. package/template/src/app/helpers/handleZodError.ts +26 -0
  16. package/template/src/app/interfaces/error.Types.ts +10 -0
  17. package/template/src/app/interfaces/index.d.ts +8 -0
  18. package/template/src/app/middlewares/checkAuth.ts +54 -0
  19. package/template/src/app/middlewares/globalErrorHandler.ts +78 -0
  20. package/template/src/app/middlewares/notFound.ts +18 -0
  21. package/template/src/app/middlewares/requestLogger.ts +20 -0
  22. package/template/src/app/middlewares/validateRequest.ts +21 -0
  23. package/template/src/app/modules/auth/auth.controller.ts +184 -0
  24. package/template/src/app/modules/auth/auth.route.ts +27 -0
  25. package/template/src/app/modules/auth/auth.service.ts +136 -0
  26. package/template/src/app/modules/auth/auth.validation.ts +53 -0
  27. package/template/src/app/modules/auth/jwt.ts +16 -0
  28. package/template/src/app/modules/otp/otp.controller.ts +32 -0
  29. package/template/src/app/modules/otp/otp.route.ts +12 -0
  30. package/template/src/app/modules/otp/otp.service.ts +120 -0
  31. package/template/src/app/modules/otp/otp.validation.ts +27 -0
  32. package/template/src/app/modules/user/user.constant.ts +1 -0
  33. package/template/src/app/modules/user/user.controller.ts +55 -0
  34. package/template/src/app/modules/user/user.interface.ts +41 -0
  35. package/template/src/app/modules/user/user.model.ts +44 -0
  36. package/template/src/app/modules/user/user.route.ts +20 -0
  37. package/template/src/app/modules/user/user.service.ts +79 -0
  38. package/template/src/app/modules/user/user.validation.ts +77 -0
  39. package/template/src/app/routes/index.ts +25 -0
  40. package/template/src/app/utils/catchAsync.ts +10 -0
  41. package/template/src/app/utils/constants.ts +1 -0
  42. package/template/src/app/utils/logger.ts +68 -0
  43. package/template/src/app/utils/queryBuilder.ts +83 -0
  44. package/template/src/app/utils/sendEmail.ts +62 -0
  45. package/template/src/app/utils/sendResponse.ts +26 -0
  46. package/template/src/app/utils/setCookie.ts +34 -0
  47. package/template/src/app/utils/templates/forgetPassword.ejs +76 -0
  48. package/template/src/app/utils/templates/otp.ejs +76 -0
  49. package/template/src/app/utils/templates/resetPassword.ejs +121 -0
  50. package/template/src/app/utils/userTokens.ts +52 -0
  51. package/template/src/app.ts +44 -0
  52. package/template/src/server.ts +66 -0
  53. package/template/tsconfig.json +14 -0
@@ -0,0 +1,21 @@
1
+ import { NextFunction, Request, Response } from "express";
2
+
3
+
4
+ export const validateRequest = (zodSchema: any) => async (req: Request, res: Response, next: NextFunction) => {
5
+ try {
6
+ if (req.body?.data) {
7
+ req.body = req.body.data;
8
+ }
9
+
10
+ const parsed = await zodSchema.parseAsync({
11
+ body: req.body || {},
12
+ query: req.query,
13
+ params: req.params,
14
+ });
15
+
16
+ req.body = parsed.body;
17
+ next();
18
+ } catch (error) {
19
+ next(error);
20
+ }
21
+ }
@@ -0,0 +1,184 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ /* eslint-disable @typescript-eslint/no-unused-vars */
3
+ import { NextFunction, Request, Response } from "express"
4
+ import httpStatus from "http-status-codes"
5
+ import { JwtPayload } from "jsonwebtoken"
6
+ import passport from "passport"
7
+ import { envVars } from "../../config/env"
8
+ import AppError from "../../errorHelpers/AppError"
9
+ import { sendResponse } from "../../utils/sendResponse"
10
+ import { setAuthCookie } from "../../utils/setCookie"
11
+ import { createUserTokens } from "../../utils/userTokens"
12
+ import { AuthServices } from "./auth.service"
13
+ import { catchAsync } from "../../utils/catchAsync"
14
+
15
+ const credentialsLogin = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
16
+ // const loginInfo = await AuthServices.credentialsLogin(req.body)
17
+
18
+ passport.authenticate("local", async (err: any, user: any, info: any) => {
19
+
20
+ if (err) {
21
+
22
+ return next(new AppError(401, err))
23
+ }
24
+
25
+ if (!user) {
26
+
27
+ return next(new AppError(401, info.message))
28
+ }
29
+
30
+ const userTokens = await createUserTokens(user)
31
+
32
+ // delete user.toObject().password
33
+
34
+ const { password: pass, ...rest } = user.toObject()
35
+
36
+
37
+ setAuthCookie(res, userTokens)
38
+
39
+ sendResponse(res, {
40
+ success: true,
41
+ statusCode: httpStatus.OK,
42
+ message: "User Logged In Successfully",
43
+ data: {
44
+ accessToken: userTokens.accessToken,
45
+ refreshToken: userTokens.refreshToken,
46
+ user: rest
47
+
48
+ },
49
+ })
50
+ })(req, res, next)
51
+
52
+
53
+ })
54
+ const getNewAccessToken = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
55
+ const refreshToken = req.cookies.refreshToken;
56
+ if (!refreshToken) {
57
+ throw new AppError(httpStatus.BAD_REQUEST, "No refresh token recieved from cookies")
58
+ }
59
+ const tokenInfo = await AuthServices.getNewAccessToken(refreshToken as string)
60
+
61
+
62
+ setAuthCookie(res, tokenInfo);
63
+
64
+ sendResponse(res, {
65
+ success: true,
66
+ statusCode: httpStatus.OK,
67
+ message: "New Access Token Retrived Successfully",
68
+ data: tokenInfo,
69
+ })
70
+ })
71
+ const logout = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
72
+
73
+ res.clearCookie("accessToken", {
74
+ httpOnly: true,
75
+ secure: true,
76
+ sameSite: "none"
77
+ })
78
+ res.clearCookie("refreshToken", {
79
+ httpOnly: true,
80
+ secure: true,
81
+ sameSite: "none"
82
+ })
83
+
84
+ sendResponse(res, {
85
+ success: true,
86
+ statusCode: httpStatus.OK,
87
+ message: "User Logged Out Successfully",
88
+ data: null,
89
+ })
90
+ })
91
+ const changePassword = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
92
+
93
+ const newPassword = req.body.newPassword;
94
+ const oldPassword = req.body.oldPassword;
95
+ const decodedToken = req.user
96
+
97
+ await AuthServices.changePassword(oldPassword, newPassword, decodedToken as JwtPayload);
98
+
99
+ sendResponse(res, {
100
+ success: true,
101
+ statusCode: httpStatus.OK,
102
+ message: "Password Changed Successfully",
103
+ data: null,
104
+ })
105
+ })
106
+ const resetPassword = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
107
+
108
+ const decodedToken = req.user
109
+
110
+ await AuthServices.resetPassword(req.body, decodedToken as JwtPayload);
111
+
112
+ sendResponse(res, {
113
+ success: true,
114
+ statusCode: httpStatus.OK,
115
+ message: "Password Changed Successfully",
116
+ data: null,
117
+ })
118
+ })
119
+ const setPassword = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
120
+
121
+ const decodedToken = req.user as JwtPayload
122
+ const { password } = req.body;
123
+
124
+ await AuthServices.setPassword(decodedToken.userId, password);
125
+
126
+ sendResponse(res, {
127
+ success: true,
128
+ statusCode: httpStatus.OK,
129
+ message: "Password Changed Successfully",
130
+ data: null,
131
+ })
132
+ })
133
+ const forgotPassword = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
134
+
135
+
136
+ const { email } = req.body;
137
+
138
+ await AuthServices.forgotPassword(email);
139
+
140
+ sendResponse(res, {
141
+ success: true,
142
+ statusCode: httpStatus.OK,
143
+ message: "Email Sent Successfully",
144
+ data: null,
145
+ })
146
+ })
147
+ const googleCallbackController = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
148
+
149
+ let redirectTo = req.query.state ? req.query.state as string : ""
150
+
151
+ // If no redirect specified, use default based on role
152
+ if (!redirectTo) {
153
+ const user = req.user as any;
154
+ redirectTo = user?.role === 'ADMIN' ? 'admin/dashboard' : 'dashboard'
155
+ }
156
+
157
+ // Remove leading slash if present
158
+ if (redirectTo.startsWith("/")) {
159
+ redirectTo = redirectTo.slice(1)
160
+ }
161
+
162
+ const user = req.user;
163
+
164
+ if (!user) {
165
+ throw new AppError(httpStatus.NOT_FOUND, "User Not Found")
166
+ }
167
+
168
+ const tokenInfo = createUserTokens(user)
169
+
170
+ setAuthCookie(res, tokenInfo)
171
+
172
+ res.redirect(`${envVars.FRONTEND_URL}/${redirectTo}`)
173
+ })
174
+
175
+ export const AuthControllers = {
176
+ credentialsLogin,
177
+ getNewAccessToken,
178
+ logout,
179
+ resetPassword,
180
+ setPassword,
181
+ forgotPassword,
182
+ changePassword,
183
+ googleCallbackController
184
+ }
@@ -0,0 +1,27 @@
1
+ import { NextFunction, Request, Response, Router } from "express";
2
+ import passport from "passport";
3
+ import { envVars } from "../../config/env";
4
+ import { Role } from "../user/user.interface";
5
+ import { AuthControllers } from "./auth.controller";
6
+ import { checkAuth } from "../../middlewares/checkAuth";
7
+
8
+ const router = Router()
9
+
10
+ router.post("/login", AuthControllers.credentialsLogin)
11
+ router.post("/refresh-token", AuthControllers.getNewAccessToken)
12
+ router.post("/logout", AuthControllers.logout)
13
+ router.post("/change-password", checkAuth(...Object.values(Role)), AuthControllers.changePassword)
14
+ router.post("/set-password", checkAuth(...Object.values(Role)), AuthControllers.setPassword)
15
+ router.post("/forgot-password", AuthControllers.forgotPassword)
16
+ router.post("/reset-password", checkAuth(...Object.values(Role)), AuthControllers.resetPassword)
17
+
18
+
19
+ router.get("/google", async (req: Request, res: Response, next: NextFunction) => {
20
+ const redirect = req.query.redirect || "/"
21
+ passport.authenticate("google", { scope: ["profile", "email"], state: redirect as string })(req, res, next)
22
+ })
23
+
24
+ // api/v1/auth/google/callback?state=/booking
25
+ router.get("/google/callback", passport.authenticate("google", { failureRedirect: `${envVars.FRONTEND_URL}/login?error=There is some issues with your account. Please contact with out support team!` }), AuthControllers.googleCallbackController)
26
+
27
+ export const AuthRoutes = router;
@@ -0,0 +1,136 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+
3
+ /* eslint-disable @typescript-eslint/no-non-null-assertion */
4
+ import bcryptjs from "bcryptjs";
5
+ import httpStatus from "http-status-codes";
6
+ import jwt, { JwtPayload } from "jsonwebtoken";
7
+ import AppError from "../../errorHelpers/AppError";
8
+ import { createNewAccessTokenWithRefreshToken } from "../../utils/userTokens";
9
+ import { IAuthProvider, IsActive } from "../user/user.interface";
10
+ import { User } from "../user/user.model";
11
+ import { sendEmail } from "../../utils/sendEmail";
12
+ import { envVars } from "../../config/env";
13
+
14
+
15
+ const getNewAccessToken = async (refreshToken: string) => {
16
+ const newAccessToken = await createNewAccessTokenWithRefreshToken(refreshToken)
17
+
18
+ return {
19
+ accessToken: newAccessToken
20
+ }
21
+
22
+ }
23
+ const resetPassword = async (payload: Record<string, any>, decodedToken: JwtPayload) => {
24
+ if (payload.id != decodedToken.userId) {
25
+ throw new AppError(httpStatus.FORBIDDEN, "You are not authorized to reset this password")
26
+ }
27
+
28
+ const isUserExist = await User.findById(decodedToken.userId)
29
+ if (!isUserExist) {
30
+ throw new AppError(httpStatus.NOT_FOUND, "User not found")
31
+ }
32
+
33
+ const hashedPassword = await bcryptjs.hash(
34
+ payload.newPassword,
35
+ Number(envVars.BCRYPT_SALT_ROUND)
36
+ )
37
+
38
+ isUserExist.password = hashedPassword;
39
+
40
+ await isUserExist.save()
41
+ }
42
+ const forgotPassword = async (email: string) => {
43
+ const isUserExist = await User.findOne({ email });
44
+
45
+ if (!isUserExist) {
46
+ throw new AppError(httpStatus.BAD_REQUEST, "User does not exist")
47
+ }
48
+ if (!isUserExist.isVerified) {
49
+ throw new AppError(httpStatus.BAD_REQUEST, "User is not verified")
50
+ }
51
+ if (isUserExist.isActive === IsActive.BLOCKED || isUserExist.isActive === IsActive.INACTIVE) {
52
+ throw new AppError(httpStatus.FORBIDDEN, `Your account has been ${isUserExist.isActive.toLowerCase()}. Please contact support for assistance`)
53
+ }
54
+ if (isUserExist.isDeleted) {
55
+ throw new AppError(httpStatus.BAD_REQUEST, "User is deleted")
56
+ }
57
+
58
+ const jwtPayload = {
59
+ userId: isUserExist._id,
60
+ email: isUserExist.email,
61
+ role: isUserExist.role
62
+ }
63
+
64
+ const resetToken = jwt.sign(jwtPayload, envVars.JWT_ACCESS_SECRET, {
65
+ expiresIn: "10m"
66
+ })
67
+
68
+ const resetUILink = `${envVars.FRONTEND_URL}/auth/reset-password?id=${isUserExist._id}&token=${resetToken}`
69
+
70
+ sendEmail({
71
+ to: isUserExist.email,
72
+ subject: "Password Reset",
73
+ templateName: "resetPassword",
74
+ templateData: {
75
+ name: isUserExist.name,
76
+ resetUILink
77
+ }
78
+ })
79
+
80
+
81
+ }
82
+ const setPassword = async (userId: string, plainPassword: string) => {
83
+ const user = await User.findById(userId);
84
+
85
+ if (!user) {
86
+ throw new AppError(404, "User not found");
87
+ }
88
+
89
+ if (user.password && user.auths.some(providerObject => providerObject.provider === "google")) {
90
+ throw new AppError(httpStatus.BAD_REQUEST, "You have already set your password. Please use the change password option in your profile settings")
91
+ }
92
+
93
+ const hashedPassword = await bcryptjs.hash(
94
+ plainPassword,
95
+ Number(envVars.BCRYPT_SALT_ROUND)
96
+ )
97
+
98
+ const credentialProvider: IAuthProvider = {
99
+ provider: "credentials",
100
+ providerId: user.email
101
+ }
102
+
103
+ const auths: IAuthProvider[] = [...user.auths, credentialProvider]
104
+
105
+ user.password = hashedPassword
106
+
107
+ user.auths = auths
108
+
109
+ await user.save()
110
+
111
+ }
112
+ const changePassword = async (oldPassword: string, newPassword: string, decodedToken: JwtPayload) => {
113
+
114
+ const user = await User.findById(decodedToken.userId)
115
+
116
+ const isOldPasswordMatch = await bcryptjs.compare(oldPassword, user!.password as string)
117
+ if (!isOldPasswordMatch) {
118
+ throw new AppError(httpStatus.UNAUTHORIZED, "Old Password does not match");
119
+ }
120
+
121
+ user!.password = await bcryptjs.hash(newPassword, Number(envVars.BCRYPT_SALT_ROUND))
122
+
123
+ user!.save();
124
+
125
+
126
+ }
127
+
128
+
129
+ export const AuthServices = {
130
+ // credentialsLogin,
131
+ getNewAccessToken,
132
+ changePassword,
133
+ setPassword,
134
+ forgotPassword,
135
+ resetPassword
136
+ }
@@ -0,0 +1,53 @@
1
+ import { z } from "zod";
2
+
3
+ const objectIdSchema = z.string().regex(/^[a-f\d]{24}$/i, "Invalid user id");
4
+
5
+ const passwordSchema = z
6
+ .string({ message: "Password must be string" })
7
+ .trim()
8
+ .min(1, { message: "Password is required" });
9
+
10
+ export const loginZodSchema = z.object({
11
+ body: z.object({
12
+ email: z.email("Invalid email address"),
13
+ password: z.string().min(1, "Password is required"),
14
+ forceLogoutOthers: z.union([z.boolean(), z.string()]).optional(),
15
+ }),
16
+ query: z.object({}).passthrough(),
17
+ params: z.object({}).passthrough(),
18
+ });
19
+
20
+ export const forgotPasswordZodSchema = z.object({
21
+ body: z.object({
22
+ email: z.email("Invalid email address"),
23
+ }),
24
+ query: z.object({}).passthrough(),
25
+ params: z.object({}).passthrough(),
26
+ });
27
+
28
+ export const changePasswordZodSchema = z.object({
29
+ body: z.object({
30
+ oldPassword: z.string().min(1, "Old password is required"),
31
+ newPassword: passwordSchema,
32
+ }),
33
+ query: z.object({}).passthrough(),
34
+ params: z.object({}).passthrough(),
35
+ });
36
+
37
+ export const setPasswordZodSchema = z.object({
38
+ body: z.object({
39
+ password: passwordSchema,
40
+ }),
41
+ query: z.object({}).passthrough(),
42
+ params: z.object({}).passthrough(),
43
+ });
44
+
45
+ export const resetPasswordZodSchema = z.object({
46
+ body: z.object({
47
+ id: objectIdSchema,
48
+ token: z.string().min(1, "Token is required"),
49
+ newPassword: passwordSchema,
50
+ }),
51
+ query: z.object({}).passthrough(),
52
+ params: z.object({}).passthrough(),
53
+ });
@@ -0,0 +1,16 @@
1
+ import jwt, { JwtPayload, SignOptions } from "jsonwebtoken";
2
+
3
+ export const generateToken = (payload: JwtPayload, secret: string, expiresIn: string) => {
4
+ const token = jwt.sign(payload, secret, {
5
+ expiresIn
6
+ } as SignOptions)
7
+
8
+ return token
9
+ }
10
+
11
+ export const verifyToken = (token: string, secret: string) => {
12
+
13
+ const verifiedToken = jwt.verify(token, secret)
14
+
15
+ return verifiedToken
16
+ }
@@ -0,0 +1,32 @@
1
+ import { Request, Response } from "express";
2
+ import { sendResponse } from "../../utils/sendResponse";
3
+ import { catchAsync } from "../../utils/catchAsync";
4
+ import { OTPService } from "./otp.service";
5
+
6
+
7
+ const sendOTP = catchAsync(async (req: Request, res: Response) => {
8
+ const { email, name } = req.body
9
+ await OTPService.sendOTP(email, name)
10
+ sendResponse(res, {
11
+ statusCode: 200,
12
+ success: true,
13
+ message: "OTP sent successfully",
14
+ data: null,
15
+ });
16
+ })
17
+
18
+ const verifyOTP = catchAsync(async (req: Request, res: Response) => {
19
+ const { email, otp } = req.body;
20
+ await OTPService.verifyOTP(email, otp)
21
+ sendResponse(res, {
22
+ statusCode: 200,
23
+ success: true,
24
+ message: "OTP verified successfully",
25
+ data: null,
26
+ });
27
+ })
28
+
29
+ export const OTPController = {
30
+ sendOTP,
31
+ verifyOTP
32
+ };
@@ -0,0 +1,12 @@
1
+ // src/modules/otp/otp.routes.ts
2
+ import express from "express";
3
+ import { OTPController } from "./otp.controller";
4
+ import { validateRequest } from "../../middlewares/validateRequest";
5
+ import { sendOtpZodSchema, verifyOtpZodSchema } from "./otp.validation";
6
+
7
+ const router = express.Router();
8
+
9
+ router.post("/send", validateRequest(sendOtpZodSchema), OTPController.sendOTP);
10
+ router.post("/verify", validateRequest(verifyOtpZodSchema), OTPController.verifyOTP);
11
+
12
+ export const OtpRoutes = router;
@@ -0,0 +1,120 @@
1
+ import crypto from "crypto"
2
+ import { sendEmail } from "../../utils/sendEmail"
3
+ import AppError from "../../errorHelpers/AppError"
4
+ import { User } from "../user/user.model"
5
+ import httpStatus from "http-status-codes"
6
+ import { logger } from "../../utils/logger"
7
+ import { redisClient } from "../../config/redis.config"
8
+ const OTP_EXPIRATION = 2 * 60
9
+
10
+ const generateOtp = (length = 6) => {
11
+ const otp = crypto.randomInt(10 ** (length - 1), 10 ** length).toString()
12
+
13
+ return otp
14
+ }
15
+
16
+ const sendOTP = async (email: string, name: string) => {
17
+ const normalizedEmail = email.trim().toLowerCase()
18
+ const resolvedName = name?.trim()
19
+
20
+ const user = await User.findOne({ email: normalizedEmail })
21
+
22
+ if (!user) {
23
+ logger.warn("OTP send rejected: user not found", { email: normalizedEmail })
24
+ throw new AppError(httpStatus.NOT_FOUND, "User not found")
25
+ }
26
+
27
+ if (user.isVerified) {
28
+ logger.warn("OTP send rejected: user already verified", {
29
+ userId: String(user._id),
30
+ email: normalizedEmail,
31
+ })
32
+ throw new AppError(httpStatus.BAD_REQUEST, "Your account is already verified")
33
+ }
34
+
35
+ const otp = generateOtp()
36
+
37
+ const redisKey = `otp:${normalizedEmail}`
38
+
39
+ await redisClient.set(redisKey, otp, {
40
+ expiration: {
41
+ type: "EX",
42
+ value: OTP_EXPIRATION
43
+ }
44
+ })
45
+
46
+ await sendEmail({
47
+ to: email,
48
+ subject: "Your Otp Code",
49
+ templateName: "otp",
50
+ templateData: {
51
+ name: resolvedName || user.name,
52
+ otp: otp
53
+ }
54
+ })
55
+
56
+ logger.info("OTP sent successfully", {
57
+ userId: String(user._id),
58
+ email: normalizedEmail,
59
+ expiresInSeconds: OTP_EXPIRATION,
60
+ })
61
+
62
+ }
63
+
64
+ const verifyOTP = async (email: string, otp: string) => {
65
+ const normalizedEmail = email.trim().toLowerCase()
66
+ const normalizedOtp = otp.trim()
67
+
68
+ const user = await User.findOne({ email: normalizedEmail })
69
+
70
+ if (!user) {
71
+ logger.warn("OTP verify rejected: user not found", { email: normalizedEmail })
72
+ throw new AppError(httpStatus.NOT_FOUND, "User not found")
73
+ }
74
+
75
+ if (user.isVerified) {
76
+ logger.warn("OTP verify rejected: user already verified", {
77
+ userId: String(user._id),
78
+ email: normalizedEmail,
79
+ })
80
+ throw new AppError(httpStatus.BAD_REQUEST, "Your account is already verified")
81
+ }
82
+
83
+
84
+ const redisKey = `otp:${normalizedEmail}`
85
+
86
+ const savedOtp = await redisClient.get(redisKey)
87
+
88
+ if (!savedOtp) {
89
+ logger.warn("OTP verify rejected: otp expired or missing", {
90
+ userId: String(user._id),
91
+ email: normalizedEmail,
92
+ })
93
+ throw new AppError(httpStatus.BAD_REQUEST, "OTP has expired. Please request a new one")
94
+ }
95
+
96
+ if (savedOtp !== normalizedOtp) {
97
+ logger.warn("OTP verify rejected: invalid otp", {
98
+ userId: String(user._id),
99
+ email: normalizedEmail,
100
+ })
101
+ throw new AppError(httpStatus.BAD_REQUEST, "Invalid OTP. Please check and try again")
102
+ }
103
+
104
+
105
+
106
+ await Promise.all([
107
+ User.updateOne({ email: normalizedEmail }, { isVerified: true }, { runValidators: true }),
108
+ redisClient.del([redisKey])
109
+ ])
110
+
111
+ logger.info("OTP verified successfully", {
112
+ userId: String(user._id),
113
+ email: normalizedEmail,
114
+ })
115
+ }
116
+
117
+ export const OTPService = {
118
+ sendOTP,
119
+ verifyOTP
120
+ }
@@ -0,0 +1,27 @@
1
+ import { z } from "zod";
2
+
3
+ export const sendOtpZodSchema = z.object({
4
+ body: z.object({
5
+ email: z.email("Invalid email address"),
6
+ name: z
7
+ .string({ message: "Name must be a string" })
8
+ .trim()
9
+ .min(1, "Name is required")
10
+ .max(100, "Name cannot exceed 100 characters")
11
+ .optional(),
12
+ }),
13
+ query: z.object({}).passthrough(),
14
+ params: z.object({}).passthrough(),
15
+ });
16
+
17
+ export const verifyOtpZodSchema = z.object({
18
+ body: z.object({
19
+ email: z.email("Invalid email address"),
20
+ otp: z
21
+ .string({ message: "OTP must be a string" })
22
+ .trim()
23
+ .regex(/^\d{6}$/, "OTP must be a valid 6-digit code"),
24
+ }),
25
+ query: z.object({}).passthrough(),
26
+ params: z.object({}).passthrough(),
27
+ });
@@ -0,0 +1 @@
1
+ export const userSearchableFields = ["name", "email", "address"];
@@ -0,0 +1,55 @@
1
+ import { NextFunction, Request, Response } from "express"
2
+ import httpStatus from "http-status-codes";
3
+ import { UserServices } from "./user.service";
4
+ import { catchAsync } from "../../utils/catchAsync";
5
+ import { sendResponse } from "../../utils/sendResponse";
6
+ import { JwtPayload } from "jsonwebtoken";
7
+
8
+
9
+
10
+ const createUser = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
11
+ const user = await UserServices.createUserService(req.body)
12
+ // res.status(httpStatus.CREATED).json({
13
+ // message: "User Created Successfully",
14
+ // user
15
+ // })
16
+
17
+ sendResponse(res, {
18
+ success: true,
19
+ statusCode: httpStatus.CREATED,
20
+ message: "User Created Successfully",
21
+ data: user
22
+ })
23
+
24
+ })
25
+
26
+
27
+ const getAllUsers = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
28
+ const query = req.query as Record<string, string>;
29
+ const result = await UserServices.getAllUsers(query);
30
+ sendResponse(res, {
31
+ success: true,
32
+ statusCode: httpStatus.OK,
33
+ message: "All Users Retrieved Successfully",
34
+ data: result.data,
35
+ meta: result.meta
36
+ })
37
+ })
38
+
39
+ const getMe = catchAsync(async (req: Request, res: Response, next: NextFunction) => {
40
+ const decodedToken = req.user as JwtPayload
41
+ const result = await UserServices.getMe(decodedToken.userId);
42
+
43
+ sendResponse(res, {
44
+ success: true,
45
+ statusCode: httpStatus.OK,
46
+ message: "Your profile Retrieved Successfully",
47
+ data: result.data
48
+ })
49
+ })
50
+
51
+ export const UserController = {
52
+ createUser,
53
+ getAllUsers,
54
+ getMe
55
+ }