auth-middleware.ts 814 B

123456789101112131415161718192021222324252627282930
  1. import { ApiError } from "../exceptions/api-error.js";
  2. import tokenService from "#modules/user/auth/services/token-service.js";
  3. export default function () {
  4. return function (req, res, next) {
  5. try {
  6. // авторизация
  7. const authorizationHeader = req.headers.authorization;
  8. if (!authorizationHeader) {
  9. return next(ApiError.UnauthorizedError());
  10. }
  11. const accessToken = authorizationHeader.split(" ")[1];
  12. if (!accessToken) {
  13. return next(ApiError.UnauthorizedError());
  14. }
  15. const userData = tokenService.validateAccessToken(accessToken);
  16. if (!userData) {
  17. return next(ApiError.UnauthorizedError());
  18. }
  19. req.user = userData;
  20. next();
  21. } catch (e) {
  22. return next(ApiError.UnauthorizedError());
  23. }
  24. };
  25. }