Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
chore: Added the try..catch block in all services.
  • Loading branch information
hanoak20 committed Feb 17, 2024
commit a6d7263c1e86c01af32b777d67995396e6d2cfcc
2 changes: 2 additions & 0 deletions src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ export const HTTP_CODES = {
};
export const HTTP_TEXTS = {
UNAUTHORIZED: "You're unauthorized to access this resource.",
S3_ERROR: "Something went wrong while handing the file",
INTERNAL_ERROR: "Internal server error, please try again later.",
SOMETHING_WENT_WRONG:
"Something went wrong while processing your request, please try again.",
CS_ERROR: "Contentstack API error",
NO_CS_USER: "No user found with the credentials",
SUCCESS_LOGIN: "Login Successful.",
TOKEN_ERROR: "Error occurred during token generation.",
Expand Down
5 changes: 2 additions & 3 deletions src/controllers/user.controller.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Request, Response } from "express";
import { userService } from "../services/user.service";
import { HTTP_CODES } from "../constants";

const getUserProfile = async (req: Request, res: Response) => {
const user = await userService.getUserProfile(req);
res.status(HTTP_CODES.OK).json(user);
const resp = await userService.getUserProfile(req);
res.status(resp?.status).json(resp?.data);
};

export const userController = {
Expand Down
9 changes: 0 additions & 9 deletions src/models/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,6 @@ export interface User {
password: string;
}

export interface UserProfile {
user: {
email: string;
first_name: string;
last_name: string;
orgs: [{ org_id: string; org_name: string }];
};
}

export interface AppTokenPayload {
region: string;
user_id: string;
Expand Down
147 changes: 86 additions & 61 deletions src/services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,84 +1,102 @@
import { Request } from "express";
import { config } from "../config";
import { safePromise } from "../utils/index";
import { safePromise, getLogMessage } from "../utils";
import https from "../utils/https.utils";
import { LoginServiceType, AppTokenPayload } from "../models/types";
import { HTTP_CODES, HTTP_TEXTS } from "../constants";
import { generateToken } from "../utils/jwt.utils";
import {
BadRequestError,
InternalServerError,
ExceptionFunction,
} from "../utils/custom-errors.utils";
import AuthenticationModel from "../models/authentication";
import logger from "../utils/logger";

const login = async (req: Request): Promise<LoginServiceType> => {
const userData = req?.body;

const [err, res] = await safePromise(
https({
method: "POST",
url: `${config.CS_API[
userData?.region as keyof typeof config.CS_API
]!}/user-session`,
headers: {
"Content-Type": "application/json",
},
data: {
user: {
email: userData?.email,
password: userData?.password,
...(userData?.tfa_token && { tfa_token: userData?.tfa_token }),
const srcFun = "Login";

try {
const userData = req?.body;

const [err, res] = await safePromise(
https({
method: "POST",
url: `${config.CS_API[
userData?.region as keyof typeof config.CS_API
]!}/user-session`,
headers: {
"Content-Type": "application/json",
},
},
})
);
data: {
user: {
email: userData?.email,
password: userData?.password,
...(userData?.tfa_token && { tfa_token: userData?.tfa_token }),
},
},
})
);

if (err)
return {
data: err?.response?.data,
status: err?.response?.status,
if (err) {
logger.error(
getLogMessage(srcFun, HTTP_TEXTS.CS_ERROR, {}, err?.response?.data)
);

return {
data: err?.response?.data,
status: err?.response?.status,
};
}

if (res?.status === HTTP_CODES.SUPPORT_DOC)
return {
data: res?.data,
status: res?.status,
};

if (!res?.data?.user) throw new BadRequestError(HTTP_TEXTS.NO_CS_USER);

const appTokenPayload: AppTokenPayload = {
region: userData?.region,
user_id: res?.data?.user.uid,
};

if (res?.status === HTTP_CODES.SUPPORT_DOC)
// Saving auth info in the DB
await AuthenticationModel.findOneAndUpdate(
appTokenPayload,
{
authtoken: res?.data.user?.authtoken,
},
{
upsert: true,
}
);

// JWT token generation
const app_token = generateToken(appTokenPayload);

return {
data: res?.data,
status: res?.status,
data: {
message: HTTP_TEXTS.SUCCESS_LOGIN,
app_token,
},
status: HTTP_CODES.OK,
};

if (!res?.data?.user) throw new BadRequestError(HTTP_TEXTS.NO_CS_USER);

const appTokenPayload: AppTokenPayload = {
region: userData?.region,
user_id: res?.data?.user.uid,
};

// Saving auth info in the DB
await AuthenticationModel.findOneAndUpdate(
appTokenPayload,
{
authtoken: res?.data.user?.authtoken,
},
{
upsert: true,
}
);

// JWT token generation
const app_token = generateToken(appTokenPayload);

return {
data: {
message: HTTP_TEXTS.SUCCESS_LOGIN,
app_token,
},
status: HTTP_CODES.OK,
};
} catch (error: any) {
logger.error(getLogMessage(srcFun, "Error while logging in", {}, error));
throw new ExceptionFunction(
error?.message || HTTP_TEXTS.INTERNAL_ERROR,
error?.status || HTTP_CODES.SERVER_ERROR
);
}
};

const requestSms = async (req: Request): Promise<LoginServiceType> => {
const userData = req?.body;
const srcFun = "requestSms";

try {
const userData = req?.body;
const [err, res] = await safePromise(
https({
method: "POST",
Expand All @@ -94,17 +112,24 @@ const requestSms = async (req: Request): Promise<LoginServiceType> => {
})
);

if (err)
if (err) {
logger.error(
getLogMessage(srcFun, HTTP_TEXTS.CS_ERROR, {}, err?.response?.data)
);

return {
data: err.response.data,
status: err.response.status,
data: err?.response?.data,
status: err?.response?.status,
};
}

return {
data: res.data,
status: res.status,
};
} catch (error) {
} catch (error: any) {
logger.error(getLogMessage(srcFun, "Error while in requestSms", {}, error));

throw new InternalServerError(HTTP_TEXTS.INTERNAL_ERROR);
}
};
Expand Down
Loading