mirror of
https://github.com/cheveguerra/whaticket-community.git
synced 2026-04-18 19:59:20 +00:00
finished user store in typscript
This commit is contained in:
@@ -1,36 +0,0 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
const util = require("util");
|
||||
|
||||
const User = require("../models/User");
|
||||
const authConfig = require("../config/auth");
|
||||
|
||||
module.exports = async (req, res, next) => {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!authHeader) {
|
||||
return res.status(401).json({ error: "Token not provided" });
|
||||
}
|
||||
|
||||
const [, token] = authHeader.split(" ");
|
||||
|
||||
try {
|
||||
const decoded = await util.promisify(jwt.verify)(token, authConfig.secret);
|
||||
|
||||
const user = await User.findByPk(decoded.userId, {
|
||||
attributes: ["id", "name", "profile", "email"],
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return res
|
||||
.status(401)
|
||||
.json({ error: "The token corresponding user does not exists." });
|
||||
}
|
||||
|
||||
req.user = user;
|
||||
|
||||
return next();
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
return res.status(401).json({ error: "Invalid Token" });
|
||||
}
|
||||
};
|
||||
35
backend/src/middleware/isAuth.ts
Normal file
35
backend/src/middleware/isAuth.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { verify } from "jsonwebtoken";
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
|
||||
import AppError from "../errors/AppError";
|
||||
import authConfig from "../config/auth";
|
||||
|
||||
interface TokenPayload {
|
||||
id: string;
|
||||
username: string;
|
||||
profile: string;
|
||||
iat: number;
|
||||
exp: number;
|
||||
}
|
||||
|
||||
const isAuth = (req: Request, res: Response, next: NextFunction): void => {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!authHeader) {
|
||||
throw new AppError("Token not provided.", 403);
|
||||
}
|
||||
|
||||
const [, token] = authHeader.split(" ");
|
||||
|
||||
const decoded = verify(token, authConfig.secret);
|
||||
const { id, profile } = decoded as TokenPayload;
|
||||
|
||||
req.user = {
|
||||
id,
|
||||
profile
|
||||
};
|
||||
|
||||
return next();
|
||||
};
|
||||
|
||||
export default isAuth;
|
||||
Reference in New Issue
Block a user