Spaces:
Sleeping

File size: 9,989 Bytes
4e83772
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a1ffec
 
 
 
 
4e83772
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a1ffec
 
 
 
 
4e83772
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import { NextFunction, Request, Response } from "express";
import { Profile, VerifyCallback } from "passport-google-oauth20";
import jwt from "jsonwebtoken";

import { ENVS } from "@/config/env.config.js";
import AppError from "@/utils/AppError.js";
import { issueAuthAccessCookies, issueAuthRefreshCookies, issueOtherCookies } from "@/utils/authUtils.js";
import { userService } from "@/instances.js";
import { STATUS_CODES } from "@/utils/statusCodes.js";
import { UserMapper } from "@/mappers/userMapper.js";
import { LoginUserDTO, SignUpUserDTO, VerifyOtpDTO } from "@/dtos/auth.dto.js";
import { generateOtpToken, RefresheTokenType } from "@/utils/generateToken.js";
import { accessCookieConfig, refreshCookieConfig } from "@/config/cookie.config.js";
import { COMMON_ERRORS, OTP_ERRORS, USER_ERRORS } from "@/constants/errors.js";
import { FRONTEND_REDIRECT_PATH } from "@/constants/paths.js";
import { notify } from "@/utils/notifyOnSignup.js";

const OTP_COOKIE = "otp_Cookie";

export const oAuthLoginCallback = (req: Request, res: Response, next: NextFunction) => {
	try {
		if (!req.user) {
			return next(new AppError(USER_ERRORS.NOT_AUTHENTICATED, STATUS_CODES.UNAUTHORIZED));
		}
		issueAuthAccessCookies(res, { id: req.user.id, plan: req.user.plan });
		issueAuthRefreshCookies(res, { id: req.user.id, plan: req.user.plan }, { currentRefresh: 0, originalIssuedAt: Date.now() });
		issueOtherCookies(res);
		const frontend = ENVS.FRONTEND_URL + FRONTEND_REDIRECT_PATH + ((req.user as any).newUser ? "?newuser=true" : "");
		// console.log({ frontend, user: req.user })
		if ((req.user as any).newUser) {
			notify(
				(req.user as any).nameString.split("%-%")[0],
				(req.user as any).nameString.split("%-%")[1],
				req.socket.remoteAddress || req.ip || "",
			);
		}
		res.redirect(frontend);
	} catch (error) {
		next(new AppError(USER_ERRORS.CALLBACK_ERROR, STATUS_CODES.INTERNAL_SERVER_ERROR, error));
	}
};

export const googleLoginStrategy = async (accessToken: string, refreshToken: string, profile: Profile, done: VerifyCallback) => {
	console.log("strategy google");
	try {
		const { user, newUser } = await userService.googleLoginStrategy(profile);
		const doneUser = {
			id: user._id,
			plan: user.plan,
			newUser,
			nameString: `${user.name}%-%${user.email}`,
		};
		done(null, doneUser);
	} catch (error) {
		done(error, false);
	}
};

export const githubLoginStrategy = async (accessToken: string, refreshToken: string, profile: Profile, done: VerifyCallback) => {
	try {
		console.log("strategy github");
		const { user, newUser } = await userService.githubLoginStrategy(profile);
		const doneUser = {
			id: user._id,
			plan: user.plan,
			newUser,
		};
		done(null, doneUser);
	} catch (error) {
		done(error, false);
	}
};

export const refresh = async (req: Request, res: Response, next: NextFunction) => {
	const refreshToken = req.cookies.refresh_token;
	if (!refreshToken) {
		console.log("No refresh token");
		res.status(STATUS_CODES.UNAUTHORIZED).json({ message: COMMON_ERRORS.COOKIE_NOT_PROVIDED });
		return;
	}
	try {
		const decoded = jwt.verify(refreshToken, ENVS.REFRESH_TOKEN_SECRET as string,
			{
				algorithms: ["HS256"],
			}
		) as RefresheTokenType;

		console.log("Trying to decode refesh", decoded);
		const user = await userService.getUser(decoded.id);
		if (!user) {
			throw new AppError(USER_ERRORS.NOT_FOUND, STATUS_CODES.NOT_FOUND);
		}

		const expiresAt = (decoded.exp as number) * 1000;
		const now = Date.now();
		const hoursLeft = (expiresAt - now) / (1000 * 60 * 60);

		if (hoursLeft < 6 && hoursLeft > 0) {
			console.log("refreshing refresh token also");
			issueAuthRefreshCookies(
				res,
				{ id: user._id, plan: user.plan },
				{ currentRefresh: decoded.crntRfrshCount + 1, originalIssuedAt: decoded.oIAT },
			);
		}
		issueAuthAccessCookies(res, { id: user._id, plan: user.plan });
		issueOtherCookies(res);
		return res.status(STATUS_CODES.OK).json({ ok: true });
	} catch (error) {
		if (error instanceof AppError) {
			next(error);
			return;
		}
		if (error instanceof Error) {
			if (error.name === "TokenExpiredError") {
				next(new AppError(USER_ERRORS.REFRESH_TOKEN_EXPIRED, STATUS_CODES.UNAUTHORIZED, error));
				return;
			}

			if (error.name === "JsonWebTokenError") {
				next(new AppError(USER_ERRORS.INVALID_TOKEN, STATUS_CODES.UNAUTHORIZED, error));
				return;
			}
		}
		next(new AppError(COMMON_ERRORS.TOKEN_VALIDATION, STATUS_CODES.INTERNAL_SERVER_ERROR, error));
		console.log("Error in token valiadation ");
	}
};

export const checkAuth = (req: Request, res: Response, next: NextFunction) => {
	return res.status(STATUS_CODES.OK).json({ ok: true, randomNumber: Math.floor(Math.random() * 1000) });
};

export const verifyAuth = (req: Request, res: Response) => {
	return res.status(STATUS_CODES.OK).json({ valid: true, user: req.user });
};

export const userLogout = (req: Request, res: Response) => {
	res.clearCookie("refresh_token", refreshCookieConfig);
	res.clearCookie("access_token", accessCookieConfig);
	res.clearCookie("is_Authenticated");
	res.status(STATUS_CODES.OK).json({ message: "user logged out" });
};

export const getAuthenticatedUser = async (req: Request, res: Response, next: NextFunction) => {
	try {
		const userId = req.user?.id as string;
		const user = await userService.getUser(userId);
		if (!user) {
			res.status(STATUS_CODES.NOT_FOUND).json({
				error: USER_ERRORS.NOT_AUTHENTICATED,
				message: USER_ERRORS.NOT_FOUND,
			});
			return;
		}
		const response = UserMapper.toUserResponse(user);
		res.status(STATUS_CODES.OK).json(response);
	} catch (error) {
		next(error);
	}
};

export const signUpUser = async (req: Request, res: Response, next: NextFunction) => {
	try {
		const userData = req.validatedBody as SignUpUserDTO;
		const result = await userService.signUpUser(userData);

		if (!result) {
			res.status(STATUS_CODES.BAD_REQUEST).json({ error: USER_ERRORS.CREATION_ERROR });
			return;
		}
		const user = result.user;
		const otpSent = result.otpResult;
		const response = UserMapper.toUserResponse(user);
		res.cookie(OTP_COOKIE, generateOtpToken(response.user._id), { ...accessCookieConfig });
		res.status(STATUS_CODES.CREATED).json({ message: "OTP Sent", otpSent, user: response.user });
	} catch (error) {
		next(error);
	}
};

export const loginUser = async (req: Request, res: Response, next: NextFunction) => {
	try {
		const userData = req.validatedBody as LoginUserDTO;
		const user = await userService.loginUser(userData);
		if (user) {
			const response = UserMapper.toUserResponse(user);
			if (!user.isVerified) {
				res.cookie(OTP_COOKIE, generateOtpToken(response.user._id), { ...accessCookieConfig });
				res.status(STATUS_CODES.FORBIDDEN).json({
					message: USER_ERRORS.EMAIL_NOT_VERIFIED,
					requiresOtpVerification: true,
					loginSuccess: false,
				});
				return;
			}
			issueAuthAccessCookies(res, { id: response.user._id, plan: response.user.plan });
			issueAuthRefreshCookies(res, { id: response.user._id, plan: response.user.plan }, { currentRefresh: 0, originalIssuedAt: Date.now() });
			issueOtherCookies(res);
			res.status(STATUS_CODES.OK).json({ loginSuccess: true, user: response.user });
			return;
		}
		res.status(STATUS_CODES.NOT_FOUND).json({ message: USER_ERRORS.NOT_FOUND, statusCode: 404 });
		return;
	} catch (error) {
		next(error);
	}
};

export const verifyOtp = async (req: Request, res: Response, next: NextFunction) => {
	try {
		const userData = req.validatedBody as VerifyOtpDTO;
		const result = await userService.verifyUserOtp(userData.email, userData.otp);
		if (result.verifyResult) {
			const { user } = result;
			if (user) {
				const response = UserMapper.toUserResponse(user);
				issueAuthAccessCookies(res, { id: response.user._id, plan: response.user.plan });
				issueAuthRefreshCookies(
					res,
					{ id: response.user._id, plan: response.user.plan },
					{ currentRefresh: 0, originalIssuedAt: Date.now() },
				);
				issueOtherCookies(res);
				res.clearCookie(OTP_COOKIE);
				res.status(STATUS_CODES.OK).json({ message: "OTP Verified succesfully", user: response.user });
				notify(user.name, user.email, req.socket.remoteAddress || req.ip || "");
				return;
			}
		}
		res.status(STATUS_CODES.BAD_REQUEST).json({
			message: OTP_ERRORS.VERIFICATION_FAILED,
			statusCode: STATUS_CODES.BAD_REQUEST,
		});
	} catch (error) {
		next(error);
	}
};

export const resendOtp = async (req: Request, res: Response, next: NextFunction) => {
	try {
		const otpCookie = req.cookies.otp_Cookie;
		if (!otpCookie) {
			res.status(STATUS_CODES.BAD_REQUEST).json({ message: "Cant send otp, insufficient data" });
			return;
		}
		const decoded = jwt.verify(otpCookie, ENVS.VERIFICATION_TOKEN_SECRET as string,
			{
				algorithms: ["HS256"],
			}
		) as { id: string };
		const { id } = decoded;

		const result = await userService.resentOtp(id || "---");
		res.status(STATUS_CODES.OK).json({ message: "OTP Sent", otpsent: result });
	} catch (error) {
		next(error);
	}
};

export const getAuthenticatedUserDetails = async (req: Request, res: Response, next: NextFunction) => {
	try {
		const userId = req.user?.id as string;
		const { user, bandwidth } = await userService.getUserDetailed(userId);
		if (!user) {
			res.status(STATUS_CODES.NOT_FOUND).json({ error: USER_ERRORS.NOT_FOUND });
			return;
		}
		const response = UserMapper.toUserDetailedResponse({ user, bandwidth });
		res.status(STATUS_CODES.OK).json(response);
	} catch (error) {
		next(error);
	}
};
export const getUserGthbInstallationInfo = async (req: Request, res: Response, next: NextFunction) => {
	try {
		const userId = req.user?.id as string;
		const result = await userService.getGithubInstallationInfo(userId);
		if (!result) {
			res.status(STATUS_CODES.OK).json({ error: COMMON_ERRORS.NOT_FOUND });
			return;
		}
		const response = UserMapper.toUserInstallationResponse(result, userId);
		res.status(STATUS_CODES.OK).json(response);
	} catch (error) {
		next(error);
	}
};