Skip to content

Commit

Permalink
Merge pull request #54 from TeamHSE/feat/logout
Browse files Browse the repository at this point in the history
Feat/logout
  • Loading branch information
AleksanderNekr authored Jun 19, 2024
2 parents 1b73b74 + 6fb7814 commit 826748c
Show file tree
Hide file tree
Showing 8 changed files with 122 additions and 2 deletions.
2 changes: 1 addition & 1 deletion backend/src/controllers/AuthControllerLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const AuthControllerLogin = [
});

res.cookie("token", token, {
httpOnly: true,
httpOnly: false,
});

return res.status(200).json({ message: "Вход выполнен успешно" });
Expand Down
19 changes: 19 additions & 0 deletions backend/src/controllers/AuthControllerLogout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Request, Response } from "express";
import { verifyToken } from "../middlewares/verifyToken";

export const UserControllerLogout = [
verifyToken,
(req: Request, res: Response) => {
try {
res.clearCookie("token", { httpOnly: true, maxAge: 0 });
return res
.status(200)
.json({ message: "Сессия завершена" });
} catch (error) {
console.error("Ошибка при выходе из системы:", error);
return res
.status(500)
.json({ message: "Произошла ошибка сервера при выходе из системы" });
}
},
];
2 changes: 1 addition & 1 deletion backend/src/controllers/AuthControllerRegister.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export const AuthControllerRegister = [
});

res.cookie("token", token, {
httpOnly: true,
httpOnly: false,
});

return res.status(200).json({ message: "Пользователь успешно зарегистрирован" });
Expand Down
43 changes: 43 additions & 0 deletions backend/src/controllers/UserInfoController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Request, Response } from "express";
import { verifyToken } from "../middlewares/verifyToken";
import { AppDataSource } from "../db";
import { User } from "../entity/User";

export const UserControllerGetUserInfo = [
verifyToken,
async (req: Request, res: Response) => {
const login = req.user?.login;
if (!login) {
return res.status(403).json({ message: "Не удалось идентифицировать пользователя" });
}

try {
const userRepository = AppDataSource.getRepository(User);
const user = await userRepository.findOne({ where: { email: login } });

if (!user) {
return res.status(404).json({ message: "Пользователь не найден" });
}

const { userId, firstName, lastName, username, email, isMale, birthDate, weight, height, achievements, healthIssues } = user;
const userInfo = {
userId,
firstName,
lastName,
username,
email,
isMale,
birthDate,
weight,
height,
achievements,
healthIssues,
};

return res.status(200).json(userInfo);
} catch (error) {
console.error("Ошибка при получении информации о пользователе:", error);
return res.status(500).json({ message: "Произошла ошибка сервера при получении информации о пользователе" });
}
},
];
1 change: 1 addition & 0 deletions backend/src/entity/Course.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
BaseEntity,
Entity,
PrimaryGeneratedColumn,
Column,
Expand Down
37 changes: 37 additions & 0 deletions backend/src/middlewares/verifyToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import fs from "fs";
import { config } from "../config/Config";
import { DecodedToken } from "../types/express";

const publicKeyPath = config.publicKeyPath;

export function verifyToken(req: Request, res: Response, next: NextFunction) {
const token = req.headers.authorization?.split(" ")[1];

if (!token) {
return res
.status(403)
.json({ message: "Необходимо предоставить токен авторизации" });
}

try {
const publicKey = fs.readFileSync(publicKeyPath, "utf8");

jwt.verify(token, publicKey, { algorithms: ["RS256"] }, (err, decoded) => {
if (err) {
console.error("Ошибка верификации токена:", err);
return res.status(403).json({ message: "Ошибка авторизации" });
}

const decodedToken = decoded as DecodedToken;
req.user = decodedToken;
next();
});
} catch (err) {
console.error("Ошибка чтения публичного ключа:", err);
return res
.status(500)
.json({ message: "Ошибка сервера при проверке токена" });
}
}
4 changes: 4 additions & 0 deletions backend/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { app } from "./server";
import { UserController } from "./controllers/UserController";
import { AuthControllerLogin } from "./controllers/AuthControllerLogin";
import { AuthControllerRegister } from "./controllers/AuthControllerRegister";
import { UserControllerGetUserInfo } from "./controllers/UserInfoController";
import { UserControllerLogout } from "./controllers/AuthControllerLogout";

export const registerControllers = () => {
app.get("/helloWorld", HelloWorldController);
Expand All @@ -12,4 +14,6 @@ export const registerControllers = () => {
app.post("/api/auth/login", AuthControllerLogin);
app.get("/user", UserController);
app.post("/user", UserController);
app.get("/api/users", UserControllerGetUserInfo);
app.post("/api/auth/logout", UserControllerLogout);
};
16 changes: 16 additions & 0 deletions backend/src/types/express.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Request } from 'express';

export interface DecodedToken {
login: string;
iat: number;
exp: number;
}

// Расширение интерфейса Request для добавления свойства user
declare global {
namespace Express {
interface Request {
user?: DecodedToken;
}
}
}

0 comments on commit 826748c

Please sign in to comment.