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,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "{{PROJECT_NAME}}",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Backend API created with create-oikko-mongo",
|
|
5
|
+
"main": "dist/server.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"dev": "tsx watch ./src/server.ts",
|
|
8
|
+
"build": "tsc",
|
|
9
|
+
"start": "node ./dist/server.js"
|
|
10
|
+
},
|
|
11
|
+
"keywords": ["express", "typescript", "mongodb", "oikko"],
|
|
12
|
+
"author": "",
|
|
13
|
+
"license": "ISC",
|
|
14
|
+
"type": "module",
|
|
15
|
+
"devDependencies": {
|
|
16
|
+
"@types/bcryptjs": "^2.4.6",
|
|
17
|
+
"@types/cookie-parser": "^1.4.8",
|
|
18
|
+
"@types/cors": "^2.8.19",
|
|
19
|
+
"@types/dotenv": "^6.1.1",
|
|
20
|
+
"@types/ejs": "^3.1.5",
|
|
21
|
+
"@types/express": "^5.0.6",
|
|
22
|
+
"@types/express-session": "^1.18.2",
|
|
23
|
+
"@types/jsonwebtoken": "^9.0.10",
|
|
24
|
+
"@types/nodemailer": "^8.0.2",
|
|
25
|
+
"@types/passport-google-oauth20": "^2.0.17",
|
|
26
|
+
"@types/passport-local": "^1.0.38",
|
|
27
|
+
"tsx": "^4.23.15",
|
|
28
|
+
"typescript": "^5.7.0"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@aws-sdk/client-s3": "^3.1146.0",
|
|
32
|
+
"bcryptjs": "^3.0.3",
|
|
33
|
+
"cookie-parser": "^1.4.7",
|
|
34
|
+
"cors": "^2.8.6",
|
|
35
|
+
"dotenv": "^18.0.5",
|
|
36
|
+
"ejs": "^7.0.1",
|
|
37
|
+
"express": "^5.2.1",
|
|
38
|
+
"express-session": "^1.18.2",
|
|
39
|
+
"http-status-codes": "^2.3.0",
|
|
40
|
+
"jsonwebtoken": "^9.0.3",
|
|
41
|
+
"mongoose": "^9.10.3",
|
|
42
|
+
"nodemailer": "^10.0.15",
|
|
43
|
+
"passport": "^0.7.0",
|
|
44
|
+
"passport-google-oauth20": "^2.0.0",
|
|
45
|
+
"passport-local": "^1.0.0",
|
|
46
|
+
"redis": "^6.3.0",
|
|
47
|
+
"winston": "^3.19.0",
|
|
48
|
+
"zod": "^4.6.5"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import dotenv from "dotenv"
|
|
2
|
+
dotenv.config()
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
interface EnvConfig {
|
|
6
|
+
PORT: string,
|
|
7
|
+
DB_URL: string,
|
|
8
|
+
NODE_ENV: "development" | "production"
|
|
9
|
+
BCRYPT_SALT_ROUND: string,
|
|
10
|
+
JWT_ACCESS_EXPIRES: string,
|
|
11
|
+
JWT_ACCESS_SECRET: string,
|
|
12
|
+
SUPER_ADMIN_EMAIL: string,
|
|
13
|
+
SUPER_ADMIN_PASSWORD: string,
|
|
14
|
+
JWT_REFRESH_SECRET: string,
|
|
15
|
+
JWT_REFRESH_EXPIRES: string,
|
|
16
|
+
GOOGLE_CLIENT_ID: string,
|
|
17
|
+
GOOGLE_CLIENT_SECRET: string,
|
|
18
|
+
GOOGLE_CALLBACK_URL: string,
|
|
19
|
+
EXPRESS_SESSION_SECRET: string,
|
|
20
|
+
FRONTEND_URL: string,
|
|
21
|
+
APP_DASHBOARD_URL: string,
|
|
22
|
+
STUDENT_PORTAL_URL: string,
|
|
23
|
+
SSL: {
|
|
24
|
+
SSL_STORE_ID: string,
|
|
25
|
+
SSL_STORE_PASS: string,
|
|
26
|
+
SSL_PAYMENT_API: string,
|
|
27
|
+
SSL_VALIDATION_API: string,
|
|
28
|
+
SSL_SUCCESS_FRONTEND_URL: string,
|
|
29
|
+
SSL_FAIL_FRONTEND_URL: string,
|
|
30
|
+
SSL_CANCEL_FRONTEND_URL: string,
|
|
31
|
+
SSL_SUCCESS_BACKEND_URL: string,
|
|
32
|
+
SSL_FAIL_BACKEND_URL: string,
|
|
33
|
+
SSL_CANCEL_BACKEND_URL: string,
|
|
34
|
+
SSL_IPN_URL: string,
|
|
35
|
+
},
|
|
36
|
+
CLOUDINARY: {
|
|
37
|
+
CLOUDINARY_CLOUD_NAME: string,
|
|
38
|
+
CLOUDINARY_API_KEY: string,
|
|
39
|
+
CLOUDINARY_API_SECRET: string
|
|
40
|
+
},
|
|
41
|
+
EMAIL_SENDER: {
|
|
42
|
+
SMTP_USER: string;
|
|
43
|
+
SMTP_PASS: string;
|
|
44
|
+
SMTP_PORT: string;
|
|
45
|
+
SMTP_HOST: string;
|
|
46
|
+
SMTP_FROM: string;
|
|
47
|
+
},
|
|
48
|
+
RESEND_API_KEY: string,
|
|
49
|
+
RESEND_FROM: string,
|
|
50
|
+
REDIS_HOST: string;
|
|
51
|
+
REDIS_PORT: string;
|
|
52
|
+
REDIS_USERNAME: string;
|
|
53
|
+
REDIS_PASSWORD: string;
|
|
54
|
+
R2: {
|
|
55
|
+
R2_ACCOUNT_ID: string,
|
|
56
|
+
R2_ACCESS_KEY_ID: string,
|
|
57
|
+
R2_SECRET_ACCESS_KEY: string,
|
|
58
|
+
R2_BUCKET_NAME: string,
|
|
59
|
+
R2_PUBLIC_URL: string,
|
|
60
|
+
},
|
|
61
|
+
MIMSMS: {
|
|
62
|
+
USERNAME: string,
|
|
63
|
+
API_KEY: string,
|
|
64
|
+
SENDER: string,
|
|
65
|
+
},
|
|
66
|
+
TELEGRAM?: {
|
|
67
|
+
BOT_TOKEN?: string,
|
|
68
|
+
CHAT_ID?: string,
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const loadEnvVaribales = (): EnvConfig => {
|
|
73
|
+
const requiredEnvVariables: string[] = ["PORT", "DB_URL", "NODE_ENV", "BCRYPT_SALT_ROUND", "JWT_ACCESS_EXPIRES",
|
|
74
|
+
"JWT_ACCESS_SECRET", "SUPER_ADMIN_EMAIL", "SUPER_ADMIN_PASSWORD", "JWT_REFRESH_SECRET",
|
|
75
|
+
"JWT_REFRESH_EXPIRES", "GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET", "GOOGLE_CALLBACK_URL",
|
|
76
|
+
"EXPRESS_SESSION_SECRET", "FRONTEND_URL", "SSL_STORE_ID", "SSL_STORE_PASS", "SSL_PAYMENT_API",
|
|
77
|
+
"SSL_VALIDATION_API",
|
|
78
|
+
"SSL_SUCCESS_FRONTEND_URL",
|
|
79
|
+
"SSL_FAIL_FRONTEND_URL",
|
|
80
|
+
"SSL_CANCEL_FRONTEND_URL",
|
|
81
|
+
"SSL_SUCCESS_BACKEND_URL",
|
|
82
|
+
"SSL_FAIL_BACKEND_URL",
|
|
83
|
+
"SSL_CANCEL_BACKEND_URL",
|
|
84
|
+
"CLOUDINARY_CLOUD_NAME",
|
|
85
|
+
"CLOUDINARY_API_KEY",
|
|
86
|
+
"CLOUDINARY_API_SECRET",
|
|
87
|
+
"SMTP_PORT",
|
|
88
|
+
"SMTP_HOST",
|
|
89
|
+
"SMTP_USER",
|
|
90
|
+
"SMTP_PASS",
|
|
91
|
+
"SMTP_FROM",
|
|
92
|
+
"RESEND_API_KEY",
|
|
93
|
+
"RESEND_FROM",
|
|
94
|
+
"REDIS_HOST",
|
|
95
|
+
"REDIS_PORT",
|
|
96
|
+
"REDIS_USERNAME",
|
|
97
|
+
"REDIS_PASSWORD",
|
|
98
|
+
"SSL_IPN_URL",
|
|
99
|
+
"R2_ACCOUNT_ID",
|
|
100
|
+
"R2_ACCESS_KEY_ID",
|
|
101
|
+
"R2_SECRET_ACCESS_KEY",
|
|
102
|
+
"R2_BUCKET_NAME",
|
|
103
|
+
"R2_PUBLIC_URL",
|
|
104
|
+
"APP_DASHBOARD_URL",
|
|
105
|
+
"STUDENT_PORTAL_URL",
|
|
106
|
+
"MIMSMS_USERNAME",
|
|
107
|
+
"MIMSMS_APIKEY",
|
|
108
|
+
"MIMSMS_SENDER"
|
|
109
|
+
]
|
|
110
|
+
|
|
111
|
+
requiredEnvVariables.forEach(key => {
|
|
112
|
+
if (!process.env[key]) {
|
|
113
|
+
throw new Error(`Missing require environment variable ${key}`)
|
|
114
|
+
}
|
|
115
|
+
})
|
|
116
|
+
const env: EnvConfig = {
|
|
117
|
+
PORT: process.env.PORT as string,
|
|
118
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
119
|
+
DB_URL: process.env.DB_URL!,
|
|
120
|
+
NODE_ENV: process.env.NODE_ENV as "development" | "production",
|
|
121
|
+
JWT_ACCESS_SECRET: process.env.JWT_ACCESS_SECRET as string,
|
|
122
|
+
JWT_ACCESS_EXPIRES: process.env.JWT_ACCESS_EXPIRES as string,
|
|
123
|
+
JWT_REFRESH_SECRET: process.env.JWT_REFRESH_SECRET as string,
|
|
124
|
+
JWT_REFRESH_EXPIRES: process.env.JWT_REFRESH_EXPIRES as string,
|
|
125
|
+
BCRYPT_SALT_ROUND: process.env.BCRYPT_SALT_ROUND as string,
|
|
126
|
+
SUPER_ADMIN_EMAIL: process.env.SUPER_ADMIN_EMAIL as string,
|
|
127
|
+
SUPER_ADMIN_PASSWORD: process.env.SUPER_ADMIN_PASSWORD as string,
|
|
128
|
+
GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID as string,
|
|
129
|
+
GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET as string,
|
|
130
|
+
GOOGLE_CALLBACK_URL: process.env.GOOGLE_CALLBACK_URL as string,
|
|
131
|
+
EXPRESS_SESSION_SECRET: process.env.EXPRESS_SESSION_SECRET as string,
|
|
132
|
+
FRONTEND_URL: process.env.FRONTEND_URL as string,
|
|
133
|
+
APP_DASHBOARD_URL: process.env.APP_DASHBOARD_URL as string,
|
|
134
|
+
STUDENT_PORTAL_URL: process.env.STUDENT_PORTAL_URL as string,
|
|
135
|
+
SSL: {
|
|
136
|
+
SSL_STORE_ID: process.env.SSL_STORE_ID as string,
|
|
137
|
+
SSL_STORE_PASS: process.env.SSL_STORE_PASS as string,
|
|
138
|
+
SSL_PAYMENT_API: process.env.SSL_PAYMENT_API as string,
|
|
139
|
+
SSL_VALIDATION_API: process.env.SSL_VALIDATION_API as string,
|
|
140
|
+
SSL_SUCCESS_FRONTEND_URL: process.env.SSL_SUCCESS_FRONTEND_URL as string,
|
|
141
|
+
SSL_FAIL_FRONTEND_URL: process.env.SSL_FAIL_FRONTEND_URL as string,
|
|
142
|
+
SSL_CANCEL_FRONTEND_URL: process.env.SSL_CANCEL_FRONTEND_URL as string,
|
|
143
|
+
SSL_SUCCESS_BACKEND_URL: process.env.SSL_SUCCESS_BACKEND_URL as string,
|
|
144
|
+
SSL_FAIL_BACKEND_URL: process.env.SSL_FAIL_BACKEND_URL as string,
|
|
145
|
+
SSL_CANCEL_BACKEND_URL: process.env.SSL_CANCEL_BACKEND_URL as string,
|
|
146
|
+
SSL_IPN_URL: process.env.SSL_IPN_URL as string
|
|
147
|
+
},
|
|
148
|
+
CLOUDINARY: {
|
|
149
|
+
CLOUDINARY_CLOUD_NAME: process.env.CLOUDINARY_CLOUD_NAME as string,
|
|
150
|
+
CLOUDINARY_API_KEY: process.env.CLOUDINARY_API_KEY as string,
|
|
151
|
+
CLOUDINARY_API_SECRET: process.env.CLOUDINARY_API_SECRET as string
|
|
152
|
+
},
|
|
153
|
+
EMAIL_SENDER: {
|
|
154
|
+
SMTP_USER: process.env.SMTP_USER as string,
|
|
155
|
+
SMTP_PASS: process.env.SMTP_PASS as string,
|
|
156
|
+
SMTP_PORT: process.env.SMTP_PORT as string,
|
|
157
|
+
SMTP_HOST: process.env.SMTP_HOST as string,
|
|
158
|
+
SMTP_FROM: process.env.SMTP_FROM as string,
|
|
159
|
+
},
|
|
160
|
+
RESEND_API_KEY: process.env.RESEND_API_KEY as string,
|
|
161
|
+
RESEND_FROM: process.env.RESEND_FROM as string,
|
|
162
|
+
REDIS_HOST: process.env.REDIS_HOST as string,
|
|
163
|
+
REDIS_PORT: process.env.REDIS_PORT as string,
|
|
164
|
+
REDIS_USERNAME: process.env.REDIS_USERNAME as string,
|
|
165
|
+
REDIS_PASSWORD: process.env.REDIS_PASSWORD as string,
|
|
166
|
+
R2: {
|
|
167
|
+
R2_ACCOUNT_ID: process.env.R2_ACCOUNT_ID as string,
|
|
168
|
+
R2_ACCESS_KEY_ID: process.env.R2_ACCESS_KEY_ID as string,
|
|
169
|
+
R2_SECRET_ACCESS_KEY: process.env.R2_SECRET_ACCESS_KEY as string,
|
|
170
|
+
R2_BUCKET_NAME: process.env.R2_BUCKET_NAME as string,
|
|
171
|
+
R2_PUBLIC_URL: process.env.R2_PUBLIC_URL as string
|
|
172
|
+
},
|
|
173
|
+
MIMSMS: {
|
|
174
|
+
USERNAME: process.env.MIMSMS_USERNAME as string,
|
|
175
|
+
API_KEY: process.env.MIMSMS_APIKEY as string,
|
|
176
|
+
SENDER: process.env.MIMSMS_SENDER as string,
|
|
177
|
+
},
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (process.env.TELEGRAM_BOT_TOKEN && process.env.TELEGRAM_CHAT_ID) {
|
|
181
|
+
env.TELEGRAM = {
|
|
182
|
+
BOT_TOKEN: process.env.TELEGRAM_BOT_TOKEN as string,
|
|
183
|
+
CHAT_ID: process.env.TELEGRAM_CHAT_ID as string,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return env;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export const envVars = loadEnvVaribales()
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
import passport from "passport";
|
|
3
|
+
import { Strategy as GoogleStrategy, Profile, VerifyCallback } from "passport-google-oauth20";
|
|
4
|
+
import { envVars } from "./env";
|
|
5
|
+
import { Strategy as LocalStrategy } from "passport-local";
|
|
6
|
+
import bcryptjs from "bcryptjs"
|
|
7
|
+
import { User } from "../modules/user/user.model";
|
|
8
|
+
import { IsActive, Role } from "../modules/user/user.interface";
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
passport.use(
|
|
13
|
+
new LocalStrategy({
|
|
14
|
+
usernameField: "email",
|
|
15
|
+
passwordField: "password"
|
|
16
|
+
}, async (email: string, password: string, done) => {
|
|
17
|
+
try {
|
|
18
|
+
const isUserExist = await User.findOne({ email })
|
|
19
|
+
|
|
20
|
+
if (!isUserExist) {
|
|
21
|
+
return done(null, false, { message: "User does not exist" })
|
|
22
|
+
}
|
|
23
|
+
if (!isUserExist.isVerified) {
|
|
24
|
+
return done("User is not verified")
|
|
25
|
+
}
|
|
26
|
+
if (isUserExist.isActive === IsActive.BLOCKED || isUserExist.isActive === IsActive.INACTIVE) {
|
|
27
|
+
return done(`User is ${isUserExist.isActive}`)
|
|
28
|
+
}
|
|
29
|
+
if (isUserExist.isDeleted) {
|
|
30
|
+
return done("User is deleted")
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
const isGoogleAuthenticated = isUserExist.auths.some(providerObjects => providerObjects.provider === "google")
|
|
35
|
+
if (isGoogleAuthenticated && !isUserExist.password) {
|
|
36
|
+
return done(null, false, { message: "You have authenticated through Google. So if you want to login with credentials, then at first login with Google and set a password for your Gmail and then you can login with email and password." })
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
const isPasswordMatched = await bcryptjs.compare(password as string, isUserExist.password as string)
|
|
41
|
+
if (!isPasswordMatched) {
|
|
42
|
+
return done(null, false, { message: "Password does not match" })
|
|
43
|
+
}
|
|
44
|
+
return done(null, isUserExist)
|
|
45
|
+
|
|
46
|
+
} catch (error) {
|
|
47
|
+
done(error)
|
|
48
|
+
}
|
|
49
|
+
})
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
passport.use(
|
|
53
|
+
new GoogleStrategy(
|
|
54
|
+
{
|
|
55
|
+
clientID: envVars.GOOGLE_CLIENT_ID,
|
|
56
|
+
clientSecret: envVars.GOOGLE_CLIENT_SECRET,
|
|
57
|
+
callbackURL: envVars.GOOGLE_CALLBACK_URL
|
|
58
|
+
}, async (_accessToken: string, _refreshToken: string, profile: Profile, done: VerifyCallback) => {
|
|
59
|
+
try {
|
|
60
|
+
const email = profile.emails?.[0]?.value
|
|
61
|
+
if (!email) {
|
|
62
|
+
return done(null, false, { message: "No email found" })
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let isUserExist = await User.findOne({ email })
|
|
66
|
+
if (isUserExist && !isUserExist.isVerified) {
|
|
67
|
+
return done(null, false, { message: "User is not verified" })
|
|
68
|
+
}
|
|
69
|
+
if (isUserExist && (isUserExist.isActive === IsActive.BLOCKED || isUserExist.isActive === IsActive.INACTIVE)) {
|
|
70
|
+
return done(`User is ${isUserExist.isActive}`)
|
|
71
|
+
}
|
|
72
|
+
if (isUserExist && isUserExist.isDeleted) {
|
|
73
|
+
return done(null, false, { message: "User is deleted" })
|
|
74
|
+
}
|
|
75
|
+
if (!isUserExist) {
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
isUserExist = await User.create({
|
|
82
|
+
email,
|
|
83
|
+
name: profile.displayName,
|
|
84
|
+
role: Role.USER,
|
|
85
|
+
isVerified: true,
|
|
86
|
+
auths: [
|
|
87
|
+
{
|
|
88
|
+
provider: "google",
|
|
89
|
+
providerId: profile.id
|
|
90
|
+
}
|
|
91
|
+
]
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
return done(null, isUserExist)
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return done(error)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
passport.serializeUser((user: any, done: (err: any, id?: unknown) => void) =>
|
|
103
|
+
done(null, user._id))
|
|
104
|
+
|
|
105
|
+
passport.deserializeUser(async (id: string, done: any) => {
|
|
106
|
+
try {
|
|
107
|
+
const user = await User.findById(id)
|
|
108
|
+
done(null, user)
|
|
109
|
+
} catch (error) {
|
|
110
|
+
done(error)
|
|
111
|
+
}
|
|
112
|
+
})
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// src/config/r2.config.ts
|
|
2
|
+
|
|
3
|
+
import { S3Client } from '@aws-sdk/client-s3';
|
|
4
|
+
import { envVars } from './env';
|
|
5
|
+
|
|
6
|
+
const r2Client = new S3Client({
|
|
7
|
+
region: 'auto',
|
|
8
|
+
endpoint: `https://${envVars.R2.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
|
|
9
|
+
credentials: {
|
|
10
|
+
accessKeyId: envVars.R2.R2_ACCESS_KEY_ID,
|
|
11
|
+
secretAccessKey: envVars.R2.R2_SECRET_ACCESS_KEY,
|
|
12
|
+
},
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export default r2Client;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { createClient } from 'redis';
|
|
2
|
+
import { envVars } from './env';
|
|
3
|
+
|
|
4
|
+
export const redisClient = createClient({
|
|
5
|
+
username: envVars.REDIS_USERNAME,
|
|
6
|
+
password: envVars.REDIS_PASSWORD,
|
|
7
|
+
socket: {
|
|
8
|
+
host: envVars.REDIS_HOST,
|
|
9
|
+
port: Number(envVars.REDIS_PORT),
|
|
10
|
+
}
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
redisClient.on('error', err => console.log('Redis Client Error', err));
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
export const connectRedis = async () => {
|
|
17
|
+
if (!redisClient.isOpen) {
|
|
18
|
+
await redisClient.connect();
|
|
19
|
+
console.log("Redis connected")
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
class AppError extends Error {
|
|
2
|
+
public statusCode: number;
|
|
3
|
+
|
|
4
|
+
constructor(statusCode: number, message: string, stack = "") {
|
|
5
|
+
super(message)
|
|
6
|
+
this.statusCode = statusCode
|
|
7
|
+
|
|
8
|
+
if (stack) {
|
|
9
|
+
this.stack = stack
|
|
10
|
+
} else {
|
|
11
|
+
Error.captureStackTrace(this, this.constructor)
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export default AppError;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
2
|
+
import mongoose from "mongoose"
|
|
3
|
+
import { IGenericErrorResponse } from "../interfaces/error.Types"
|
|
4
|
+
|
|
5
|
+
export const handleCastError = (err: mongoose.Error.CastError): IGenericErrorResponse => {
|
|
6
|
+
return {
|
|
7
|
+
statusCode: 400,
|
|
8
|
+
message: "Invalid Mongodb ObjectID. Please provide a valid Id"
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
|
|
3
|
+
import { IGenericErrorResponse } from "../interfaces/error.Types"
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
export const handleDuplicateError = (err: any): IGenericErrorResponse => {
|
|
7
|
+
const matchedArray = err.message.match(/"([^"]*)"/)
|
|
8
|
+
return {
|
|
9
|
+
statusCode: 400,
|
|
10
|
+
message: `${matchedArray[1]} already exists!!`
|
|
11
|
+
}
|
|
12
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
import mongoose from "mongoose"
|
|
3
|
+
import { IErrorSources, IGenericErrorResponse } from "../interfaces/error.Types"
|
|
4
|
+
|
|
5
|
+
export const handleValidationError = (err: mongoose.Error.ValidationError): IGenericErrorResponse => {
|
|
6
|
+
const errorSources: IErrorSources[] = []
|
|
7
|
+
|
|
8
|
+
const errors = Object.values(err.errors)
|
|
9
|
+
errors.forEach((errorObject: any) => errorSources.push({
|
|
10
|
+
path: errorObject.path,
|
|
11
|
+
message: errorObject.message
|
|
12
|
+
}))
|
|
13
|
+
return {
|
|
14
|
+
statusCode: 400,
|
|
15
|
+
message: "Validation Error",
|
|
16
|
+
errorSources
|
|
17
|
+
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
import { IErrorSources, IGenericErrorResponse } from "../interfaces/error.Types"
|
|
3
|
+
|
|
4
|
+
export const handleZodError = (err: any): IGenericErrorResponse => {
|
|
5
|
+
const issues = err.issues || err.errors || []
|
|
6
|
+
|
|
7
|
+
const errorSources: IErrorSources[] = issues.map((issue: any) => {
|
|
8
|
+
const path = issue.path?.length ? issue.path.join(".") : "unknown"
|
|
9
|
+
|
|
10
|
+
return {
|
|
11
|
+
path,
|
|
12
|
+
message: issue.message
|
|
13
|
+
}
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
const message =
|
|
17
|
+
errorSources.length > 0
|
|
18
|
+
? errorSources.map((source) => source.message).join("; ")
|
|
19
|
+
: "Validation failed"
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
statusCode: 400,
|
|
23
|
+
message,
|
|
24
|
+
errorSources
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { JwtPayload } from "jsonwebtoken";
|
|
2
|
+
import { NextFunction, Request, Response } from "express";
|
|
3
|
+
import AppError from "../errorHelpers/AppError";
|
|
4
|
+
import { envVars } from "../config/env";
|
|
5
|
+
import { User } from "../modules/user/user.model";
|
|
6
|
+
import httpStatus from "http-status-codes";
|
|
7
|
+
import { IsActive } from "../modules/user/user.interface";
|
|
8
|
+
import { verifyToken } from "../modules/auth/jwt";
|
|
9
|
+
|
|
10
|
+
export const checkAuth =
|
|
11
|
+
(...authRoles: string[]) =>
|
|
12
|
+
async (req: Request, res: Response, next: NextFunction) => {
|
|
13
|
+
try {
|
|
14
|
+
const accessToken = req.headers.authorization || req.cookies.accessToken;
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
if (!accessToken) {
|
|
18
|
+
throw new AppError(httpStatus.FORBIDDEN, "No token received");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const verifiedToken = verifyToken(
|
|
22
|
+
accessToken,
|
|
23
|
+
envVars.JWT_ACCESS_SECRET
|
|
24
|
+
) as JwtPayload;
|
|
25
|
+
|
|
26
|
+
const user = await User.findOne({ email: verifiedToken.email });
|
|
27
|
+
|
|
28
|
+
if (!user) {
|
|
29
|
+
throw new AppError(httpStatus.NOT_FOUND, "User does not exist");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (
|
|
33
|
+
user.isActive === IsActive.BLOCKED ||
|
|
34
|
+
user.isActive === IsActive.INACTIVE
|
|
35
|
+
) {
|
|
36
|
+
throw new AppError(
|
|
37
|
+
httpStatus.FORBIDDEN,
|
|
38
|
+
`User is ${user.isActive.toLowerCase()}`
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (!authRoles.includes(verifiedToken.role)) {
|
|
43
|
+
throw new AppError(
|
|
44
|
+
httpStatus.FORBIDDEN,
|
|
45
|
+
"You are not permitted to view this route!"
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
req.user = verifiedToken;
|
|
50
|
+
next();
|
|
51
|
+
} catch (error) {
|
|
52
|
+
next(error);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
2
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
3
|
+
import { NextFunction, Request, Response } from "express"
|
|
4
|
+
|
|
5
|
+
import AppError from "../errorHelpers/AppError"
|
|
6
|
+
import { IErrorSources } from "../interfaces/error.Types"
|
|
7
|
+
import { handleDuplicateError } from "../helpers/handleDuplicateError"
|
|
8
|
+
import { handleCastError } from "../helpers/handleCastError"
|
|
9
|
+
import { handleZodError } from "../helpers/handleZodError"
|
|
10
|
+
import { handleValidationError } from "../helpers/handleValidationError"
|
|
11
|
+
import { envVars } from "../config/env"
|
|
12
|
+
import { errorLogger } from "../utils/logger"
|
|
13
|
+
// import { deleteImageFromCloudinary } from "../config/cloudinary.config"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
export const globalErrorHandler = async (err: any, req: Request, res: Response, next: NextFunction) => {
|
|
19
|
+
|
|
20
|
+
// if (req.file) {
|
|
21
|
+
// await deleteImageFromCloudinary(req.file.path)
|
|
22
|
+
// }
|
|
23
|
+
|
|
24
|
+
// if (req.files && Array.isArray(req.files) && req.files.length) {
|
|
25
|
+
// const imageUrls = (req.files as Express.Multer.File[]).map(file => file.path)
|
|
26
|
+
|
|
27
|
+
// await Promise.all(imageUrls.map(url => deleteImageFromCloudinary(url)))
|
|
28
|
+
// }
|
|
29
|
+
|
|
30
|
+
let errorSources: IErrorSources[] = []
|
|
31
|
+
|
|
32
|
+
let statusCode = 500
|
|
33
|
+
let message = `Something went wrong!!`
|
|
34
|
+
|
|
35
|
+
if (err.code === 1100) {
|
|
36
|
+
const simplifiedError = handleDuplicateError(err)
|
|
37
|
+
statusCode = simplifiedError.statusCode;
|
|
38
|
+
message = simplifiedError.message
|
|
39
|
+
}
|
|
40
|
+
else if (err.name === "CastError") {
|
|
41
|
+
const simplifiedError = handleCastError(err)
|
|
42
|
+
statusCode = simplifiedError.statusCode;
|
|
43
|
+
message = simplifiedError.message
|
|
44
|
+
}
|
|
45
|
+
else if (err.name === "ZodError") {
|
|
46
|
+
const simplifiedError = handleZodError(err)
|
|
47
|
+
statusCode = simplifiedError.statusCode;
|
|
48
|
+
message = simplifiedError.message
|
|
49
|
+
errorSources = simplifiedError.errorSources as IErrorSources[]
|
|
50
|
+
}
|
|
51
|
+
else if (err.name === "ValidationError") {
|
|
52
|
+
const simplifiedError = handleValidationError(err)
|
|
53
|
+
statusCode = simplifiedError.statusCode;
|
|
54
|
+
errorSources = simplifiedError.errorSources as IErrorSources[]
|
|
55
|
+
message = simplifiedError.message
|
|
56
|
+
}
|
|
57
|
+
else if (err instanceof AppError) {
|
|
58
|
+
statusCode = err.statusCode
|
|
59
|
+
message = err.message
|
|
60
|
+
} else if (err instanceof Error) {
|
|
61
|
+
statusCode = 500
|
|
62
|
+
message = err.message
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
errorLogger("Unhandled application error", err, {
|
|
66
|
+
method: req.method,
|
|
67
|
+
path: req.originalUrl,
|
|
68
|
+
statusCode,
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
res.status(statusCode).json({
|
|
72
|
+
success: false,
|
|
73
|
+
message,
|
|
74
|
+
errorSources,
|
|
75
|
+
err: envVars.NODE_ENV === "development" ? err : null,
|
|
76
|
+
stack: envVars.NODE_ENV === "development" ? err.stack : null,
|
|
77
|
+
})
|
|
78
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Request, Response } from "express"
|
|
2
|
+
import httpStatus from "http-status-codes"
|
|
3
|
+
import { requestLogger } from "../utils/logger"
|
|
4
|
+
|
|
5
|
+
const notFound = (req: Request, res: Response) => {
|
|
6
|
+
requestLogger("Route not found", {
|
|
7
|
+
method: req.method,
|
|
8
|
+
path: req.originalUrl,
|
|
9
|
+
ip: req.ip,
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
res.status(httpStatus.NOT_FOUND).json({
|
|
13
|
+
success: false,
|
|
14
|
+
message: "Route not found"
|
|
15
|
+
})
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export default notFound
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { NextFunction, Request, Response } from "express";
|
|
2
|
+
import { requestLogger } from "../utils/logger";
|
|
3
|
+
|
|
4
|
+
export const logHttpRequests = (req: Request, res: Response, next: NextFunction) => {
|
|
5
|
+
const startedAt = Date.now();
|
|
6
|
+
|
|
7
|
+
res.on("finish", () => {
|
|
8
|
+
const durationMs = Date.now() - startedAt;
|
|
9
|
+
requestLogger("HTTP request", {
|
|
10
|
+
method: req.method,
|
|
11
|
+
path: req.originalUrl,
|
|
12
|
+
statusCode: res.statusCode,
|
|
13
|
+
durationMs,
|
|
14
|
+
ip: req.ip,
|
|
15
|
+
userAgent: req.get("user-agent"),
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
next();
|
|
20
|
+
};
|