|
@@ -1,8 +1,3 @@
|
|
-// router
|
|
|
|
-import express from "express";
|
|
|
|
-const router = express.Router();
|
|
|
|
-export default router;
|
|
|
|
-
|
|
|
|
// db
|
|
// db
|
|
import { selPool, updPool } from "#db";
|
|
import { selPool, updPool } from "#db";
|
|
import { DbSchema } from "#db-schema";
|
|
import { DbSchema } from "#db-schema";
|
|
@@ -14,11 +9,6 @@ import { AuthApi } from "#api";
|
|
// error
|
|
// error
|
|
import { ApiError } from "#exceptions/api-error.js";
|
|
import { ApiError } from "#exceptions/api-error.js";
|
|
|
|
|
|
-// dayjs
|
|
|
|
-import dayjs from "dayjs";
|
|
|
|
-import utc from "dayjs/plugin/utc.js";
|
|
|
|
-dayjs.extend(utc);
|
|
|
|
-
|
|
|
|
// other
|
|
// other
|
|
import { z } from "zod";
|
|
import { z } from "zod";
|
|
import bcript from "bcrypt";
|
|
import bcript from "bcrypt";
|
|
@@ -26,21 +16,22 @@ import { v7 as uuidv7 } from "uuid";
|
|
|
|
|
|
import tokenService from "../services/token-service.js";
|
|
import tokenService from "../services/token-service.js";
|
|
import { UserAuthService } from "../services/user-auth-service.js";
|
|
import { UserAuthService } from "../services/user-auth-service.js";
|
|
-import { ConfirmPinsService } from "#modules/users-management/confirm-pins/confirm-pins-service.js";
|
|
|
|
|
|
+import { ConfirmPinsService } from "#modules/users/confirm-pins/confirm-pins-service.js";
|
|
import { RouterUtils } from "#utils/router-utils.js";
|
|
import { RouterUtils } from "#utils/router-utils.js";
|
|
import { config } from "#config";
|
|
import { config } from "#config";
|
|
-
|
|
|
|
-dayjs.extend(utc);
|
|
|
|
-
|
|
|
|
-router.post("/registration", async (req, res, next) => {
|
|
|
|
- try {
|
|
|
|
|
|
+import { Request, Response } from "express";
|
|
|
|
+
|
|
|
|
+class authController {
|
|
|
|
+ // --- Регистрация ---
|
|
|
|
+ async register(
|
|
|
|
+ req: Request,
|
|
|
|
+ res: Response,
|
|
|
|
+ // next: NextFunction
|
|
|
|
+ ) {
|
|
// валидация запроса
|
|
// валидация запроса
|
|
const { email } = AuthApi.POST_Registration.req.parse(req.body);
|
|
const { email } = AuthApi.POST_Registration.req.parse(req.body);
|
|
|
|
|
|
- // проверка на существование пользователя
|
|
|
|
- const isUserExist = await selPool.exists(
|
|
|
|
- sql.unsafe`select email from usr.users where email = ${email}`,
|
|
|
|
- );
|
|
|
|
|
|
+ const isUserExist = await UserAuthService.checkUserExistByEmail(email);
|
|
|
|
|
|
// если пользователь уже зарегистрирован
|
|
// если пользователь уже зарегистрирован
|
|
if (isUserExist) {
|
|
if (isUserExist) {
|
|
@@ -72,14 +63,9 @@ router.post("/registration", async (req, res, next) => {
|
|
code: "pinIsSent",
|
|
code: "pinIsSent",
|
|
transactionId: transactionId,
|
|
transactionId: transactionId,
|
|
});
|
|
});
|
|
- } catch (e) {
|
|
|
|
- next(e);
|
|
|
|
}
|
|
}
|
|
-});
|
|
|
|
|
|
|
|
-// TODO добавить компанию
|
|
|
|
-router.post("/confirm-registration", async (req, res, next) => {
|
|
|
|
- try {
|
|
|
|
|
|
+ async confirmRegistration(req: Request, res: Response) {
|
|
// валидация запроса
|
|
// валидация запроса
|
|
const { password, name, transactionId, confirmPin } =
|
|
const { password, name, transactionId, confirmPin } =
|
|
AuthApi.POST_ConfirmRegistration.req.parse(req.body);
|
|
AuthApi.POST_ConfirmRegistration.req.parse(req.body);
|
|
@@ -90,40 +76,37 @@ router.post("/confirm-registration", async (req, res, next) => {
|
|
confirmPin,
|
|
confirmPin,
|
|
);
|
|
);
|
|
|
|
|
|
- // если пин протухший
|
|
|
|
- if (pinInfo.status === "rotten") {
|
|
|
|
- RouterUtils.validAndSendResponse(
|
|
|
|
- AuthApi.POST_ConfirmRegistration.res,
|
|
|
|
- res,
|
|
|
|
- { code: "pinIsRotten" },
|
|
|
|
- 400,
|
|
|
|
- );
|
|
|
|
- return;
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // слишком много попыток
|
|
|
|
- if (pinInfo.status === "tooManyTries") {
|
|
|
|
- RouterUtils.validAndSendResponse(
|
|
|
|
- AuthApi.POST_ConfirmRegistration.res,
|
|
|
|
- res,
|
|
|
|
- { code: "tooManyTries" },
|
|
|
|
- 400,
|
|
|
|
- );
|
|
|
|
- return;
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- // неправильный
|
|
|
|
- if (pinInfo.status === "wrong") {
|
|
|
|
- RouterUtils.validAndSendResponse(
|
|
|
|
- AuthApi.POST_ConfirmRegistration.res,
|
|
|
|
- res,
|
|
|
|
- {
|
|
|
|
- code: "pinIsWrong",
|
|
|
|
- triesRemained: pinInfo.triesRemained,
|
|
|
|
- },
|
|
|
|
- 400,
|
|
|
|
- );
|
|
|
|
- return;
|
|
|
|
|
|
+ switch (pinInfo.status) {
|
|
|
|
+ case "rotten": {
|
|
|
|
+ RouterUtils.validAndSendResponse(
|
|
|
|
+ AuthApi.POST_ConfirmRegistration.res,
|
|
|
|
+ res,
|
|
|
|
+ { code: "pinIsRotten" },
|
|
|
|
+ 400,
|
|
|
|
+ );
|
|
|
|
+ return;
|
|
|
|
+ }
|
|
|
|
+ case "tooManyTries": {
|
|
|
|
+ RouterUtils.validAndSendResponse(
|
|
|
|
+ AuthApi.POST_ConfirmRegistration.res,
|
|
|
|
+ res,
|
|
|
|
+ { code: "tooManyTries" },
|
|
|
|
+ 400,
|
|
|
|
+ );
|
|
|
|
+ return;
|
|
|
|
+ }
|
|
|
|
+ case "wrong": {
|
|
|
|
+ RouterUtils.validAndSendResponse(
|
|
|
|
+ AuthApi.POST_ConfirmRegistration.res,
|
|
|
|
+ res,
|
|
|
|
+ {
|
|
|
|
+ code: "pinIsWrong",
|
|
|
|
+ triesRemained: pinInfo.triesRemained,
|
|
|
|
+ },
|
|
|
|
+ 400,
|
|
|
|
+ );
|
|
|
|
+ return;
|
|
|
|
+ }
|
|
}
|
|
}
|
|
|
|
|
|
// пин правильный
|
|
// пин правильный
|
|
@@ -133,10 +116,10 @@ router.post("/confirm-registration", async (req, res, next) => {
|
|
const userId = uuidv7();
|
|
const userId = uuidv7();
|
|
await updPool.query(
|
|
await updPool.query(
|
|
sql.unsafe`
|
|
sql.unsafe`
|
|
- insert into usr.users
|
|
|
|
- (user_id, email, name, password)
|
|
|
|
- values
|
|
|
|
- (${userId}, ${email}, ${name}, ${hashPassword})`,
|
|
|
|
|
|
+ insert into usr.users
|
|
|
|
+ (user_id, email, name, password)
|
|
|
|
+ values
|
|
|
|
+ (${userId}, ${email}, ${name}, ${hashPassword})`,
|
|
);
|
|
);
|
|
|
|
|
|
// токены
|
|
// токены
|
|
@@ -146,11 +129,7 @@ router.post("/confirm-registration", async (req, res, next) => {
|
|
});
|
|
});
|
|
await tokenService.insertRefreshToken(userId, refreshToken);
|
|
await tokenService.insertRefreshToken(userId, refreshToken);
|
|
|
|
|
|
- res.cookie("refreshToken", refreshToken, {
|
|
|
|
- maxAge: 30 * 24 * 60 * 60 * 1000, //30d
|
|
|
|
- httpOnly: true, //запрет на изменение пользователем
|
|
|
|
- // secure: true, //после включения https
|
|
|
|
- });
|
|
|
|
|
|
+ tokenService.setRefreshTokenInCookie(res, refreshToken);
|
|
|
|
|
|
RouterUtils.validAndSendResponse(
|
|
RouterUtils.validAndSendResponse(
|
|
AuthApi.POST_ConfirmRegistration.res,
|
|
AuthApi.POST_ConfirmRegistration.res,
|
|
@@ -158,20 +137,15 @@ router.post("/confirm-registration", async (req, res, next) => {
|
|
{
|
|
{
|
|
code: "registered",
|
|
code: "registered",
|
|
accessToken,
|
|
accessToken,
|
|
- refreshToken,
|
|
|
|
userData: {
|
|
userData: {
|
|
email,
|
|
email,
|
|
userId,
|
|
userId,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
);
|
|
);
|
|
- } catch (e) {
|
|
|
|
- next(e);
|
|
|
|
}
|
|
}
|
|
-});
|
|
|
|
|
|
|
|
-router.post("/login", async (req, res, next) => {
|
|
|
|
- try {
|
|
|
|
|
|
+ async login(req: Request, res: Response) {
|
|
// валидация запроса
|
|
// валидация запроса
|
|
const { email, password } = AuthApi.POST_Login.req.parse(req.body);
|
|
const { email, password } = AuthApi.POST_Login.req.parse(req.body);
|
|
|
|
|
|
@@ -184,14 +158,14 @@ router.post("/login", async (req, res, next) => {
|
|
wrongPassTries: DbSchema.usr.users.wrongPassTries,
|
|
wrongPassTries: DbSchema.usr.users.wrongPassTries,
|
|
}),
|
|
}),
|
|
)`
|
|
)`
|
|
- select
|
|
|
|
- user_id as "userId",
|
|
|
|
- password,
|
|
|
|
- wrong_pass_tries as "wrongPassTries"
|
|
|
|
- from
|
|
|
|
- usr.users
|
|
|
|
- where
|
|
|
|
- email = ${email}`,
|
|
|
|
|
|
+ select
|
|
|
|
+ user_id as "userId",
|
|
|
|
+ password,
|
|
|
|
+ wrong_pass_tries as "wrongPassTries"
|
|
|
|
+ from
|
|
|
|
+ usr.users
|
|
|
|
+ where
|
|
|
|
+ email = ${email}`,
|
|
);
|
|
);
|
|
if (!user) {
|
|
if (!user) {
|
|
RouterUtils.validAndSendResponse(
|
|
RouterUtils.validAndSendResponse(
|
|
@@ -247,11 +221,8 @@ router.post("/login", async (req, res, next) => {
|
|
userId: user.userId,
|
|
userId: user.userId,
|
|
});
|
|
});
|
|
await tokenService.insertRefreshToken(user.userId, refreshToken);
|
|
await tokenService.insertRefreshToken(user.userId, refreshToken);
|
|
- res.cookie("refreshToken", refreshToken, {
|
|
|
|
- maxAge: 30 * 24 * 60 * 60 * 1000, //30d
|
|
|
|
- httpOnly: true, //запрет на изменение пользователем
|
|
|
|
- // secure: true, //после включения https
|
|
|
|
- });
|
|
|
|
|
|
+
|
|
|
|
+ tokenService.setRefreshTokenInCookie(res, refreshToken);
|
|
|
|
|
|
RouterUtils.validAndSendResponse(
|
|
RouterUtils.validAndSendResponse(
|
|
AuthApi.POST_Login.res,
|
|
AuthApi.POST_Login.res,
|
|
@@ -259,17 +230,13 @@ router.post("/login", async (req, res, next) => {
|
|
{
|
|
{
|
|
code: "success",
|
|
code: "success",
|
|
accessToken,
|
|
accessToken,
|
|
- refreshToken,
|
|
|
|
userData: { email, userId: user.userId },
|
|
userData: { email, userId: user.userId },
|
|
},
|
|
},
|
|
200,
|
|
200,
|
|
);
|
|
);
|
|
- } catch (e) {
|
|
|
|
- next(e);
|
|
|
|
}
|
|
}
|
|
-});
|
|
|
|
-router.post("/logout", async (req, res, next) => {
|
|
|
|
- try {
|
|
|
|
|
|
+
|
|
|
|
+ async logout(req: Request, res: Response) {
|
|
const { refreshToken } = req.cookies;
|
|
const { refreshToken } = req.cookies;
|
|
|
|
|
|
const userData = tokenService.validateRefreshToken(refreshToken);
|
|
const userData = tokenService.validateRefreshToken(refreshToken);
|
|
@@ -280,13 +247,9 @@ router.post("/logout", async (req, res, next) => {
|
|
RouterUtils.validAndSendResponse(AuthApi.POST_Logout.res, res, {
|
|
RouterUtils.validAndSendResponse(AuthApi.POST_Logout.res, res, {
|
|
code: "success",
|
|
code: "success",
|
|
});
|
|
});
|
|
- } catch (e) {
|
|
|
|
- next(e);
|
|
|
|
}
|
|
}
|
|
-});
|
|
|
|
|
|
|
|
-router.post("/logoutAllDevices", async (req, res, next) => {
|
|
|
|
- try {
|
|
|
|
|
|
+ async logoutAllDevices(req: Request, res: Response) {
|
|
const { refreshToken } = req.cookies;
|
|
const { refreshToken } = req.cookies;
|
|
|
|
|
|
const userData = tokenService.validateRefreshToken(refreshToken);
|
|
const userData = tokenService.validateRefreshToken(refreshToken);
|
|
@@ -297,13 +260,9 @@ router.post("/logoutAllDevices", async (req, res, next) => {
|
|
RouterUtils.validAndSendResponse(AuthApi.POST_LogoutAllDevices.res, res, {
|
|
RouterUtils.validAndSendResponse(AuthApi.POST_LogoutAllDevices.res, res, {
|
|
code: "success",
|
|
code: "success",
|
|
});
|
|
});
|
|
- } catch (e) {
|
|
|
|
- next(e);
|
|
|
|
}
|
|
}
|
|
-});
|
|
|
|
|
|
|
|
-router.get("/refresh", async (req, res, next) => {
|
|
|
|
- try {
|
|
|
|
|
|
+ async refresh(req: Request, res: Response) {
|
|
const { refreshToken } = req.cookies;
|
|
const { refreshToken } = req.cookies;
|
|
|
|
|
|
if (!refreshToken) throw ApiError.UnauthorizedError();
|
|
if (!refreshToken) throw ApiError.UnauthorizedError();
|
|
@@ -346,13 +305,12 @@ router.get("/refresh", async (req, res, next) => {
|
|
code: "success",
|
|
code: "success",
|
|
|
|
|
|
accessToken: newTokens.accessToken,
|
|
accessToken: newTokens.accessToken,
|
|
- refreshToken: newTokens.refreshToken,
|
|
|
|
userData: {
|
|
userData: {
|
|
email: newUserData.email,
|
|
email: newUserData.email,
|
|
userId: userData.userId,
|
|
userId: userData.userId,
|
|
},
|
|
},
|
|
});
|
|
});
|
|
- } catch (e) {
|
|
|
|
- next(e);
|
|
|
|
}
|
|
}
|
|
-});
|
|
|
|
|
|
+}
|
|
|
|
+
|
|
|
|
+export const AuthController = new authController();
|