mirror of
https://github.com/dadosfera/maestro.git
synced 2026-08-31 19:58:21 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f6e4e88a5 | ||
|
|
32ab834834 | ||
|
|
ebbfe0abff | ||
|
|
d76a2b4ab8 | ||
|
|
047737eadd | ||
|
|
e20ae71672 | ||
|
|
97b6047cf1 | ||
|
|
9c6d2b499a | ||
|
|
f43c270c33 | ||
|
|
b0ccb39f2c | ||
|
|
9f900882cb | ||
|
|
a24abed9ed | ||
|
|
b04a38bcc0 | ||
|
|
67706c5fc3 | ||
|
|
0fa4dcb933 | ||
|
|
04284e1feb | ||
|
|
3e7581e20c | ||
|
|
c61c37b268 | ||
|
|
5ce8099c25 | ||
|
|
9cdb0a5d38 | ||
|
|
57f47d3b2e | ||
|
|
4ab955a7a1 | ||
|
|
1ca3694b75 | ||
|
|
a6a35c507a | ||
|
|
cfcb8c1c42 | ||
|
|
a55da8e20f | ||
|
|
82310c6314 | ||
|
|
52f9d06ad0 | ||
|
|
a83f91a720 | ||
|
|
ccef7628f9 | ||
|
|
a5e424c854 | ||
|
|
339432df16 | ||
|
|
7dfa10d5ee | ||
|
|
c87ceec77b | ||
|
|
071c524a2e | ||
|
|
1de4eedd38 | ||
|
|
29276d6070 | ||
|
|
344a251de1 | ||
|
|
3b95032554 | ||
|
|
a0089b5d5d | ||
|
|
1b620b6fb0 | ||
|
|
1eb76d4b1c | ||
|
|
314bc5a562 | ||
|
|
d01b0357ed | ||
|
|
a206aad8db | ||
|
|
de57bfed1e | ||
|
|
14cfc46492 | ||
|
|
9d10e58b1b | ||
|
|
6dec2c1e56 | ||
|
|
23a65d18a6 | ||
|
|
d5cd562860 | ||
|
|
f5064420a7 | ||
|
|
bb5befb2f6 | ||
|
|
398360fadb | ||
|
|
13072978f5 | ||
|
|
b9612609d9 | ||
|
|
e7b37629a1 | ||
|
|
5b6994b247 | ||
|
|
039f837914 | ||
|
|
83dcc7942c | ||
|
|
5c079bb4f5 | ||
|
|
f383cf49d5 | ||
|
|
db78ee3d8b | ||
|
|
730fab8ed1 | ||
|
|
04e1e1ff2b | ||
|
|
d309c20cbf | ||
|
|
4cff593695 | ||
|
|
03d42df3fd | ||
|
|
ea04f59e04 | ||
|
|
d1961a9710 | ||
|
|
358dd6a15a | ||
|
|
cc3b34d87e | ||
|
|
88bc7fe625 | ||
|
|
137f129e13 | ||
|
|
f49c5ac1c1 | ||
|
|
d288a4f357 | ||
|
|
9f009309cb | ||
|
|
395db05b05 | ||
|
|
2d69e6db70 | ||
|
|
9514134db1 | ||
|
|
0c69cebca1 | ||
|
|
9791b8bdb0 | ||
|
|
6803ab3420 | ||
|
|
6aa7be98d2 | ||
|
|
f5665557c9 | ||
|
|
366987399e | ||
|
|
4356adea65 | ||
|
|
4c49dbc0ea | ||
|
|
59ffb24985 | ||
|
|
1cd191e970 | ||
|
|
7e92ca2c36 | ||
|
|
12af510d36 | ||
|
|
61871958aa | ||
|
|
64d84f9148 | ||
|
|
2c099ba491 | ||
|
|
65b2578f15 | ||
|
|
8d23eaeea2 |
@@ -6,6 +6,7 @@ module.exports = {
|
||||
},
|
||||
plugins: ['@typescript-eslint/eslint-plugin'],
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:prettier/recommended',
|
||||
],
|
||||
|
||||
@@ -35,9 +35,7 @@ jobs:
|
||||
semantic_release:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
#new_release_published: ${{ steps.semantic.outputs.last_release_version != steps.semantic.outputs.new_release_version }}
|
||||
new_release_published: ${{ steps.semantic.outputs.new_release_published }}
|
||||
#new_release_version: ${{ steps.semantic.outputs.new_release_version }}
|
||||
new_release_version: ${{ (steps.semantic.outputs.new_release_published == 'true' && steps.semantic.outputs.new_release_version) || (github.event_name == 'workflow_dispatch' && '0.0.0') }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -57,7 +55,6 @@ jobs:
|
||||
]
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
deploy:
|
||||
if: ${{ github.event_name == 'workflow_dispatch' || needs.semantic_release.outputs.new_release_published == 'true' }}
|
||||
@@ -107,9 +104,8 @@ jobs:
|
||||
ENV: ${{ needs.extract_environment.outputs.environment }}
|
||||
IMAGE_TAG: ${{ needs.semantic_release.outputs.new_release_version }}
|
||||
ACCOUNT_ID: ${{ steps.aws.outputs.aws-account-id }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
docker-compose -f build.docker-compose.yml build --build-arg NPM_TOKEN=${NPM_TOKEN}
|
||||
docker-compose -f build.docker-compose.yml build
|
||||
docker-compose -f build.docker-compose.yml push
|
||||
|
||||
- name: Create ZIP file to Deploy AWS Beanstalk
|
||||
|
||||
@@ -2,8 +2,6 @@ name: Test
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- alpha
|
||||
- beta
|
||||
- main
|
||||
|
||||
jobs:
|
||||
@@ -21,23 +19,22 @@ jobs:
|
||||
env:
|
||||
ENV: test
|
||||
IMAGE_TAG: test
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
export ENV=test
|
||||
export IMAGE_TAG=test
|
||||
export ACCOUNT_ID=test
|
||||
docker-compose -f build.docker-compose.yml build --build-arg NPM_TOKEN=${NPM_TOKEN}
|
||||
docker-compose -f build.docker-compose.yml build
|
||||
|
||||
- name: Run Test
|
||||
env:
|
||||
ENV: test
|
||||
IMAGE_TAG: test
|
||||
ACCOUNT_ID: test
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
APP_NAME: ${{ github.event.repository.name }}
|
||||
run: |
|
||||
export ENV=test
|
||||
export IMAGE_TAG=test
|
||||
docker-compose -f build.docker-compose.yml run -e NPM_TOKEN=${NPM_TOKEN} --rm --entrypoint="npm run test" maestro
|
||||
docker-compose -f build.docker-compose.yml run --rm --entrypoint="npm run test" $APP_NAME
|
||||
|
||||
- name: Remove Docker's Trash
|
||||
if: always()
|
||||
|
||||
@@ -26,7 +26,6 @@
|
||||
"preset": "eslint"
|
||||
}
|
||||
],
|
||||
"@semantic-release/npm",
|
||||
"@semantic-release/github"
|
||||
]
|
||||
}
|
||||
|
||||
+6
-13
@@ -1,23 +1,16 @@
|
||||
FROM node:18.3.0-alpine3.15 as packages
|
||||
WORKDIR /packages
|
||||
ARG NPM_TOKEN
|
||||
COPY package.json .
|
||||
COPY package-lock.json .
|
||||
COPY .npmrc .
|
||||
RUN apk update \
|
||||
&& apk add --no-cache aws-cli \
|
||||
&& aws codeartifact login --tool npm --repository dadosfera-npm --domain dadosfera --domain-owner 611330257153 --region us-east-1 \
|
||||
&& npm install
|
||||
|
||||
RUN apk update && apk add curl unzip
|
||||
RUN apk add --no-cache aws-cli
|
||||
|
||||
RUN aws codeartifact login --tool npm --repository dadosfera-npm --domain dadosfera --domain-owner 611330257153 --region us-east-1
|
||||
|
||||
RUN npm install
|
||||
RUN rm -f ./.npmrc
|
||||
|
||||
FROM node:14.15.4-alpine3.12
|
||||
FROM node:18.3.0-alpine3.15
|
||||
WORKDIR /app
|
||||
COPY . /app/
|
||||
ARG NPM_TOKEN
|
||||
COPY --from=packages /packages/node_modules /app/node_modules
|
||||
RUN npm run build
|
||||
EXPOSE 3333
|
||||
ENTRYPOINT npm run start
|
||||
ENTRYPOINT npm run start
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,50 +1,301 @@
|
||||
# Maestro
|
||||
<p align="center">
|
||||
<image src="./assets/maestro.svg" style="width:10rem">
|
||||
<h1 align="center">Maestro</h1>
|
||||
</p>
|
||||
This is the Dadosfera´s gateway repository, it´s responsable for the communication between frontend application and Dadosfera´s mirosservices.
|
||||
|
||||
## 💻 Requirements
|
||||
# Maestro
|
||||
Maestro is the Dadosfera's gateway, it's responsible for the communication between the frontend application and Dadosfera's microservices.
|
||||
|
||||
Before you start, make sure you have done the following steps:
|
||||
## 🚀 Starting
|
||||
These instructions will allow you to get a working copy of the project on your local machine for development and testing purposes.
|
||||
|
||||
* Installed Nodejs version 16.14.2
|
||||
* Installed latest NPM version
|
||||
### 📋 Requirements
|
||||
- [NodeJS v18.3.0 LTS / NPM v8.11](https://nodejs.org/pt-br/download/) (you can opt to use [NVM](https://github.com/nvm-sh/nvm) to easily manage node versions)
|
||||
- Request access to AWS Console dev account for **all services** (avoid gradually asking for each needed service. it will slow down your development cycle)
|
||||
- Create your Access Key on the "Security credentials" menu
|
||||
- Set the Access Key on your local development machine
|
||||
- Request access to the dev, stg and prd VPNs
|
||||
|
||||
### 🔧 Installation<a id="installation"></a>
|
||||
- Clone the repository
|
||||
- SSH
|
||||
```
|
||||
git clone git@github.com:dadosfera/maestro.git
|
||||
```
|
||||
or
|
||||
|
||||
- HTTPS
|
||||
```
|
||||
git clone https://github.com/dadosfera/maestro.git
|
||||
```
|
||||
|
||||
## 🚀 Installing Maestro
|
||||
- Select the correct node version (optional, only if using [NVM](https://github.com/nvm-sh/nvm)):
|
||||
```sh
|
||||
nvm use
|
||||
```
|
||||
|
||||
First of all clone the repository:
|
||||
* SSH:
|
||||
```
|
||||
git clone git@github.com:dadosfera/maestro.git
|
||||
```
|
||||
* HTTPS:
|
||||
```
|
||||
git clone git@github.com:dadosfera/maestro.git
|
||||
- Install the project dependencies:
|
||||
```sh
|
||||
npm i
|
||||
```
|
||||
|
||||
- Setup the following enviroment variables:
|
||||
```
|
||||
ENV=
|
||||
DUC_URL=
|
||||
INFACTORY_URL=
|
||||
OTFACTORY_URL=
|
||||
PIFACTORY_URL=
|
||||
SM_OAUTH_PATH=
|
||||
```
|
||||
|
||||
- Start the server:
|
||||
```sh
|
||||
# dev mode
|
||||
npm run start:dev
|
||||
|
||||
# or in debug mode
|
||||
npm run start:debug
|
||||
```
|
||||
The service should start successfully.
|
||||
|
||||
## Authentication decorators
|
||||
Maestro have utilities to ease the user authentication on every controller and route. The following decorators are available:
|
||||
|
||||
### `@Authenticated`
|
||||
If the user must be authenticated to make request, we can use the `@Authenticated` decorator in the controller or route, as needed.
|
||||
|
||||
```ts
|
||||
import { Authenticated } from '../../authentication/authentication.decorator';
|
||||
|
||||
@Controller('foo')
|
||||
@Authenticated()
|
||||
class FooController {
|
||||
/* ... */
|
||||
|
||||
@Get('bar')
|
||||
async getBar() {
|
||||
this.logger.info('user is authenticated!');
|
||||
|
||||
return { authenticated: true };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Enviroment variables
|
||||
```ts
|
||||
import { Authenticated } from '../../authentication/authentication.decorator';
|
||||
|
||||
Here is a list of enviroment variables needed in order to run the application correctly.
|
||||
@Controller('foo')
|
||||
class FooController {
|
||||
/* ... */
|
||||
|
||||
```
|
||||
ENV=
|
||||
DUC_URL=
|
||||
INFACTORY_URL=
|
||||
TRFACTORY_URL=
|
||||
OTFACTORY_URL=
|
||||
PIFACTORY_URL=
|
||||
JWT_PRIVATE_KEY=
|
||||
AWS_IDENTITY_POOL_ID=
|
||||
@Get('bar')
|
||||
@Authenticated()
|
||||
async getBar() {
|
||||
this.logger.info('user is authenticated!');
|
||||
|
||||
return { authenticated: true };
|
||||
}
|
||||
|
||||
@Post('bar')
|
||||
async postBar() {
|
||||
this.logger.info('user is NOT authenticated!');
|
||||
|
||||
return { authenticated: false };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Running Maestro
|
||||
### `@RequireAllPermissions`
|
||||
This decorator requires that **all permissions** listed are granted to the requesting user.
|
||||
|
||||
In order to run Maestro just run the following command:
|
||||
```ts
|
||||
import { RequireAllPermissions } from '../../authentication/authentication.decorator';
|
||||
import { Permissions } from '../../authentication/permissions.enum';
|
||||
|
||||
@Controller('foo')
|
||||
class FooController {
|
||||
/* ... */
|
||||
|
||||
@Get('bar')
|
||||
@RequireAllPermissions(Permissions.BAR.MANAGE, Permissions.BAR.CREATE)
|
||||
async getBar() {
|
||||
/* ... */
|
||||
}
|
||||
}
|
||||
```
|
||||
npm run start:dev
|
||||
|
||||
### `@RequireSomePermission`
|
||||
In the following case, the user is required to have **at least one** listed permission.
|
||||
|
||||
```ts
|
||||
import { RequireSomePermission } from '../../authentication/authentication.decorator';
|
||||
import { Permissions } from '../../authentication/permissions.enum';
|
||||
|
||||
@Controller('foo')
|
||||
@RequireSomePermission(Permissions.FOO.MANAGE, Permissions.FOO.CREATE)
|
||||
class FooController {
|
||||
/* ... */
|
||||
|
||||
@Get('bar')
|
||||
async getBar() {
|
||||
/* ... */
|
||||
}
|
||||
}
|
||||
```
|
||||
If everything is fine the Maestro will start and be ready to receive HTTP requests
|
||||
|
||||
### `@AuthenticateCondition`
|
||||
If a more complicated authentication check needs to be done, we can use the `@AuthenticateCondition` decorator to define it. The custom function must return `true` to authenticate the request.
|
||||
|
||||
In the following example:
|
||||
- all routes on the `FooController` controller can only be requested from localhost
|
||||
- `POST /foo/bar` can only be requested from localhost **and** by users from customer id `111...eef`
|
||||
|
||||
```ts
|
||||
import { AuthenticateCondition } from '../../authentication/authentication.decorator';
|
||||
|
||||
@Controller('foo')
|
||||
// allow requests only from localhost
|
||||
@AuthenticateCondition((request: Request) => request.ip === '::ffff:127.0.0.1')
|
||||
class FooController {
|
||||
/* ... */
|
||||
|
||||
@Get('bar')
|
||||
async getBar() {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
@Post('bar')
|
||||
// allow requests only from a specific customer
|
||||
@AuthenticateCondition((request: Request, user: RequestUser) => user.customer_id === '1113e943-2187-4fdd-9c2c-54338fedaeef')
|
||||
async postBar() {
|
||||
/* ... */
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Note on authentication decorators
|
||||
- The old authentication method placed the user data in the `request.body.info` field, this imposes certain issues regarding the request body because this data should be from the frontend without any modification by Maestro. Now this usage is ⚠️ **DEPRECATED** ⚠️. We are working to migrate to the `@User` parameter decorator. The old method is working while the migration is in progress.
|
||||
|
||||
- Authentication decorators can be used together and all of them **must** pass to the request be authenticated, but in the general case you don't need to (*and wouldn't like to...*) use all of them together, as you can code all of the authentication logic in the `@AuthenticateCondition` decorator.
|
||||
|
||||
```ts
|
||||
import {
|
||||
RequireAllPermissions,
|
||||
RequireSomePermission,
|
||||
AuthenticateCondition,
|
||||
} from '../../authentication/authentication.decorator';
|
||||
import { Permissions } from '../../authentication/permissions.enum';
|
||||
import { Waa, Baz } from './authenticationFunctions'
|
||||
|
||||
@Controller('foo')
|
||||
@RequireAllPermissions(Permissions.FOO.USE, Permissions.FOO.REQUEST)
|
||||
@RequireSomePermission(Permissions.FOO.MANAGE, Permissions.FOO.ADMIN)
|
||||
@AuthenticateCondition(Waa)
|
||||
@AuthenticateCondition(Baz)
|
||||
class FooController {
|
||||
/* ... */
|
||||
|
||||
@Get('bar')
|
||||
async getBar() {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
@Post('bar')
|
||||
@RequireAllPermissions(Permissions.BAR.MANAGE, Permissions.BAR.USE, Permissions.BAR.REQUEST)
|
||||
async postBar() {
|
||||
/* ... */
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- If `@RequireAllPermissions` and `@RequireSomePermission` are used with **only a single permission**, they present the **exactly same behavior**.
|
||||
|
||||
```ts
|
||||
// same behavior
|
||||
@RequireAllPermissions(Permissions.BAR.MANAGE)
|
||||
@RequireSomePermission(Permissions.BAR.MANAGE)
|
||||
```
|
||||
|
||||
|
||||
|
||||
## `@User` parameter decorator
|
||||
The requesting user data can be obtained using the @User parameter decorator, like in the following snippet:
|
||||
|
||||
```ts
|
||||
import { User, RequestUser } from '../../authentication/user.decorator';
|
||||
|
||||
@Controller('foo')
|
||||
class FooController {
|
||||
/* ... */
|
||||
|
||||
@Get('bar')
|
||||
async getBar(@User() user: RequestUser) {
|
||||
this.logger.info(user);
|
||||
|
||||
return { user };
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If the user is required to be logged in, set `required` to `true`, as you would want in the `change-password` operation:
|
||||
|
||||
```ts
|
||||
import { User, RequestUser } from '../../authentication/user.decorator';
|
||||
|
||||
@Controller('user')
|
||||
class UserController {
|
||||
/* ... */
|
||||
|
||||
@Post('change-password')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async changePassword(
|
||||
@User({ required: true }) user: RequestUser,
|
||||
@Body() body: AuthChangePasswordRequest,
|
||||
) {
|
||||
const { oldPassword, newPassword } = body;
|
||||
|
||||
return this.authClient.changePassword({
|
||||
userId: user.user_id,
|
||||
oldPassword,
|
||||
newPassword,
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 📦 Development
|
||||
### ⌨️ Coding Style
|
||||
By default, we use [ESLint](https://eslint.org/) + [Prettier](https://prettier.io/) with default settings.
|
||||
|
||||
**We recommend using Visual Studio Code and installing the recommended extensions to ease the development process.**
|
||||
|
||||
### Commits pattern
|
||||
Our workflow pipeline follows the conventional commits specs ([cheat sheets](https://cheatography.com/albelop/cheat-sheets/conventional-commits/)) to release versions accordingly.
|
||||
|
||||
Format: `<type>[optional scope]: <description>`
|
||||
|
||||
Example: `FIX: ensure Range headers adhere more closely to RFC 2616`
|
||||
|
||||
### Branching naming convention
|
||||
- **Feature**: Any code changes for a new module or use case should be done on a feature branch. This branch is created based on the `main` branch. When all changes are done, a Pull Request/Merge Request is needed to put all of these changes back to the `main` branch. Examples: `feature/integrate-swagger`, `feature/JIRA-1234`, `feature/JIRA-1234_support-dark-theme`.
|
||||
|
||||
**It is recommended to use all lower caps letters and hyphen (-) to separate words unless it is a specific item name or ID. Underscore (_) could be used to separate the ID and description.**
|
||||
|
||||
- **Bug Fix**: If the code changes made from the feature branch were rejected after a release, sprint or demo, any necessary fixes after that should be done on the bugfix branch. Examples: `bugfix/more-gray-shades`, `bugfix/JIRA-1444_gray-on-blur-fix`.
|
||||
|
||||
- **Hot Fix**: If there is a need to fix a blocker, do a temporary patch, apply a critical framework or configuration change that should be handled immediately, it should be created as a Hotfix. Examples: `hotfix/disable-endpoint-zero-day-exploit`, `hotfix/increase-scaling-threshold`.
|
||||
|
||||
- **Experimental**: A branch for playing around. Any new feature or idea that is not part of a release or a sprint. Example: `experimental/dark-theme-support`.
|
||||
|
||||
### Making a Pull Request
|
||||
1. Commit your changes
|
||||
2. Open the Pull Request on GitHub
|
||||
3. Send Pull Request link in microsfera Google Chat Group for review and possible approval
|
||||
|
||||
## 🛠️ Built with
|
||||
Some technologies used in this project:
|
||||
|
||||
- [NestJS](https://docs.nestjs.com) - Framework for building efficient and scalable NodeJS server-side applications
|
||||
|
||||
## ⚙️ Back-end Architecture
|
||||
The architecture can be found at [this link](https://sites.google.com/dadosfera.ai/wikidoproduto/time/back-end).
|
||||
|
||||
+5
-1
@@ -3,7 +3,11 @@
|
||||
"sourceRoot": "src",
|
||||
"compilerOptions": {
|
||||
"assets": [
|
||||
"**/*.proto"
|
||||
"**/*.proto",
|
||||
{
|
||||
"include": "i18n/**/*",
|
||||
"watchAssets": true
|
||||
}
|
||||
],
|
||||
"plugins": [
|
||||
"@nestjs/swagger"
|
||||
|
||||
Generated
+73
-15
@@ -35,8 +35,8 @@
|
||||
"passport-google-oauth20": "^2.0.0",
|
||||
"passport-hubspot-oauth2": "^1.0.3",
|
||||
"passport-mailchimp": "^1.1.0",
|
||||
"protospack": "2.5.1",
|
||||
"protospack-v2": "1.1.1",
|
||||
"protospack": "2.5.2",
|
||||
"protospack-v2": "3.9.6",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"rxjs": "^7.5.5",
|
||||
@@ -4237,6 +4237,17 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/class-validator": {
|
||||
"version": "0.13.2",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/class-validator/-/class-validator-0.13.2.tgz",
|
||||
"integrity": "sha512-yBUcQy07FPlGzUjoLuUfIOXzgynnQPPruyK1Ge2B74k9ROwnle1E+NxLWnUv5OLU8hA/qL5leAE9XnXq3byaBw==",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"libphonenumber-js": "^1.9.43",
|
||||
"validator": "^13.7.0"
|
||||
}
|
||||
},
|
||||
"node_modules/cli-cursor": {
|
||||
"version": "3.1.0",
|
||||
"dev": true,
|
||||
@@ -7823,6 +7834,13 @@
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/libphonenumber-js": {
|
||||
"version": "1.10.7",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/libphonenumber-js/-/libphonenumber-js-1.10.7.tgz",
|
||||
"integrity": "sha512-jZXLCCWMe1b/HXkjiLeYt2JsytZMcqH26jLFIdzFDFF0xvSUWrYKyvPlyPG+XJzEyKUFbcZxLdWGMwQsWaHDxQ==",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/lines-and-columns": {
|
||||
"version": "1.2.4",
|
||||
"dev": true,
|
||||
@@ -8989,18 +9007,19 @@
|
||||
}
|
||||
},
|
||||
"node_modules/protospack": {
|
||||
"version": "2.5.1",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/protospack/-/protospack-2.5.1.tgz",
|
||||
"integrity": "sha512-4JTx7B7WxpC1G3S8T7SUEAEgVM9UjdYrOG37fr42wKxl9y6wOyCZJYjG/lXeAqFXOEPj9KSlM+MqBfLIMHWHeA==",
|
||||
"version": "2.5.2",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/protospack/-/protospack-2.5.2.tgz",
|
||||
"integrity": "sha512-t7NyWE4WDuAVixjL10SDUXHu8iW4H0azndTC3n/w335D/IodPgN47ebm3iMXbvoQTlQcCbjjc+HblaRa9oR8bA==",
|
||||
"dependencies": {
|
||||
"rxjs": "^7.5.5"
|
||||
}
|
||||
},
|
||||
"node_modules/protospack-v2": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/protospack-v2/-/protospack-v2-1.1.1.tgz",
|
||||
"integrity": "sha512-BqIJSORaqauAT9kF4/cP/uJNCyoT3KxkVkamd7SWARMxnywFB/mpYJg/VDGcyvVOAU4IOLyjnXkrvRuylE0Q2w==",
|
||||
"version": "3.9.6",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/protospack-v2/-/protospack-v2-3.9.6.tgz",
|
||||
"integrity": "sha512-7aSYhzxlly6GPGmCH2JsNDB3Z6rOPhmY5iK5n1Ich3WLLgsOmGAXJH2zWD9IUfjhKKwBZGvitdewpBVyCvAg0A==",
|
||||
"dependencies": {
|
||||
"@grpc/grpc-js": "^1.6.7",
|
||||
"rxjs": "^7.5.5",
|
||||
"ts-proto": "^1.112.2"
|
||||
}
|
||||
@@ -9868,8 +9887,9 @@
|
||||
},
|
||||
"node_modules/supertest": {
|
||||
"version": "6.2.3",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/supertest/-/supertest-6.2.3.tgz",
|
||||
"integrity": "sha512-3GSdMYTMItzsSYjnIcljxMVZKPW1J9kYHZY+7yLfD0wpPwww97GeImZC1oOk0S5+wYl2niJwuFusBJqwLqYM3g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"methods": "^1.1.2",
|
||||
"superagent": "^7.1.3"
|
||||
@@ -10569,6 +10589,16 @@
|
||||
"node": ">=10.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/validator": {
|
||||
"version": "13.7.0",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/validator/-/validator-13.7.0.tgz",
|
||||
"integrity": "sha512-nYXQLCBkpJ8X6ltALua9dRrZDHVYxjJ1wgskNt1lH9fzGjs3tgojGSCBjmEPwkWS1y29+DrizMTW19Pr9uB2nw==",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/vary": {
|
||||
"version": "1.1.2",
|
||||
"license": "MIT",
|
||||
@@ -13968,6 +13998,17 @@
|
||||
"version": "1.2.2",
|
||||
"dev": true
|
||||
},
|
||||
"class-validator": {
|
||||
"version": "0.13.2",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/class-validator/-/class-validator-0.13.2.tgz",
|
||||
"integrity": "sha512-yBUcQy07FPlGzUjoLuUfIOXzgynnQPPruyK1Ge2B74k9ROwnle1E+NxLWnUv5OLU8hA/qL5leAE9XnXq3byaBw==",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"requires": {
|
||||
"libphonenumber-js": "^1.9.43",
|
||||
"validator": "^13.7.0"
|
||||
}
|
||||
},
|
||||
"cli-cursor": {
|
||||
"version": "3.1.0",
|
||||
"dev": true,
|
||||
@@ -16406,6 +16447,13 @@
|
||||
"type-check": "~0.4.0"
|
||||
}
|
||||
},
|
||||
"libphonenumber-js": {
|
||||
"version": "1.10.7",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/libphonenumber-js/-/libphonenumber-js-1.10.7.tgz",
|
||||
"integrity": "sha512-jZXLCCWMe1b/HXkjiLeYt2JsytZMcqH26jLFIdzFDFF0xvSUWrYKyvPlyPG+XJzEyKUFbcZxLdWGMwQsWaHDxQ==",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"lines-and-columns": {
|
||||
"version": "1.2.4",
|
||||
"dev": true
|
||||
@@ -17189,18 +17237,19 @@
|
||||
}
|
||||
},
|
||||
"protospack": {
|
||||
"version": "2.5.1",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/protospack/-/protospack-2.5.1.tgz",
|
||||
"integrity": "sha512-4JTx7B7WxpC1G3S8T7SUEAEgVM9UjdYrOG37fr42wKxl9y6wOyCZJYjG/lXeAqFXOEPj9KSlM+MqBfLIMHWHeA==",
|
||||
"version": "2.5.2",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/protospack/-/protospack-2.5.2.tgz",
|
||||
"integrity": "sha512-t7NyWE4WDuAVixjL10SDUXHu8iW4H0azndTC3n/w335D/IodPgN47ebm3iMXbvoQTlQcCbjjc+HblaRa9oR8bA==",
|
||||
"requires": {
|
||||
"rxjs": "^7.5.5"
|
||||
}
|
||||
},
|
||||
"protospack-v2": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/protospack-v2/-/protospack-v2-1.1.1.tgz",
|
||||
"integrity": "sha512-BqIJSORaqauAT9kF4/cP/uJNCyoT3KxkVkamd7SWARMxnywFB/mpYJg/VDGcyvVOAU4IOLyjnXkrvRuylE0Q2w==",
|
||||
"version": "3.9.6",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/protospack-v2/-/protospack-v2-3.9.6.tgz",
|
||||
"integrity": "sha512-7aSYhzxlly6GPGmCH2JsNDB3Z6rOPhmY5iK5n1Ich3WLLgsOmGAXJH2zWD9IUfjhKKwBZGvitdewpBVyCvAg0A==",
|
||||
"requires": {
|
||||
"@grpc/grpc-js": "^1.6.7",
|
||||
"rxjs": "^7.5.5",
|
||||
"ts-proto": "^1.112.2"
|
||||
}
|
||||
@@ -17790,6 +17839,8 @@
|
||||
},
|
||||
"supertest": {
|
||||
"version": "6.2.3",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/supertest/-/supertest-6.2.3.tgz",
|
||||
"integrity": "sha512-3GSdMYTMItzsSYjnIcljxMVZKPW1J9kYHZY+7yLfD0wpPwww97GeImZC1oOk0S5+wYl2niJwuFusBJqwLqYM3g==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"methods": "^1.1.2",
|
||||
@@ -18238,6 +18289,13 @@
|
||||
"source-map": "^0.7.3"
|
||||
}
|
||||
},
|
||||
"validator": {
|
||||
"version": "13.7.0",
|
||||
"resolved": "https://dadosfera-611330257153.d.codeartifact.us-east-1.amazonaws.com:443/npm/dadosfera-npm/validator/-/validator-13.7.0.tgz",
|
||||
"integrity": "sha512-nYXQLCBkpJ8X6ltALua9dRrZDHVYxjJ1wgskNt1lH9fzGjs3tgojGSCBjmEPwkWS1y29+DrizMTW19Pr9uB2nw==",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"vary": {
|
||||
"version": "1.1.2"
|
||||
},
|
||||
|
||||
+11
-5
@@ -36,13 +36,11 @@
|
||||
"@nestjs/platform-express": "^8.4.7",
|
||||
"@nestjs/schedule": "^1.1.0",
|
||||
"@nestjs/swagger": "^5.2.1",
|
||||
"protospack": "2.5.1",
|
||||
"protospack-v2": "1.1.1",
|
||||
"axios": "^0.25.0",
|
||||
"cron-parser": "^4.4.0",
|
||||
"dadosfera-logs": "^1.0.0-alpha.10",
|
||||
"elastic-apm-node": "^3.36.0",
|
||||
"dotenv": "^14.3.2",
|
||||
"elastic-apm-node": "^3.36.0",
|
||||
"helmet": "^5.1.0",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"jwk-to-pem": "^2.0.5",
|
||||
@@ -52,6 +50,8 @@
|
||||
"passport-google-oauth20": "^2.0.0",
|
||||
"passport-hubspot-oauth2": "^1.0.3",
|
||||
"passport-mailchimp": "^1.1.0",
|
||||
"protospack": "2.5.2",
|
||||
"protospack-v2": "3.9.6",
|
||||
"reflect-metadata": "^0.1.13",
|
||||
"rimraf": "^3.0.2",
|
||||
"rxjs": "^7.5.5",
|
||||
@@ -96,7 +96,13 @@
|
||||
"json",
|
||||
"ts"
|
||||
],
|
||||
"rootDir": "src",
|
||||
"rootDir": ".",
|
||||
"modulePaths": [
|
||||
"<rootDir>"
|
||||
],
|
||||
"moduleDirectories": [
|
||||
"node_modules"
|
||||
],
|
||||
"testRegex": ".*\\.spec\\.ts$",
|
||||
"transform": {
|
||||
"^.+\\.(t|j)s$": "ts-jest"
|
||||
@@ -107,4 +113,4 @@
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-24
@@ -1,13 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
import { InputsController } from './modules/inputs/inputs.controller';
|
||||
import { TransformationsController } from './modules/transformations/transformations.controller';
|
||||
import { OutputsController } from './modules/outputs/outputs.controllers';
|
||||
import { PipelinesController } from './modules/pipelines/pipelines.controller';
|
||||
import { AuthController } from './modules/auth/auth.controller';
|
||||
import { HealthController } from './modules/health/health.controller';
|
||||
|
||||
import { InputsService } from './modules/inputs/inputs.service';
|
||||
@@ -16,16 +13,13 @@ import { OutputsService } from './modules/outputs/outputs.service';
|
||||
import { PipelinesService } from './modules/pipelines/pipelines.service';
|
||||
import { HealthService } from './modules/health/health.service';
|
||||
|
||||
import { AuthClientService } from './clients/auth/client.service';
|
||||
import { InputsClientService } from './clients/inputs/client.service';
|
||||
import { TransformationsClientService } from './clients/transformations/client.service';
|
||||
import { OutputsClientService } from './clients/outputs/client.service';
|
||||
import { PipelinesClientService } from './clients/pipelines/client.service';
|
||||
import { PermissionsClientService } from './clients/permissions/client.service';
|
||||
|
||||
import { OutputsClientConfiguration } from './clients/outputs/client.config';
|
||||
import { TransformationsClientConfiguration } from './clients/transformations/client.config';
|
||||
import { DucClient } from './clients/duc/client.config';
|
||||
import { InputsClientConfiguration } from './clients/inputs/client.config';
|
||||
import { PipelinesClientConfiguration } from './clients/pipelines/client.config';
|
||||
import { CatalogController } from './modules/catalog/catalog.controller';
|
||||
@@ -39,16 +33,20 @@ import { APP_GUARD } from '@nestjs/core';
|
||||
import { GoogleStrategy } from './modules/oauth/passport-strategies/google-strategy';
|
||||
import { MailChimpStrategy } from './modules/oauth/passport-strategies/mailchimp-strategy';
|
||||
import { SalesforceStrategy } from './modules/oauth/passport-strategies/salesforce-strategy';
|
||||
import { ConnectorClientConfiguration } from './clients/connector/client.config';
|
||||
import { ConnectorController } from './modules/connector/connector.controller';
|
||||
import { ConnectorClientService } from './clients/connector/client.service';
|
||||
import { UsersModule } from './modules/users/users.module';
|
||||
import { RolesModule } from './modules/roles/roles.module';
|
||||
|
||||
import { ConnectorModule } from './modules/connector/connector.module';
|
||||
import { AuthModule } from './modules/auth/auth.module';
|
||||
import { PermissionsModule } from './modules/permissions/permissions.module';
|
||||
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { TermsOfUseModule } from './modules/termsOfUse/termsOfUse.module';
|
||||
|
||||
const ducClient = new DucClient();
|
||||
const inputClient = new InputsClientConfiguration();
|
||||
const outputClient = new OutputsClientConfiguration();
|
||||
const pipelineClient = new PipelinesClientConfiguration();
|
||||
const transformationClient = new TransformationsClientConfiguration();
|
||||
const connectorClient = new ConnectorClientConfiguration();
|
||||
|
||||
@Module({
|
||||
controllers: [
|
||||
@@ -56,11 +54,9 @@ const connectorClient = new ConnectorClientConfiguration();
|
||||
TransformationsController,
|
||||
OutputsController,
|
||||
PipelinesController,
|
||||
AuthController,
|
||||
HealthController,
|
||||
CatalogController,
|
||||
OauthController,
|
||||
ConnectorController,
|
||||
],
|
||||
providers: [
|
||||
DadosferaLogger,
|
||||
@@ -69,14 +65,11 @@ const connectorClient = new ConnectorClientConfiguration();
|
||||
TransformationsService,
|
||||
OutputsService,
|
||||
PipelinesService,
|
||||
ConnectorClientService,
|
||||
HealthService,
|
||||
InputsClientService,
|
||||
TransformationsClientService,
|
||||
OutputsClientService,
|
||||
PipelinesClientService,
|
||||
AuthClientService,
|
||||
PermissionsClientService,
|
||||
CatalogService,
|
||||
HubspotStrategy,
|
||||
FacebookStrategy,
|
||||
@@ -92,6 +85,10 @@ const connectorClient = new ConnectorClientConfiguration();
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
}),
|
||||
ConnectorModule,
|
||||
AuthModule,
|
||||
PermissionsModule,
|
||||
TermsOfUseModule,
|
||||
|
||||
ClientsModule.register([
|
||||
{
|
||||
@@ -106,19 +103,15 @@ const connectorClient = new ConnectorClientConfiguration();
|
||||
name: 'OUTPUTS_PACKAGE',
|
||||
...outputClient.config(),
|
||||
},
|
||||
{
|
||||
name: 'DUC_PACKAGE',
|
||||
...ducClient.config(),
|
||||
},
|
||||
{
|
||||
name: 'PIPELINES_PACKAGE',
|
||||
...pipelineClient.config(),
|
||||
},
|
||||
{
|
||||
name: 'CONNECTOR_PACKAGE',
|
||||
...connectorClient.config(),
|
||||
},
|
||||
]),
|
||||
|
||||
UsersModule,
|
||||
|
||||
RolesModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -1,28 +1,56 @@
|
||||
import { SetMetadata, applyDecorators } from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
import { Permission } from './permissions.enum';
|
||||
import { CustomDecorator } from '@nestjs/common';
|
||||
import { PermissionsObjectPermission } from './permissions.enum';
|
||||
import { RequestUser } from './user.decorator';
|
||||
|
||||
export const PERMISSIONS_KEY = '__PERMISSIONS__';
|
||||
export const MUST_BE_AUTHENTICATED_KEY = '__MUST_BE_AUTHENTICATED__';
|
||||
export const CUSTOM_AUTHENTICATION_FUNCTION_KEY =
|
||||
'__CUSTOM_AUTHENTICATION_FUNCTION__';
|
||||
export const AUTH_FUNCTION_KEY = '__AUTH_FUNCTION__';
|
||||
|
||||
export type AuthenticationFunction = (req: Request, user: any) => boolean;
|
||||
|
||||
export function RequirePermissions(...permissions: Permission[]) {
|
||||
return applyDecorators(
|
||||
SetMetadata(PERMISSIONS_KEY, permissions),
|
||||
SetMetadata(MUST_BE_AUTHENTICATED_KEY, true),
|
||||
// implementation copied from SetMetadata, but tweaked to get existing values
|
||||
// of the metadataKey and accumulate it with the new metadataValue
|
||||
function SetMultipleMetadata(metadataKey, metadataValue): CustomDecorator {
|
||||
const decoratorFactory = (target, key, descriptor) => {
|
||||
// .start: tweak
|
||||
// descriptor?.value = function decorator; target = class decorator
|
||||
const accumulatedVal =
|
||||
Reflect.getMetadata(metadataKey, descriptor?.value ?? target) ?? [];
|
||||
accumulatedVal.push(metadataValue);
|
||||
// .end: tweak
|
||||
|
||||
if (descriptor) {
|
||||
Reflect.defineMetadata(metadataKey, accumulatedVal, descriptor.value);
|
||||
return descriptor;
|
||||
}
|
||||
|
||||
Reflect.defineMetadata(metadataKey, accumulatedVal, target);
|
||||
return target;
|
||||
};
|
||||
|
||||
decoratorFactory.KEY = metadataKey;
|
||||
return decoratorFactory as any;
|
||||
}
|
||||
|
||||
export function RequireAllPermissions(
|
||||
...permissions: PermissionsObjectPermission[]
|
||||
) {
|
||||
return SetMultipleMetadata(AUTH_FUNCTION_KEY, (req, user: RequestUser) =>
|
||||
permissions.every(({ seqid }) => user.permissions.includes(seqid)),
|
||||
);
|
||||
}
|
||||
|
||||
export function RequireSomePermission(
|
||||
...permissions: PermissionsObjectPermission[]
|
||||
) {
|
||||
return SetMultipleMetadata(AUTH_FUNCTION_KEY, (req, user: RequestUser) =>
|
||||
permissions.some(({ seqid }) => user.permissions.includes(seqid)),
|
||||
);
|
||||
}
|
||||
|
||||
export function AuthenticateCondition(func: AuthenticationFunction) {
|
||||
return applyDecorators(
|
||||
SetMetadata(CUSTOM_AUTHENTICATION_FUNCTION_KEY, func),
|
||||
SetMetadata(MUST_BE_AUTHENTICATED_KEY, true),
|
||||
);
|
||||
return SetMultipleMetadata(AUTH_FUNCTION_KEY, func);
|
||||
}
|
||||
|
||||
export function Authenticated() {
|
||||
return SetMetadata(MUST_BE_AUTHENTICATED_KEY, true);
|
||||
return SetMultipleMetadata(AUTH_FUNCTION_KEY, () => true);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,457 @@
|
||||
import request from 'supertest';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { HttpStatus, INestApplication } from '@nestjs/common';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
import { Body, Controller, Get } from '@nestjs/common';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import {
|
||||
AuthenticateCondition,
|
||||
Authenticated,
|
||||
RequireAllPermissions,
|
||||
RequireSomePermission,
|
||||
} from './authentication.decorator';
|
||||
import { AuthenticationGuard } from './authentication.guard';
|
||||
import { PERMISSIONS } from './permissions.enum';
|
||||
import { AuthClientService } from '../modules/auth/auth.service';
|
||||
|
||||
import ErrorCodes from '../utils/errorCodes';
|
||||
|
||||
const logger = {
|
||||
info: (...args) => args,
|
||||
error: (...args) => args,
|
||||
};
|
||||
@Controller('no-class-auth')
|
||||
class NoClassAuthController {
|
||||
@Get('body')
|
||||
async getBody(@Body() body) {
|
||||
return { body };
|
||||
}
|
||||
|
||||
@Get('authenticated')
|
||||
@Authenticated()
|
||||
async mustBeAuthenticated(@Body() body) {
|
||||
return { body };
|
||||
}
|
||||
|
||||
@Get('required-permission')
|
||||
@RequireSomePermission(PERMISSIONS.ZENDESK.permissions.OPEN)
|
||||
async requiredPermission(@Body() body) {
|
||||
return { body };
|
||||
}
|
||||
|
||||
@Get('has-all-permissions')
|
||||
@RequireAllPermissions(
|
||||
PERMISSIONS.ZENDESK.permissions.OPEN,
|
||||
PERMISSIONS.METABASE.permissions.OPEN,
|
||||
)
|
||||
async hasAllPermissions(@Body() body) {
|
||||
return { body };
|
||||
}
|
||||
|
||||
@Get('has-some-permission')
|
||||
@RequireSomePermission(
|
||||
PERMISSIONS.ZENDESK.permissions.OPEN,
|
||||
PERMISSIONS.METABASE.permissions.OPEN,
|
||||
)
|
||||
async hasSomePermission(@Body() body) {
|
||||
return { body };
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('class-auth-condition')
|
||||
@AuthenticateCondition((req) => req.get('x-on-class') === 'ok')
|
||||
@RequireSomePermission(PERMISSIONS.METABASE.permissions.OPEN)
|
||||
class ClassAuthConditionController {
|
||||
@Get('body')
|
||||
async getBody(@Body() body) {
|
||||
return { body };
|
||||
}
|
||||
|
||||
@Get('authenticated')
|
||||
@Authenticated()
|
||||
async mustBeAuthenticated(@Body() body) {
|
||||
return { body };
|
||||
}
|
||||
|
||||
@Get('required-permission')
|
||||
@AuthenticateCondition((req) => req.get('x-on-route') === 'ok')
|
||||
@RequireSomePermission(PERMISSIONS.ZENDESK.permissions.OPEN)
|
||||
async requiredPermission(@Body() body) {
|
||||
return { body };
|
||||
}
|
||||
}
|
||||
|
||||
describe('authentication.guard', () => {
|
||||
let app: INestApplication;
|
||||
const jwtSecretA = {
|
||||
kid: 'token-a-testing-shared-key',
|
||||
pem: '$tr0ng-SH4Red-secr3t!!!~gl0ba1~]',
|
||||
};
|
||||
const jwtSecretB = {
|
||||
kid: 'token-b',
|
||||
pem: 'another-shared-token',
|
||||
};
|
||||
const fakeUserPayload = {
|
||||
user_id: 'd50d33c7-6c2b-463c-861f-e21667e7c125',
|
||||
username: 'super.admin',
|
||||
customer_id: '9d18e8ae-24b9-41a3-9e8f-a25ce57555b11',
|
||||
customer_name: 'dadosfera',
|
||||
customer_tier: 'BASIC',
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: AuthClientService,
|
||||
useValue: {
|
||||
getPublicKeys: async () => ({
|
||||
keys: [jwtSecretA, jwtSecretB],
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: DadosferaLogger,
|
||||
useValue: { logger },
|
||||
},
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: AuthenticationGuard,
|
||||
},
|
||||
],
|
||||
controllers: [NoClassAuthController, ClassAuthConditionController],
|
||||
}).compile();
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
function AssertBodyNoAuth(res: request.Response) {
|
||||
expect(res.statusCode).toBe(HttpStatus.OK);
|
||||
expect(res.body).toStrictEqual({ body: {} });
|
||||
}
|
||||
|
||||
function AssertBodyWithAuth(res: request.Response) {
|
||||
expect(res.statusCode).toBe(HttpStatus.OK);
|
||||
expect(res.body).toStrictEqual({
|
||||
body: {
|
||||
info: {
|
||||
customer: 'dadosfera',
|
||||
customer_id: '9d18e8ae-24b9-41a3-9e8f-a25ce57555b11',
|
||||
customer_tier: 'BASIC',
|
||||
user_id: 'd50d33c7-6c2b-463c-861f-e21667e7c125',
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function AssertUnauthorized(res: request.Response) {
|
||||
expect(res.statusCode).toBe(HttpStatus.UNAUTHORIZED);
|
||||
expect(res.body).toStrictEqual({
|
||||
code: ErrorCodes.AUTH.UNAUTHORIZED,
|
||||
error: 'Não autenticado',
|
||||
message: 'É necessário estar logado para realizar essa operação',
|
||||
statusCode: HttpStatus.UNAUTHORIZED,
|
||||
});
|
||||
}
|
||||
|
||||
function AssertForbidden(res: request.Response) {
|
||||
expect(res.statusCode).toBe(HttpStatus.FORBIDDEN);
|
||||
expect(res.body).toStrictEqual({
|
||||
code: ErrorCodes.AUTH.FORBIDDEN,
|
||||
error: 'Não autorizado',
|
||||
message:
|
||||
'Você não tem permissões suficientes para realizar essa operação',
|
||||
statusCode: HttpStatus.FORBIDDEN,
|
||||
});
|
||||
}
|
||||
|
||||
function NoClassAuthTest(accessToken: string, tokenName: string[]) {
|
||||
const route = '/no-class-auth';
|
||||
|
||||
describe(`${route}, ${tokenName?.length ? tokenName : 'none'} auth`, () => {
|
||||
it('should GET /body with user data (if available)', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/body`)
|
||||
.set({ Authorization: accessToken });
|
||||
|
||||
if (tokenName?.length) {
|
||||
AssertBodyWithAuth(res);
|
||||
} else {
|
||||
AssertBodyNoAuth(res);
|
||||
}
|
||||
});
|
||||
|
||||
it('should GET /authenticated if authenticated', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/authenticated`)
|
||||
.set({ Authorization: accessToken });
|
||||
|
||||
if (tokenName?.length) {
|
||||
AssertBodyWithAuth(res);
|
||||
} else {
|
||||
AssertUnauthorized(res);
|
||||
}
|
||||
});
|
||||
|
||||
it('should GET /required-permission if authenticated', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/required-permission`)
|
||||
.set({ Authorization: accessToken });
|
||||
|
||||
// zendesk required
|
||||
if (tokenName?.includes('zendesk')) {
|
||||
AssertBodyWithAuth(res);
|
||||
} else if (tokenName?.length) {
|
||||
AssertForbidden(res);
|
||||
} else {
|
||||
AssertUnauthorized(res);
|
||||
}
|
||||
});
|
||||
|
||||
it('should GET /has-all-permissions if authenticated', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/has-all-permissions`)
|
||||
.set({ Authorization: accessToken });
|
||||
|
||||
// zendesk and metabase
|
||||
if (tokenName?.includes('zendesk') && tokenName?.includes('metabase')) {
|
||||
AssertBodyWithAuth(res);
|
||||
} else if (tokenName?.length) {
|
||||
AssertForbidden(res);
|
||||
} else {
|
||||
AssertUnauthorized(res);
|
||||
}
|
||||
});
|
||||
|
||||
it('should GET /has-some-permission if authenticated', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/has-some-permission`)
|
||||
.set({ Authorization: accessToken });
|
||||
|
||||
// zendesk or metabase
|
||||
if (tokenName?.includes('zendesk') || tokenName?.includes('metabase')) {
|
||||
AssertBodyWithAuth(res);
|
||||
} else if (tokenName?.length) {
|
||||
AssertForbidden(res);
|
||||
} else {
|
||||
AssertUnauthorized(res);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function ClassAuthConditionTest(accessToken: string, tokenName: string[]) {
|
||||
const route = '/class-auth-condition';
|
||||
|
||||
describe(`${route}, ${tokenName?.length ? tokenName : 'none'} auth`, () => {
|
||||
describe('GET /body', () => {
|
||||
it('should GET /body if authenticated and with correct headers', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/body`)
|
||||
.set({
|
||||
'x-on-class': 'ok',
|
||||
Authorization: accessToken,
|
||||
});
|
||||
|
||||
// metabase required
|
||||
if (tokenName?.includes('metabase')) {
|
||||
AssertBodyWithAuth(res);
|
||||
} else if (tokenName?.length) {
|
||||
AssertForbidden(res);
|
||||
} else {
|
||||
AssertUnauthorized(res);
|
||||
}
|
||||
});
|
||||
|
||||
it('should not GET /body without correct headers', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/body`)
|
||||
.set({ Authorization: accessToken });
|
||||
|
||||
if (tokenName?.length) {
|
||||
AssertForbidden(res);
|
||||
} else {
|
||||
AssertUnauthorized(res);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /authenticated', () => {
|
||||
it('should GET /authenticated if authenticated and with correct headers', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/authenticated`)
|
||||
.set({
|
||||
'x-on-class': 'ok',
|
||||
Authorization: accessToken,
|
||||
});
|
||||
|
||||
// metabase required
|
||||
if (tokenName?.includes('metabase')) {
|
||||
AssertBodyWithAuth(res);
|
||||
} else if (tokenName?.length) {
|
||||
AssertForbidden(res);
|
||||
} else {
|
||||
AssertUnauthorized(res);
|
||||
}
|
||||
});
|
||||
|
||||
it('should not GET /authenticated without correct class headers', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/authenticated`)
|
||||
.set({ Authorization: accessToken });
|
||||
|
||||
if (tokenName?.length) {
|
||||
AssertForbidden(res);
|
||||
} else {
|
||||
AssertUnauthorized(res);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /required-permission', () => {
|
||||
it('should GET /required-permission if authenticated and with correct headers', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/required-permission`)
|
||||
.set({
|
||||
'x-on-class': 'ok',
|
||||
'x-on-route': 'ok',
|
||||
Authorization: accessToken,
|
||||
});
|
||||
|
||||
// zendesk and metabase
|
||||
if (
|
||||
tokenName?.includes('zendesk') &&
|
||||
tokenName?.includes('metabase')
|
||||
) {
|
||||
AssertBodyWithAuth(res);
|
||||
} else if (tokenName?.length) {
|
||||
AssertForbidden(res);
|
||||
} else {
|
||||
AssertUnauthorized(res);
|
||||
}
|
||||
});
|
||||
|
||||
it('should not GET /required-permission without correct route headers', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/required-permission`)
|
||||
.set({
|
||||
'x-on-class': 'ok',
|
||||
Authorization: accessToken,
|
||||
});
|
||||
|
||||
if (tokenName?.length) {
|
||||
AssertForbidden(res);
|
||||
} else {
|
||||
AssertUnauthorized(res);
|
||||
}
|
||||
});
|
||||
|
||||
it('should not GET /required-permission without correct class headers', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get(`${route}/required-permission`)
|
||||
.set({
|
||||
'x-on-route': 'ok',
|
||||
Authorization: accessToken,
|
||||
});
|
||||
|
||||
if (tokenName?.length) {
|
||||
AssertForbidden(res);
|
||||
} else {
|
||||
AssertUnauthorized(res);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
describe('token validation', () => {
|
||||
it('should accept token kid A', async () => {
|
||||
const Authorization = CreateToken([], {
|
||||
jwt: {
|
||||
kid: jwtSecretA.kid,
|
||||
pem: jwtSecretA.pem,
|
||||
},
|
||||
});
|
||||
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/no-class-auth/authenticated')
|
||||
.set({
|
||||
Authorization,
|
||||
});
|
||||
|
||||
AssertBodyWithAuth(res);
|
||||
});
|
||||
|
||||
it('should accept token kid B', async () => {
|
||||
const Authorization = CreateToken([], {
|
||||
jwt: {
|
||||
kid: jwtSecretB.kid,
|
||||
pem: jwtSecretB.pem,
|
||||
},
|
||||
});
|
||||
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/no-class-auth/authenticated')
|
||||
.set({
|
||||
Authorization,
|
||||
});
|
||||
|
||||
AssertBodyWithAuth(res);
|
||||
});
|
||||
|
||||
it('should not accept unknown kid', async () => {
|
||||
const Authorization = CreateToken([], {
|
||||
jwt: {
|
||||
kid: 'unknown-key-id',
|
||||
pem: jwtSecretA.pem,
|
||||
},
|
||||
});
|
||||
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/no-class-auth/authenticated')
|
||||
.set({
|
||||
Authorization,
|
||||
});
|
||||
|
||||
AssertUnauthorized(res);
|
||||
});
|
||||
});
|
||||
|
||||
function CreateToken(permissions, overrides?: { user?: any; jwt?: any }) {
|
||||
const tokenPayload = {
|
||||
...fakeUserPayload,
|
||||
permissions: permissions.map(({ seqid }) => seqid),
|
||||
token_use: 'access',
|
||||
...overrides?.user,
|
||||
};
|
||||
|
||||
return jwt.sign(tokenPayload, overrides?.jwt?.pem ?? jwtSecretA.pem, {
|
||||
keyid: overrides?.jwt?.kid ?? jwtSecretA.kid,
|
||||
});
|
||||
}
|
||||
|
||||
NoClassAuthTest(null, null);
|
||||
ClassAuthConditionTest(null, null);
|
||||
|
||||
const tokenZ = CreateToken([PERMISSIONS.ZENDESK.permissions.OPEN]);
|
||||
NoClassAuthTest(tokenZ, ['zendesk']);
|
||||
ClassAuthConditionTest(tokenZ, ['zendesk']);
|
||||
|
||||
const tokenM = CreateToken([PERMISSIONS.METABASE.permissions.OPEN]);
|
||||
NoClassAuthTest(tokenM, ['metabase']);
|
||||
ClassAuthConditionTest(tokenM, ['metabase']);
|
||||
|
||||
const tokenZM = CreateToken([
|
||||
PERMISSIONS.ZENDESK.permissions.OPEN,
|
||||
PERMISSIONS.METABASE.permissions.OPEN,
|
||||
]);
|
||||
NoClassAuthTest(tokenZM, ['zendesk', 'metabase']);
|
||||
ClassAuthConditionTest(tokenZM, ['zendesk', 'metabase']);
|
||||
});
|
||||
@@ -3,21 +3,18 @@ import {
|
||||
CanActivate,
|
||||
OnApplicationBootstrap,
|
||||
ExecutionContext,
|
||||
Logger,
|
||||
Inject,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import assert from 'assert';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { AuthClientService } from '../clients/auth/client.service';
|
||||
import { Permission } from './permissions.enum';
|
||||
import { AuthClientService } from '../modules/auth/auth.service';
|
||||
import {
|
||||
AuthenticationFunction,
|
||||
PERMISSIONS_KEY,
|
||||
CUSTOM_AUTHENTICATION_FUNCTION_KEY,
|
||||
MUST_BE_AUTHENTICATED_KEY,
|
||||
AUTH_FUNCTION_KEY,
|
||||
} from './authentication.decorator';
|
||||
import { RequestUser } from './user.decorator';
|
||||
import ErrorBuilder from '../utils/ErrorBuilder';
|
||||
import ErrorCodes from '../utils/errorCodes';
|
||||
|
||||
@@ -43,7 +40,7 @@ export class AuthenticationGuard
|
||||
return this.loadDucJWKS();
|
||||
}
|
||||
|
||||
async loadDucJWKS() {
|
||||
private async loadDucJWKS() {
|
||||
const { keys } = await this.authClient.getPublicKeys();
|
||||
|
||||
keys.forEach((key) => {
|
||||
@@ -52,57 +49,38 @@ export class AuthenticationGuard
|
||||
}
|
||||
|
||||
canActivate(ctx: ExecutionContext): boolean {
|
||||
const requiredPermissions = this.reflector.getAllAndOverride<Permission[]>(
|
||||
PERMISSIONS_KEY,
|
||||
[ctx.getHandler(), ctx.getClass()],
|
||||
);
|
||||
const customAuthenticationFunction =
|
||||
this.reflector.getAllAndOverride<AuthenticationFunction>(
|
||||
CUSTOM_AUTHENTICATION_FUNCTION_KEY,
|
||||
[ctx.getHandler(), ctx.getClass()],
|
||||
);
|
||||
const mustBeAuthenticated = this.reflector.getAllAndOverride<boolean>(
|
||||
MUST_BE_AUTHENTICATED_KEY,
|
||||
[ctx.getHandler(), ctx.getClass()],
|
||||
);
|
||||
const authFunctions = this.reflector.getAllAndMerge<
|
||||
AuthenticationFunction[]
|
||||
>(AUTH_FUNCTION_KEY, [ctx.getClass(), ctx.getHandler()]);
|
||||
const mustBeAuthenticated = authFunctions.length > 0;
|
||||
|
||||
const request = ctx.switchToHttp().getRequest();
|
||||
const accessToken = this.verifyToken(request, mustBeAuthenticated);
|
||||
const accessToken = this.validateToken(request, mustBeAuthenticated);
|
||||
|
||||
if (!mustBeAuthenticated) {
|
||||
// no need to be authenticated
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!accessToken) {
|
||||
// couldn't load valid token
|
||||
|
||||
if (!mustBeAuthenticated) {
|
||||
// no need to be authenticated
|
||||
return true;
|
||||
}
|
||||
|
||||
throw new ErrorBuilder(ErrorCodes.AUTH.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
if (
|
||||
typeof customAuthenticationFunction === 'function' &&
|
||||
!customAuthenticationFunction(request, request.user)
|
||||
) {
|
||||
// custom authentication function forbidden this request
|
||||
throw new ErrorBuilder(ErrorCodes.AUTH.FORBIDDEN);
|
||||
}
|
||||
|
||||
if (
|
||||
Array.isArray(requiredPermissions) &&
|
||||
requiredPermissions.length > 0 &&
|
||||
!this.matchPermissions(requiredPermissions, accessToken.permissions)
|
||||
) {
|
||||
// couldn't match permissions
|
||||
// every authentication function must return true to authenticate
|
||||
if (!authFunctions.every((func) => func(request, accessToken))) {
|
||||
throw new ErrorBuilder(ErrorCodes.AUTH.FORBIDDEN);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private verifyToken(request, mustBeAuthenticated: boolean) {
|
||||
private validateToken(
|
||||
request,
|
||||
mustBeAuthenticated: boolean,
|
||||
): RequestUser | false {
|
||||
const accessToken = request.get('Authorization');
|
||||
let accessTokenPayload;
|
||||
let accessTokenPayload: RequestUser;
|
||||
|
||||
// If the user isn't authenticated, an error will occurr anywhere here.
|
||||
// Fancy error avoidance isn't performed by purpose, such as avoiding to access null values.
|
||||
@@ -117,7 +95,7 @@ export class AuthenticationGuard
|
||||
);*/
|
||||
|
||||
assert(
|
||||
accessTokenDecoded.payload.token_use === 'access',
|
||||
accessTokenDecoded?.payload?.token_use === 'access',
|
||||
'should be an access token',
|
||||
);
|
||||
|
||||
@@ -129,7 +107,7 @@ export class AuthenticationGuard
|
||||
} catch (err) {
|
||||
// log errors if authentication is required
|
||||
if (mustBeAuthenticated) {
|
||||
this.logger.error('Unable to verify duc access token\n' + err.stack);
|
||||
this.logger.error('Unable to verify duc access token\n' + err?.stack);
|
||||
}
|
||||
|
||||
return false;
|
||||
@@ -143,6 +121,7 @@ export class AuthenticationGuard
|
||||
customer_id: accessTokenPayload.customer_id,
|
||||
customer_name: accessTokenPayload.customer_name,
|
||||
customer_tier: accessTokenPayload.customer_tier,
|
||||
access_token: accessToken,
|
||||
};
|
||||
// TODO: for backwards compatibility. remove in the future
|
||||
request.body.info = {
|
||||
@@ -154,13 +133,4 @@ export class AuthenticationGuard
|
||||
|
||||
return accessTokenPayload;
|
||||
}
|
||||
|
||||
private matchPermissions(
|
||||
requiredPermissions: Permission[],
|
||||
userPermissions: number[],
|
||||
) {
|
||||
return requiredPermissions.some((permission) =>
|
||||
userPermissions.includes(permission.seqid),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import assert from 'assert';
|
||||
import { LanguageEnum } from 'src/utils/languages.enum';
|
||||
|
||||
const logger = new Logger();
|
||||
|
||||
@@ -8,10 +9,24 @@ export enum PermissionUsages {
|
||||
INTERNAL = 'internal',
|
||||
}
|
||||
|
||||
export interface Permission {
|
||||
export interface PermissionsObjectPermission {
|
||||
seqid: number;
|
||||
claim: string;
|
||||
usage: PermissionUsages;
|
||||
name?: Record<LanguageEnum, string>;
|
||||
}
|
||||
export interface PermissionsObjectPermissionTranslated {
|
||||
seqid: number;
|
||||
claim: string;
|
||||
usage: PermissionUsages;
|
||||
name?: string;
|
||||
}
|
||||
export interface PermissionsObjectGroup {
|
||||
title: {
|
||||
'pt-br': string;
|
||||
'en-us': string;
|
||||
};
|
||||
permissions: Record<string, PermissionsObjectPermission>;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -22,216 +37,422 @@ export interface Permission {
|
||||
/*export const Permissions: {
|
||||
[P in keyof any]: { [Q in keyof any]: Permission };
|
||||
} = {*/
|
||||
export const Permissions = {
|
||||
export const PERMISSIONS = {
|
||||
AUTH: {
|
||||
CREATE: {
|
||||
seqid: 18,
|
||||
claim: 'POST /auth',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
title: {
|
||||
'pt-br': 'Autenticação',
|
||||
'en-us': 'Authentication',
|
||||
},
|
||||
permissions: {
|
||||
CREATE: {
|
||||
seqid: 18,
|
||||
claim: 'POST /auth',
|
||||
usage: PermissionUsages.INTERNAL,
|
||||
name: {
|
||||
'pt-br': '',
|
||||
'en-us': '',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
PIPELINE: {
|
||||
CREATE: {
|
||||
seqid: 23,
|
||||
claim: 'POST /pipelines',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
title: {
|
||||
'pt-br': 'Pipelines',
|
||||
'en-us': 'Pipelines',
|
||||
},
|
||||
GET: {
|
||||
seqid: 13,
|
||||
claim: 'GET /pipelines',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 29,
|
||||
claim: 'PUT /pipelines',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 5,
|
||||
claim: 'DELETE /pipelines',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
permissions: {
|
||||
CREATE: {
|
||||
seqid: 23,
|
||||
claim: 'POST /pipelines',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Criar pipelines',
|
||||
'en-us': 'Create pipelines',
|
||||
},
|
||||
},
|
||||
GET: {
|
||||
seqid: 13,
|
||||
claim: 'GET /pipelines',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Buscar pipelines',
|
||||
'en-us': 'Get pipelines',
|
||||
},
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 29,
|
||||
claim: 'PUT /pipelines',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Atualizar pipeline',
|
||||
'en-us': 'Update pipeline',
|
||||
},
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 5,
|
||||
claim: 'DELETE /pipelines',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Remover pipeline',
|
||||
'en-us': 'Delete pipeline',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
INPUT: {
|
||||
CREATE: {
|
||||
seqid: 21,
|
||||
claim: 'POST /inputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
title: {
|
||||
'pt-br': 'Conexões',
|
||||
'en-us': 'Connections',
|
||||
},
|
||||
GET: {
|
||||
seqid: 9,
|
||||
claim: 'GET /inputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 27,
|
||||
claim: 'PUT /inputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
UPDATE_PARTIAL: {
|
||||
seqid: 17,
|
||||
claim: 'PATCH /inputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 3,
|
||||
claim: 'DELETE /inputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
GET_ENTITIES: {
|
||||
seqid: 10,
|
||||
claim: 'GET /inputs/available-entities',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
permissions: {
|
||||
CREATE: {
|
||||
seqid: 21,
|
||||
claim: 'POST /inputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Criar conexões',
|
||||
'en-us': 'Create connections',
|
||||
},
|
||||
},
|
||||
GET: {
|
||||
seqid: 9,
|
||||
claim: 'GET /inputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Buscar conexões',
|
||||
'en-us': 'Get connections',
|
||||
},
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 27,
|
||||
claim: 'PUT /inputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Atualizar conexões',
|
||||
'en-us': 'Create connections',
|
||||
},
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 3,
|
||||
claim: 'DELETE /inputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Remover conexões',
|
||||
'en-us': 'Delete connections',
|
||||
},
|
||||
},
|
||||
GET_ENTITIES: {
|
||||
seqid: 10,
|
||||
claim: 'GET /inputs/available-entities',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Remover conexões',
|
||||
'en-us': 'Delete connections',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
OUTPUT: {
|
||||
CREATE: {
|
||||
seqid: 22,
|
||||
claim: 'POST /outputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
title: {
|
||||
'pt-br': 'Output',
|
||||
'en-us': 'Output',
|
||||
},
|
||||
GET: {
|
||||
seqid: 12,
|
||||
claim: 'GET /outputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 28,
|
||||
claim: 'PUT /outputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 4,
|
||||
claim: 'DELETE /outputs',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
permissions: {
|
||||
CREATE: {
|
||||
seqid: 22,
|
||||
claim: 'POST /outputs',
|
||||
usage: PermissionUsages.INTERNAL,
|
||||
name: {
|
||||
'pt-br': 'Criar outputs',
|
||||
'en-us': 'Create outputs',
|
||||
},
|
||||
},
|
||||
GET: {
|
||||
seqid: 12,
|
||||
claim: 'GET /outputs',
|
||||
usage: PermissionUsages.INTERNAL,
|
||||
name: {
|
||||
'pt-br': 'Buscar outputs',
|
||||
'en-us': 'Get outputs',
|
||||
},
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 28,
|
||||
claim: 'PUT /outputs',
|
||||
usage: PermissionUsages.INTERNAL,
|
||||
name: {
|
||||
'pt-br': 'Editar outputs',
|
||||
'en-us': 'Edit outputs',
|
||||
},
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 4,
|
||||
claim: 'DELETE /outputs',
|
||||
usage: PermissionUsages.INTERNAL,
|
||||
name: {
|
||||
'pt-br': 'Remover outputs',
|
||||
'en-us': 'Remove outputs',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
TRANSFORMATIONS: {
|
||||
CREATE: {
|
||||
seqid: 24,
|
||||
claim: 'POST /transformations',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
title: {
|
||||
'pt-br': 'Micro-transformações',
|
||||
'en-us': 'Micro-transformations',
|
||||
},
|
||||
GET: {
|
||||
seqid: 15,
|
||||
claim: 'GET /transformations',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 30,
|
||||
claim: 'PUT /transformations',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 6,
|
||||
claim: 'DELETE /transformations',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
permissions: {
|
||||
CREATE: {
|
||||
seqid: 24,
|
||||
claim: 'POST /transformations',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Criar micro-transformações',
|
||||
'en-us': 'Create micro-transformations',
|
||||
},
|
||||
},
|
||||
GET: {
|
||||
seqid: 15,
|
||||
claim: 'GET /transformations',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Buscar micro-transformações',
|
||||
'en-us': 'Get micro-transformations',
|
||||
},
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 30,
|
||||
claim: 'PUT /transformations',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Editar micro-transformações',
|
||||
'en-us': 'Edit micro-transformations',
|
||||
},
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 6,
|
||||
claim: 'DELETE /transformations',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Remover micro-transformações',
|
||||
'en-us': 'Remove micro-transformations',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
CATALOG: {
|
||||
CREATE: {
|
||||
seqid: 19,
|
||||
claim: 'POST /catalog',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
title: {
|
||||
'pt-br': 'Catálogo',
|
||||
'en-us': 'Catalog',
|
||||
},
|
||||
GET: {
|
||||
seqid: 7,
|
||||
claim: 'GET /catalog',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 25,
|
||||
claim: 'PUT /catalog',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 1,
|
||||
claim: 'DELETE /catalog',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
permissions: {
|
||||
CREATE: {
|
||||
seqid: 19,
|
||||
claim: 'POST /catalog',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Criar atributos no catálogo',
|
||||
'en-us': 'Create catalog attributes',
|
||||
},
|
||||
},
|
||||
GET: {
|
||||
seqid: 7,
|
||||
claim: 'GET /catalog',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Buscar catálogos',
|
||||
'en-us': 'Get catalogs',
|
||||
},
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 25,
|
||||
claim: 'PUT /catalog',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Editar catálogo',
|
||||
'en-us': 'Edit catalogs',
|
||||
},
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 1,
|
||||
claim: 'DELETE /catalog',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Remover catálogo',
|
||||
'en-us': 'Remove catalogs',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
CONNECTORS: {
|
||||
CREATE: {
|
||||
seqid: 20,
|
||||
claim: 'POST /connectors',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
title: {
|
||||
'pt-br': 'Conectores',
|
||||
'en-us': 'Connectors',
|
||||
},
|
||||
GET: {
|
||||
seqid: 8,
|
||||
claim: 'GET /connectors',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 26,
|
||||
claim: 'PUT /connectors',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 2,
|
||||
claim: 'DELETE /connectors',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
permissions: {
|
||||
CREATE: {
|
||||
seqid: 20,
|
||||
claim: 'POST /connectors',
|
||||
usage: PermissionUsages.INTERNAL,
|
||||
name: {
|
||||
'pt-br': 'Criar conectores',
|
||||
'en-us': 'Create connectors',
|
||||
},
|
||||
},
|
||||
GET: {
|
||||
seqid: 8,
|
||||
claim: 'GET /connectors',
|
||||
usage: PermissionUsages.INTERNAL,
|
||||
name: {
|
||||
'pt-br': 'Buscar conectores',
|
||||
'en-us': 'Get connectors',
|
||||
},
|
||||
},
|
||||
UPDATE: {
|
||||
seqid: 26,
|
||||
claim: 'PUT /connectors',
|
||||
usage: PermissionUsages.INTERNAL,
|
||||
name: {
|
||||
'pt-br': 'Editar conectores',
|
||||
'en-us': 'Edit connectors',
|
||||
},
|
||||
},
|
||||
DELETE: {
|
||||
seqid: 2,
|
||||
claim: 'DELETE /connectors',
|
||||
usage: PermissionUsages.INTERNAL,
|
||||
name: {
|
||||
'pt-br': 'Remover conectores',
|
||||
'en-us': 'Remove connectors',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
SNOWFLAKE: {
|
||||
OPEN: {
|
||||
seqid: 14,
|
||||
claim: 'GET /snowflake',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
title: {
|
||||
'pt-br': 'Snowflake',
|
||||
'en-us': 'Snowflake',
|
||||
},
|
||||
permissions: {
|
||||
OPEN: {
|
||||
seqid: 14,
|
||||
claim: 'GET /snowflake',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Acessar Snowflake',
|
||||
'en-us': 'Access Snowflake',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
ZENDESK: {
|
||||
OPEN: {
|
||||
seqid: 16,
|
||||
claim: 'GET /zendesk',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
title: {
|
||||
'pt-br': 'Zendesk',
|
||||
'en-us': 'Zendesk',
|
||||
},
|
||||
permissions: {
|
||||
OPEN: {
|
||||
seqid: 16,
|
||||
claim: 'GET /zendesk',
|
||||
usage: PermissionUsages.INTERNAL,
|
||||
name: {
|
||||
'pt-br': 'Acessar Zendesk',
|
||||
'en-us': 'Access Zendesk',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
METABASE: {
|
||||
OPEN: {
|
||||
seqid: 11,
|
||||
claim: 'GET /metabase',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
title: {
|
||||
'pt-br': 'Metabase',
|
||||
'en-us': 'Metabase',
|
||||
},
|
||||
permissions: {
|
||||
OPEN: {
|
||||
seqid: 11,
|
||||
claim: 'GET /metabase',
|
||||
usage: PermissionUsages.INTERNAL,
|
||||
name: {
|
||||
'pt-br': 'Acessar Metabase',
|
||||
'en-us': 'Access Metabase',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
ORCHEST: {
|
||||
INTELLIGENCE: {
|
||||
seqid: 31,
|
||||
claim: 'intelligence:open',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
title: {
|
||||
'pt-br': 'Orchest',
|
||||
'en-us': 'Orchest',
|
||||
},
|
||||
APP_BUILDER: {
|
||||
seqid: 32,
|
||||
claim: 'app-builder:open',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
permissions: {
|
||||
INTELLIGENCE: {
|
||||
seqid: 31,
|
||||
claim: 'intelligence:open',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Acessar inteligência',
|
||||
'en-us': 'Access intelligence',
|
||||
},
|
||||
},
|
||||
APP_BUILDER: {
|
||||
seqid: 32,
|
||||
claim: 'app-builder:open',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Acessar App Builder',
|
||||
'en-us': 'Access App Builder',
|
||||
},
|
||||
},
|
||||
MACHINE_LEARNING: {
|
||||
seqid: 33,
|
||||
claim: 'machine-learning:open',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Acessar Machine Learning',
|
||||
'en-us': 'Access Machine Learning',
|
||||
},
|
||||
},
|
||||
},
|
||||
MACHINE_LEARNING: {
|
||||
seqid: 33,
|
||||
claim: 'machine-learning:open',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
},
|
||||
USERS: {
|
||||
title: {
|
||||
'pt-br': 'Usuários',
|
||||
'en-us': 'Users',
|
||||
},
|
||||
permissions: {
|
||||
ADMIN: {
|
||||
seqid: 34,
|
||||
claim: 'users:admin',
|
||||
usage: PermissionUsages.PUBLIC,
|
||||
name: {
|
||||
'pt-br': 'Administrar usuários e grupos',
|
||||
'en-us': 'Manage user and roles',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// traverses the object searching for duplicate seqids or claims (executes at runtime)
|
||||
let nextAvailableSeqid = 0;
|
||||
const seqids = Object.values(Permissions).flatMap((namespace) =>
|
||||
Object.values(namespace).map(({ seqid }) => seqid),
|
||||
const seqids = Object.values(PERMISSIONS).flatMap((namespace) =>
|
||||
Object.values(namespace.permissions).map(({ seqid }) => seqid),
|
||||
);
|
||||
const claims = Object.values(Permissions).flatMap((namespace) =>
|
||||
Object.values(namespace).map(({ claim }) => claim),
|
||||
const claims = Object.values(PERMISSIONS).flatMap((namespace) =>
|
||||
Object.values(namespace.permissions).map(({ claim }) => claim),
|
||||
);
|
||||
Object.values(Permissions).map((namespace) =>
|
||||
Object.values(namespace).map(({ seqid, claim }) => {
|
||||
Object.values(PERMISSIONS).map((namespace) =>
|
||||
Object.values(namespace.permissions).map(({ seqid, claim }) => {
|
||||
const seqidsCount = seqids.filter((x) => x === seqid).length;
|
||||
assert(seqidsCount === 1, `seqid ${seqid} count is not 1`);
|
||||
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
import request from 'supertest';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { HttpStatus, INestApplication } from '@nestjs/common';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { AuthenticationGuard } from './authentication.guard';
|
||||
import { AuthClientService } from '../modules/auth/auth.service';
|
||||
|
||||
import ErrorCodes from '../utils/errorCodes';
|
||||
import { User } from './user.decorator';
|
||||
import { PERMISSIONS } from './permissions.enum';
|
||||
|
||||
const logger = {
|
||||
info: (...args) => args,
|
||||
error: (...args) => args,
|
||||
};
|
||||
@Controller('user')
|
||||
class UserController {
|
||||
@Get()
|
||||
public getUser(@User() user) {
|
||||
return { user };
|
||||
}
|
||||
|
||||
@Get('options')
|
||||
public getUserWithOptions(@User({}) user) {
|
||||
return { user };
|
||||
}
|
||||
|
||||
@Get('not-required')
|
||||
public getUserNotRequired(@User({ required: false }) user) {
|
||||
return { user };
|
||||
}
|
||||
|
||||
@Get('required')
|
||||
public getUserRequired(@User({ required: true }) user) {
|
||||
return { user };
|
||||
}
|
||||
}
|
||||
|
||||
describe('user.decorator', () => {
|
||||
let app: INestApplication;
|
||||
const jwt_secret = {
|
||||
kid: 'token-testing-shared-key',
|
||||
pem: '$tr0ng-SH4Red-secr3t!!!~gl0ba1~]',
|
||||
};
|
||||
const fakeUserPayload = {
|
||||
user_id: 'd50d33c7-6c2b-463c-861f-e21667e7c125',
|
||||
username: 'super.admin',
|
||||
permissions: [PERMISSIONS.METABASE.permissions.OPEN].map(
|
||||
({ seqid }) => seqid,
|
||||
),
|
||||
customer_id: '9d18e8ae-24b9-41a3-9e8f-a25ce57555b11',
|
||||
customer_name: 'dadosfera',
|
||||
customer_tier: 'BASIC',
|
||||
access_token: '',
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
providers: [
|
||||
{
|
||||
provide: AuthClientService,
|
||||
useValue: {
|
||||
getPublicKeys: async () => ({
|
||||
keys: [jwt_secret],
|
||||
}),
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: DadosferaLogger,
|
||||
useValue: { logger },
|
||||
},
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: AuthenticationGuard,
|
||||
},
|
||||
],
|
||||
controllers: [UserController],
|
||||
}).compile();
|
||||
|
||||
app = moduleRef.createNestApplication();
|
||||
await app.init();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
function AssertNoAuth(res: request.Response) {
|
||||
expect(res.statusCode).toBe(HttpStatus.OK);
|
||||
expect(res.body).toStrictEqual({});
|
||||
}
|
||||
|
||||
function AssertWithAuth(res: request.Response) {
|
||||
expect(res.statusCode).toBe(HttpStatus.OK);
|
||||
expect(res.body).toStrictEqual({ user: fakeUserPayload });
|
||||
}
|
||||
|
||||
function AssertRequiredNoAuth(res: request.Response) {
|
||||
expect(res.statusCode).toBe(HttpStatus.UNAUTHORIZED);
|
||||
expect(res.body).toStrictEqual({
|
||||
code: ErrorCodes.AUTH.UNAUTHORIZED,
|
||||
error: 'Não autenticado',
|
||||
message: 'É necessário estar logado para realizar essa operação',
|
||||
statusCode: HttpStatus.UNAUTHORIZED,
|
||||
});
|
||||
}
|
||||
|
||||
function UserTest(accessToken: string) {
|
||||
describe(`with${accessToken ? '' : 'out'} token`, () => {
|
||||
it('should GET /user', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/user')
|
||||
.set({ Authorization: accessToken });
|
||||
|
||||
if (accessToken) {
|
||||
AssertWithAuth(res);
|
||||
} else {
|
||||
AssertNoAuth(res);
|
||||
}
|
||||
});
|
||||
|
||||
it('should GET /user/options', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/user/options')
|
||||
.set({ Authorization: accessToken });
|
||||
|
||||
if (accessToken) {
|
||||
AssertWithAuth(res);
|
||||
} else {
|
||||
AssertNoAuth(res);
|
||||
}
|
||||
});
|
||||
|
||||
it('should GET /user/not-required', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/user/not-required')
|
||||
.set({ Authorization: accessToken });
|
||||
|
||||
if (accessToken) {
|
||||
AssertWithAuth(res);
|
||||
} else {
|
||||
AssertNoAuth(res);
|
||||
}
|
||||
});
|
||||
|
||||
it('should GET /user/required if logged', async () => {
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/user/required')
|
||||
.set({ Authorization: accessToken });
|
||||
|
||||
if (accessToken) {
|
||||
AssertWithAuth(res);
|
||||
} else {
|
||||
AssertRequiredNoAuth(res);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function CreateToken(overrides?) {
|
||||
const tokenPayload = {
|
||||
...fakeUserPayload,
|
||||
token_use: 'access',
|
||||
...overrides?.user,
|
||||
};
|
||||
|
||||
return jwt.sign(tokenPayload, jwt_secret.pem, {
|
||||
keyid: jwt_secret.kid,
|
||||
...overrides?.jwt,
|
||||
});
|
||||
}
|
||||
|
||||
UserTest(null);
|
||||
|
||||
const token = CreateToken();
|
||||
fakeUserPayload.access_token = token;
|
||||
UserTest(token);
|
||||
});
|
||||
@@ -6,18 +6,20 @@ import ErrorCodes from '../utils/errorCodes';
|
||||
export interface RequestUser {
|
||||
user_id: string;
|
||||
username: string;
|
||||
permissions: string;
|
||||
permissions: number[];
|
||||
customer_id: string;
|
||||
customer_name: string;
|
||||
customer_tier: string;
|
||||
access_token: string;
|
||||
}
|
||||
|
||||
export const User = createParamDecorator((data: any, ctx: ExecutionContext) => {
|
||||
const request = ctx.switchToHttp().getRequest();
|
||||
export const User: (options?: { required?: boolean }) => ParameterDecorator =
|
||||
createParamDecorator((options: any, ctx: ExecutionContext) => {
|
||||
const request = ctx.switchToHttp().getRequest();
|
||||
|
||||
if (!request.user && data?.required) {
|
||||
throw new ErrorBuilder(ErrorCodes.AUTH.UNAUTHORIZED);
|
||||
}
|
||||
if (!request.user && options?.required) {
|
||||
throw new ErrorBuilder(ErrorCodes.AUTH.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
return request.user;
|
||||
});
|
||||
return request.user;
|
||||
});
|
||||
|
||||
@@ -1,307 +0,0 @@
|
||||
import {
|
||||
OnModuleInit,
|
||||
Inject,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { ClientGrpc } from '@nestjs/microservices';
|
||||
import { ConnectorManager } from 'protospack-v2';
|
||||
import { from } from 'rxjs';
|
||||
|
||||
export class ConnectorClientService implements OnModuleInit {
|
||||
private connectorServiceRead: ConnectorManager.ReadService.ConnectorManagerReadServices;
|
||||
private connectorServiceWrite: ConnectorManager.WriteService.ConnectorManagerWriteServices;
|
||||
logger: any;
|
||||
constructor(
|
||||
@Inject(DadosferaLogger)
|
||||
dadosferaLogger: DadosferaLogger,
|
||||
@Inject('CONNECTOR_PACKAGE') private readonly grpcClient: ClientGrpc,
|
||||
) {
|
||||
this.logger = dadosferaLogger.logger;
|
||||
}
|
||||
|
||||
onModuleInit() {
|
||||
this.connectorServiceWrite =
|
||||
this.grpcClient.getService<ConnectorManager.WriteService.ConnectorManagerWriteServices>(
|
||||
ConnectorManager.ProtoServices.ConnectorManagerWriteServices,
|
||||
);
|
||||
|
||||
this.connectorServiceRead =
|
||||
this.grpcClient.getService<ConnectorManager.ReadService.ConnectorManagerReadServices>(
|
||||
ConnectorManager.ProtoServices.ConnectorManagerReadServices,
|
||||
);
|
||||
}
|
||||
|
||||
async uploadConnector(uploadConnector) {
|
||||
const connector: ConnectorManager.Entities.ConnectorCreateRequest = {
|
||||
file: {
|
||||
buffer: uploadConnector.file.buffer,
|
||||
mimetypes: uploadConnector.file.mimetype,
|
||||
},
|
||||
connector: JSON.stringify(uploadConnector.connector),
|
||||
};
|
||||
const serviceBody: ConnectorManager.Messages.RegisterConnectorRequest = {
|
||||
connector,
|
||||
};
|
||||
|
||||
const observable = from(
|
||||
this.connectorServiceWrite.RegisterConnector(serviceBody),
|
||||
);
|
||||
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
observable.subscribe({
|
||||
next(x) {
|
||||
resolve(x);
|
||||
},
|
||||
error(err) {
|
||||
reject(err);
|
||||
},
|
||||
complete() {
|
||||
//console.log('done');
|
||||
},
|
||||
});
|
||||
})
|
||||
.then((res) => {
|
||||
this.logger.info('Done');
|
||||
return res;
|
||||
})
|
||||
.catch((err) => {
|
||||
this.logger.error(err.details);
|
||||
this.logger.error(err);
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
|
||||
this.logger.info('ConnectorClientService - Upload');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async uploadFile(uploadFile) {
|
||||
const body: ConnectorManager.Messages.UploadFileRequest = {
|
||||
file: {
|
||||
buffer: uploadFile.file.buffer,
|
||||
mimetypes: uploadFile.file.mimetype,
|
||||
},
|
||||
name: uploadFile.name,
|
||||
};
|
||||
|
||||
const observable = from(this.connectorServiceWrite.UploadFile(body));
|
||||
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
observable.subscribe({
|
||||
next(x) {
|
||||
resolve(x);
|
||||
},
|
||||
error(err) {
|
||||
reject(err);
|
||||
},
|
||||
complete() {
|
||||
//console.log('done');
|
||||
},
|
||||
});
|
||||
})
|
||||
.then((res) => {
|
||||
this.logger.info('Done');
|
||||
return res;
|
||||
})
|
||||
.catch((err) => {
|
||||
this.logger.error(err.details);
|
||||
this.logger.error(err);
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
|
||||
this.logger.info('ConnectorClientService - Upload');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getAllConnectors(body) {
|
||||
const observable = from(
|
||||
this.connectorServiceRead.GetAllConnectors({
|
||||
search: body.search,
|
||||
filters: JSON.stringify(body.filters),
|
||||
}),
|
||||
);
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
observable.subscribe({
|
||||
next(x) {
|
||||
resolve(x);
|
||||
},
|
||||
error(err) {
|
||||
reject(err);
|
||||
},
|
||||
complete() {
|
||||
//console.log('done');
|
||||
},
|
||||
});
|
||||
})
|
||||
.then((res) => {
|
||||
this.logger.info('Done');
|
||||
return res;
|
||||
})
|
||||
.catch((err) => {
|
||||
this.logger.error(err);
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
|
||||
this.logger.info('ConnectorClientService - getAllConnectors');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getConnectorDetails(plugin: string) {
|
||||
const observable = from(
|
||||
this.connectorServiceRead.GetConnectorDetails({
|
||||
plugin,
|
||||
}),
|
||||
);
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
observable.subscribe({
|
||||
next(x) {
|
||||
resolve(x);
|
||||
},
|
||||
error(err) {
|
||||
reject(err);
|
||||
},
|
||||
complete() {
|
||||
//console.log('done');
|
||||
},
|
||||
});
|
||||
})
|
||||
.then((res) => {
|
||||
this.logger.info('Done');
|
||||
return res;
|
||||
})
|
||||
.catch((err) => {
|
||||
this.logger.error(err);
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
|
||||
this.logger.info('ConnectorClientService - getAllConnectors');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getConnector(plugin: string) {
|
||||
const observable = from(
|
||||
this.connectorServiceRead.GetConnector({
|
||||
plugin,
|
||||
}),
|
||||
);
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
observable.subscribe({
|
||||
next(x) {
|
||||
resolve(x);
|
||||
},
|
||||
error(err) {
|
||||
reject(err);
|
||||
},
|
||||
complete() {
|
||||
//console.log('done');
|
||||
},
|
||||
});
|
||||
})
|
||||
.then((res) => {
|
||||
this.logger.info('Done');
|
||||
return res;
|
||||
})
|
||||
.catch((err) => {
|
||||
this.logger.error(err);
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
|
||||
this.logger.info('ConnectorClientService - getAllConnectors');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async deleteConnector(plugin: string, version: string) {
|
||||
const observable = from(
|
||||
this.connectorServiceWrite.DeleteConnector({
|
||||
version,
|
||||
plugin,
|
||||
}),
|
||||
);
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
observable.subscribe({
|
||||
next(x) {
|
||||
resolve(x);
|
||||
},
|
||||
error(err) {
|
||||
reject(err);
|
||||
},
|
||||
complete() {
|
||||
//console.log('done');
|
||||
},
|
||||
});
|
||||
})
|
||||
.then((res) => {
|
||||
this.logger.info('Done');
|
||||
return res;
|
||||
})
|
||||
.catch((err) => {
|
||||
this.logger.error(err);
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
|
||||
this.logger.info('ConnectorClientService - getAllConnectors');
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async updateConnector({ plugin, changes }) {
|
||||
const observable = from(
|
||||
this.connectorServiceWrite.UpdateConnector({
|
||||
plugin,
|
||||
changes,
|
||||
}),
|
||||
);
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
observable.subscribe({
|
||||
next(x) {
|
||||
resolve(x);
|
||||
},
|
||||
error(err) {
|
||||
reject(err);
|
||||
},
|
||||
complete() {
|
||||
//console.log('done');
|
||||
},
|
||||
});
|
||||
})
|
||||
.then((res) => {
|
||||
this.logger.info('Done');
|
||||
return res;
|
||||
})
|
||||
.catch((err) => {
|
||||
this.logger.error(err);
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
|
||||
this.logger.info('ConnectorClientService - getAllConnectors');
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
import { credentials } from '@grpc/grpc-js';
|
||||
import { ClientOptions, Transport } from '@nestjs/microservices';
|
||||
import {
|
||||
ProtoPackages,
|
||||
ProtoPaths,
|
||||
} from 'protospack-v2/dist/lib/Duc';
|
||||
import { ProtoPackages, ProtoPaths } from 'protospack-v2/dist/lib/Duc';
|
||||
|
||||
export class DucClient {
|
||||
config(): ClientOptions {
|
||||
@@ -12,6 +9,7 @@ export class DucClient {
|
||||
options: {
|
||||
url: process.env.DUC_URL,
|
||||
package: ProtoPackages.WritePackage,
|
||||
// credentials: credentials.createSsl(),
|
||||
credentials: process.env.LOCAL_ENV
|
||||
? undefined
|
||||
: credentials.createSsl(),
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { Controller, Inject, OnModuleInit } from '@nestjs/common';
|
||||
import { ClientGrpc, Payload } from '@nestjs/microservices';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import {
|
||||
OutputServicesNames,
|
||||
OutputsServiceInterface,
|
||||
} from 'protospack';
|
||||
import { OutputServicesNames, OutputsServiceInterface } from 'protospack';
|
||||
import {
|
||||
objectCamelToSnake,
|
||||
objectSnakeToCamel,
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { OnModuleInit, Inject } from '@nestjs/common';
|
||||
import { ClientGrpc } from '@nestjs/microservices';
|
||||
|
||||
import { ProtoServices } from 'protospack-v2/dist/lib/Duc';
|
||||
import { PermissionsProtoService as PermissionsServiceInterface } from 'protospack-v2/dist/lib/Duc/interfaces/write-service';
|
||||
import {
|
||||
Empty,
|
||||
InjectPermissionsRequest,
|
||||
} from 'protospack-v2/dist/lib/Duc/interfaces/messages';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import grpcHandler from '../../utils/grpcHandler';
|
||||
|
||||
export class PermissionsClientService implements OnModuleInit {
|
||||
logger: any;
|
||||
|
||||
private permissionsService: PermissionsServiceInterface;
|
||||
constructor(
|
||||
@Inject(DadosferaLogger)
|
||||
dadosferaLogger: DadosferaLogger,
|
||||
@Inject('DUC_PACKAGE') private readonly grpcClient: ClientGrpc,
|
||||
) {
|
||||
this.logger = dadosferaLogger.logger;
|
||||
}
|
||||
|
||||
onModuleInit() {
|
||||
this.permissionsService =
|
||||
this.grpcClient.getService<PermissionsServiceInterface>(
|
||||
ProtoServices.PermissionsProtoService,
|
||||
);
|
||||
}
|
||||
|
||||
async injectPermissions({ permissions }: InjectPermissionsRequest) {
|
||||
this.logger.info('InjectPermissions');
|
||||
|
||||
return grpcHandler<Empty>(
|
||||
this.permissionsService.InjectPermissions({ permissions }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,5 @@
|
||||
import { ClientOptions, Transport } from '@nestjs/microservices';
|
||||
import {
|
||||
PipelinePackages,
|
||||
PipelineProtoFilePath,
|
||||
} from 'protospack';
|
||||
import { PipelinePackages, PipelineProtoFilePath } from 'protospack';
|
||||
import { credentials } from '@grpc/grpc-js';
|
||||
|
||||
export class PipelinesClientConfiguration {
|
||||
|
||||
@@ -255,7 +255,7 @@ export class PipelinesClientService implements OnModuleInit {
|
||||
reject(err);
|
||||
},
|
||||
complete() {
|
||||
this.logger.info('Done');
|
||||
//this.logger.info('Done');
|
||||
},
|
||||
});
|
||||
})
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
|
||||
import ErrorBuilder from '../utils/ErrorBuilder';
|
||||
|
||||
@Catch(Error)
|
||||
export class GrpcToHttpExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: any, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
|
||||
// return this exception directly if is already of type ErrorBuilder,
|
||||
// else transform it using the ErrorBuilder
|
||||
const err =
|
||||
exception.constructor.name === ErrorBuilder.name
|
||||
? exception
|
||||
: new ErrorBuilder(exception.details);
|
||||
|
||||
const { statusCode } = err.response;
|
||||
return response.status(statusCode).json(err.response);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import { HttpExceptionFilter } from './http-exception.filter';
|
||||
|
||||
describe('HttpExceptionFilter', () => {
|
||||
it('should be defined', () => {
|
||||
expect(new HttpExceptionFilter()).toBeDefined();
|
||||
});
|
||||
});
|
||||
+6
-4
@@ -1,20 +1,17 @@
|
||||
import 'elastic-apm-node/start';
|
||||
if (process.env.ENV !== 'local') require('elastic-apm-node/start');
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { writeFileSync } from 'fs';
|
||||
import helmet from 'helmet';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
import documentEmpty from '../swagger_empty.json';
|
||||
|
||||
import { AppModule } from './app.module';
|
||||
|
||||
async function bootstrap() {
|
||||
DadosferaLogger.setupLogger({
|
||||
serviceName: 'maestro',
|
||||
serviceEnvironment: process.env.ENV,
|
||||
});
|
||||
|
||||
const logger = new DadosferaLogger().logger;
|
||||
|
||||
const orginalWinstonLog = logger.log.bind(logger);
|
||||
@@ -45,6 +42,11 @@ async function bootstrap() {
|
||||
.setDescription('Documentation for Maestro gateway')
|
||||
.setVersion('1.0')
|
||||
.addBearerAuth()
|
||||
.addServer(
|
||||
process.env.ENV === 'local'
|
||||
? 'http://127.0.0.1:3333'
|
||||
: 'https://maestro.dev.dadosfera.ai',
|
||||
)
|
||||
.build();
|
||||
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
|
||||
@@ -5,8 +5,8 @@ import {
|
||||
Post,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
OnApplicationBootstrap,
|
||||
Inject,
|
||||
UseFilters,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import {
|
||||
@@ -21,50 +21,24 @@ import {
|
||||
AuthVerifyTotpMfaRequest,
|
||||
} from 'protospack-v2/dist/lib/Duc/interfaces/messages';
|
||||
|
||||
import { AuthClientService } from '../../clients/auth/client.service';
|
||||
import { PermissionsClientService } from '../../clients/permissions/client.service';
|
||||
import { Permissions } from '../../authentication/permissions.enum';
|
||||
import { AuthClientService } from './auth.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import ErrorBuilder from '../../utils/ErrorBuilder';
|
||||
import { GrpcToHttpExceptionFilter } from '../../error/grpc-to-http-exception.filter';
|
||||
|
||||
@ApiTags('Auth')
|
||||
@UseFilters(new GrpcToHttpExceptionFilter())
|
||||
@Controller('auth')
|
||||
export class AuthController implements OnApplicationBootstrap {
|
||||
export class AuthController {
|
||||
logger: any;
|
||||
|
||||
constructor(
|
||||
@Inject(DadosferaLogger)
|
||||
dadosferaLogger: DadosferaLogger,
|
||||
private authClient: AuthClientService,
|
||||
private permissionsClient: PermissionsClientService,
|
||||
) {
|
||||
this.logger = dadosferaLogger.logger;
|
||||
}
|
||||
|
||||
// internally used to send permissions to duc on microservice startup
|
||||
async onApplicationBootstrap() {
|
||||
this.logger.info('sending permissions to DUC...');
|
||||
|
||||
const permissions = Object.values(Permissions).flatMap((namespace) =>
|
||||
Object.values(namespace),
|
||||
);
|
||||
|
||||
return this.permissionsClient
|
||||
.injectPermissions({ permissions })
|
||||
.catch((err: ErrorBuilder) => {
|
||||
if (
|
||||
err.code === 'No connection established' &&
|
||||
process.env.LOCAL_ENV === 'true'
|
||||
) {
|
||||
return this.logger.info(
|
||||
"couldn't connect to DUC. suppresing in local env",
|
||||
);
|
||||
}
|
||||
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
@Post('sign-in')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async signIn(@Body() { username, password, totp }: AuthSignInRequest) {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthClientService } from './auth.service';
|
||||
|
||||
import { DucClient } from '../../clients/duc/client.config';
|
||||
const ducClient = new DucClient();
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ClientsModule.register([
|
||||
{
|
||||
name: 'DUC_PACKAGE',
|
||||
...ducClient.config(),
|
||||
},
|
||||
]),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthClientService, DadosferaLogger],
|
||||
exports: [AuthClientService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -1,35 +1,24 @@
|
||||
import { OnModuleInit, Inject } from '@nestjs/common';
|
||||
import { OnModuleInit, Inject, Injectable } from '@nestjs/common';
|
||||
import { ClientGrpc } from '@nestjs/microservices';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
|
||||
import { ProtoServices } from 'protospack-v2/dist/lib/Duc';
|
||||
import { AuthProtoService as AuthServiceInterface } from 'protospack-v2/dist/lib/Duc/interfaces/write-service';
|
||||
import {
|
||||
AuthGetPublicKeysResponse,
|
||||
AuthSignInRequest,
|
||||
AuthSignInResponse,
|
||||
AuthRefreshAccessTokenRequest,
|
||||
AuthRefreshAccessTokenResponse,
|
||||
AuthEnableTotpMfaRequest,
|
||||
AuthEnableTotpMfaResponse,
|
||||
AuthDisableTotpMfaRequest,
|
||||
AuthDisableTotpMfaResponse,
|
||||
AuthDismissTotpMfaRequest,
|
||||
AuthDismissTotpMfaResponse,
|
||||
AuthVerifyTotpMfaRequest,
|
||||
AuthVerifyTotpMfaResponse,
|
||||
AuthChangePasswordRequest,
|
||||
AuthChangePasswordResponse,
|
||||
AuthResetPasswordRequest,
|
||||
AuthResetPasswordResponse,
|
||||
AuthVerifyResetPasswordCodeRequest,
|
||||
AuthVerifyResetPasswordCodeResponse,
|
||||
AuthConfirmResetPasswordRequest,
|
||||
AuthConfirmResetPasswordResponse,
|
||||
} from 'protospack-v2/dist/lib/Duc/interfaces/messages';
|
||||
|
||||
import grpcHandler from '../../utils/grpcHandler';
|
||||
|
||||
@Injectable()
|
||||
export class AuthClientService implements OnModuleInit {
|
||||
logger: any;
|
||||
|
||||
@@ -51,15 +40,13 @@ export class AuthClientService implements OnModuleInit {
|
||||
async getPublicKeys() {
|
||||
this.logger.info('GetPublicKeys');
|
||||
|
||||
return grpcHandler<AuthGetPublicKeysResponse>(
|
||||
this.authService.AuthGetPublicKeys({}),
|
||||
);
|
||||
return lastValueFrom(this.authService.AuthGetPublicKeys({}));
|
||||
}
|
||||
|
||||
async signIn({ username, password, totp }: AuthSignInRequest) {
|
||||
this.logger.info('SignIn');
|
||||
|
||||
return grpcHandler<AuthSignInResponse>(
|
||||
return lastValueFrom(
|
||||
this.authService.AuthSignIn({ username, password, totp }),
|
||||
);
|
||||
}
|
||||
@@ -67,7 +54,7 @@ export class AuthClientService implements OnModuleInit {
|
||||
async refreshAccessToken({ refreshToken }: AuthRefreshAccessTokenRequest) {
|
||||
this.logger.info('RefreshAccessToken');
|
||||
|
||||
return grpcHandler<AuthRefreshAccessTokenResponse>(
|
||||
return lastValueFrom(
|
||||
this.authService.AuthRefreshAccessToken({ refreshToken }),
|
||||
);
|
||||
}
|
||||
@@ -79,7 +66,7 @@ export class AuthClientService implements OnModuleInit {
|
||||
}: AuthChangePasswordRequest) {
|
||||
this.logger.info('ChangePassword');
|
||||
|
||||
return grpcHandler<AuthChangePasswordResponse>(
|
||||
return lastValueFrom(
|
||||
this.authService.AuthChangePassword({
|
||||
accessToken,
|
||||
oldPassword,
|
||||
@@ -91,9 +78,7 @@ export class AuthClientService implements OnModuleInit {
|
||||
async resetPassword({ username }: AuthResetPasswordRequest) {
|
||||
this.logger.info('resetPassword');
|
||||
|
||||
return grpcHandler<AuthResetPasswordResponse>(
|
||||
this.authService.AuthResetPassword({ username }),
|
||||
);
|
||||
return lastValueFrom(this.authService.AuthResetPassword({ username }));
|
||||
}
|
||||
|
||||
async verifyResetPasswordCode({
|
||||
@@ -102,7 +87,7 @@ export class AuthClientService implements OnModuleInit {
|
||||
}: AuthVerifyResetPasswordCodeRequest) {
|
||||
this.logger.info('verifyResetPasswordCode');
|
||||
|
||||
return grpcHandler<AuthVerifyResetPasswordCodeResponse>(
|
||||
return lastValueFrom(
|
||||
this.authService.AuthVerifyResetPasswordCode({ username, code }),
|
||||
);
|
||||
}
|
||||
@@ -114,7 +99,7 @@ export class AuthClientService implements OnModuleInit {
|
||||
}: AuthConfirmResetPasswordRequest) {
|
||||
this.logger.info('confirmResetPassword');
|
||||
|
||||
return grpcHandler<AuthConfirmResetPasswordResponse>(
|
||||
return lastValueFrom(
|
||||
this.authService.AuthConfirmResetPassword({
|
||||
username,
|
||||
code,
|
||||
@@ -126,7 +111,7 @@ export class AuthClientService implements OnModuleInit {
|
||||
async enableTotpMFA({ accessToken, password }: AuthEnableTotpMfaRequest) {
|
||||
this.logger.info('enableTotpMFA');
|
||||
|
||||
return grpcHandler<AuthEnableTotpMfaResponse>(
|
||||
return lastValueFrom(
|
||||
this.authService.AuthEnableTotpMfa({ accessToken, password }),
|
||||
);
|
||||
}
|
||||
@@ -134,7 +119,7 @@ export class AuthClientService implements OnModuleInit {
|
||||
async disableTotpMFA({ accessToken, password }: AuthDisableTotpMfaRequest) {
|
||||
this.logger.info('disableTotpMFA');
|
||||
|
||||
return grpcHandler<AuthDisableTotpMfaResponse>(
|
||||
return lastValueFrom(
|
||||
this.authService.AuthDisableTotpMfa({ accessToken, password }),
|
||||
);
|
||||
}
|
||||
@@ -142,15 +127,13 @@ export class AuthClientService implements OnModuleInit {
|
||||
async dismissTotpMFA({ accessToken }: AuthDismissTotpMfaRequest) {
|
||||
this.logger.info('dismissTotpMFA');
|
||||
|
||||
return grpcHandler<AuthDismissTotpMfaResponse>(
|
||||
this.authService.AuthDismissTotpMfa({ accessToken }),
|
||||
);
|
||||
return lastValueFrom(this.authService.AuthDismissTotpMfa({ accessToken }));
|
||||
}
|
||||
|
||||
async verifyTotp({ accessToken, totp }: AuthVerifyTotpMfaRequest) {
|
||||
this.logger.info('disableTotpMFA');
|
||||
|
||||
return grpcHandler<AuthVerifyTotpMfaResponse>(
|
||||
return lastValueFrom(
|
||||
this.authService.AuthVerifyTotpMfa({ accessToken, totp }),
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { AuthenticateCondition } from '../../authentication/authentication.decorator';
|
||||
import { Permissions } from '../../authentication/permissions.enum';
|
||||
import { PERMISSIONS } from '../../authentication/permissions.enum';
|
||||
import { CatalogService } from './catalog.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
@@ -32,7 +32,9 @@ import { DadosferaLogger } from 'dadosfera-logs';
|
||||
action = req.method;
|
||||
}
|
||||
|
||||
return user.permissions.includes(Permissions.CATALOG[action].seqid);
|
||||
return user.permissions.includes(
|
||||
PERMISSIONS.CATALOG.permissions[action].seqid,
|
||||
);
|
||||
})
|
||||
export class CatalogController {
|
||||
logger: any;
|
||||
|
||||
@@ -12,10 +12,10 @@ export class ConnectorClientConfiguration {
|
||||
ConnectorManager.ProtoPackages.WritePackage,
|
||||
ConnectorManager.ProtoPackages.ReadPackage,
|
||||
],
|
||||
credentials:
|
||||
process.env.LOCAL_ENV === 'local'
|
||||
? undefined
|
||||
: credentials.createSsl(),
|
||||
// credentials: undefined,
|
||||
credentials: process.env.LOCAL_ENV
|
||||
? undefined
|
||||
: credentials.createSsl(),
|
||||
protoPath: [
|
||||
ConnectorManager.ProtoPaths.WriteFilePath,
|
||||
ConnectorManager.ProtoPaths.ReadFilePath,
|
||||
@@ -0,0 +1,193 @@
|
||||
import { Metadata } from '@grpc/grpc-js';
|
||||
import {
|
||||
OnModuleInit,
|
||||
Inject,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
import { ClientGrpc } from '@nestjs/microservices';
|
||||
import { ConnectorManager } from 'protospack-v2';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
|
||||
export class ConnectorClientService implements OnModuleInit {
|
||||
private connectorServiceRead: ConnectorManager.ReadService.ConnectorManagerReadServices;
|
||||
private connectorServiceWrite: ConnectorManager.WriteService.ConnectorManagerWriteServices;
|
||||
constructor(
|
||||
@Inject('CONNECTOR_PACKAGE') private readonly grpcClient: ClientGrpc,
|
||||
) {}
|
||||
|
||||
onModuleInit() {
|
||||
this.connectorServiceWrite =
|
||||
this.grpcClient.getService<ConnectorManager.WriteService.ConnectorManagerWriteServices>(
|
||||
ConnectorManager.ProtoServices.ConnectorManagerWriteServices,
|
||||
);
|
||||
|
||||
this.connectorServiceRead =
|
||||
this.grpcClient.getService<ConnectorManager.ReadService.ConnectorManagerReadServices>(
|
||||
ConnectorManager.ProtoServices.ConnectorManagerReadServices,
|
||||
);
|
||||
}
|
||||
|
||||
async uploadConnector(uploadConnector) {
|
||||
const connector: ConnectorManager.Entities.ConnectorCreateRequest = {
|
||||
file: {
|
||||
buffer: uploadConnector.file.buffer,
|
||||
mimetypes: uploadConnector.file.mimetype,
|
||||
},
|
||||
connector: JSON.stringify(uploadConnector.connector),
|
||||
};
|
||||
const serviceBody: ConnectorManager.Messages.RegisterConnectorRequest = {
|
||||
connector,
|
||||
};
|
||||
|
||||
return lastValueFrom(
|
||||
this.connectorServiceWrite.RegisterConnector(serviceBody),
|
||||
).catch((err) => {
|
||||
console.log(err.details);
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async uploadFile(uploadFile) {
|
||||
const body: ConnectorManager.Messages.UploadFileRequest = {
|
||||
file: {
|
||||
buffer: uploadFile.file.buffer,
|
||||
mimetypes: uploadFile.file.mimetype,
|
||||
},
|
||||
name: uploadFile.name,
|
||||
};
|
||||
|
||||
return lastValueFrom(this.connectorServiceWrite.UploadFile(body)).catch(
|
||||
(err) => {
|
||||
console.log(err.details);
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async uploadConnectorsFile(uploadFile) {
|
||||
const connectors = JSON.parse(uploadFile.file.buffer.toString('utf8'));
|
||||
|
||||
const body = connectors.map((connector) => {
|
||||
return JSON.stringify(connector);
|
||||
});
|
||||
|
||||
const request = {
|
||||
connectors: body,
|
||||
};
|
||||
|
||||
return lastValueFrom(
|
||||
this.connectorServiceWrite.RegisterMultipleConnectorsWithoutImage(
|
||||
request,
|
||||
),
|
||||
).catch((err) => {
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async getAllConnectors(body) {
|
||||
const meta = new Metadata();
|
||||
meta.add('Language', body.language);
|
||||
return lastValueFrom(
|
||||
this.connectorServiceRead.GetAllConnectors(
|
||||
{
|
||||
search: body.search,
|
||||
filters: JSON.stringify(body.filters),
|
||||
language: body.language,
|
||||
page: body.page,
|
||||
size: body.size,
|
||||
},
|
||||
meta,
|
||||
),
|
||||
).catch((err) => {
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async getConnectorDetails(plugin: string, language: string) {
|
||||
const meta = new Metadata();
|
||||
meta.add('Language', language);
|
||||
return lastValueFrom(
|
||||
this.connectorServiceRead.GetConnectorDetails(
|
||||
{
|
||||
plugin,
|
||||
},
|
||||
meta,
|
||||
),
|
||||
).catch((err) => {
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async getConnector(plugin: string, language: string) {
|
||||
const meta = new Metadata();
|
||||
meta.add('Language', language);
|
||||
return lastValueFrom(
|
||||
this.connectorServiceRead.GetConnector(
|
||||
{
|
||||
plugin,
|
||||
},
|
||||
meta,
|
||||
),
|
||||
).catch((err) => {
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async getConnectorsTags() {
|
||||
return lastValueFrom(this.connectorServiceRead.GetConnectorsTags({})).catch(
|
||||
(err) => {
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async deleteConnector(plugin: string, version: string) {
|
||||
return lastValueFrom(
|
||||
this.connectorServiceWrite.DeleteConnector({
|
||||
version,
|
||||
plugin,
|
||||
}),
|
||||
).catch((err) => {
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async updateConnector({ plugin, changes }) {
|
||||
return lastValueFrom(
|
||||
this.connectorServiceWrite.UpdateConnector({
|
||||
plugin,
|
||||
changes,
|
||||
}),
|
||||
).catch((err) => {
|
||||
throw new HttpException(
|
||||
err.details,
|
||||
err.code === 6 ? HttpStatus.CONFLICT : 400,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -11,21 +11,29 @@ import {
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
Inject,
|
||||
Headers,
|
||||
UploadedFiles,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
|
||||
import { ApiBearerAuth, ApiConsumes, ApiTags } from '@nestjs/swagger';
|
||||
import { ConnectorClientService } from 'src/clients/connector/client.service';
|
||||
import { ConnectorClientService } from './client.service';
|
||||
import { AddTagDto } from './dtos/add-tag';
|
||||
import { CreateConnectorDto } from './dtos/create-connector';
|
||||
import { UploadConnectorsFileDto } from './dtos/create-multiple-connector';
|
||||
import { DeleteConnectorDto } from './dtos/delete-connector';
|
||||
import { GetAllDto } from './dtos/get-all';
|
||||
import { RemoveTagDto } from './dtos/remove-tag';
|
||||
import { UpdateDto } from './dtos/update';
|
||||
import { UploadFileDto } from './dtos/upload-file';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import {
|
||||
Authenticated,
|
||||
RequireAllPermissions,
|
||||
} from 'src/authentication/authentication.decorator';
|
||||
import { PERMISSIONS } from 'src/authentication/permissions.enum';
|
||||
|
||||
@ApiTags('connectors')
|
||||
@ApiBearerAuth()
|
||||
@Authenticated()
|
||||
@Controller('connectors')
|
||||
export class ConnectorController {
|
||||
logger: any;
|
||||
@@ -38,6 +46,7 @@ export class ConnectorController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequireAllPermissions(PERMISSIONS.CONNECTORS.permissions.CREATE)
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
async uploadConnector(
|
||||
@@ -54,29 +63,53 @@ export class ConnectorController {
|
||||
return response;
|
||||
}
|
||||
|
||||
@Post('/upload')
|
||||
@Post('/uploads')
|
||||
@RequireAllPermissions(PERMISSIONS.CONNECTORS.permissions.CREATE)
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(FilesInterceptor('files'))
|
||||
async uploadFile(@UploadedFiles() files) {
|
||||
this.logger.info('/upload - Upload Connector Route');
|
||||
const promises = files.map(async (file) => {
|
||||
return await this.connectorClientService.uploadFile({
|
||||
file,
|
||||
name: file.originalname.split('.')[0],
|
||||
});
|
||||
});
|
||||
|
||||
const response = await Promise.all(promises);
|
||||
return response;
|
||||
}
|
||||
|
||||
@Post('/multiple-connectors-upload')
|
||||
@RequireAllPermissions(PERMISSIONS.CONNECTORS.permissions.CREATE)
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(FileInterceptor('file'))
|
||||
async uploadFile(@UploadedFile() file, @Body() { name }: UploadFileDto) {
|
||||
this.logger.info('/upload - Upload Connector Route');
|
||||
async uploadConnectorsFile(@UploadedFile() file: UploadConnectorsFileDto) {
|
||||
console.log(`/upload`, 'Upload Connector Route');
|
||||
|
||||
const response = await this.connectorClientService.uploadFile({
|
||||
const response = await this.connectorClientService.uploadConnectorsFile({
|
||||
file,
|
||||
name,
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
@Get()
|
||||
async getAllConnectors(@Query() queries: GetAllDto) {
|
||||
@RequireAllPermissions(PERMISSIONS.CONNECTORS.permissions.GET)
|
||||
async getAllConnectors(
|
||||
@Headers('dadosfera-lang') language,
|
||||
@Query() queries: GetAllDto,
|
||||
) {
|
||||
this.logger.info('/upload - Upload Connector Route');
|
||||
|
||||
const { search, ...filters } = queries;
|
||||
const { search, size, page, ...filters } = queries;
|
||||
|
||||
const response: any = await this.connectorClientService.getAllConnectors({
|
||||
filters: filters || {},
|
||||
search: search || '',
|
||||
language: language || 'pt-br',
|
||||
size: size || 10,
|
||||
page: page || 1,
|
||||
});
|
||||
|
||||
const connectors = JSON.parse(response.connectors).connectors;
|
||||
@@ -87,8 +120,16 @@ export class ConnectorController {
|
||||
};
|
||||
}
|
||||
|
||||
@Get('/tags')
|
||||
@RequireAllPermissions(PERMISSIONS.CONNECTORS.permissions.GET)
|
||||
async getConnectorsTags() {
|
||||
return await this.connectorClientService.getConnectorsTags();
|
||||
}
|
||||
|
||||
@Get('/:plugin')
|
||||
@RequireAllPermissions(PERMISSIONS.CONNECTORS.permissions.GET)
|
||||
async getConnector(
|
||||
@Headers('dadosfera-lang') language,
|
||||
@Param('plugin') plugin: string,
|
||||
@Query('version') version: string,
|
||||
) {
|
||||
@@ -98,6 +139,7 @@ export class ConnectorController {
|
||||
|
||||
const response: any = await this.connectorClientService.getConnector(
|
||||
pluginId,
|
||||
language,
|
||||
);
|
||||
|
||||
return {
|
||||
@@ -107,7 +149,9 @@ export class ConnectorController {
|
||||
}
|
||||
|
||||
@Get('/:plugin/details')
|
||||
@RequireAllPermissions(PERMISSIONS.CONNECTORS.permissions.GET)
|
||||
async getConnectorDetails(
|
||||
@Headers('dadosfera-lang') language,
|
||||
@Param('plugin') plugin: string,
|
||||
@Query('version') version: string,
|
||||
) {
|
||||
@@ -117,6 +161,7 @@ export class ConnectorController {
|
||||
|
||||
const response: any = await this.connectorClientService.getConnectorDetails(
|
||||
pluginId,
|
||||
language || 'pt-br',
|
||||
);
|
||||
|
||||
return {
|
||||
@@ -126,6 +171,7 @@ export class ConnectorController {
|
||||
}
|
||||
|
||||
@Put('/:plugin')
|
||||
@RequireAllPermissions(PERMISSIONS.CONNECTORS.permissions.UPDATE)
|
||||
@ApiConsumes('multipart/form-data')
|
||||
async updateConnector(
|
||||
@Param('plugin') plugin: string,
|
||||
@@ -147,6 +193,7 @@ export class ConnectorController {
|
||||
}
|
||||
|
||||
@Put('/:plugin/add-tag')
|
||||
@RequireAllPermissions(PERMISSIONS.CONNECTORS.permissions.UPDATE)
|
||||
async addTagOnConnector(
|
||||
@Param('plugin') plugin: string,
|
||||
@Body() body: AddTagDto,
|
||||
@@ -173,6 +220,7 @@ export class ConnectorController {
|
||||
}
|
||||
|
||||
@Put('/:plugin/remove-tag')
|
||||
@RequireAllPermissions(PERMISSIONS.CONNECTORS.permissions.UPDATE)
|
||||
async removeTagOnConnector(
|
||||
@Param('plugin') plugin: string,
|
||||
@Body() body: RemoveTagDto,
|
||||
@@ -200,6 +248,7 @@ export class ConnectorController {
|
||||
}
|
||||
|
||||
@Delete('/:plugin')
|
||||
@RequireAllPermissions(PERMISSIONS.CONNECTORS.permissions.DELETE)
|
||||
async deleteConnector(
|
||||
@Param('plugin') plugin: string,
|
||||
@Body() { version }: DeleteConnectorDto,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { ConnectorClientService } from './client.service';
|
||||
import { ConnectorClientConfiguration } from './client.config';
|
||||
import { ConnectorController } from './connector.controller';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
const connectorClient = new ConnectorClientConfiguration();
|
||||
|
||||
@Module({
|
||||
controllers: [ConnectorController],
|
||||
providers: [ConnectorClientService, DadosferaLogger],
|
||||
imports: [
|
||||
ClientsModule.register([
|
||||
{
|
||||
name: 'CONNECTOR_PACKAGE',
|
||||
...connectorClient.config(),
|
||||
},
|
||||
]),
|
||||
],
|
||||
})
|
||||
export class ConnectorModule {}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class UploadConnectorsFileDto {
|
||||
@ApiProperty({ format: 'binary' })
|
||||
file: string;
|
||||
}
|
||||
@@ -4,6 +4,15 @@ export class GetAllDto {
|
||||
@ApiProperty()
|
||||
search: string;
|
||||
|
||||
@ApiProperty()
|
||||
language: string;
|
||||
|
||||
@ApiProperty()
|
||||
size: string;
|
||||
|
||||
@ApiProperty()
|
||||
page: string;
|
||||
|
||||
@ApiProperty()
|
||||
filters: any;
|
||||
}
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
describe('PipelinesGrpcServerService', () => {
|
||||
it('should be defined', () => {
|
||||
expect(2 + 2).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@ import { InputsService } from './inputs.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { InputsClientService } from 'src/clients/inputs/client.service';
|
||||
import { UpdateInputRequest } from 'src/clients/inputs/interfaces';
|
||||
import { Permissions } from '../../authentication/permissions.enum';
|
||||
import { PERMISSIONS } from '../../authentication/permissions.enum';
|
||||
import { AuthenticateCondition } from 'src/authentication/authentication.decorator';
|
||||
import { ApiOkResponse, ApiTags } from '@nestjs/swagger';
|
||||
import {
|
||||
@@ -41,7 +41,7 @@ import {
|
||||
break;
|
||||
|
||||
case 'PATCH':
|
||||
action = 'UPDATE_PARTIAL';
|
||||
action = 'UPDATE';
|
||||
break;
|
||||
|
||||
default:
|
||||
@@ -55,7 +55,7 @@ import {
|
||||
action = 'GET_ENTITIES';
|
||||
}
|
||||
|
||||
return user.permissions.includes(Permissions.INPUT[action].seqid);
|
||||
return user.permissions.includes(PERMISSIONS.INPUT.permissions[action].seqid);
|
||||
})
|
||||
export class InputsController {
|
||||
inputService: InputsService;
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
describe('PipelinesGrpcServerService', () => {
|
||||
it('should be defined', () => {
|
||||
expect(2 + 2).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -7,7 +7,7 @@ import { IIdRequest, Info } from 'src/clients/inputs/interfaces';
|
||||
|
||||
@Injectable()
|
||||
export class InputsService {
|
||||
constructor(private inputClient: InputsClientService) { }
|
||||
constructor(private inputClient: InputsClientService) {}
|
||||
secondsInADay = 60 * 60 * 24;
|
||||
secondsInAnHour = 60 * 60;
|
||||
|
||||
@@ -54,7 +54,7 @@ export class InputsService {
|
||||
switch (data.plugin.toLowerCase()) {
|
||||
case 'csv':
|
||||
case 'json':
|
||||
case 'parquet':
|
||||
case 'parquet': {
|
||||
const { info, ...input } = data;
|
||||
const inputPayload = this.generateInputS3Payload(input);
|
||||
response = await this.inputClient.createS3Inputs({
|
||||
@@ -62,6 +62,7 @@ export class InputsService {
|
||||
info,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'oracle':
|
||||
case 'mysql':
|
||||
case 'postgresql':
|
||||
|
||||
@@ -12,7 +12,7 @@ import { Payload } from '@nestjs/microservices';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { OutputsClientService } from 'src/clients/outputs/client.service';
|
||||
import { AuthenticateCondition } from 'src/authentication/authentication.decorator';
|
||||
import { Permissions } from '../../authentication/permissions.enum';
|
||||
import { PERMISSIONS } from '../../authentication/permissions.enum';
|
||||
import { OutputsService } from './outputs.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
@@ -34,7 +34,9 @@ import { DadosferaLogger } from 'dadosfera-logs';
|
||||
action = req.method;
|
||||
}
|
||||
|
||||
return user.permissions.includes(Permissions.OUTPUT[action].seqid);
|
||||
return user.permissions.includes(
|
||||
PERMISSIONS.OUTPUT.permissions[action].seqid,
|
||||
);
|
||||
})
|
||||
export class OutputsController {
|
||||
logger: any;
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
describe('PipelinesGrpcServerService', () => {
|
||||
it('should be defined', () => {
|
||||
expect(2 + 2).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class PermissionGroupPermission {
|
||||
@ApiProperty()
|
||||
name: string;
|
||||
@ApiProperty()
|
||||
id: number;
|
||||
}
|
||||
|
||||
export class PermissionGroup {
|
||||
@ApiProperty()
|
||||
title: string;
|
||||
@ApiProperty({ type: [PermissionGroupPermission] })
|
||||
permissions: PermissionGroupPermission[];
|
||||
}
|
||||
|
||||
export class Permission {
|
||||
@ApiProperty()
|
||||
id: string;
|
||||
@ApiProperty()
|
||||
seqid: number;
|
||||
@ApiProperty()
|
||||
name: string;
|
||||
@ApiProperty()
|
||||
claim: string;
|
||||
@ApiProperty()
|
||||
createdAt: string;
|
||||
@ApiProperty()
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export class PermissionDto {
|
||||
@ApiProperty()
|
||||
id: number;
|
||||
@ApiProperty()
|
||||
seqid: number;
|
||||
@ApiProperty()
|
||||
name: string;
|
||||
@ApiProperty()
|
||||
claim: string;
|
||||
@ApiProperty()
|
||||
createdAt: string;
|
||||
@ApiProperty()
|
||||
updatedAt: string;
|
||||
}
|
||||
export class GetPublicPermissionsRes {
|
||||
@ApiProperty({ type: [PermissionGroup] })
|
||||
permissionGroups: PermissionGroup[];
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { DucClient } from 'src/clients/duc/client.config';
|
||||
import { PermissionsController } from './permissions.controller';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { PermissionsService } from './permissions.service';
|
||||
|
||||
const ducClient = new DucClient();
|
||||
const logger = {
|
||||
info: (...args) => args,
|
||||
error: (...args) => args,
|
||||
};
|
||||
describe('PermissionsController', () => {
|
||||
let controller: PermissionsController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [
|
||||
ClientsModule.register([
|
||||
{
|
||||
name: 'DUC_PACKAGE',
|
||||
...ducClient.config(),
|
||||
},
|
||||
]),
|
||||
],
|
||||
controllers: [PermissionsController],
|
||||
providers: [
|
||||
{
|
||||
provide: DadosferaLogger,
|
||||
useValue: { logger },
|
||||
},
|
||||
PermissionsService,
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<PermissionsController>(PermissionsController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Controller, Get, Headers, Inject } from '@nestjs/common';
|
||||
import { ApiHeader, ApiOkResponse, ApiTags } from '@nestjs/swagger';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import {
|
||||
Authenticated,
|
||||
RequireAllPermissions,
|
||||
} from 'src/authentication/authentication.decorator';
|
||||
import {
|
||||
PERMISSIONS,
|
||||
PermissionUsages,
|
||||
} from 'src/authentication/permissions.enum';
|
||||
import { RequestUser, User } from 'src/authentication/user.decorator';
|
||||
import { LanguageEnum } from 'src/utils/languages.enum';
|
||||
import { GetPublicPermissionsRes } from './dto/entities';
|
||||
import { PermissionsService } from './permissions.service';
|
||||
|
||||
@ApiTags('Permissions')
|
||||
@Controller('permissions')
|
||||
@ApiHeader({
|
||||
name: 'dadosfera-lang',
|
||||
enum: LanguageEnum,
|
||||
required: false,
|
||||
description: 'Defaults to pt-br',
|
||||
})
|
||||
@Authenticated()
|
||||
export class PermissionsController {
|
||||
logger: any;
|
||||
|
||||
constructor(
|
||||
@Inject(DadosferaLogger)
|
||||
dadosferaLogger: DadosferaLogger,
|
||||
private permissionsService: PermissionsService,
|
||||
) {
|
||||
this.logger = dadosferaLogger.logger;
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOkResponse({ type: GetPublicPermissionsRes })
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
getPublicPermissions(
|
||||
@User() user: RequestUser,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('getPublicPermissions', { user });
|
||||
const permissionGroups = this.permissionsService.getPermissionsGrouped(
|
||||
PermissionUsages.PUBLIC,
|
||||
language,
|
||||
);
|
||||
return { permissionGroups };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
import { PermissionsService } from './permissions.service';
|
||||
|
||||
import { DucClient } from '../../clients/duc/client.config';
|
||||
import { PermissionsController } from './permissions.controller';
|
||||
|
||||
const ducClient = new DucClient();
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ClientsModule.register([
|
||||
{
|
||||
name: 'DUC_PACKAGE',
|
||||
...ducClient.config(),
|
||||
},
|
||||
]),
|
||||
],
|
||||
providers: [PermissionsService, DadosferaLogger],
|
||||
controllers: [PermissionsController],
|
||||
exports: [PermissionsService],
|
||||
})
|
||||
export class PermissionsModule {}
|
||||
@@ -0,0 +1,118 @@
|
||||
import {
|
||||
OnApplicationBootstrap,
|
||||
OnModuleInit,
|
||||
Inject,
|
||||
Injectable,
|
||||
} from '@nestjs/common';
|
||||
import { ClientGrpc } from '@nestjs/microservices';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
|
||||
import { ProtoServices } from 'protospack-v2/dist/lib/Duc';
|
||||
import { PermissionsProtoService as PermissionsServiceInterface } from 'protospack-v2/dist/lib/Duc/interfaces/write-service';
|
||||
import { InjectPermissionsRequest } from 'protospack-v2/dist/lib/Duc/interfaces/messages';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import {
|
||||
PERMISSIONS,
|
||||
PermissionUsages,
|
||||
PermissionsObjectGroup,
|
||||
PermissionsObjectPermissionTranslated,
|
||||
} from '../../authentication/permissions.enum';
|
||||
import ErrorBuilder from '../../utils/ErrorBuilder';
|
||||
import { PermissionGroupPermission, PermissionGroup } from './dto/entities';
|
||||
import { LanguageEnum } from 'src/utils/languages.enum';
|
||||
|
||||
@Injectable()
|
||||
export class PermissionsService
|
||||
implements OnModuleInit, OnApplicationBootstrap
|
||||
{
|
||||
logger: any;
|
||||
|
||||
private permissionsClientService: PermissionsServiceInterface;
|
||||
constructor(
|
||||
@Inject(DadosferaLogger)
|
||||
dadosferaLogger: DadosferaLogger,
|
||||
@Inject('DUC_PACKAGE') private readonly grpcClient: ClientGrpc,
|
||||
) {
|
||||
this.logger = dadosferaLogger.logger;
|
||||
}
|
||||
|
||||
onModuleInit() {
|
||||
this.permissionsClientService =
|
||||
this.grpcClient.getService<PermissionsServiceInterface>(
|
||||
ProtoServices.PermissionsProtoService,
|
||||
);
|
||||
}
|
||||
|
||||
// internally used to send permissions to duc on microservice startup
|
||||
async onApplicationBootstrap() {
|
||||
this.logger.info('sending permissions to DUC...');
|
||||
|
||||
const permissions = Object.values(PERMISSIONS).flatMap((namespace) =>
|
||||
Object.values(namespace.permissions),
|
||||
);
|
||||
|
||||
return this.injectPermissions({
|
||||
permissions,
|
||||
}).catch((err: ErrorBuilder) => {
|
||||
if (
|
||||
err.code === 'No connection established' &&
|
||||
process.env.LOCAL_ENV === 'true'
|
||||
) {
|
||||
return this.logger.info(
|
||||
"couldn't connect to DUC. suppresing in local env",
|
||||
);
|
||||
}
|
||||
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
async injectPermissions({ permissions }: InjectPermissionsRequest) {
|
||||
this.logger.info('InjectPermissions');
|
||||
|
||||
return lastValueFrom(
|
||||
this.permissionsClientService.InjectPermissions({ permissions }),
|
||||
);
|
||||
}
|
||||
getPermissionsGrouped(
|
||||
permissionUsage?: PermissionUsages,
|
||||
language: LanguageEnum = LanguageEnum.ptbr,
|
||||
): PermissionGroup[] {
|
||||
const groups: PermissionGroup[] = [];
|
||||
for (const key in PERMISSIONS) {
|
||||
const permissionGroup: PermissionsObjectGroup = PERMISSIONS[key];
|
||||
const title = permissionGroup.title[language];
|
||||
const permissions: PermissionGroupPermission[] = Object.values(
|
||||
permissionGroup.permissions,
|
||||
)
|
||||
.filter(({ usage }) =>
|
||||
permissionUsage ? usage === permissionUsage : true,
|
||||
)
|
||||
.map(({ seqid, name }) => ({ id: seqid, name: name[language] }));
|
||||
if (permissions?.length)
|
||||
groups.push({
|
||||
title,
|
||||
permissions,
|
||||
});
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
getAllPermissions(language: LanguageEnum = LanguageEnum.ptbr) {
|
||||
let permissions: PermissionsObjectPermissionTranslated[] = [];
|
||||
for (const key in PERMISSIONS) {
|
||||
const permissionGroup: PermissionsObjectGroup = PERMISSIONS[key];
|
||||
const permissionGroupPermissions: PermissionsObjectPermissionTranslated[] =
|
||||
Object.values(permissionGroup.permissions).map((p) => ({
|
||||
...p,
|
||||
name: p.name[language],
|
||||
}));
|
||||
permissions = permissions.concat(permissionGroupPermissions);
|
||||
}
|
||||
return permissions;
|
||||
}
|
||||
getPermissionsBySeqId(seqIds: number[]) {
|
||||
const permissionGroupPermissions = this.getAllPermissions();
|
||||
|
||||
return permissionGroupPermissions.filter((p) => seqIds.includes(p.seqid));
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { PipelinesClientService } from 'src/clients/pipelines/client.service';
|
||||
import { AuthenticateCondition } from 'src/authentication/authentication.decorator';
|
||||
import { Permissions } from '../../authentication/permissions.enum';
|
||||
import { PERMISSIONS } from '../../authentication/permissions.enum';
|
||||
import { PipelinesService } from './pipelines.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
@@ -33,7 +33,9 @@ import { DadosferaLogger } from 'dadosfera-logs';
|
||||
action = req.method;
|
||||
}
|
||||
|
||||
return user.permissions.includes(Permissions.PIPELINE[action].seqid);
|
||||
return user.permissions.includes(
|
||||
PERMISSIONS.PIPELINE.permissions[action].seqid,
|
||||
);
|
||||
})
|
||||
export class PipelinesController {
|
||||
logger: any;
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
describe('PipelinesGrpcServerService', () => {
|
||||
it('should be defined', () => {
|
||||
expect(2 + 2).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { ApiProperty, ApiPropertyOptional, OmitType } from '@nestjs/swagger';
|
||||
import { PermissionDto } from 'src/modules/permissions/dto/entities';
|
||||
import {
|
||||
Customer,
|
||||
UserNoRolesAndCustomer,
|
||||
} from 'src/modules/users/dtos/entities';
|
||||
export class RoleDto {
|
||||
@ApiProperty()
|
||||
id: string;
|
||||
@ApiProperty()
|
||||
name: string;
|
||||
@ApiProperty()
|
||||
description: string;
|
||||
@ApiPropertyOptional({ type: () => [PermissionDto] })
|
||||
permissions: PermissionDto[];
|
||||
@ApiPropertyOptional({ type: () => [UserNoRolesAndCustomer] })
|
||||
users?: UserNoRolesAndCustomer[];
|
||||
@ApiProperty()
|
||||
createdAt: string;
|
||||
@ApiProperty()
|
||||
updatedAt: string;
|
||||
@ApiProperty()
|
||||
isPublic: boolean;
|
||||
@ApiProperty({ type: () => Customer })
|
||||
customer?: Customer;
|
||||
}
|
||||
|
||||
export class CustomerRole extends OmitType(RoleDto, ['customer']) {}
|
||||
export class UserRole extends OmitType(RoleDto, ['users']) {}
|
||||
|
||||
export enum TrueOrFalseEnum {
|
||||
true = 'true',
|
||||
false = 'false',
|
||||
}
|
||||
export class GetRolesByCustomerReq {
|
||||
@ApiPropertyOptional()
|
||||
permissionId: string[];
|
||||
@ApiPropertyOptional({ enum: TrueOrFalseEnum })
|
||||
getUsers: TrueOrFalseEnum;
|
||||
}
|
||||
|
||||
export class GetRolesByCustomerRes {
|
||||
@ApiProperty({ type: [RoleDto] })
|
||||
roles: RoleDto[];
|
||||
}
|
||||
export class CreateRoleReq {
|
||||
@ApiProperty()
|
||||
name: string;
|
||||
@ApiProperty()
|
||||
permissionIds: number[];
|
||||
@ApiPropertyOptional()
|
||||
userIds: string[];
|
||||
@ApiProperty()
|
||||
description: string;
|
||||
}
|
||||
export class CreateRoleRes {
|
||||
@ApiProperty()
|
||||
role: CustomerRole;
|
||||
}
|
||||
|
||||
export class GrantPermissionsToRoleReq {
|
||||
@ApiProperty()
|
||||
roleId: string;
|
||||
@ApiProperty()
|
||||
permissionIds: number[];
|
||||
}
|
||||
export class GrantPermissionsToRoleRes {
|
||||
@ApiProperty()
|
||||
role: RoleDto;
|
||||
}
|
||||
|
||||
export class RevokePermissionsFromRoleReq {
|
||||
@ApiProperty()
|
||||
roleId: string;
|
||||
@ApiProperty()
|
||||
permissionIds: number[];
|
||||
}
|
||||
export class RevokePermissionsFromRoleRes {
|
||||
@ApiProperty()
|
||||
role: RoleDto;
|
||||
}
|
||||
|
||||
export class UpdateRoleReq {
|
||||
@ApiPropertyOptional()
|
||||
name: string;
|
||||
@ApiPropertyOptional()
|
||||
description: string;
|
||||
}
|
||||
|
||||
export class UpdateRoleRes {
|
||||
@ApiProperty()
|
||||
role: RoleDto;
|
||||
}
|
||||
|
||||
export class SetRolePermissionsReq {
|
||||
@ApiProperty()
|
||||
roleId: string;
|
||||
@ApiProperty()
|
||||
permissionIds: number[];
|
||||
}
|
||||
export class SetRolePermissionsRes {
|
||||
@ApiProperty()
|
||||
role: RoleDto;
|
||||
}
|
||||
|
||||
export class SetRoleUsersReq {
|
||||
@ApiProperty()
|
||||
roleId: string;
|
||||
@ApiProperty()
|
||||
userIds: string[];
|
||||
}
|
||||
export class SetRoleUsersRes {
|
||||
@ApiProperty()
|
||||
role: RoleDto;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { DucClient } from 'src/clients/duc/client.config';
|
||||
import { RolesController } from './roles.controller';
|
||||
import { RolesService } from './roles.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
|
||||
const ducClient = new DucClient();
|
||||
|
||||
const logger = {
|
||||
info: (...args) => args,
|
||||
error: (...args) => args,
|
||||
};
|
||||
describe('RolesController', () => {
|
||||
let controller: RolesController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [
|
||||
ClientsModule.register([
|
||||
{
|
||||
name: 'DUC_PACKAGE',
|
||||
...ducClient.config(),
|
||||
},
|
||||
]),
|
||||
PermissionsModule,
|
||||
],
|
||||
controllers: [RolesController],
|
||||
providers: [
|
||||
RolesService,
|
||||
{
|
||||
provide: DadosferaLogger,
|
||||
useValue: { logger },
|
||||
},
|
||||
],
|
||||
exports: [RolesService],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<RolesController>(RolesController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Headers,
|
||||
Inject,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
UseFilters,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiCreatedResponse,
|
||||
ApiHeader,
|
||||
ApiOkResponse,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { RequestUser, User } from 'src/authentication/user.decorator';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { RolesService } from './roles.service';
|
||||
import {
|
||||
GrantPermissionsToRoleReq,
|
||||
GrantPermissionsToRoleRes,
|
||||
CreateRoleReq,
|
||||
CreateRoleRes,
|
||||
GetRolesByCustomerReq,
|
||||
GetRolesByCustomerRes,
|
||||
RevokePermissionsFromRoleReq,
|
||||
RevokePermissionsFromRoleRes,
|
||||
UpdateRoleReq,
|
||||
UpdateRoleRes,
|
||||
RoleDto,
|
||||
SetRolePermissionsReq,
|
||||
SetRolePermissionsRes,
|
||||
SetRoleUsersRes,
|
||||
SetRoleUsersReq,
|
||||
} from './dto/entities';
|
||||
import { GrpcToHttpExceptionFilter } from 'src/error/grpc-to-http-exception.filter';
|
||||
import { PERMISSIONS } from 'src/authentication/permissions.enum';
|
||||
import {
|
||||
Authenticated,
|
||||
RequireAllPermissions,
|
||||
} from 'src/authentication/authentication.decorator';
|
||||
import { LanguageEnum } from 'src/utils/languages.enum';
|
||||
|
||||
@ApiTags('Roles')
|
||||
@ApiHeader({
|
||||
name: 'dadosfera-lang',
|
||||
enum: LanguageEnum,
|
||||
required: false,
|
||||
description: 'Defaults to pt-br',
|
||||
})
|
||||
@UseFilters(new GrpcToHttpExceptionFilter())
|
||||
@Authenticated()
|
||||
@Controller('roles')
|
||||
export class RolesController {
|
||||
logger: any;
|
||||
|
||||
constructor(
|
||||
@Inject(DadosferaLogger)
|
||||
dadosferaLogger: DadosferaLogger,
|
||||
private rolesService: RolesService,
|
||||
) {
|
||||
this.logger = dadosferaLogger.logger;
|
||||
}
|
||||
|
||||
@Get()
|
||||
@ApiOkResponse({ type: GetRolesByCustomerRes })
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
async searchRoles(
|
||||
@User() user: RequestUser,
|
||||
@Query() filters: GetRolesByCustomerReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('searchRoles', { user });
|
||||
this.rolesService.setLanguage(language);
|
||||
return await this.rolesService.roleSearch(filters, user);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@ApiCreatedResponse({ type: CreateRoleRes })
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
async createRole(
|
||||
@User() user: RequestUser,
|
||||
@Body() body: CreateRoleReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('createRole', { user });
|
||||
this.rolesService.setLanguage(language);
|
||||
return await this.rolesService.createRole(body, user);
|
||||
}
|
||||
|
||||
@Put('permissions')
|
||||
@ApiOkResponse({ type: GrantPermissionsToRoleRes })
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
async grantPermissionsToRole(
|
||||
@User() user: RequestUser,
|
||||
@Body() body: GrantPermissionsToRoleReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('grantPermissionsToRole', { user });
|
||||
this.rolesService.setLanguage(language);
|
||||
return await this.rolesService.grantPermissionsToRole(body, user);
|
||||
}
|
||||
|
||||
@Delete('permissions')
|
||||
@ApiOkResponse({ type: RevokePermissionsFromRoleRes })
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
async revokePermissionsFromRole(
|
||||
@User() user: RequestUser,
|
||||
@Body() body: RevokePermissionsFromRoleReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('revokePermissionsToRole', { user });
|
||||
this.rolesService.setLanguage(language);
|
||||
return await this.rolesService.revokePermissionFromRole(body, user);
|
||||
}
|
||||
|
||||
@Patch('permissions')
|
||||
@ApiOkResponse({ type: SetRolePermissionsRes })
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
async setRolePermissions(
|
||||
@User() user: RequestUser,
|
||||
@Body() body: SetRolePermissionsReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('setRolePermissions', { user });
|
||||
this.rolesService.setLanguage(language);
|
||||
return this.rolesService.setRolePermissions(body, user);
|
||||
}
|
||||
|
||||
@Patch('users')
|
||||
@ApiOkResponse({ type: SetRoleUsersRes })
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
async setRoleUsers(
|
||||
@User() user: RequestUser,
|
||||
@Body() body: SetRoleUsersReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('setRoleUsers', { user });
|
||||
this.rolesService.setLanguage(language);
|
||||
return this.rolesService.setRoleUsers(body, user);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOkResponse({ type: RoleDto })
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
async getRoleById(
|
||||
@User() user: RequestUser,
|
||||
@Param('id') id: string,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('getRoleById', { user });
|
||||
this.rolesService.setLanguage(language);
|
||||
return await this.rolesService.getRolesById(id, user);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
async deleteRole(
|
||||
@User() user: RequestUser,
|
||||
@Param('id') id: string,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('deleteRole', { user });
|
||||
this.rolesService.setLanguage(language);
|
||||
return await this.rolesService.removeRole(id, user);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@ApiOkResponse({ type: UpdateRoleRes })
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
async updateRole(
|
||||
@User() user: RequestUser,
|
||||
@Param('id') id: string,
|
||||
@Body() body: UpdateRoleReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('updateRole', { user });
|
||||
this.rolesService.setLanguage(language);
|
||||
return this.rolesService.updateRole(id, body, user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { DucClient } from 'src/clients/duc/client.config';
|
||||
import { RolesController } from './roles.controller';
|
||||
import { RolesService } from './roles.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
|
||||
const ducClient = new DucClient();
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ClientsModule.register([
|
||||
{
|
||||
name: 'DUC_PACKAGE',
|
||||
...ducClient.config(),
|
||||
},
|
||||
]),
|
||||
PermissionsModule,
|
||||
],
|
||||
controllers: [RolesController],
|
||||
providers: [RolesService, DadosferaLogger],
|
||||
exports: [RolesService],
|
||||
})
|
||||
export class RolesModule {}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { RolesController } from './roles.controller';
|
||||
import { RolesService } from './roles.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { DucClient } from 'src/clients/duc/client.config';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
|
||||
const ducClient = new DucClient();
|
||||
|
||||
const logger = {
|
||||
info: (...args) => args,
|
||||
error: (...args) => args,
|
||||
};
|
||||
describe('RolesService', () => {
|
||||
let service: RolesService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [
|
||||
ClientsModule.register([
|
||||
{
|
||||
name: 'DUC_PACKAGE',
|
||||
...ducClient.config(),
|
||||
},
|
||||
]),
|
||||
PermissionsModule,
|
||||
],
|
||||
controllers: [RolesController],
|
||||
providers: [
|
||||
RolesService,
|
||||
{
|
||||
provide: DadosferaLogger,
|
||||
useValue: { logger },
|
||||
},
|
||||
],
|
||||
exports: [RolesService],
|
||||
}).compile();
|
||||
|
||||
service = module.get<RolesService>(RolesService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,260 @@
|
||||
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
|
||||
import { ProtoServices } from 'protospack-v2/dist/lib/Duc';
|
||||
import { RolesProtoService } from 'protospack-v2/dist/lib/Duc/interfaces/write-service';
|
||||
import {
|
||||
CreateRoleReq,
|
||||
GetRolesByCustomerReq,
|
||||
GrantPermissionsToRoleReq,
|
||||
RevokePermissionsFromRoleReq,
|
||||
RoleDto,
|
||||
SetRolePermissionsReq,
|
||||
SetRoleUsersReq,
|
||||
UpdateRoleReq,
|
||||
} from './dto/entities';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { Metadata } from '@grpc/grpc-js';
|
||||
import { ClientGrpc } from '@nestjs/microservices';
|
||||
import { Permission } from 'protospack-v2/dist/lib/Duc/interfaces/entities';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { LanguageEnum } from 'src/utils/languages.enum';
|
||||
import { RequestUser } from 'src/authentication/user.decorator';
|
||||
|
||||
interface GetRolesPermissionsName {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
permissions: Permission[];
|
||||
isPublic?: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@Injectable()
|
||||
export class RolesService {
|
||||
logger: any;
|
||||
private language: LanguageEnum = LanguageEnum.ptbr;
|
||||
private rolesClientService: RolesProtoService;
|
||||
constructor(
|
||||
@Inject(DadosferaLogger)
|
||||
dadosferaLogger: DadosferaLogger,
|
||||
@Inject('DUC_PACKAGE') private readonly grpcClient: ClientGrpc,
|
||||
private permissionsService: PermissionsService,
|
||||
) {
|
||||
this.logger = dadosferaLogger.logger;
|
||||
}
|
||||
setLanguage(lang: LanguageEnum = LanguageEnum.ptbr) {
|
||||
if (Object.values(LanguageEnum).includes(lang)) this.language = lang;
|
||||
this.language = lang;
|
||||
}
|
||||
|
||||
onModuleInit() {
|
||||
this.rolesClientService = this.grpcClient.getService<RolesProtoService>(
|
||||
ProtoServices.RolesProtoService,
|
||||
);
|
||||
}
|
||||
|
||||
async getRolesById(id: string, { access_token }: RequestUser) {
|
||||
const meta = new Metadata();
|
||||
meta.add('access_token', access_token);
|
||||
const role = await lastValueFrom(
|
||||
this.rolesClientService.RoleFindOneById(
|
||||
{
|
||||
id,
|
||||
},
|
||||
meta,
|
||||
),
|
||||
);
|
||||
const [roleTreated] = this.getRolesPermissionsName([role.role]);
|
||||
return { role: roleTreated };
|
||||
}
|
||||
|
||||
async roleSearch(
|
||||
filters: GetRolesByCustomerReq,
|
||||
{ customer_id, access_token }: RequestUser,
|
||||
) {
|
||||
const meta = new Metadata();
|
||||
meta.add('access_token', access_token);
|
||||
let { permissionId: permissionIds } = filters;
|
||||
if (permissionIds && !Array.isArray(permissionIds))
|
||||
permissionIds = [permissionIds];
|
||||
const { getUsers } = filters;
|
||||
const isGetUsers = getUsers === 'true';
|
||||
const permissionSeqIds =
|
||||
permissionIds?.map((id) => {
|
||||
const seqId = Number(id);
|
||||
if (isNaN(seqId))
|
||||
throw new BadRequestException(`permissionId ${id} not valid`);
|
||||
return seqId;
|
||||
}) || [];
|
||||
const roles = await lastValueFrom(
|
||||
this.rolesClientService.RoleSearch(
|
||||
{
|
||||
customerId: customer_id,
|
||||
getUsers: isGetUsers,
|
||||
permissionIds: [],
|
||||
permissionSeqIds,
|
||||
},
|
||||
meta,
|
||||
),
|
||||
);
|
||||
const rolesTreated = this.getRolesPermissionsName(roles.roles);
|
||||
return { roles: rolesTreated };
|
||||
}
|
||||
|
||||
async createRole(
|
||||
data: CreateRoleReq,
|
||||
{ customer_id, access_token }: RequestUser,
|
||||
) {
|
||||
const meta = new Metadata();
|
||||
meta.add('access_token', access_token);
|
||||
const { description, name, permissionIds, userIds } = data;
|
||||
const role = await lastValueFrom(
|
||||
this.rolesClientService.RoleCreate(
|
||||
{
|
||||
customerId: customer_id,
|
||||
name,
|
||||
permissionIds: [],
|
||||
permissionSeqIds: permissionIds,
|
||||
description,
|
||||
userIds,
|
||||
},
|
||||
meta,
|
||||
),
|
||||
);
|
||||
const [roleTreated] = this.getRolesPermissionsName([role.role]);
|
||||
return { role: roleTreated };
|
||||
}
|
||||
|
||||
async removeRole(id: string, { access_token }: RequestUser) {
|
||||
const meta = new Metadata();
|
||||
meta.add('access_token', access_token);
|
||||
return lastValueFrom(this.rolesClientService.RoleRemove({ id }, meta));
|
||||
}
|
||||
async grantPermissionsToRole(
|
||||
{ roleId, permissionIds }: GrantPermissionsToRoleReq,
|
||||
{ access_token }: RequestUser,
|
||||
) {
|
||||
const meta = new Metadata();
|
||||
meta.add('access_token', access_token);
|
||||
const role = await lastValueFrom(
|
||||
this.rolesClientService.GrantPermissionsToRole(
|
||||
{
|
||||
permissionIds: [],
|
||||
roleId,
|
||||
permissionSeqIds: permissionIds,
|
||||
},
|
||||
meta,
|
||||
),
|
||||
);
|
||||
|
||||
const [roleTreated] = this.getRolesPermissionsName([role.role]);
|
||||
return { role: roleTreated };
|
||||
}
|
||||
|
||||
async revokePermissionFromRole(
|
||||
{ roleId, permissionIds }: RevokePermissionsFromRoleReq,
|
||||
{ access_token }: RequestUser,
|
||||
) {
|
||||
const meta = new Metadata();
|
||||
meta.add('access_token', access_token);
|
||||
const role = await lastValueFrom(
|
||||
this.rolesClientService.RevokePermissionsFromRole(
|
||||
{
|
||||
permissionIds: [],
|
||||
roleId,
|
||||
permissionSeqIds: permissionIds,
|
||||
},
|
||||
meta,
|
||||
),
|
||||
);
|
||||
const [roleTreated] = this.getRolesPermissionsName([role.role]);
|
||||
return { role: roleTreated };
|
||||
}
|
||||
|
||||
async updateRole(
|
||||
id: string,
|
||||
req: UpdateRoleReq,
|
||||
{ access_token }: RequestUser,
|
||||
) {
|
||||
const meta = new Metadata();
|
||||
meta.add('access_token', access_token);
|
||||
const { description, name } = req;
|
||||
const role = await lastValueFrom(
|
||||
this.rolesClientService.RoleUpdate(
|
||||
{
|
||||
id,
|
||||
description,
|
||||
name,
|
||||
},
|
||||
meta,
|
||||
),
|
||||
);
|
||||
const [roleTreated] = this.getRolesPermissionsName([role.role]);
|
||||
return { role: roleTreated };
|
||||
}
|
||||
|
||||
async setRolePermissions(
|
||||
req: SetRolePermissionsReq,
|
||||
{ access_token }: RequestUser,
|
||||
) {
|
||||
const meta = new Metadata();
|
||||
meta.add('access_token', access_token);
|
||||
const { roleId: id, permissionIds } = req;
|
||||
const clearPermissions =
|
||||
Array.isArray(permissionIds) && permissionIds.length === 0;
|
||||
const role = await lastValueFrom(
|
||||
this.rolesClientService.RoleSetPermissions(
|
||||
{
|
||||
id,
|
||||
permissionSeqIds: permissionIds,
|
||||
clearPermissions,
|
||||
},
|
||||
meta,
|
||||
),
|
||||
);
|
||||
const [roleTreated] = this.getRolesPermissionsName([role.role]);
|
||||
return { role: roleTreated };
|
||||
}
|
||||
|
||||
async setRoleUsers(req: SetRoleUsersReq, { access_token }: RequestUser) {
|
||||
const meta = new Metadata();
|
||||
meta.add('access_token', access_token);
|
||||
const { roleId: id, userIds } = req;
|
||||
const clearUsers = Array.isArray(userIds) && userIds.length === 0;
|
||||
const role = await lastValueFrom(
|
||||
this.rolesClientService.RoleSetUsers(
|
||||
{
|
||||
id,
|
||||
userIds,
|
||||
clearUsers,
|
||||
},
|
||||
meta,
|
||||
),
|
||||
);
|
||||
const [roleTreated] = this.getRolesPermissionsName([role.role]);
|
||||
return { role: roleTreated };
|
||||
}
|
||||
getRolesPermissionsName(roles: GetRolesPermissionsName[]): RoleDto[] {
|
||||
const newRoles: RoleDto[] = [];
|
||||
for (const role of roles) {
|
||||
const allPermissions = this.permissionsService.getAllPermissions(
|
||||
this.language,
|
||||
);
|
||||
const newPermissions = role.permissions.map((p) => {
|
||||
const permission = allPermissions.find((per) => per.seqid === p.seqid);
|
||||
return {
|
||||
...p,
|
||||
name: permission.name,
|
||||
id: p.seqid,
|
||||
};
|
||||
});
|
||||
const newRole: RoleDto = {
|
||||
...role,
|
||||
permissions: newPermissions,
|
||||
isPublic: role.isPublic,
|
||||
};
|
||||
newRoles.push(newRole);
|
||||
}
|
||||
return newRoles;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Post,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Inject,
|
||||
Headers,
|
||||
UseFilters,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { TermsOfUseAcceptRequest } from 'protospack-v2/dist/lib/Duc/interfaces/messages';
|
||||
|
||||
import { TermsOfUseClientService } from './termsOfUse.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
import { GrpcToHttpExceptionFilter } from '../../error/grpc-to-http-exception.filter';
|
||||
import { RequestUser, User } from '../../authentication/user.decorator';
|
||||
|
||||
@ApiTags('TermsOfUse')
|
||||
@UseFilters(new GrpcToHttpExceptionFilter())
|
||||
@Controller('terms-of-use')
|
||||
export class TermsOfUseController {
|
||||
logger: any;
|
||||
|
||||
constructor(
|
||||
@Inject(DadosferaLogger)
|
||||
dadosferaLogger: DadosferaLogger,
|
||||
private termsOfUseClient: TermsOfUseClientService,
|
||||
) {
|
||||
this.logger = dadosferaLogger.logger;
|
||||
}
|
||||
|
||||
@Get('token')
|
||||
async getToken(@User({ required: true }) user: RequestUser) {
|
||||
this.logger.info('/terms-of-use - get token');
|
||||
|
||||
return this.termsOfUseClient.getToken({ userId: user.user_id });
|
||||
}
|
||||
|
||||
@Post('accept')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async accept(@Body() body: TermsOfUseAcceptRequest, @Headers() headers) {
|
||||
this.logger.info('/terms-of-use - accept');
|
||||
|
||||
const { token } = body;
|
||||
const fingerprint = {
|
||||
ip: process.env.ENV !== 'local' ? headers['x-forwarded-for'] : '0.0.0.0',
|
||||
port: process.env.ENV !== 'local' ? headers['x-forwarded-port'] : '00000',
|
||||
userAgent: headers['user-agent'],
|
||||
};
|
||||
|
||||
return this.termsOfUseClient.accept({ token, fingerprint });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
import { TermsOfUseController } from './termsOfUse.controller';
|
||||
import { TermsOfUseClientService } from './termsOfUse.service';
|
||||
|
||||
import { DucClient } from '../../clients/duc/client.config';
|
||||
const ducClient = new DucClient();
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ClientsModule.register([
|
||||
{
|
||||
name: 'DUC_PACKAGE',
|
||||
...ducClient.config(),
|
||||
},
|
||||
]),
|
||||
],
|
||||
controllers: [TermsOfUseController],
|
||||
providers: [TermsOfUseClientService, DadosferaLogger],
|
||||
exports: [TermsOfUseClientService],
|
||||
})
|
||||
export class TermsOfUseModule {}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { OnModuleInit, Inject, Injectable } from '@nestjs/common';
|
||||
import { ClientGrpc } from '@nestjs/microservices';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
|
||||
import { ProtoServices } from 'protospack-v2/dist/lib/Duc';
|
||||
import { TermsOfUseProtoService as TermsOfUseServiceInterface } from 'protospack-v2/dist/lib/Duc/interfaces/write-service';
|
||||
import {
|
||||
TermsOfUseGetTokenRequest,
|
||||
TermsOfUseAcceptRequest,
|
||||
} from 'protospack-v2/dist/lib/Duc/interfaces/messages';
|
||||
|
||||
@Injectable()
|
||||
export class TermsOfUseClientService implements OnModuleInit {
|
||||
logger: any;
|
||||
|
||||
private termsOfUseService: TermsOfUseServiceInterface;
|
||||
constructor(
|
||||
@Inject(DadosferaLogger)
|
||||
dadosferaLogger: DadosferaLogger,
|
||||
@Inject('DUC_PACKAGE') private readonly grpcClient: ClientGrpc,
|
||||
) {
|
||||
this.logger = dadosferaLogger.logger;
|
||||
}
|
||||
|
||||
onModuleInit() {
|
||||
this.termsOfUseService =
|
||||
this.grpcClient.getService<TermsOfUseServiceInterface>(
|
||||
ProtoServices.TermsOfUseProtoService,
|
||||
);
|
||||
}
|
||||
|
||||
async getToken(data: TermsOfUseGetTokenRequest) {
|
||||
return lastValueFrom(this.termsOfUseService.TermsOfUseGetToken(data));
|
||||
}
|
||||
|
||||
async accept(data: TermsOfUseAcceptRequest) {
|
||||
return lastValueFrom(this.termsOfUseService.TermsOfUseAccept(data));
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import { ApiTags } from '@nestjs/swagger';
|
||||
import { TransformationsClientService } from 'src/clients/transformations/client.service';
|
||||
import { IIdRequest } from 'src/clients/transformations/interfaces';
|
||||
import { AuthenticateCondition } from 'src/authentication/authentication.decorator';
|
||||
import { Permissions } from '../../authentication/permissions.enum';
|
||||
import { PERMISSIONS } from '../../authentication/permissions.enum';
|
||||
import { TransformationsService } from './transformations.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
@@ -35,7 +35,9 @@ import { DadosferaLogger } from 'dadosfera-logs';
|
||||
action = req.method;
|
||||
}
|
||||
|
||||
return user.permissions.includes(Permissions.TRANSFORMATIONS[action].seqid);
|
||||
return user.permissions.includes(
|
||||
PERMISSIONS.TRANSFORMATIONS.permissions[action].seqid,
|
||||
);
|
||||
})
|
||||
export class TransformationsController {
|
||||
logger: any;
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
describe('PipelinesGrpcServerService', () => {
|
||||
it('should be defined', () => {
|
||||
expect(2 + 2).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import { ApiProperty, ApiPropertyOptional, OmitType } from '@nestjs/swagger';
|
||||
import { UserRole } from 'src/modules/roles/dto/entities';
|
||||
|
||||
export class Hierarchy {
|
||||
@ApiProperty()
|
||||
id: string;
|
||||
@ApiProperty()
|
||||
name: string;
|
||||
}
|
||||
export class Customer {
|
||||
@ApiProperty()
|
||||
id: string;
|
||||
@ApiProperty()
|
||||
name: string;
|
||||
@ApiProperty()
|
||||
domain: string;
|
||||
@ApiProperty()
|
||||
tier: string;
|
||||
@ApiProperty()
|
||||
info: string;
|
||||
@ApiProperty()
|
||||
createdAt: string;
|
||||
@ApiProperty()
|
||||
updatedAt: string;
|
||||
}
|
||||
export class User {
|
||||
@ApiProperty()
|
||||
id: string;
|
||||
@ApiProperty()
|
||||
name: string;
|
||||
@ApiProperty()
|
||||
email: string;
|
||||
@ApiProperty({ type: [UserRole] })
|
||||
roles: UserRole[];
|
||||
@ApiProperty()
|
||||
jobTitle?: string;
|
||||
@ApiProperty()
|
||||
department?: string;
|
||||
@ApiProperty()
|
||||
hierarchy?: string;
|
||||
@ApiPropertyOptional()
|
||||
customer?: Customer;
|
||||
@ApiProperty()
|
||||
mfaStatus: string;
|
||||
@ApiProperty()
|
||||
createdAt: string;
|
||||
@ApiProperty()
|
||||
updatedAt: string;
|
||||
@ApiProperty()
|
||||
status: string;
|
||||
@ApiPropertyOptional()
|
||||
lastLogin?: string;
|
||||
}
|
||||
export class UserNoRoles extends OmitType(User, ['roles']) {}
|
||||
export class UserNoRolesAndCustomer extends OmitType(UserNoRoles, [
|
||||
'customer',
|
||||
]) {}
|
||||
export class UserByCustomer extends OmitType(User, ['customer']) {}
|
||||
|
||||
export class CreateUserReq {
|
||||
@ApiPropertyOptional()
|
||||
name?: string;
|
||||
@ApiProperty()
|
||||
email: string;
|
||||
@ApiPropertyOptional()
|
||||
roleNames?: string[];
|
||||
@ApiPropertyOptional()
|
||||
jobTitle?: string;
|
||||
@ApiPropertyOptional()
|
||||
department?: string;
|
||||
@ApiPropertyOptional()
|
||||
hierarchy?: string;
|
||||
}
|
||||
export class CreateUserRes {
|
||||
@ApiProperty()
|
||||
user: User;
|
||||
}
|
||||
export class BatchCreateUserReq {
|
||||
@ApiProperty({ type: [CreateUserReq] })
|
||||
users: CreateUserReq[];
|
||||
}
|
||||
|
||||
class ErrorUsers {
|
||||
@ApiProperty()
|
||||
user: CreateUserReq;
|
||||
@ApiProperty()
|
||||
error: string;
|
||||
}
|
||||
|
||||
export class BatchCreateUserRes {
|
||||
@ApiProperty({ type: [User] })
|
||||
usersCreated: User[];
|
||||
@ApiProperty({ type: [ErrorUsers] })
|
||||
errorUsers: ErrorUsers[];
|
||||
}
|
||||
|
||||
export class UpdateUserReq {
|
||||
@ApiPropertyOptional()
|
||||
name?: string;
|
||||
@ApiPropertyOptional()
|
||||
jobTitle?: string;
|
||||
@ApiPropertyOptional()
|
||||
department?: string;
|
||||
@ApiPropertyOptional()
|
||||
hierarchy?: string;
|
||||
@ApiPropertyOptional()
|
||||
roleNames?: string[];
|
||||
}
|
||||
|
||||
export class UpdateUserRes {
|
||||
@ApiProperty()
|
||||
user: UserByCustomer;
|
||||
}
|
||||
export class GetAllUsersByCustomerIdRes {
|
||||
@ApiProperty({ type: [UserByCustomer] })
|
||||
users: UserByCustomer[];
|
||||
@ApiProperty()
|
||||
departments: string[];
|
||||
@ApiProperty()
|
||||
jobTitles: string[];
|
||||
}
|
||||
|
||||
export class AssignRoleToUserReq {
|
||||
@ApiProperty()
|
||||
userId: string;
|
||||
@ApiProperty()
|
||||
roleId: string;
|
||||
}
|
||||
export class UnassignRoleToUserReq {
|
||||
@ApiProperty()
|
||||
userId: string;
|
||||
@ApiProperty()
|
||||
roleId: string;
|
||||
}
|
||||
export class DeleteUserRes {
|
||||
@ApiProperty()
|
||||
id: string;
|
||||
}
|
||||
|
||||
export class SearchUserReq {
|
||||
@ApiProperty()
|
||||
s: string;
|
||||
}
|
||||
|
||||
export class SetUserRolesReq {
|
||||
@ApiProperty()
|
||||
userId: string;
|
||||
@ApiProperty()
|
||||
roleNames: string[];
|
||||
}
|
||||
|
||||
export class SetUserRolesRes {
|
||||
@ApiProperty()
|
||||
user: UserByCustomer;
|
||||
}
|
||||
|
||||
export class SearchUserRes extends GetAllUsersByCustomerIdRes {}
|
||||
|
||||
export class GetAllHierarchiesRes {
|
||||
@ApiProperty({ type: [Hierarchy] })
|
||||
hierarchies: Hierarchy[];
|
||||
}
|
||||
|
||||
export class GetAllJobTitlesRes {
|
||||
@ApiProperty()
|
||||
jobTitles: string[];
|
||||
}
|
||||
export class GetAllDepartmentsRes {
|
||||
@ApiProperty()
|
||||
departments: string[];
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { LanguageEnum } from 'src/utils/languages.enum';
|
||||
|
||||
interface InternalHierarchyType {
|
||||
name: Record<LanguageEnum, string>;
|
||||
}
|
||||
export const HIERARCHIES: Record<string, InternalHierarchyType> = {
|
||||
presidence: {
|
||||
name: {
|
||||
'pt-br': 'Presidência',
|
||||
'en-us': 'Presidence',
|
||||
},
|
||||
},
|
||||
directory: {
|
||||
name: {
|
||||
'pt-br': 'Diretoria',
|
||||
'en-us': 'Directory',
|
||||
},
|
||||
},
|
||||
management: {
|
||||
name: {
|
||||
'pt-br': 'Gerência',
|
||||
'en-us': 'Management',
|
||||
},
|
||||
},
|
||||
specialist: {
|
||||
name: {
|
||||
'pt-br': 'Especialista',
|
||||
'en-us': 'Specialist',
|
||||
},
|
||||
},
|
||||
supervisor: {
|
||||
name: {
|
||||
'pt-br': 'Coordenador ou Supervisor',
|
||||
'en-us': 'Supervisor',
|
||||
},
|
||||
},
|
||||
trainee: {
|
||||
name: {
|
||||
'pt-br': 'Trainee',
|
||||
'en-us': 'Trainee',
|
||||
},
|
||||
},
|
||||
'senior-analyst': {
|
||||
name: {
|
||||
'pt-br': 'Analista Sênior',
|
||||
'en-us': 'Senior Analyst',
|
||||
},
|
||||
},
|
||||
'midlevel-analyst': {
|
||||
name: {
|
||||
'pt-br': 'Analista Pleno',
|
||||
'en-us': 'Mid-level Analyst',
|
||||
},
|
||||
},
|
||||
'junior-analyst': {
|
||||
name: {
|
||||
'pt-br': 'Analista Júnior',
|
||||
'en-us': 'Junior Analyst',
|
||||
},
|
||||
},
|
||||
intern: {
|
||||
name: {
|
||||
'pt-br': 'Estagiário',
|
||||
'en-us': 'Intern',
|
||||
},
|
||||
},
|
||||
'youth-apprentice': {
|
||||
name: {
|
||||
'pt-br': 'Jovem aprendiz',
|
||||
'en-us': 'Youth Apprentice',
|
||||
},
|
||||
},
|
||||
other: {
|
||||
name: {
|
||||
'pt-br': 'Outro',
|
||||
'en-us': 'Other',
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { DucClient } from 'src/clients/duc/client.config';
|
||||
import { UsersController } from './users.controller';
|
||||
import { UsersService } from './users.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { RolesModule } from '../roles/roles.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
|
||||
const ducClient = new DucClient();
|
||||
|
||||
const logger = {
|
||||
info: (...args) => args,
|
||||
error: (...args) => args,
|
||||
};
|
||||
describe('UsersController', () => {
|
||||
let controller: UsersController;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [
|
||||
ClientsModule.register([
|
||||
{
|
||||
name: 'DUC_PACKAGE',
|
||||
...ducClient.config(),
|
||||
},
|
||||
]),
|
||||
RolesModule,
|
||||
PermissionsModule,
|
||||
],
|
||||
controllers: [UsersController],
|
||||
providers: [
|
||||
UsersService,
|
||||
{
|
||||
provide: DadosferaLogger,
|
||||
useValue: { logger },
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<UsersController>(UsersController);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,238 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Headers,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Inject,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
Req,
|
||||
UseFilters,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiCreatedResponse,
|
||||
ApiHeader,
|
||||
ApiOkResponse,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { RequireAllPermissions } from 'src/authentication/authentication.decorator';
|
||||
import { PERMISSIONS } from 'src/authentication/permissions.enum';
|
||||
import { RequestUser, User } from 'src/authentication/user.decorator';
|
||||
import { GrpcToHttpExceptionFilter } from 'src/error/grpc-to-http-exception.filter';
|
||||
import { LanguageEnum } from 'src/utils/languages.enum';
|
||||
import {
|
||||
AssignRoleToUserReq,
|
||||
BatchCreateUserReq,
|
||||
BatchCreateUserRes,
|
||||
CreateUserReq,
|
||||
CreateUserRes,
|
||||
DeleteUserRes,
|
||||
GetAllDepartmentsRes,
|
||||
GetAllHierarchiesRes,
|
||||
GetAllJobTitlesRes,
|
||||
GetAllUsersByCustomerIdRes,
|
||||
SetUserRolesReq,
|
||||
SetUserRolesRes,
|
||||
UnassignRoleToUserReq,
|
||||
UpdateUserReq,
|
||||
UpdateUserRes,
|
||||
UserByCustomer,
|
||||
} from './dtos/entities';
|
||||
import { UsersService } from './users.service';
|
||||
|
||||
// TODO GET de hierarquias e do PATCH em usuário
|
||||
@ApiTags('Users')
|
||||
@Controller('users')
|
||||
@ApiHeader({
|
||||
name: 'dadosfera-lang',
|
||||
enum: LanguageEnum,
|
||||
required: false,
|
||||
description: 'Defaults to pt-br',
|
||||
})
|
||||
@UseFilters(GrpcToHttpExceptionFilter)
|
||||
export class UsersController {
|
||||
logger: any;
|
||||
|
||||
constructor(
|
||||
@Inject(DadosferaLogger)
|
||||
dadosferaLogger: DadosferaLogger,
|
||||
private userService: UsersService,
|
||||
) {
|
||||
this.logger = dadosferaLogger.logger;
|
||||
}
|
||||
|
||||
@Get()
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
@ApiOkResponse({
|
||||
type: GetAllUsersByCustomerIdRes,
|
||||
description: 'List of users of a customer',
|
||||
})
|
||||
async getAllUsersByCustomerId(
|
||||
@User() user: RequestUser,
|
||||
@Headers('dadosfera-lang') language,
|
||||
): Promise<GetAllUsersByCustomerIdRes> {
|
||||
this.logger.info('getAllUsersByCustomerId', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.findAllUsersByCustomerId(user.customer_id);
|
||||
}
|
||||
|
||||
@Get('hierarchies')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
@ApiOkResponse({ type: GetAllHierarchiesRes })
|
||||
async getAllHierarchies(
|
||||
@User() user: RequestUser,
|
||||
@Headers('dadosfera-lang') language,
|
||||
): Promise<GetAllHierarchiesRes> {
|
||||
this.logger.info('getAllHierarchies', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.getAllHierarchies();
|
||||
}
|
||||
|
||||
@Get('departments')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
@ApiOkResponse({ type: GetAllDepartmentsRes })
|
||||
async getAllDepartments(
|
||||
@User() user: RequestUser,
|
||||
@Headers('dadosfera-lang') language,
|
||||
): Promise<GetAllDepartmentsRes> {
|
||||
this.logger.info('getAllHierarchies', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.getAllDepartments(user.customer_id);
|
||||
}
|
||||
|
||||
@Get('jobTitles')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
@ApiOkResponse({ type: GetAllDepartmentsRes })
|
||||
async getAllJobTitles(
|
||||
@User() user: RequestUser,
|
||||
@Headers('dadosfera-lang') language,
|
||||
): Promise<GetAllJobTitlesRes> {
|
||||
this.logger.info('getAllHierarchies', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.getAllJobTitles(user.customer_id);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
@ApiOkResponse({
|
||||
type: UserByCustomer,
|
||||
})
|
||||
async findOneById(
|
||||
@User() user: RequestUser,
|
||||
@Param('id') id: string,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('findOneById', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.findOneById(id);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
@ApiCreatedResponse({ type: CreateUserRes })
|
||||
async createUser(
|
||||
@User() user: RequestUser,
|
||||
@Body() body: CreateUserReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('createUser', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.createUser(body);
|
||||
}
|
||||
|
||||
@Post('batch')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
@ApiCreatedResponse({ type: BatchCreateUserRes })
|
||||
async batchCreateUser(
|
||||
@User() user: RequestUser,
|
||||
@Body() body: BatchCreateUserReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('batchCreateUser', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.batchCreateUser(body);
|
||||
}
|
||||
|
||||
@Post(':id/resend-invite')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
@HttpCode(HttpStatus.OK)
|
||||
async resendInvite(
|
||||
@User() user: RequestUser,
|
||||
@Param('id') id: string,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('resendInvite', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return this.userService.resendInvite({ id });
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
@ApiOkResponse({ type: DeleteUserRes })
|
||||
async deleteUser(
|
||||
@User() user: RequestUser,
|
||||
@Param('id') id: string,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('deleteUser', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.deleteUser({ id });
|
||||
}
|
||||
|
||||
@Patch('roles')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
@ApiOkResponse({ type: SetUserRolesRes })
|
||||
async setUserRoles(
|
||||
@User() user: RequestUser,
|
||||
@Body() body: SetUserRolesReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('createUser', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.setRoles(body, user.customer_id);
|
||||
}
|
||||
|
||||
@Put('role')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
async assignRoleToUser(
|
||||
@User() user: RequestUser,
|
||||
@Body() body: AssignRoleToUserReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('assignRoleToUser', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.assignRoleToUser(body);
|
||||
}
|
||||
|
||||
@Delete('role')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
async unassignRoleToUser(
|
||||
@User() user: RequestUser,
|
||||
@Req() request: UnassignRoleToUserReq,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('unassignRoleToUser', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.unassignRoleToUser(request);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
@RequireAllPermissions(PERMISSIONS.USERS.permissions.ADMIN)
|
||||
@ApiOkResponse({ type: UpdateUserRes })
|
||||
async updateUser(
|
||||
@User() user: RequestUser,
|
||||
@Body() body: UpdateUserReq,
|
||||
@Param('id') id: string,
|
||||
@Headers('dadosfera-lang') language,
|
||||
) {
|
||||
this.logger.info('updateUser', { user });
|
||||
this.userService.setLanguage(language);
|
||||
return await this.userService.updateUser(body, id, user.customer_id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UsersController } from './users.controller';
|
||||
import { UsersService } from './users.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { DucClient } from 'src/clients/duc/client.config';
|
||||
import { RolesModule } from '../roles/roles.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
|
||||
const ducClient = new DucClient();
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ClientsModule.register([
|
||||
{
|
||||
name: 'DUC_PACKAGE',
|
||||
...ducClient.config(),
|
||||
},
|
||||
]),
|
||||
RolesModule,
|
||||
PermissionsModule,
|
||||
],
|
||||
controllers: [UsersController],
|
||||
providers: [UsersService, DadosferaLogger],
|
||||
})
|
||||
export class UsersModule {}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { ClientsModule } from '@nestjs/microservices';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { UsersController } from './users.controller';
|
||||
import { UsersService } from './users.service';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
import { DucClient } from 'src/clients/duc/client.config';
|
||||
import { RolesModule } from '../roles/roles.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
|
||||
const ducClient = new DucClient();
|
||||
|
||||
const logger = {
|
||||
info: (...args) => args,
|
||||
error: (...args) => args,
|
||||
};
|
||||
describe('UsersService', () => {
|
||||
let service: UsersService;
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [
|
||||
ClientsModule.register([
|
||||
{
|
||||
name: 'DUC_PACKAGE',
|
||||
...ducClient.config(),
|
||||
},
|
||||
]),
|
||||
RolesModule,
|
||||
PermissionsModule,
|
||||
],
|
||||
controllers: [UsersController],
|
||||
providers: [
|
||||
UsersService,
|
||||
{
|
||||
provide: DadosferaLogger,
|
||||
useValue: { logger },
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<UsersService>(UsersService);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import { OnModuleInit, Inject, Injectable } from '@nestjs/common';
|
||||
import { ClientGrpc } from '@nestjs/microservices';
|
||||
import { DadosferaLogger } from 'dadosfera-logs';
|
||||
|
||||
import { ProtoServices } from 'protospack-v2/dist/lib/Duc';
|
||||
import { UsersProtoService } from 'protospack-v2/dist/lib/Duc/interfaces/write-service';
|
||||
import {
|
||||
AssignRoleToUserRequest,
|
||||
IdRequest,
|
||||
UnassignRoleFromUserRequest,
|
||||
UserCreateRequest,
|
||||
} from 'protospack-v2/dist/lib/Duc/interfaces/messages';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
import {
|
||||
BatchCreateUserReq,
|
||||
CreateUserReq,
|
||||
Hierarchy,
|
||||
SetUserRolesReq,
|
||||
UpdateUserReq,
|
||||
} from './dtos/entities';
|
||||
import { RolesService } from '../roles/roles.service';
|
||||
import { HIERARCHIES } from './hierarchies';
|
||||
import { LanguageEnum } from 'src/utils/languages.enum';
|
||||
import { UserByCustomer } from 'protospack-v2/dist/lib/Duc/interfaces/entities';
|
||||
import { EnrichErrorCode } from 'src/utils/ErrorBuilder';
|
||||
|
||||
@Injectable()
|
||||
export class UsersService implements OnModuleInit {
|
||||
logger: any;
|
||||
language: LanguageEnum = LanguageEnum.ptbr;
|
||||
|
||||
private usersClientService: UsersProtoService;
|
||||
constructor(
|
||||
@Inject(DadosferaLogger)
|
||||
dadosferaLogger: DadosferaLogger,
|
||||
@Inject('DUC_PACKAGE') private readonly grpcClient: ClientGrpc,
|
||||
private rolesService: RolesService,
|
||||
) {
|
||||
this.logger = dadosferaLogger.logger;
|
||||
}
|
||||
|
||||
onModuleInit() {
|
||||
this.usersClientService = this.grpcClient.getService<UsersProtoService>(
|
||||
ProtoServices.UsersProtoService,
|
||||
);
|
||||
}
|
||||
|
||||
setLanguage(l: LanguageEnum = LanguageEnum.ptbr) {
|
||||
if (Object.values(LanguageEnum).includes(l)) this.language = l;
|
||||
this.rolesService.setLanguage(l);
|
||||
}
|
||||
|
||||
async findAllUsersByCustomerId(customerId: string) {
|
||||
const { users } = await lastValueFrom(
|
||||
this.usersClientService.UserFindAllByCustomerId({ customerId }),
|
||||
);
|
||||
const usersAdj = this.adjustUsersPayload(users);
|
||||
const dintinctDepartments = [...new Set(usersAdj.map((u) => u.department))]
|
||||
.filter((value) => value != null)
|
||||
.sort();
|
||||
const dintinctJobTitles = [...new Set(usersAdj.map((u) => u.jobTitle))]
|
||||
.filter((value) => value != null)
|
||||
.sort();
|
||||
return {
|
||||
users: usersAdj,
|
||||
jobTitles: dintinctJobTitles,
|
||||
departments: dintinctDepartments,
|
||||
};
|
||||
}
|
||||
|
||||
async findOneById(id: string) {
|
||||
const { user } = await lastValueFrom(
|
||||
this.usersClientService.UserFindOneById({ id }),
|
||||
);
|
||||
return { user: this.adjustUsersPayload([user])[0] };
|
||||
}
|
||||
|
||||
async createUser(req: CreateUserReq) {
|
||||
const { email, department, hierarchy, jobTitle, name, roleNames } = req;
|
||||
const { user } = await lastValueFrom(
|
||||
this.usersClientService.UserCreate({
|
||||
email,
|
||||
hierarchy,
|
||||
name,
|
||||
roleIds: [],
|
||||
department,
|
||||
jobTitle,
|
||||
roleNames,
|
||||
}),
|
||||
);
|
||||
return { user: this.adjustUsersPayload([user])[0] };
|
||||
}
|
||||
|
||||
async updateUser(req: UpdateUserReq, id: string, customerId: string) {
|
||||
const { department, hierarchy, jobTitle, name, roleNames } = req;
|
||||
if (roleNames) {
|
||||
await this.setRoles({ roleNames, userId: id }, customerId);
|
||||
}
|
||||
const { user } = await lastValueFrom(
|
||||
this.usersClientService.UserUpdate({
|
||||
name,
|
||||
customerId,
|
||||
id,
|
||||
department,
|
||||
hierarchy,
|
||||
jobTitle,
|
||||
}),
|
||||
);
|
||||
return { user: this.adjustUsersPayload([user])[0] };
|
||||
}
|
||||
|
||||
async setRoles(body: SetUserRolesReq, customerId: string) {
|
||||
const { roleNames, userId } = body;
|
||||
const clearRoles = roleNames && roleNames.length === 0;
|
||||
const { user } = await lastValueFrom(
|
||||
this.usersClientService.UserSetRoles({
|
||||
userId,
|
||||
roleIds: [],
|
||||
roleNames,
|
||||
clearRoles,
|
||||
customerId,
|
||||
}),
|
||||
);
|
||||
|
||||
return { user: this.adjustUsersPayload([user])[0] };
|
||||
}
|
||||
|
||||
async batchCreateUser({ users }: BatchCreateUserReq) {
|
||||
const usersToCreate: UserCreateRequest[] = users.map(
|
||||
({ roleNames, email, department, hierarchy, jobTitle, name }) => ({
|
||||
roleNames,
|
||||
email,
|
||||
department,
|
||||
hierarchy,
|
||||
jobTitle,
|
||||
name,
|
||||
roleIds: [],
|
||||
}),
|
||||
);
|
||||
const { errorUsers, usersCreated } = await lastValueFrom(
|
||||
this.usersClientService.UserBatchCreate({
|
||||
users: usersToCreate,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
usersCreated: this.adjustUsersPayload(usersCreated),
|
||||
// mapping error code to message
|
||||
errorUsers: errorUsers.map(({ user, error }) => ({
|
||||
user,
|
||||
error: EnrichErrorCode(error).message,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async resendInvite(body: IdRequest) {
|
||||
return lastValueFrom(this.usersClientService.UserResendInvite(body));
|
||||
}
|
||||
|
||||
async assignRoleToUser(body: AssignRoleToUserRequest) {
|
||||
return lastValueFrom(this.usersClientService.AssignRoleToUser(body));
|
||||
}
|
||||
|
||||
async unassignRoleToUser(body: UnassignRoleFromUserRequest) {
|
||||
return lastValueFrom(this.usersClientService.UnassignRoleFromUser(body));
|
||||
}
|
||||
|
||||
async deleteUser(id: IdRequest) {
|
||||
return lastValueFrom(this.usersClientService.UserRemove(id));
|
||||
}
|
||||
|
||||
getAllHierarchies(): { hierarchies: Hierarchy[] } {
|
||||
const hierarchies = Object.keys(HIERARCHIES).map((key) => ({
|
||||
id: key,
|
||||
name: HIERARCHIES[key]?.name[this.language] || key,
|
||||
}));
|
||||
return { hierarchies };
|
||||
}
|
||||
|
||||
async getAllDepartments(customerId?: string) {
|
||||
return lastValueFrom(
|
||||
this.usersClientService.FindDistinctDepartments({ customerId }),
|
||||
);
|
||||
}
|
||||
|
||||
async getAllJobTitles(customerId?: string) {
|
||||
return lastValueFrom(
|
||||
this.usersClientService.FindDistinctJobTitles({ customerId }),
|
||||
);
|
||||
}
|
||||
|
||||
private adjustUsersPayload(users: UserByCustomer[]) {
|
||||
return users.map((u) => {
|
||||
if (!u) return undefined;
|
||||
return {
|
||||
...u,
|
||||
roles: this.rolesService.getRolesPermissionsName(u.roles),
|
||||
hierarchy: HIERARCHIES[u.hierarchy]?.name[this.language] || u.hierarchy,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { RpcException } from '@nestjs/microservices';
|
||||
|
||||
import ErrorCodes from './errorCodes';
|
||||
|
||||
function enrichErrorCode(code: string) {
|
||||
export function EnrichErrorCode(code: string) {
|
||||
switch (code) {
|
||||
case ErrorCodes.AUTH.WRONG_CREDENTIALS:
|
||||
return {
|
||||
@@ -86,6 +86,22 @@ function enrichErrorCode(code: string) {
|
||||
code,
|
||||
};
|
||||
|
||||
case ErrorCodes.TERMS_OF_USE.UP_TO_DATE:
|
||||
return {
|
||||
statusCode: HttpStatus.FORBIDDEN,
|
||||
error: 'Não autorizado',
|
||||
message: 'Você já assinou os termos de uso',
|
||||
code,
|
||||
};
|
||||
|
||||
case ErrorCodes.TERMS_OF_USE.REQUIRED:
|
||||
return {
|
||||
statusCode: HttpStatus.FORBIDDEN,
|
||||
error: 'Não autorizado',
|
||||
message: 'É necessário aceitar os termos de uso para prosseguir',
|
||||
code,
|
||||
};
|
||||
|
||||
case ErrorCodes.RATE_LIMIT:
|
||||
return {
|
||||
statusCode: HttpStatus.TOO_MANY_REQUESTS,
|
||||
@@ -112,6 +128,49 @@ function enrichErrorCode(code: string) {
|
||||
code,
|
||||
};
|
||||
|
||||
case ErrorCodes.ROLE.ALREADY_EXIST:
|
||||
return {
|
||||
statusCode: HttpStatus.BAD_REQUEST,
|
||||
error: 'Grupo já existe',
|
||||
message: 'Não é possível criar um grupo com esse nome',
|
||||
code,
|
||||
};
|
||||
case ErrorCodes.ROLE.NOT_FOUND:
|
||||
case ErrorCodes.ROLE.FROM_ANOTHER_CUSTOMER:
|
||||
return {
|
||||
statusCode: HttpStatus.NOT_FOUND,
|
||||
error: 'Grupo não encontrado',
|
||||
message: 'Grupo solicitado não encontrado',
|
||||
code: ErrorCodes.ROLE.NOT_FOUND,
|
||||
};
|
||||
case ErrorCodes.ROLE.CANNOT_EDIT_PUBLIC_ROLE:
|
||||
return {
|
||||
statusCode: HttpStatus.FORBIDDEN,
|
||||
error: 'Grupo público',
|
||||
message: 'Você não tem permissão para editar esse grupo',
|
||||
code,
|
||||
};
|
||||
case ErrorCodes.USER.NOT_FOUND:
|
||||
return {
|
||||
statusCode: HttpStatus.NOT_FOUND,
|
||||
error: 'Usuário não encontrado',
|
||||
message: 'Usuário solicitado não encontrado',
|
||||
code,
|
||||
};
|
||||
case ErrorCodes.USER.ALREADY_EXISTS:
|
||||
return {
|
||||
statusCode: HttpStatus.NOT_FOUND,
|
||||
error: 'Usuário encontrado',
|
||||
message: 'Nome de usuário já existente',
|
||||
code,
|
||||
};
|
||||
case ErrorCodes.USER.INVALID_ID:
|
||||
return {
|
||||
statusCode: HttpStatus.NOT_FOUND,
|
||||
error: 'Id inválido',
|
||||
message: 'Id encontra-se num formato inválido',
|
||||
code,
|
||||
};
|
||||
case ErrorCodes.INTERNAL:
|
||||
case ErrorCodes.UNKNOWN:
|
||||
default:
|
||||
@@ -121,6 +180,7 @@ function enrichErrorCode(code: string) {
|
||||
message:
|
||||
'Erro desconhecido. Tente novamente ou entre em contato com o suporte',
|
||||
code: ErrorCodes.UNKNOWN,
|
||||
details: code,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -130,16 +190,22 @@ const logger = new Logger();
|
||||
export default class ErrorBuilder extends HttpException {
|
||||
code: string;
|
||||
|
||||
constructor(code: string | RpcException) {
|
||||
constructor(code: string | RpcException = '') {
|
||||
if (typeof code !== 'string') {
|
||||
logger.log(code.stack);
|
||||
logger.log(code?.stack);
|
||||
code = (code as any).details as string;
|
||||
} else {
|
||||
logger.log(code);
|
||||
}
|
||||
|
||||
const { statusCode, message, error, code: rCode } = enrichErrorCode(code);
|
||||
super({ statusCode, message, error, code: rCode }, statusCode);
|
||||
const {
|
||||
statusCode,
|
||||
message,
|
||||
error,
|
||||
code: rCode,
|
||||
details,
|
||||
} = EnrichErrorCode(code);
|
||||
super({ statusCode, message, error, code: rCode, details }, statusCode);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,12 +13,40 @@ export const AUTH = {
|
||||
RESET_PASSWORD_CODE_INVALID: 'AUTH.RESET_PASSWORD_CODE_INVALID',
|
||||
WEAK_NEW_PASSWORD: 'AUTH.WEAK_NEW_PASSWORD',
|
||||
};
|
||||
export const ROLE = {
|
||||
ALREADY_EXIST: 'ROLE.ALREADY_EXISTS',
|
||||
NOT_FOUND: 'ROLE.NOT_FOUND',
|
||||
FROM_ANOTHER_CUSTOMER: 'ROLE.FROM_ANOTHER_CUSTOMER',
|
||||
CANNOT_EDIT_PUBLIC_ROLE: 'ROLE.CANNOT_EDIT_PUBLIC_ROLE',
|
||||
};
|
||||
|
||||
export const USER = {
|
||||
INVALID_ID: 'USER.INVALID_ID',
|
||||
NOT_FOUND: 'USER.NOT_FOUND',
|
||||
ALREADY_EXISTS: 'USER.ALREADY_EXISTS',
|
||||
ROLE_ALREADY_ASSIGNED: 'USER.ROLE_ALREADY_ASSIGNED',
|
||||
ROLE_NOT_ASSIGNED: 'USER.ROLE_NOT_ASSIGNED',
|
||||
};
|
||||
|
||||
export const CUSTOMER = {
|
||||
INVALID_ID: 'CUSTOMER.INVALID_ID',
|
||||
NOT_FOUND: 'CUSTOMER.NOT_FOUND',
|
||||
ALREADY_EXISTS: 'CUSTOMER.ALREADY_EXISTS',
|
||||
};
|
||||
const TERMS_OF_USE = {
|
||||
UP_TO_DATE: 'TERMS_OF_USE.UP_TO_DATE',
|
||||
REQUIRED: 'TERMS_OF_USE.REQUIRED',
|
||||
};
|
||||
|
||||
const ErrorCodes = {
|
||||
UNKNOWN: 'UNKNOWN',
|
||||
RATE_LIMIT: 'RATE_LIMIT',
|
||||
INTERNAL: 'INTERNAL',
|
||||
AUTH,
|
||||
ROLE,
|
||||
TERMS_OF_USE,
|
||||
USER,
|
||||
CUSTOMER,
|
||||
};
|
||||
|
||||
export default ErrorCodes;
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { RpcException } from '@nestjs/microservices';
|
||||
import { from } from 'rxjs';
|
||||
|
||||
import ErrorBuilder from './ErrorBuilder';
|
||||
|
||||
const logger = new Logger();
|
||||
|
||||
export default async function grpcHandler<T>(method: Promise<T>) {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
from(method).subscribe({
|
||||
next: resolve,
|
||||
error: reject,
|
||||
complete: () => logger.log('done'),
|
||||
});
|
||||
}).catch((err: RpcException) => {
|
||||
throw new ErrorBuilder(err);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export enum LanguageEnum {
|
||||
ptbr = 'pt-br',
|
||||
enus = 'en-us',
|
||||
}
|
||||
Reference in New Issue
Block a user