Skip to content

Commit b4836bc

Browse files
committed
core modules are separated
1 parent 646d7a7 commit b4836bc

File tree

13 files changed

+113
-101
lines changed

13 files changed

+113
-101
lines changed

src/middlewares/can-access.middleware.ts

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { NextFunction, Request, Response } from 'express';
22
import { StatusCodes } from 'http-status-codes';
33
import { RoleType } from '../enums';
4-
import { getUserById } from '../user/user.services';
4+
import { getUserById } from '../modules/user/user.services';
55
import { errorResponse } from '../utils/api.utils';
66
import { JwtPayload } from '../utils/auth.utils';
77

@@ -29,7 +29,7 @@ export const canAccess =
2929
StatusCodes.UNAUTHORIZED,
3030
);
3131
}
32-
const currentUser = await getUserById({ id: requestUser.sub });
32+
const currentUser = await getUserById(requestUser.sub);
3333

3434
if (!currentUser) {
3535
return errorResponse(res, 'Login again', StatusCodes.UNAUTHORIZED);
@@ -43,14 +43,6 @@ export const canAccess =
4343
);
4444
}
4545

46-
if (!currentUser.isActive) {
47-
return errorResponse(
48-
res,
49-
'Your account has been disabled',
50-
StatusCodes.UNAUTHORIZED,
51-
);
52-
}
53-
5446
let can = false;
5547

5648
const accessorsToScanFor = access;
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { CookieOptions } from 'express';
2-
import config from '../config/config.service';
2+
import config from '../../config/config.service';
33

44
const clientSideUrl = new URL(config.CLIENT_SIDE_URL);
55

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { Request, Response } from 'express';
2-
import config from '../config/config.service';
3-
import { GoogleCallbackQuery } from '../types';
4-
import { successResponse } from '../utils/api.utils';
5-
import { JwtPayload } from '../utils/auth.utils';
2+
import config from '../../config/config.service';
3+
import { GoogleCallbackQuery } from '../../types';
4+
import { successResponse } from '../../utils/api.utils';
5+
import { JwtPayload } from '../../utils/auth.utils';
66
import { AUTH_COOKIE_KEY, COOKIE_CONFIG } from './auth.constants';
77
import {
88
ChangePasswordSchemaType,
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { canAccess } from '../middlewares/can-access.middleware';
2-
import MagicRouter from '../openapi/magic-router';
1+
import { canAccess } from '../../middlewares/can-access.middleware';
2+
import MagicRouter from '../../openapi/magic-router';
33
import {
44
handleChangePassword,
55
handleForgetPassword,
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import z from 'zod';
22
import validator from 'validator';
3-
import { passwordValidationSchema } from '../common/common.schema';
3+
import { passwordValidationSchema } from '../../common/common.schema';
44
import { baseCreateUser } from '../user/user.schema';
55

66
export const resetPasswordSchema = z.object({
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,21 @@
1-
import { ROLE_ENUM, RoleType, SOCIAL_ACCOUNT_ENUM } from '../enums';
2-
import { GoogleCallbackQuery } from '../types';
3-
import { UserType } from '../user/user.dto';
4-
import User from '../user/user.model';
5-
import { createUser } from '../user/user.services';
1+
import { ROLE_ENUM, RoleType, SOCIAL_ACCOUNT_ENUM } from '../../enums';
2+
import { GoogleCallbackQuery } from '../../types';
63
import {
74
compareHash,
85
fetchGoogleTokens,
96
getUserInfo,
107
hashPassword,
118
JwtPayload,
129
signToken,
13-
} from '../utils/auth.utils';
14-
import { generateRandomNumbers } from '../utils/common.utils';
10+
} from '../../utils/auth.utils';
11+
import { generateRandomNumbers } from '../../utils/common.utils';
12+
import { UserType } from '../user/user.dto';
13+
import {
14+
createUser,
15+
getUserByEmail,
16+
getUserById,
17+
updateUser,
18+
} from '../user/user.services';
1519
import {
1620
ChangePasswordSchemaType,
1721
ForgetPasswordSchemaType,
@@ -21,11 +25,9 @@ import {
2125
} from './auth.schema';
2226

2327
export const resetPassword = async (payload: ResetPasswordSchemaType) => {
24-
const user = User.findOne({
25-
_id: payload.userId,
26-
passwordResetCode: payload.code,
27-
});
28-
if (!user) {
28+
const user = await getUserById(payload.userId);
29+
30+
if (!user || user.passwordResetCode !== payload.code) {
2931
throw new Error('token is not valid or expired, please try again');
3032
}
3133

@@ -35,51 +37,33 @@ export const resetPassword = async (payload: ResetPasswordSchemaType) => {
3537

3638
const hashedPassword = await hashPassword(payload.password);
3739

38-
await User.updateOne(
39-
{
40-
_id: payload.userId,
41-
},
42-
{
43-
$set: {
44-
password: hashedPassword,
45-
passwordResetCode: null,
46-
},
47-
},
48-
);
40+
await updateUser(payload.userId, {
41+
password: hashedPassword,
42+
passwordResetCode: null,
43+
});
4944
};
5045

5146
export const forgetPassword = async (
5247
payload: ForgetPasswordSchemaType,
5348
): Promise<UserType> => {
54-
const user = await User.findOne({
55-
phoneNo: payload.email,
56-
});
49+
const user = await getUserByEmail(payload.email);
5750

5851
if (!user) {
5952
throw new Error("user doesn't exists");
6053
}
6154

6255
const code = generateRandomNumbers(4);
6356

64-
await User.updateOne(
65-
{
66-
_id: user._id,
67-
},
68-
{
69-
$set: { passwordResetCode: code },
70-
},
71-
);
57+
await updateUser(user._id, { passwordResetCode: code });
7258

73-
return user.toObject();
59+
return user;
7460
};
7561

7662
export const changePassword = async (
7763
userId: string,
7864
payload: ChangePasswordSchemaType,
7965
): Promise<void> => {
80-
const user = await User.findOne({
81-
_id: userId,
82-
}).select('+password');
66+
const user = await getUserById(userId, '+password');
8367

8468
if (!user || !user.password) {
8569
throw new Error('User is not found');
@@ -96,15 +80,13 @@ export const changePassword = async (
9680

9781
const hashedPassword = await hashPassword(payload.newPassword);
9882

99-
await User.updateOne({ _id: userId }, { $set: { password: hashedPassword } });
83+
await updateUser(userId, { password: hashedPassword });
10084
};
10185

10286
export const registerUserByEmail = async (
10387
payload: RegisterUserByEmailSchemaType,
10488
): Promise<UserType> => {
105-
const userExistByEmail = await User.findOne({
106-
email: payload.email,
107-
});
89+
const userExistByEmail = await getUserByEmail(payload.email);
10890

10991
if (userExistByEmail) {
11092
throw new Error('Account already exist with same email address');
@@ -120,7 +102,7 @@ export const registerUserByEmail = async (
120102
export const loginUserByEmail = async (
121103
payload: LoginUserByEmailSchemaType,
122104
): Promise<string> => {
123-
const user = await User.findOne({ email: payload.email }).select('+password');
105+
const user = await getUserByEmail(payload.email, '+password');
124106

125107
if (!user || !(await compareHash(String(user.password), payload.password))) {
126108
throw new Error('Invalid email or password');
@@ -143,6 +125,7 @@ export const googleLogin = async (
143125
payload: GoogleCallbackQuery,
144126
): Promise<UserType> => {
145127
const { code, error } = payload;
128+
146129
if (error) {
147130
throw new Error(error);
148131
}
@@ -157,9 +140,11 @@ export const googleLogin = async (
157140
const userInfoResponse = await getUserInfo(access_token);
158141

159142
const { id, email, name, picture } = userInfoResponse;
160-
const existingUser = await User.findOne({ email });
161-
if (!existingUser) {
162-
return await createUser({
143+
144+
const user = await getUserByEmail(email);
145+
146+
if (!user) {
147+
const newUser = await createUser({
163148
email,
164149
username: name,
165150
avatar: picture,
@@ -175,18 +160,21 @@ export const googleLogin = async (
175160
},
176161
],
177162
});
178-
} else {
179-
existingUser.socialAccount = [
163+
164+
return newUser;
165+
}
166+
167+
const updatedUser = await updateUser(user._id, {
168+
socialAccount: [
180169
{
181170
refreshToken: refresh_token,
182171
tokenExpiry: new Date(Date.now() + expires_in * 1000),
183172
accountType: SOCIAL_ACCOUNT_ENUM.GOOGLE,
184173
accessToken: access_token,
185174
accountID: id,
186175
},
187-
];
188-
await existingUser.save();
189-
}
176+
],
177+
});
190178

191-
return existingUser.toObject();
179+
return updatedUser;
192180
};
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { Request, Response } from 'express';
22
import { StatusCodes } from 'http-status-codes';
3-
import { MongoIdSchemaType } from '../common/common.schema';
4-
import { successResponse } from '../utils/api.utils';
5-
import { generateRandomPassword } from '../utils/auth.utils';
3+
import { MongoIdSchemaType } from '../../common/common.schema';
4+
import { successResponse } from '../../utils/api.utils';
5+
import { generateRandomPassword } from '../../utils/auth.utils';
66
import { CreateUserSchemaType, GetUsersSchemaType } from './user.schema';
77
import { createUser, deleteUser, getUsers } from './user.services';
88

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
11
import z from 'zod';
2-
import { definePaginatedResponse } from '../common/common.utils';
2+
import { definePaginatedResponse } from '../../common/common.utils';
33
import {
44
ROLE_ENUM,
55
RoleType,
66
SOCIAL_ACCOUNT_ENUM,
77
SocialAccountType,
8-
} from '../enums';
8+
} from '../../enums';
99

10-
const SocialAccountTypeZ = z.enum(
10+
export const SocialAccountTypeZ = z.enum(
1111
Object.keys(SOCIAL_ACCOUNT_ENUM) as [SocialAccountType],
1212
);
13-
const RoleTypeZ = z.enum(Object.keys(ROLE_ENUM) as [RoleType]);
1413

15-
const socialAccountInfoSchema = z.object({
14+
export const RoleTypeZ = z.enum(Object.keys(ROLE_ENUM) as [RoleType]);
15+
16+
export const socialAccountInfoSchema = z.object({
1617
accountType: SocialAccountTypeZ,
1718
accessToken: z.string(),
1819
tokenExpiry: z.date(),
1920
refreshToken: z.string().optional(),
2021
accountID: z.string(),
2122
});
2223

23-
const userOutSchema = z.object({
24-
_id: z.string().optional(),
24+
export const userOutSchema = z.object({
2525
email: z.string().email(),
2626
avatar: z.string().url().optional(),
2727
name: z.string().optional(),
@@ -33,14 +33,15 @@ const userOutSchema = z.object({
3333
createdAt: z.date().optional(),
3434
});
3535

36-
const userSchema = userOutSchema.extend({
36+
export const userSchema = userOutSchema.extend({
3737
otp: z.string().nullable().optional(),
3838
password: z.string(),
39-
passwordResetCode: z.string().optional(),
39+
passwordResetCode: z.string().optional().nullable(),
4040
});
4141

4242
export const usersPaginatedSchema = definePaginatedResponse(userOutSchema);
4343

44-
export type UserType = z.infer<typeof userSchema>;
44+
export type UserModelType = z.infer<typeof userSchema>;
45+
export type UserType = z.infer<typeof userSchema> & { id: string; _id: string };
4546
export type SocialAccountInfoType = z.infer<typeof socialAccountInfoSchema>;
4647
export type UserPaginatedType = z.infer<typeof usersPaginatedSchema>;
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import mongoose, { Document, Schema } from 'mongoose';
2-
import { ROLE_ENUM, SOCIAL_ACCOUNT_ENUM } from '../enums'; // Import rolesEnums
3-
import { SocialAccountInfoType, UserType } from './user.dto';
2+
import { ROLE_ENUM, SOCIAL_ACCOUNT_ENUM } from '../../enums'; // Import rolesEnums
3+
import { SocialAccountInfoType, UserModelType, UserType } from './user.dto';
44

55
const SocialAccountSchema = new Schema<SocialAccountInfoType>({
66
accountType: {
@@ -36,6 +36,6 @@ const UserSchema: Schema<UserType> = new Schema(
3636
export interface ISocialAccountDocument
3737
extends SocialAccountInfoType,
3838
Document {}
39-
export interface IUserDocument extends UserType, Document<string> {}
39+
export interface IUserDocument extends Document<string>, UserModelType {}
4040
const User = mongoose.model<UserType>('User', UserSchema);
4141
export default User;
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { canAccess } from '../middlewares/can-access.middleware';
2-
import MagicRouter from '../openapi/magic-router';
1+
import { canAccess } from '../../middlewares/can-access.middleware';
2+
import MagicRouter from '../../openapi/magic-router';
33
import {
44
handleCreateSuperAdmin,
55
handleCreateUser,

0 commit comments

Comments
 (0)