-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Added authorization middleware * Added authentication middleware * Added authorization middleware * Added authorization middleware * Added authorization middleware
- Loading branch information
1 parent
7582873
commit b0606a1
Showing
7 changed files
with
287 additions
and
61 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,36 +1,37 @@ | ||
/* eslint-disable comma-dangle */ | ||
import dotenv from "dotenv"; | ||
|
||
dotenv.config(); | ||
|
||
const commonDatabaseConfig = { | ||
dialect: "postgres" | ||
dialect: "postgres", | ||
}; | ||
|
||
const sequelizeConfig = { | ||
development: { | ||
...commonDatabaseConfig, | ||
url: process.env.DATABASE_URL_DEV | ||
url: process.env.DATABASE_URL_DEV, | ||
}, | ||
test: { | ||
...commonDatabaseConfig, | ||
url: process.env.DATABASE_URL_TEST, | ||
dialectOptions: { | ||
ssl: { | ||
require: true, | ||
rejectUnauthorized: false | ||
} | ||
} | ||
rejectUnauthorized: false, | ||
}, | ||
}, | ||
}, | ||
production: { | ||
...commonDatabaseConfig, | ||
url: process.env.DATABASE_URL_PRO, | ||
dialectOptions: { | ||
ssl: { | ||
require: true, | ||
rejectUnauthorized: false | ||
} | ||
} | ||
} | ||
rejectUnauthorized: false, | ||
}, | ||
}, | ||
}, | ||
}; | ||
|
||
module.exports = sequelizeConfig; | ||
module.exports = sequelizeConfig; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,147 @@ | ||
import chai, { expect } from "chai"; | ||
import chaiHttp from "chai-http"; | ||
/* eslint-disable @typescript-eslint/no-var-requires */ | ||
/* eslint-disable comma-dangle */ | ||
import app from "./index"; | ||
import chai from "chai"; | ||
import chaiHttp from "chai-http"; | ||
const { expect } = require("chai"); | ||
const sinon = require("sinon"); | ||
const sinonChai = require("sinon-chai"); | ||
const { userAuthorization } = require("./middlewares/authorization"); | ||
const httpStatus = require("http-status"); | ||
import * as helpers from "./helpers/index"; | ||
import authRepositories from "./modules/auth/repository/authRepositories"; | ||
|
||
chai.use(chaiHttp); | ||
const router = () => chai.request(app) | ||
chai.use(sinonChai); | ||
// | ||
const router = () => chai.request(app); | ||
|
||
describe("Initial configuration", () => { | ||
it("Should return `Welcome to the e-Commerce-Ninja BackEnd` when GET on /", (done) => { | ||
router() | ||
.get("/") | ||
.end((err, res) => { | ||
expect(res).to.have.status(200); | ||
expect(res.body).to.be.a("object"); | ||
expect(res.body).to.have.property( | ||
"message", | ||
"Welcome to the e-Commerce Ninjas BackEnd." | ||
); | ||
done(err); | ||
}); | ||
}); | ||
}); | ||
|
||
describe("userAuthorization middleware", () => { | ||
let req, res, next, roles; | ||
|
||
beforeEach(() => { | ||
roles = ["admin", "user"]; | ||
req = { | ||
headers: {}, | ||
user: null, | ||
session: null, | ||
}; | ||
res = { | ||
status: sinon.stub().returnsThis(), | ||
json: sinon.stub().returnsThis(), | ||
}; | ||
next = sinon.spy(); | ||
}); | ||
|
||
afterEach(() => { | ||
sinon.restore(); | ||
}); | ||
|
||
it("should respond with 401 if no authorization header", async () => { | ||
const middleware = userAuthorization(roles); | ||
await middleware(req, res, next); | ||
|
||
expect(res.status).to.have.been.calledWith(httpStatus.UNAUTHORIZED); | ||
expect(res.json).to.have.been.calledWith({ | ||
status: httpStatus.UNAUTHORIZED, | ||
message: "Not authorized", | ||
}); | ||
}); | ||
|
||
it("should respond with 401 if no session found", async () => { | ||
req.headers.authorization = "Bearer validToken"; | ||
sinon.stub(helpers, "decodeToken").resolves({ id: "userId" }); | ||
sinon.stub(authRepositories, "findSessionByUserIdAndToken").resolves(null); | ||
|
||
const middleware = userAuthorization(roles); | ||
await middleware(req, res, next); | ||
|
||
expect(res.status).to.have.been.calledWith(httpStatus.UNAUTHORIZED); | ||
expect(res.json).to.have.been.calledWith({ | ||
status: httpStatus.UNAUTHORIZED, | ||
message: "Not authorized", | ||
}); | ||
}); | ||
|
||
it("should respond with 401 if no user found", async () => { | ||
req.headers.authorization = "Bearer validToken"; | ||
sinon.stub(helpers, "decodeToken").resolves({ id: "userId" }); | ||
sinon.stub(authRepositories, "findSessionByUserIdAndToken").resolves({}); | ||
sinon.stub(authRepositories, "findUserByAttributes").resolves(null); | ||
|
||
const middleware = userAuthorization(roles); | ||
await middleware(req, res, next); | ||
|
||
expect(res.status).to.have.been.calledWith(httpStatus.UNAUTHORIZED); | ||
expect(res.json).to.have.been.calledWith({ | ||
status: httpStatus.UNAUTHORIZED, | ||
message: "Not authorized", | ||
}); | ||
}); | ||
|
||
it("should respond with 401 if user role is not authorized", async () => { | ||
req.headers.authorization = "Bearer validToken"; | ||
sinon.stub(helpers, "decodeToken").resolves({ id: "userId" }); | ||
sinon.stub(authRepositories, "findSessionByUserIdAndToken").resolves({}); | ||
sinon | ||
.stub(authRepositories, "findUserByAttributes") | ||
.resolves({ role: "guest" }); | ||
|
||
const middleware = userAuthorization(roles); | ||
await middleware(req, res, next); | ||
|
||
expect(res.status).to.have.been.calledWith(httpStatus.UNAUTHORIZED); | ||
expect(res.json).to.have.been.calledWith({ | ||
status: httpStatus.UNAUTHORIZED, | ||
message: "Not authorized", | ||
}); | ||
}); | ||
|
||
it("should call next if user is authorized", async () => { | ||
req.headers.authorization = "Bearer validToken"; | ||
sinon.stub(helpers, "decodeToken").resolves({ id: "userId" }); | ||
sinon.stub(authRepositories, "findSessionByUserIdAndToken").resolves({}); | ||
sinon | ||
.stub(authRepositories, "findUserByAttributes") | ||
.resolves({ role: "admin" }); | ||
|
||
const middleware = userAuthorization(roles); | ||
await middleware(req, res, next); | ||
|
||
expect(next).to.have.been.calledOnce; | ||
expect(req.user).to.deep.equal({ role: "admin" }); | ||
expect(req.session).to.deep.equal({}); | ||
}); | ||
|
||
it("should respond with 500 if an unexpected error occurs", async () => { | ||
req.headers.authorization = "Bearer validToken"; | ||
sinon.stub(helpers, "decodeToken").rejects(new Error("Unexpected error")); | ||
|
||
const middleware = userAuthorization(roles); | ||
await middleware(req, res, next); | ||
|
||
it("Should return `Welcome to the e-Commerce-Ninja BackEnd` when GET on /", (done) => { | ||
router() | ||
.get("/") | ||
.end((err, res) => { | ||
expect(res).to.have.status(200); | ||
expect(res.body).to.be.a("object"); | ||
expect(res.body).to.have.property("message", "Welcome to the e-Commerce Ninjas BackEnd."); | ||
done(err); | ||
}); | ||
expect(res.status).to.have.been.calledWith( | ||
httpStatus.INTERNAL_SERVER_ERROR | ||
); | ||
expect(res.json).to.have.been.calledWith({ | ||
status: httpStatus.INTERNAL_SERVER_ERROR, | ||
message: "Unexpected error", | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
/* eslint-disable comma-dangle */ | ||
/* eslint-disable @typescript-eslint/no-explicit-any */ | ||
import { Request, Response, NextFunction } from "express"; | ||
import { UsersAttributes } from "../databases/models/users"; | ||
import authRepository from "../modules/auth/repository/authRepositories"; | ||
import httpStatus from "http-status"; | ||
import { decodeToken } from "../helpers"; | ||
import Session from "../databases/models/session"; | ||
|
||
interface ExtendedRequest extends Request { | ||
user: UsersAttributes; | ||
session: Session; | ||
} | ||
|
||
export const userAuthorization = function (roles: string[]) { | ||
return async (req: ExtendedRequest, res: Response, next: NextFunction) => { | ||
try { | ||
let token: string; | ||
if (req.headers.authorization?.startsWith("Bearer")) { | ||
token = req.headers.authorization.split(" ").at(-1); | ||
} | ||
|
||
if (!token) { | ||
res | ||
.status(httpStatus.UNAUTHORIZED) | ||
.json({ status: httpStatus.UNAUTHORIZED, message: "Not authorized" }); | ||
} | ||
|
||
const decoded: any = await decodeToken(token); | ||
|
||
const session: Session = await authRepository.findSessionByUserIdAndToken( | ||
decoded.id, token | ||
); | ||
if (!session) { | ||
res | ||
.status(httpStatus.UNAUTHORIZED) | ||
.json({ status: httpStatus.UNAUTHORIZED, message: "Not authorized" }); | ||
} | ||
|
||
const user = await authRepository.findUserByAttributes("id", decoded.id); | ||
|
||
if (!user) { | ||
res | ||
.status(httpStatus.UNAUTHORIZED) | ||
.json({ status: httpStatus.UNAUTHORIZED, message: "Not authorized" }); | ||
} | ||
|
||
if (!roles.includes(user.role)) { | ||
res | ||
.status(httpStatus.UNAUTHORIZED) | ||
.json({ status: httpStatus.UNAUTHORIZED, message: "Not authorized" }); | ||
} | ||
|
||
req.user = user; | ||
req.session = session; | ||
next(); | ||
} catch (error: any) { | ||
res.status(httpStatus.INTERNAL_SERVER_ERROR).json({ | ||
status: httpStatus.INTERNAL_SERVER_ERROR, | ||
message: error.message, | ||
}); | ||
} | ||
}; | ||
}; |
Oops, something went wrong.