mirror of
https://github.com/dadosfera/maestro.git
synced 2026-11-18 13:59:08 +00:00
Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6ababbe7a | ||
|
|
82290285d0 | ||
|
|
c490814a98 | ||
|
|
7616b1e32c | ||
|
|
3ba2c91893 | ||
|
|
e789076ed4 | ||
|
|
3b6ddaaee6 | ||
|
|
8073194604 | ||
|
|
cd2c53b5c5 | ||
|
|
adf1b3b97e | ||
|
|
d84b5e184b | ||
|
|
6d608a0457 | ||
|
|
b8be2c7803 | ||
|
|
24fce721e3 | ||
|
|
23a9a27db1 | ||
|
|
0f5ed50af9 | ||
|
|
5f8f6a64ab | ||
|
|
8800ac2736 | ||
|
|
bdb82c2ce4 | ||
|
|
6d9ecc3568 | ||
|
|
7764447adc | ||
|
|
576fdecf89 | ||
|
|
3de1e90fa8 | ||
|
|
5e90950660 | ||
|
|
3ed26e648f | ||
|
|
fff3523152 | ||
|
|
19e4daeea4 | ||
|
|
8624d3f016 | ||
|
|
dc1d1400d8 | ||
|
|
06ba759ea3 |
@@ -56,9 +56,9 @@ jobs:
|
|||||||
|
|
||||||
- name: Install Helmfile
|
- name: Install Helmfile
|
||||||
run: |
|
run: |
|
||||||
wget https://github.com/helmfile/helmfile/releases/download/v0.148.0/helmfile_0.148.0_linux_amd64.tar.gz
|
curl -fsSLO https://github.com/helmfile/helmfile/releases/download/v0.148.0/helmfile_0.148.0_linux_amd64.tar.gz
|
||||||
tar -xzf helmfile_0.148.0_linux_amd64.tar.gz
|
tar -xzf helmfile_0.148.0_linux_amd64.tar.gz
|
||||||
mv helmfile /usr/local/bin/
|
sudo mv helmfile /usr/local/bin/
|
||||||
helmfile --version
|
helmfile --version
|
||||||
|
|
||||||
- name: Install Helm Diff Plugin
|
- name: Install Helm Diff Plugin
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Maestro
|
# Maestro
|
||||||
|
|
||||||
Maestro é a API principal da Dadosfera. É responsável pela comunicação do Frontend com nossos microsserviços.
|
Maestro é a API principal da Dadosfera. É responsável pela comunicação do Frontend com nossos microsserviços.
|
||||||
|
|||||||
@@ -104,6 +104,8 @@ spec:
|
|||||||
value: {{ .Values.maestro.redis_host }}
|
value: {{ .Values.maestro.redis_host }}
|
||||||
- name: REDIS_PORT
|
- name: REDIS_PORT
|
||||||
value: "{{ .Values.maestro.redis_port }}"
|
value: "{{ .Values.maestro.redis_port }}"
|
||||||
|
- name: REDIS_TLS
|
||||||
|
value: "{{ .Values.maestro.redis_tls }}"
|
||||||
- name: JWT_PRIVATE_KEY
|
- name: JWT_PRIVATE_KEY
|
||||||
valueFrom:
|
valueFrom:
|
||||||
secretKeyRef:
|
secretKeyRef:
|
||||||
|
|||||||
@@ -4,9 +4,18 @@ metadata:
|
|||||||
annotations:
|
annotations:
|
||||||
nginx.ingress.kubernetes.io/whitelist-source-range: "69.49.241.121/32" # hostgator ip
|
nginx.ingress.kubernetes.io/whitelist-source-range: "69.49.241.121/32" # hostgator ip
|
||||||
nginx.ingress.kubernetes.io/proxy-body-size: "0"
|
nginx.ingress.kubernetes.io/proxy-body-size: "0"
|
||||||
|
nginx.ingress.kubernetes.io/proxy-read-timeout: "300"
|
||||||
|
nginx.ingress.kubernetes.io/proxy-connect-timeout: "300"
|
||||||
|
nginx.ingress.kubernetes.io/proxy-send-timeout: "300"
|
||||||
nginx.ingress.kubernetes.io/server-snippet: |
|
nginx.ingress.kubernetes.io/server-snippet: |
|
||||||
underscores_in_headers on;
|
underscores_in_headers on;
|
||||||
ignore_invalid_headers on;
|
ignore_invalid_headers on;
|
||||||
|
nginx.ingress.kubernetes.io/proxy-buffer-size: "16k"
|
||||||
|
nginx.ingress.kubernetes.io/proxy-buffers-number: "8"
|
||||||
|
nginx.ingress.kubernetes.io/proxy-busy-buffers-size: "64k"
|
||||||
|
{{- if .Values.maestro.restricted_ip}}
|
||||||
|
nginx.ingress.kubernetes.io/whitelist-source-range: {{ .Values.maestro.restricted_ip }}
|
||||||
|
{{- end }}
|
||||||
|
|
||||||
generation: 1
|
generation: 1
|
||||||
labels:
|
labels:
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ maestro:
|
|||||||
redis_host: "aaapzppmlyamkocqwstpo7zvopczyyiyuy6xzm2g6c5k4mq3a66be4a-0.redis.sa-saopaulo-1.oci.oraclecloud.com"
|
redis_host: "aaapzppmlyamkocqwstpo7zvopczyyiyuy6xzm2g6c5k4mq3a66be4a-0.redis.sa-saopaulo-1.oci.oraclecloud.com"
|
||||||
redis_port: "6379"
|
redis_port: "6379"
|
||||||
redis_database: "0"
|
redis_database: "0"
|
||||||
|
redis_tls: "true"
|
||||||
cookie_secret: "13cc5e136d3074bcc05bec8697092ec1f5f376bf"
|
cookie_secret: "13cc5e136d3074bcc05bec8697092ec1f5f376bf"
|
||||||
autoscaling:
|
autoscaling:
|
||||||
enabled: false
|
enabled: false
|
||||||
|
|||||||
Vendored
+1
@@ -16,6 +16,7 @@ declare global {
|
|||||||
OPEN_CUSTOMER_ID: string;
|
OPEN_CUSTOMER_ID: string;
|
||||||
DEDICATED_PROXY: string;
|
DEDICATED_PROXY: string;
|
||||||
COOKIE_SECRET: string;
|
COOKIE_SECRET: string;
|
||||||
|
REDIS_TLS?: string;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import jwt, { JwtPayload } from 'jsonwebtoken';
|
||||||
|
|
||||||
|
export function extractUserFrom(aRawJwt: string) {
|
||||||
|
const decodedToken = jwt.decode(aRawJwt, {
|
||||||
|
complete: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = decodedToken.payload as JwtPayload;
|
||||||
|
|
||||||
|
return {
|
||||||
|
user_id: payload.user_id,
|
||||||
|
username: payload.username,
|
||||||
|
permissions: payload.permissions,
|
||||||
|
customer_id: payload.customer_id,
|
||||||
|
customer_name: payload.customer_name,
|
||||||
|
customer_tier: payload.customer_tier,
|
||||||
|
customer_modules: payload.customer_modules,
|
||||||
|
access_token: aRawJwt,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,6 +26,7 @@ async function bootstrap() {
|
|||||||
corsOrigins.push(
|
corsOrigins.push(
|
||||||
'https://app.stg.dadosfera.ai',
|
'https://app.stg.dadosfera.ai',
|
||||||
'https://app.dadosfera.ai',
|
'https://app.dadosfera.ai',
|
||||||
|
'https://private-frontend.stg.dadosfera.ai',
|
||||||
'https://unimed.dadosfera.ai',
|
'https://unimed.dadosfera.ai',
|
||||||
'https://boston-scientific.dadosfera.ai',
|
'https://boston-scientific.dadosfera.ai',
|
||||||
'https://plataforma.dadosfera.ai'
|
'https://plataforma.dadosfera.ai'
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Controller, Post, Body, Put, Get} from '@nestjs/common';
|
import { Controller, Body, Put, Get, NotFoundException} from '@nestjs/common';
|
||||||
import { AssignService } from './assign.service';
|
import { AssignService } from './assign.service';
|
||||||
import { CreateAssignDto } from './dto/create-assign.dto';
|
import { CreateAssignDto } from './dto/create-assign.dto';
|
||||||
import { Authenticated, RequireModule, RequireSomePermission } from 'src/decorators/authentication.decorator';
|
import { Authenticated, RequireModule, RequireSomePermission } from 'src/decorators/authentication.decorator';
|
||||||
@@ -28,6 +28,10 @@ export class AssignController {
|
|||||||
@RequireModule(DADOSFERA_MODULES_KEYS.EMBED_ASSIGNED)
|
@RequireModule(DADOSFERA_MODULES_KEYS.EMBED_ASSIGNED)
|
||||||
async get(@User() user: RequestUser) {
|
async get(@User() user: RequestUser) {
|
||||||
const metadata = PackTheMetadata(user);
|
const metadata = PackTheMetadata(user);
|
||||||
return await this.assignService.get(metadata);
|
try {
|
||||||
|
return await this.assignService.get(metadata);
|
||||||
|
} catch (error) {
|
||||||
|
throw new NotFoundException(error.message)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
Req,
|
Req,
|
||||||
Param,
|
Param,
|
||||||
Res,
|
Res,
|
||||||
|
UnauthorizedException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
import {
|
import {
|
||||||
ApiHeaders,
|
ApiHeaders,
|
||||||
@@ -54,7 +55,6 @@ import jwt, { JwtPayload } from 'jsonwebtoken';
|
|||||||
import { LanguageEnum } from 'src/utils/languages.enum';
|
import { LanguageEnum } from 'src/utils/languages.enum';
|
||||||
import { Language } from 'src/decorators/language.decorator';
|
import { Language } from 'src/decorators/language.decorator';
|
||||||
import { ApiInternalOnlyEndpoint } from 'src/decorators/swagger.decorator';
|
import { ApiInternalOnlyEndpoint } from 'src/decorators/swagger.decorator';
|
||||||
import { Cookie } from 'express-session';
|
|
||||||
|
|
||||||
type CookiesValues = {
|
type CookiesValues = {
|
||||||
accessToken?: string;
|
accessToken?: string;
|
||||||
@@ -103,14 +103,13 @@ export class AuthController {
|
|||||||
const data = await this.authClient.signIn({ username, password, totp }, metadata);
|
const data = await this.authClient.signIn({ username, password, totp }, metadata);
|
||||||
|
|
||||||
if (data.tokens) {
|
if (data.tokens) {
|
||||||
this.addTokenInCookie(res, {
|
this.authClient.writeAuthSession(res, {
|
||||||
accessToken: data.tokens.accessToken,
|
accessToken: data.tokens.accessToken,
|
||||||
refreshToken: data.tokens.refreshToken,
|
refreshToken: data.tokens.refreshToken,
|
||||||
userId: data.user.id
|
userId: data.user.id
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
return res.send(data);
|
return res.send(data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error('/auth - SignIn - ERROR', error);
|
this.logger.error('/auth - SignIn - ERROR', error);
|
||||||
@@ -127,27 +126,8 @@ export class AuthController {
|
|||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
this.logger.info('/auth - SignOut');
|
this.logger.info('/auth - SignOut');
|
||||||
const exp = 1000 * 60 * 3;
|
|
||||||
|
this.authClient.cleanUpAuthSession(res);
|
||||||
res.cookie('ddf-auth', '', {
|
|
||||||
domain: 'dadosfera.local',
|
|
||||||
maxAge: Date.now() - exp,
|
|
||||||
expires: new Date(),
|
|
||||||
httpOnly: true,
|
|
||||||
secure: true,
|
|
||||||
sameSite: 'none', // Necessário para cookies em requisições cross-site
|
|
||||||
});
|
|
||||||
|
|
||||||
res.cookie('ddf-refresh-auth', '', {
|
|
||||||
domain: 'dadosfera.local',
|
|
||||||
maxAge: Date.now() - exp,
|
|
||||||
expires: new Date(),
|
|
||||||
httpOnly: true,
|
|
||||||
secure: true,
|
|
||||||
sameSite: 'none', // Necessário para cookies em requisições cross-site
|
|
||||||
});
|
|
||||||
|
|
||||||
this.logger.info('Clean cookie sessions');
|
|
||||||
|
|
||||||
return res.send();
|
return res.send();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -176,8 +156,9 @@ export class AuthController {
|
|||||||
|
|
||||||
const data = await this.authClient.refreshAccessToken({ refreshToken, userId }, metadata);
|
const data = await this.authClient.refreshAccessToken({ refreshToken, userId }, metadata);
|
||||||
|
|
||||||
this.addTokenInCookie(res, {
|
this.authClient.writeAuthSession(res, {
|
||||||
accessToken: data.accessToken,
|
accessToken: data.accessToken,
|
||||||
|
refreshToken: data.refreshToken,
|
||||||
userId
|
userId
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -493,114 +474,36 @@ export class AuthController {
|
|||||||
@Get('me')
|
@Get('me')
|
||||||
async getMe(@Req() req: Request, @Res() res: Response) {
|
async getMe(@Req() req: Request, @Res() res: Response) {
|
||||||
this.logger.info('GET /auth/me ')
|
this.logger.info('GET /auth/me ')
|
||||||
// Lê cookies
|
|
||||||
|
// Get token and headers
|
||||||
const accessToken = req.cookies['ddf-auth'];
|
const accessToken = req.cookies['ddf-auth'];
|
||||||
const userId = req.cookies['ddf-user-id'];
|
const refreshToken = req.cookies['ddf-refresh-auth'];
|
||||||
|
const userId = req.cookies['ddf-user-id'];
|
||||||
|
const resourceHost = req.headers["host"]
|
||||||
|
|
||||||
|
const hasUserSession = Boolean(accessToken) && Boolean(userId);
|
||||||
|
this.logger.info('Has User Session: ' + hasUserSession);
|
||||||
|
|
||||||
|
if (!hasUserSession) {
|
||||||
|
throw new UnauthorizedException()
|
||||||
|
}
|
||||||
|
|
||||||
this.logger.info('Has cookie: ' + Boolean(accessToken))
|
|
||||||
let payload: any;
|
|
||||||
let userInfo: any = {};
|
|
||||||
try {
|
try {
|
||||||
// Decodifica e valida o JWT de acesso
|
const userDto = await this.authClient.validateUserSession(accessToken, resourceHost);
|
||||||
const decoded: any = accessToken && jwt.decode(accessToken, { complete: true });
|
return res.status(200).json(userDto);
|
||||||
if (!decoded) throw new Error('Invalid token')
|
} catch (error) {
|
||||||
const { kid } = decoded.header;
|
|
||||||
// Busca a chave pública
|
|
||||||
const { keys } = await this.authClient.getPublicKeys();
|
|
||||||
const pemValue = keys.find((k) => k.kid === kid)?.pem;
|
|
||||||
if (!pemValue) throw new Error('Public key not found');
|
|
||||||
jwt.verify(accessToken, pemValue);
|
|
||||||
payload = decoded.payload;
|
|
||||||
userInfo = {
|
|
||||||
id: payload.user_id,
|
|
||||||
name: payload.username,
|
|
||||||
customer: {
|
|
||||||
id: payload.customer_id,
|
|
||||||
name: payload.customer_name,
|
|
||||||
tier: payload.customer_tier,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return res.status(200).json(userInfo);
|
|
||||||
} catch (err) {
|
|
||||||
this.logger.error(err.message);
|
|
||||||
const refreshToken = req.cookies['ddf-refresh-auth'];
|
|
||||||
|
|
||||||
this.logger.info('Token is invalid')
|
if (!refreshToken) {
|
||||||
this.logger.info('Has Refresh Token: '+ Boolean(refreshToken))
|
|
||||||
// Se access token inválido, tenta refresh
|
|
||||||
if (!refreshToken || !userId) {
|
|
||||||
this.logger.error('Invalid refresh token or customer name');
|
this.logger.error('Invalid refresh token or customer name');
|
||||||
return res.status(401).json({ error: 'Not authenticated' });
|
throw new UnauthorizedException("Invalid refresh token or customer name");
|
||||||
}
|
};
|
||||||
try {
|
|
||||||
// Chama refreshAccessToken
|
|
||||||
const metadata = PackTheMetadata({
|
|
||||||
});
|
|
||||||
this.logger.info('Call Refresh Token')
|
|
||||||
const data = await this.authClient.refreshAccessToken({ refreshToken, userId }, metadata);
|
|
||||||
this.logger.info('Finish Refresh Token')
|
|
||||||
// Retorna novo access token e dados mínimos
|
|
||||||
this.addTokenInCookie(res, {
|
|
||||||
accessToken: data.accessToken,
|
|
||||||
userId
|
|
||||||
});
|
|
||||||
// Decodifica novo token
|
|
||||||
const decoded: any = jwt.decode(data.accessToken, { complete: true });
|
|
||||||
const payload = decoded.payload;
|
|
||||||
userInfo = {
|
|
||||||
id: payload.user_id,
|
|
||||||
name: payload.username,
|
|
||||||
customer: {
|
|
||||||
id: payload.customer_id,
|
|
||||||
name: payload.customer_name,
|
|
||||||
tier: payload.customer_tier,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return res.status(200).json(userInfo);
|
|
||||||
} catch (refreshErr) {
|
|
||||||
this.logger.error(refreshErr)
|
|
||||||
return res.status(401).json({ error: 'Not authenticated' });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private addTokenInCookie(res: Response, data: CookiesValues) {
|
const {
|
||||||
let exp = 1000 * 60 * 5; // 5 minutes
|
authSession,
|
||||||
|
user
|
||||||
if (data.accessToken) {
|
} = await this.authClient.refreshUserSession(refreshToken, userId, resourceHost);
|
||||||
const { exp: expiration } = jwt.decode(data.accessToken) as JwtPayload;
|
this.authClient.writeAuthSession(res, authSession);
|
||||||
exp = (expiration - 30) * 1000; // exp em segundos, maxAge em ms
|
return res.status(200).json(user);
|
||||||
|
|
||||||
this.logger.info('Set Cookie ddf-auth')
|
|
||||||
res.cookie('ddf-auth', data.accessToken, {
|
|
||||||
domain: '.dadosfera.ai',
|
|
||||||
maxAge: exp,
|
|
||||||
httpOnly: true,
|
|
||||||
secure: true,
|
|
||||||
sameSite: 'none', // Necessário para cookies em requisições cross-site
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.refreshToken) {
|
|
||||||
this.logger.info('Set Cookie ddf-refresh-auth')
|
|
||||||
res.cookie('ddf-refresh-auth', data.refreshToken, {
|
|
||||||
domain: '.dadosfera.ai',
|
|
||||||
maxAge: exp,
|
|
||||||
httpOnly: true,
|
|
||||||
secure: true,
|
|
||||||
sameSite: 'none', // Necessário para cookies em requisições cross-site
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.userId) {
|
|
||||||
this.logger.info('Set Cookie ddf-refresh-auth')
|
|
||||||
res.cookie('ddf-user-id', data.userId, {
|
|
||||||
domain: '.dadosfera.ai',
|
|
||||||
maxAge: exp,
|
|
||||||
httpOnly: true,
|
|
||||||
secure: true,
|
|
||||||
sameSite: 'none', // Necessário para cookies em requisições cross-site
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,20 @@
|
|||||||
import { OnModuleInit, Inject, Injectable, ForbiddenException } from '@nestjs/common';
|
import {
|
||||||
|
OnModuleInit,
|
||||||
|
Inject,
|
||||||
|
Injectable,
|
||||||
|
ForbiddenException,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
import { ClientGrpc } from '@nestjs/microservices';
|
import { ClientGrpc } from '@nestjs/microservices';
|
||||||
import { DadosferaLogger } from '@dadosfera/dadosfera-logs';
|
import { DadosferaLogger } from '@dadosfera/dadosfera-logs';
|
||||||
import { lastValueFrom } from 'rxjs';
|
import { lastValueFrom } from 'rxjs';
|
||||||
|
|
||||||
import { ProtoServices } from '@dadosfera/protospack-v2/dist/lib/Duc';
|
import { ProtoServices } from '@dadosfera/protospack-v2/dist/lib/Duc';
|
||||||
import { AuthProtoService as AuthServiceInterface, IdentityProviderProtoService } from '@dadosfera/protospack-v2/dist/lib/Duc/interfaces/write-service';
|
import {
|
||||||
|
AuthProtoService as AuthServiceInterface,
|
||||||
|
IdentityProviderProtoService,
|
||||||
|
UsersProtoService,
|
||||||
|
} from '@dadosfera/protospack-v2/dist/lib/Duc/interfaces/write-service';
|
||||||
import {
|
import {
|
||||||
AuthSnowflakeSignInRequest,
|
AuthSnowflakeSignInRequest,
|
||||||
AuthSignInRequest,
|
AuthSignInRequest,
|
||||||
@@ -21,18 +31,24 @@ import {
|
|||||||
} from '@dadosfera/protospack-v2/dist/lib/Duc/interfaces/messages';
|
} from '@dadosfera/protospack-v2/dist/lib/Duc/interfaces/messages';
|
||||||
import { DucClient } from '../duc/client.config';
|
import { DucClient } from '../duc/client.config';
|
||||||
import { Metadata } from '@grpc/grpc-js';
|
import { Metadata } from '@grpc/grpc-js';
|
||||||
import { BulkEditResponse } from './dtos/login';
|
import { BulkEditResponse, UserDTO } from './dtos/login';
|
||||||
|
import jwt, { JwtPayload } from 'jsonwebtoken';
|
||||||
|
import { PackTheMetadata } from 'src/utils/PackTheMetadata';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
|
||||||
|
type AuthSession = {
|
||||||
|
accessToken?: string;
|
||||||
|
refreshToken?: string;
|
||||||
|
userId?: string;
|
||||||
|
};
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthClientService implements OnModuleInit {
|
export class AuthClientService implements OnModuleInit {
|
||||||
|
|
||||||
|
|
||||||
logger: DadosferaLogger;
|
logger: DadosferaLogger;
|
||||||
|
|
||||||
|
|
||||||
private authService: AuthServiceInterface;
|
private authService: AuthServiceInterface;
|
||||||
private identityProviderService: IdentityProviderProtoService;
|
private userService: UsersProtoService;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@Inject(DadosferaLogger)
|
@Inject(DadosferaLogger)
|
||||||
dadosferaLogger: DadosferaLogger,
|
dadosferaLogger: DadosferaLogger,
|
||||||
@@ -46,8 +62,8 @@ export class AuthClientService implements OnModuleInit {
|
|||||||
ProtoServices.AuthProtoService,
|
ProtoServices.AuthProtoService,
|
||||||
);
|
);
|
||||||
|
|
||||||
this.identityProviderService = this.grpcClient.getService<IdentityProviderProtoService>(
|
this.userService = this.grpcClient.getService<UsersProtoService>(
|
||||||
ProtoServices.IdentityProviderProtoService,
|
ProtoServices.UsersProtoService,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,11 +79,11 @@ export class AuthClientService implements OnModuleInit {
|
|||||||
return lastValueFrom(this.authService.AuthSnowflakeSignIn(input));
|
return lastValueFrom(this.authService.AuthSnowflakeSignIn(input));
|
||||||
}
|
}
|
||||||
|
|
||||||
checkDedicatedProxy({
|
checkDedicatedProxy({ customer }: AuthSignInResponse) {
|
||||||
customer
|
|
||||||
}: AuthSignInResponse) {
|
|
||||||
const DEDICATED_PROXY = process.env.DEDICATED_PROXY || '';
|
const DEDICATED_PROXY = process.env.DEDICATED_PROXY || '';
|
||||||
this.logger.info('SignIn - Setting customer ID for dedicated proxy: ' + DEDICATED_PROXY);
|
this.logger.info(
|
||||||
|
'SignIn - Setting customer ID for dedicated proxy: ' + DEDICATED_PROXY,
|
||||||
|
);
|
||||||
this.logger.info('Customer ID: ' + customer.id);
|
this.logger.info('Customer ID: ' + customer.id);
|
||||||
|
|
||||||
if (DEDICATED_PROXY !== '' && DEDICATED_PROXY !== customer.id) {
|
if (DEDICATED_PROXY !== '' && DEDICATED_PROXY !== customer.id) {
|
||||||
@@ -75,7 +91,9 @@ export class AuthClientService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Bloquear o customer de acesso o maestro publico
|
// Bloquear o customer de acesso o maestro publico
|
||||||
this.logger.info('Check if customer have network policy: ' + customer.modules);
|
this.logger.info(
|
||||||
|
'Check if customer have network policy: ' + customer.modules,
|
||||||
|
);
|
||||||
const hasNetworkPolicyModule = customer.modules.includes('network-policy');
|
const hasNetworkPolicyModule = customer.modules.includes('network-policy');
|
||||||
if (hasNetworkPolicyModule && DEDICATED_PROXY === '') {
|
if (hasNetworkPolicyModule && DEDICATED_PROXY === '') {
|
||||||
throw new ForbiddenException();
|
throw new ForbiddenException();
|
||||||
@@ -94,7 +112,6 @@ export class AuthClientService implements OnModuleInit {
|
|||||||
result = await lastValueFrom(
|
result = await lastValueFrom(
|
||||||
this.authService.AuthSignIn({ username, password, totp }, metadata),
|
this.authService.AuthSignIn({ username, password, totp }, metadata),
|
||||||
);
|
);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error('SignIn - Error during sign-in');
|
this.logger.error('SignIn - Error during sign-in');
|
||||||
this.logger.error(error);
|
this.logger.error(error);
|
||||||
@@ -105,7 +122,7 @@ export class AuthClientService implements OnModuleInit {
|
|||||||
this.checkDedicatedProxy(result);
|
this.checkDedicatedProxy(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
async refreshAccessToken(
|
async refreshAccessToken(
|
||||||
@@ -115,7 +132,10 @@ export class AuthClientService implements OnModuleInit {
|
|||||||
this.logger.info('RefreshAccessToken');
|
this.logger.info('RefreshAccessToken');
|
||||||
|
|
||||||
return lastValueFrom(
|
return lastValueFrom(
|
||||||
this.authService.AuthRefreshAccessToken({ refreshToken, userId }, metadata),
|
this.authService.AuthRefreshAccessToken(
|
||||||
|
{ refreshToken, userId },
|
||||||
|
metadata,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,4 +303,178 @@ export class AuthClientService implements OnModuleInit {
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async validateUserSession(accessToken: any, originHeader: string) {
|
||||||
|
const payload = await this.validateJwtToken(accessToken);
|
||||||
|
|
||||||
|
const userDto = await this.getUserfromPayload(payload);
|
||||||
|
|
||||||
|
this.validateResourceAccess(originHeader, userDto);
|
||||||
|
return userDto;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async refreshUserSession(
|
||||||
|
refreshToken: string,
|
||||||
|
userId: string,
|
||||||
|
originHeader: string,
|
||||||
|
): Promise<{
|
||||||
|
user: UserDTO;
|
||||||
|
authSession: AuthSession;
|
||||||
|
}> {
|
||||||
|
const metadata = PackTheMetadata({});
|
||||||
|
|
||||||
|
this.logger.info('Call Refresh Token');
|
||||||
|
const refreshCredentials = await this.refreshAccessToken(
|
||||||
|
{ refreshToken, userId },
|
||||||
|
metadata,
|
||||||
|
);
|
||||||
|
this.logger.info('Finish Refresh Token');
|
||||||
|
|
||||||
|
const userDto = await this.validateUserSession(
|
||||||
|
refreshCredentials.accessToken,
|
||||||
|
originHeader,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
user: userDto,
|
||||||
|
authSession: {
|
||||||
|
accessToken: refreshCredentials.accessToken,
|
||||||
|
refreshToken: refreshCredentials.refreshToken,
|
||||||
|
userId,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public writeAuthSession(res: Response, data: AuthSession) {
|
||||||
|
let exp = 1000 * 60 * 5; // 5 minutes
|
||||||
|
|
||||||
|
if (data.accessToken) {
|
||||||
|
const { exp: expiration } = jwt.decode(data.accessToken) as JwtPayload;
|
||||||
|
exp = (expiration - 30) * 1000; // exp em segundos, maxAge em ms
|
||||||
|
|
||||||
|
this.logger.info('Set Cookie ddf-auth');
|
||||||
|
res.cookie('ddf-auth', data.accessToken, {
|
||||||
|
domain: '.dadosfera.ai',
|
||||||
|
maxAge: exp,
|
||||||
|
httpOnly: true,
|
||||||
|
secure: true,
|
||||||
|
sameSite: 'none', // Necessário para cookies em requisições cross-site
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.refreshToken) {
|
||||||
|
this.logger.info('Set Cookie ddf-refresh-auth');
|
||||||
|
res.cookie('ddf-refresh-auth', data.refreshToken, {
|
||||||
|
domain: '.dadosfera.ai',
|
||||||
|
maxAge: exp,
|
||||||
|
httpOnly: true,
|
||||||
|
secure: true,
|
||||||
|
sameSite: 'none', // Necessário para cookies em requisições cross-site
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.userId) {
|
||||||
|
this.logger.info('Set Cookie ddf-refresh-auth');
|
||||||
|
res.cookie('ddf-user-id', data.userId, {
|
||||||
|
domain: '.dadosfera.ai',
|
||||||
|
maxAge: exp,
|
||||||
|
httpOnly: true,
|
||||||
|
secure: true,
|
||||||
|
sameSite: 'none', // Necessário para cookies em requisições cross-site
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public cleanUpAuthSession(res: Response) {
|
||||||
|
const exp = 1000 * 60 * 3;
|
||||||
|
|
||||||
|
res.cookie('ddf-auth', '', {
|
||||||
|
domain: 'dadosfera.ai',
|
||||||
|
maxAge: Date.now() - exp,
|
||||||
|
expires: new Date(),
|
||||||
|
httpOnly: true,
|
||||||
|
secure: true,
|
||||||
|
sameSite: 'none', // Necessário para cookies em requisições cross-site
|
||||||
|
});
|
||||||
|
|
||||||
|
res.cookie('ddf-refresh-auth', '', {
|
||||||
|
domain: 'dadosfera.ai',
|
||||||
|
maxAge: Date.now() - exp,
|
||||||
|
expires: new Date(),
|
||||||
|
httpOnly: true,
|
||||||
|
secure: true,
|
||||||
|
sameSite: 'none', // Necessário para cookies em requisições cross-site
|
||||||
|
});
|
||||||
|
|
||||||
|
this.logger.info('Clean cookie sessions');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async validateJwtToken(token: string) {
|
||||||
|
const decoded: any = token && jwt.decode(token, { complete: true });
|
||||||
|
if (!decoded) throw new Error('Invalid token');
|
||||||
|
|
||||||
|
const { kid } = decoded.header;
|
||||||
|
// Busca a chave pública
|
||||||
|
const { keys } = await this.getPublicKeys();
|
||||||
|
const pemValue = keys.find((k) => k.kid === kid)?.pem;
|
||||||
|
if (!pemValue) throw new Error('Public key not found');
|
||||||
|
jwt.verify(token, pemValue);
|
||||||
|
|
||||||
|
return decoded.payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getUserfromPayload(payload: JwtPayload): Promise<UserDTO> {
|
||||||
|
this.logger.info('getUser');
|
||||||
|
|
||||||
|
const metadata = PackTheMetadata({
|
||||||
|
customer_id: payload.customer_id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { user } = await lastValueFrom(
|
||||||
|
this.userService.UserFindOneById({ id: payload.user_id }, metadata),
|
||||||
|
);
|
||||||
|
|
||||||
|
const userDto: UserDTO = {
|
||||||
|
id: user.id,
|
||||||
|
name: user.username,
|
||||||
|
jobTitle: user?.jobTitle || null,
|
||||||
|
department: user?.department || null,
|
||||||
|
hierarchy: user?.hierarchy || null,
|
||||||
|
customer: {
|
||||||
|
id: payload.customer_id,
|
||||||
|
name: payload.customer_name,
|
||||||
|
tier: payload.customer_tier,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return userDto;
|
||||||
|
}
|
||||||
|
|
||||||
|
private validateResourceAccess(host: string, user: UserDTO) {
|
||||||
|
this.logger.info(
|
||||||
|
"Validate whether the source URL is a resource belonging to the user's client",
|
||||||
|
);
|
||||||
|
this.logger.info('Host: ' + host);
|
||||||
|
this.logger.info('Customer: ' + user.customer.name);
|
||||||
|
|
||||||
|
const hostParts = host.split('.');
|
||||||
|
const domain = hostParts[0];
|
||||||
|
const isResouceStg = hostParts[1] === 'stg';
|
||||||
|
|
||||||
|
const domainParts = domain.split('-');
|
||||||
|
const customerInDomain = domainParts[domainParts.length - 1];
|
||||||
|
|
||||||
|
if (isResouceStg && process.env.ENV !== 'stg') {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
`Customer ${user.customer.name} cannot access ${origin}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (customerInDomain != user.customer.name) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
`Customer ${user.customer.name} cannot access ${origin}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -140,3 +140,16 @@ export interface BulkEditResponse {
|
|||||||
successfulUsers: string[];
|
successfulUsers: string[];
|
||||||
failedUsers: string[];
|
failedUsers: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type UserDTO = {
|
||||||
|
id: string,
|
||||||
|
name: string,
|
||||||
|
jobTitle?: string,
|
||||||
|
department?: string,
|
||||||
|
hierarchy?: string,
|
||||||
|
customer: {
|
||||||
|
id: string,
|
||||||
|
name: string,
|
||||||
|
tier: string,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -197,9 +197,11 @@ class CatalogService implements OnModuleInit {
|
|||||||
async getUserRolesIds(userId: string) {
|
async getUserRolesIds(userId: string) {
|
||||||
const result = await this.userService.findOneById(userId).catch(() => null);
|
const result = await this.userService.findOneById(userId).catch(() => null);
|
||||||
|
|
||||||
const roles_ids = result.user.roles.map((role) => role.id);
|
if (result) {
|
||||||
|
return result.user.roles.map((role) => role.id);
|
||||||
|
}
|
||||||
|
|
||||||
return roles_ids;
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
async searchDataAssets(
|
async searchDataAssets(
|
||||||
|
|||||||
@@ -1,29 +1,46 @@
|
|||||||
import { Body, Controller, Inject, Param, Post, Req } from '@nestjs/common';
|
import { Body, Controller, Inject, Param, Post, Req } from '@nestjs/common';
|
||||||
import { init } from 'mixpanel';
|
|
||||||
import { Authenticated } from 'src/decorators/authentication.decorator';
|
|
||||||
import { ApiInternalOnlyController } from 'src/decorators/swagger.decorator';
|
import { ApiInternalOnlyController } from 'src/decorators/swagger.decorator';
|
||||||
import { RequestUser, User } from 'src/decorators/user.decorator';
|
import { RequestUser } from 'src/decorators/user.decorator';
|
||||||
import { MixpanelService } from './mixpanel.service';
|
import { MixpanelService } from './mixpanel.service';
|
||||||
|
import { extractUserFrom } from 'src/authentication/extract-user';
|
||||||
|
import DadosferaLogger from '@dadosfera/dadosfera-logs';
|
||||||
|
|
||||||
@ApiInternalOnlyController()
|
@ApiInternalOnlyController()
|
||||||
@Controller('trackEvent')
|
@Controller('trackEvent')
|
||||||
export class MixpanelController {
|
export class MixpanelController {
|
||||||
|
logger: DadosferaLogger;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private mixpanelService: MixpanelService
|
@Inject(DadosferaLogger)
|
||||||
) {}
|
dadosferaLogger: DadosferaLogger,
|
||||||
|
private mixpanelService: MixpanelService,
|
||||||
|
) {
|
||||||
|
this.logger = dadosferaLogger.logger;
|
||||||
|
}
|
||||||
|
|
||||||
@Post(':id')
|
@Post(':id')
|
||||||
async trackEvent(
|
async trackEvent(
|
||||||
@Param('id') id,
|
@Param('id') id,
|
||||||
@Body() body,
|
@Body() body,
|
||||||
@User() user: RequestUser,
|
|
||||||
@Req() request
|
@Req() request
|
||||||
) {
|
) {
|
||||||
|
this.logger.info(`POST Track Event: ${id}`)
|
||||||
delete body.info;
|
delete body.info;
|
||||||
|
|
||||||
|
const anonymousUser = {
|
||||||
|
username: "anonymous",
|
||||||
|
customer_name: "anonymous"
|
||||||
|
} as RequestUser
|
||||||
|
|
||||||
|
const hasToken = request.headers['authorization'];
|
||||||
|
|
||||||
|
const user = hasToken ? extractUserFrom(hasToken) : anonymousUser;
|
||||||
|
|
||||||
|
this.logger.info(`Has user: ${typeof hasToken == "string"}`)
|
||||||
|
|
||||||
await this.mixpanelService.track(id, user, request, body)
|
await this.mixpanelService.track(id, user, request, body)
|
||||||
|
|
||||||
|
this.logger.info(`Event successful`)
|
||||||
return { id, body, user: user.username };
|
return { id, body, user: user.username };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import { redisStore } from 'cache-manager-ioredis-yet';
|
|||||||
keyPrefix: 'maestro:sso',
|
keyPrefix: 'maestro:sso',
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.env.ENV !== 'local') {
|
if (process.env.REDIS_TLS === 'true') {
|
||||||
baseRedisConfig['tls'] = {
|
baseRedisConfig['tls'] = {
|
||||||
servername: process.env.REDIS_HOST,
|
servername: process.env.REDIS_HOST,
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user