Skip to content

Commit

Permalink
feat(auth): Add interceptor to add jwt token in the requests
Browse files Browse the repository at this point in the history
  • Loading branch information
joaomfiumari authored and miltonbsn committed Sep 24, 2023
1 parent 84551cb commit 680f141
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 13 deletions.
13 changes: 11 additions & 2 deletions app/angular/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,16 @@ app.config(['$httpProvider', ($httpProvider) => {
config.url = `${apiUrl}${config.url}`
return config;
}
}))
}]);
}));
$httpProvider.interceptors.push(($injector) => ({
"request": (config) => {
if ($injector.get("AuthService").isAuthenticated()) {
config.headers["brx-access-token"] = $injector.get("AuthService").token;
}
return config;
}
}));
}]);

app.config([
"$urlRouterProvider",
Expand Down Expand Up @@ -228,6 +236,7 @@ app.run(function ($transitions, $rootScope, AuthService, $state) {
if (requireLogin) {
if (AuthService.isAuthenticated()) {
$rootScope.loggeduser = AuthService.loggeduser;
$rootScope.token = AuthService.token;
} else {
$state.go("login");
}
Expand Down
3 changes: 3 additions & 0 deletions app/angular/service/authService.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const authService = function ($http, $cookies) {
$cookies.put("sessionId", user.sessionId, { expires: expired });
$cookies.put("userId", user.userId, { expires: expired });
$cookies.put("userName", user.userName, { expires: expired });
$cookies.put("userToken", user.token, { expires: expired });
return user;
});
};
Expand All @@ -25,6 +26,7 @@ const authService = function ($http, $cookies) {
$cookies.remove("sessionId");
$cookies.remove("userId");
$cookies.remove("userName");
$cookies.remove("userToken");
};

service.register = function (credentials) {
Expand All @@ -39,6 +41,7 @@ const authService = function ($http, $cookies) {
const userId = $cookies.get("userId");
service.loggeduser = userId;
service.loggeduserName = $cookies.get("userName");
service.token = $cookies.get("userToken");
return !!userId;
};

Expand Down
67 changes: 59 additions & 8 deletions server_app/model/handler.test.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,36 @@
const request = require("supertest");
const fs = require("fs");
const app = require("../app");

jest.mock("./service");
jest.mock('jsonwebtoken');
process.env.SECRET_TOKEN = 'mockSecretToken';


const mockModelService = require("./service");
const { encrypt } = require("../helpers/crypto");

jest.mock('../helpers/config', () => ({
SecretToken: 'mockSecretToken',
}));
jest.mock('jsonwebtoken', () => ({
...jest.requireActual('jsonwebtoken'), // import and keep all other methods unchanged
sign: jest.fn(() => 'mockedToken'),
verify: jest.fn((token, secret, cb) => {
cb(null, { id: 'global-user-id' });
}),
}));


afterEach(() => {
jest.restoreAllMocks();
jest.clearAllMocks();
});


describe("Test save /models", () => {
test("It should send 422 when validation fails", async () => {
const response = await request(app)
.post("/models")
.set("brx-access-token", 'mockToken')
.send({
name: "Teste",
type: "conceptual",
Expand All @@ -25,6 +42,7 @@ describe("Test save /models", () => {
test("It should send 200 when user model is saved", async () => {
const response = await request(app)
.post("/models")
.set("brx-access-token", 'mockToken')
.send({
name: "Teste",
type: "conceptual",
Expand All @@ -49,7 +67,10 @@ describe("Test list all /models", () => {
});

test("It should send 200 user exists", async () => {
const response = await request(app).get("/models").send([]);
const response = await request(app)
.get("/models")
.set("brx-access-token", 'mockToken')
.send([]);
mockModelService.listAll.mockResolvedValue([]);

expect(response.statusCode).toBe(200);
Expand Down Expand Up @@ -90,6 +111,7 @@ describe("Test export /models", () => {

const response = await request(app)
.get("/models/6179eacfc9cac3976aef0fec/export")
.set("brx-access-token", 'mockToken')
.send(encrypt(JSON.stringify(model)));

expect(response.header).toHaveProperty("content-type");
Expand All @@ -111,6 +133,7 @@ describe("Test export /models", () => {

const response = await request(app)
.get("/models/6179eacfc9cac3976aef0fec/export")
.set("brx-access-token", 'mockToken')
.send(encrypt(JSON.stringify(model)));

expect(response.statusCode).toBe(500);
Expand All @@ -123,27 +146,40 @@ describe("Test import /models", () => {
beforeEach(() => {
jest.resetModules();
process.env = { ...OLD_ENV };

});
afterAll(() => {
process.env = OLD_ENV;

});

const fileToUpload = `${__dirname}/test_files/test.brm`;
process.env.SECRET_TOKEN = "talkischeapshowmethecode";

test("It should return 400 when no file is uploaded", async () => {
const response = await request(app)
.post("/models/import")
.set("brx-access-token", 'mockToken')
.set("x-user-id", "6179eac1c9cac3976aef0fe8")
.attach("model", null, "test.brm");
.attach("model", null, "test01.brm");
expect(response.statusCode).toBe(400);
expect(mockModelService.save).not.toHaveBeenCalled();
});

test("It should return 422 when file is uploaded with any model validation error", async () => {
const jsonObject = {
name: "someName",
type: "someType",
model: {},
userId: "someUserId"
};
const jsonString = JSON.stringify(jsonObject);
const encryptedString = encrypt(jsonString);
const buffer = Buffer.from(encryptedString, 'utf-8');

const response = await request(app)
.post("/models/import")
.attach("model", fs.readFileSync(fileToUpload), "test.brm");
.attach("model", buffer, "test01.brm")
.set("brx-access-token", 'mockToken');

expect(response.statusCode).toBe(422);
expect(mockModelService.save).not.toHaveBeenCalled();
Expand All @@ -162,26 +198,41 @@ describe("Test import /models", () => {
__v: 0,
};
mockModelService.save.mockReturnValue(importedModel);
const jsonString = JSON.stringify(importedModel);
const encryptedString = encrypt(jsonString);
const buffer = Buffer.from(encryptedString, 'utf-8');

const response = await request(app)
.post("/models/import")
.set("brx-access-token", 'mockToken')
.set("x-user-id", "6179eac1c9cac3976aef0fe8")
.attach("model", fs.readFileSync(fileToUpload), "test.brm");
.attach("model", buffer, "test01.brm");

expect(response.statusCode).toBe(200);
expect(response.body).toEqual(importedModel);
expect(mockModelService.save).toHaveBeenCalled();
});

test("It should return 500 when model is not imported", async () => {

const jsonObject = {
name: "someName",
type: "someType",
model: {},
userId: "someUserId"
};
const jsonString = JSON.stringify(jsonObject);
const encryptedString = encrypt(jsonString);
const buffer = Buffer.from(encryptedString, 'utf-8');
mockModelService.save.mockImplementation(() => {
throw new Error();
});

const response = await request(app)
.post("/models/import")
.set("brx-access-token", 'mockToken')
.set("x-user-id", "6179eac1c9cac3976aef0fe8")
.attach("model", fs.readFileSync(fileToUpload), "test.brm");
.attach("model", buffer, "test01.brm");

expect(response.statusCode).toBe(500);
expect(mockModelService.save).toHaveBeenCalled();
Expand Down
Binary file removed server_app/model/test_files/test.brm
Binary file not shown.
28 changes: 25 additions & 3 deletions server_app/user/handler.test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,21 @@
const request = require("supertest");

const app = require("../app");
const mockUserService = require("./service");
jest.mock("./service");

jest.mock('../helpers/config', () => ({
SecretToken: 'mockSecretToken',
}));

jest.mock('jsonwebtoken', () => ({
...jest.requireActual('jsonwebtoken'), // import and keep all other methods unchanged
sign: jest.fn(() => 'mockedToken'),
verify: jest.fn((token, secret, cb) => {
cb(null, { id: 'global-user-id' });
}),
}));

describe("Test /users/login", () => {

test("It should response 422 when validation password fails", async () => {
Expand Down Expand Up @@ -71,7 +84,10 @@ describe("Test /users/create", () => {
describe("Test /users/delete", () => {

test("It should response 200 when user deleted", async () => {
const response = await request(app).delete("/users/delete").send({"userId": "63bb161ff8d5c483cb28047c"});
const response = await request(app)
.delete("/users/delete")
.set("brx-access-token", 'mockToken')
.send({"userId": "63bb161ff8d5c483cb28047c"});
mockUserService.deleteAccount.mockResolvedValueOnce(true);
expect(response.statusCode).toBe(200);
expect(mockUserService.deleteAccount).toHaveBeenCalled();
Expand All @@ -80,7 +96,10 @@ describe("Test /users/delete", () => {
test("It should response 500 when user has created models", async () => {
mockUserService.deleteAccount.mockReset();
mockUserService.deleteAccount.mockRejectedValueOnce(new Error('Async error message'));
const response = await request(app).delete("/users/delete").send({ "userId": "63bb161ff8d5c483cb28047c" });
const response = await request(app)
.delete("/users/delete")
.set("brx-access-token", 'mockToken')
.send({ "userId": "63bb161ff8d5c483cb28047c" });
expect(response.statusCode).toBe(500);
expect(mockUserService.deleteAccount).toHaveBeenCalled();
});
Expand All @@ -91,7 +110,10 @@ describe("Test /users/delete", () => {

mockUserService.deleteAccount.mockReset();
mockUserService.deleteAccount.mockRejectedValueOnce(modelsError);
const response = await request(app).delete("/users/delete").send({ "userId": "63bb161ff8d5c483cb28047c" });
const response = await request(app)
.delete("/users/delete")
.set("brx-access-token", 'mockToken')
.send({ "userId": "63bb161ff8d5c483cb28047c" });
expect(response.statusCode).toBe(400);
expect(mockUserService.deleteAccount).toHaveBeenCalled();
});
Expand Down

0 comments on commit 680f141

Please sign in to comment.