FEAT: magalu id login

This commit is contained in:
Gabriel Rosa
2023-12-06 20:36:14 -03:00
parent faa98cae8b
commit 86b076246e
10 changed files with 2910 additions and 1584 deletions
+5 -5
View File
@@ -39,11 +39,11 @@ jobs:
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
uses: actions/checkout@v3
uses: actions/checkout@v4
- if: github.event_name != 'workflow_dispatch'
name: Semantic Release
uses: cycjimmy/semantic-release-action@v3
uses: cycjimmy/semantic-release-action@v4
id: semantic
with:
extra_plugins: |
@@ -76,7 +76,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Update Pip
run: |
@@ -95,14 +95,14 @@ jobs:
python3 -m pip install awsebcli --upgrade
- name: Configure AWS Region
uses: aws-actions/configure-aws-credentials@v1-node16
uses: aws-actions/configure-aws-credentials@v4
id: aws
with:
aws-region: us-east-1
- name: Login to AWS ECR
id: login_ecr
uses: aws-actions/amazon-ecr-login@v1
uses: aws-actions/amazon-ecr-login@v2
- name: Build, Tag, and Push Image to AWS ECR
env:
+2 -1
View File
@@ -12,6 +12,7 @@
"start:debug"
],
"runtimeExecutable": "npm",
"runtimeVersion": "18.10.0",
"skipFiles": [
"<node_internals>/**"
],
@@ -19,4 +20,4 @@
"console": "integratedTerminal"
}
]
}
}
+62 -1
View File
@@ -542,6 +542,67 @@
]
}
},
"/auth/oauth/magalu-id": {
"get": {
"operationId": "AuthController_magaluIdOauth",
"parameters": [
{
"name": "dadosfera-lang",
"in": "header",
"required": false,
"schema": {
"enum": [
"pt-br",
"en-us"
],
"type": "string"
}
}
],
"responses": {
"200": {
"description": "",
"content": {
"application/json": {
"schema": {
"type": "boolean"
}
}
}
}
},
"tags": [
"Auth"
]
}
},
"/auth/oauth/magalu-id/callback": {
"get": {
"operationId": "AuthController_magaluIdOauthCallback",
"parameters": [
{
"name": "dadosfera-lang",
"in": "header",
"required": false,
"schema": {
"enum": [
"pt-br",
"en-us"
],
"type": "string"
}
}
],
"responses": {
"200": {
"description": ""
}
},
"tags": [
"Auth"
]
}
},
"/connections": {
"post": {
"operationId": "ConnectionController_createConnection",
@@ -5076,7 +5137,7 @@
}
},
"info": {
"title": "Maestro - feat/generate-token",
"title": "Maestro - ci/dockerhub",
"description": "This is the Maestro API",
"version": "1.0.0",
"contact": {}
+2707 -1557
View File
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -29,7 +29,7 @@
"dependencies": {
"@aws-sdk/client-secrets-manager": "^3.112.0",
"@dadosfera/dadosfera-logs": "^1.0.0-beta.4",
"@dadosfera/protospack-v2": "3.31.0",
"@dadosfera/protospack-v2": "3.32.0-beta.1",
"@grpc/grpc-js": "^1.6.7",
"@grpc/proto-loader": "^0.6.13",
"@nestjs/cli": "^9.4.2",
@@ -43,7 +43,7 @@
"@nestjs/schematics": "^9.1.0",
"@nestjs/swagger": "^6.3.0",
"@nestjs/testing": "^9.4.0",
"axios": "^0.27.2",
"axios": "^1.6.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"cron-parser": "^4.4.0",
@@ -80,8 +80,8 @@
"@types/passport-google-oauth20": "^2.0.11",
"@types/passport-oauth2": "^1.4.11",
"@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^5.29.0",
"@typescript-eslint/parser": "^5.29.0",
"@typescript-eslint/eslint-plugin": "^5.35.0",
"@typescript-eslint/parser": "^5.35.0",
"eslint": "^8.18.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.0.0",
+78 -10
View File
@@ -101,9 +101,6 @@ export class AuthController {
this.logger.info('/auth - RefreshAccessToken');
const { refreshToken, customerName: customer_name } = body;
this.logger.info(`refreshToken: ${refreshToken}`)
this.logger.info(`body: ${body}`);
const metadata = PackTheMetadata({
customer_name,
language,
@@ -272,7 +269,13 @@ export class AuthController {
@UseGuards(AuthGuard('google-login'))
@Redirect()
async googleOauthCallback(@Req() req) {
const { url, email, token, language = 'pt-br' } = await this.callback(req);
const {
url,
email,
token,
refreshToken,
language = 'pt-br',
} = await this.callback(req);
if (url.searchParams.get('error')) {
this.logger.error('/oauth/google - ERROR');
return { url: url.href };
@@ -282,6 +285,7 @@ export class AuthController {
.oauthSignIn({
username: email,
token,
refreshToken,
})
.then(({ session }) => {
this.logger.info('/oauth/google - SUCESS');
@@ -311,11 +315,70 @@ export class AuthController {
return { url: url.href };
}
async callback(req: Request) {
@ApiInternalOnlyEndpoint()
@Get('oauth/magalu-id')
@UseGuards(AuthGuard('magalu-id-login'))
magaluIdOauth() {
this.logger.info('/oauth/magalu-id');
return true;
}
@ApiInternalOnlyEndpoint()
@Get('oauth/magalu-id/callback')
@UseGuards(AuthGuard('magalu-id-login'))
@Redirect()
async magaluIdOauthCallback(@Req() req) {
const {
url,
email,
token,
refreshToken,
language = 'pt-br',
} = await this.callback(req, 'magalu-id');
if (url.searchParams.get('error')) {
this.logger.error('/oauth/magalu-id - ERROR');
return { url: url.href };
}
await this.authClient
.oauthSignIn({
username: email,
token,
refreshToken,
})
.then(({ session }) => {
this.logger.info('/oauth/magalu-id - SUCESS');
url.searchParams.set('session', session);
})
.catch((err) => {
this.logger.error('/oauth/magalu-id - ERROR');
let error = OauthErrors.INVALID_CREDENTIALS[language].error;
let error_description =
OauthErrors.INVALID_CREDENTIALS[language].error_description;
switch (err.details) {
case ErrorCodes.USER.NOT_FOUND:
error = OauthErrors.USER_NOT_FOUND[language].error;
error_description =
OauthErrors.USER_NOT_FOUND[language].error_description(email);
break;
case ErrorCodes.AUTH.UNAUTHORIZED:
error = OauthErrors.INVALID_SESSION[language].error;
error_description =
OauthErrors.INVALID_SESSION[language].error_description;
break;
}
url.searchParams.set('error', error);
url.searchParams.set('error_description', error_description);
return null;
});
return { url: url.href };
}
async callback(req: Request, oauth_type?: 'google' | 'magalu-id') {
const { error, state } = req.query;
const { authInfo } = req;
const url = new URL(this.redirectUrl);
let email, token, error_title, error_description;
let email, token, refreshToken, error_title, error_description;
let language: 'pt-br' | 'en-us' = 'pt-br';
const stateObject = jwt.verify(
@@ -333,11 +396,16 @@ export class AuthController {
OauthErrors.INVALID_CREDENTIALS[language].error_description;
if (error) error_description += ` - [${error}]`;
} else {
const { accessToken } = authInfo as any;
const { _json: userInfo } = req.user as any;
const { accessToken, refreshToken: rt } = authInfo as any;
const { _json: userInfo = {} } = req.user as any;
email = userInfo.email;
token = accessToken;
refreshToken = rt;
if (oauth_type === 'magalu-id') {
const jwtDecoded = jwt.decode(token, { json: true });
email = jwtDecoded.email;
}
}
if (error_title) {
@@ -345,6 +413,6 @@ export class AuthController {
url.searchParams.set('error_description', error_description);
}
return { token, email, url, language };
return { token, refreshToken, email, url, language };
}
}
+2
View File
@@ -8,6 +8,7 @@ import { AuthClientService } from './auth.service';
import { DucClient } from '../duc/client.config';
import { GoogleLoginStrategy } from './passport-strategies/google-strategy';
import { getOauthSecrets } from 'src/utils/OauthSecrets';
import { MagaluIdStrategy } from './passport-strategies/magalu-id-strategy';
const client = new DucClient();
@Module({
@@ -17,6 +18,7 @@ const client = new DucClient();
AuthClientService,
DadosferaLogger,
GoogleLoginStrategy,
MagaluIdStrategy,
{ provide: 'OAUTH_SECRETS', useValue: getOauthSecrets() },
],
exports: [AuthClientService],
+3 -3
View File
@@ -17,6 +17,7 @@ import {
AuthResetPasswordRequest,
AuthVerifyResetPasswordCodeRequest,
AuthConfirmResetPasswordRequest,
AuthOauthSignInRequest,
} from '@dadosfera/protospack-v2/dist/lib/Duc/interfaces/messages';
import { DucClient } from '../duc/client.config';
import { Metadata } from '@grpc/grpc-js';
@@ -162,8 +163,7 @@ export class AuthClientService implements OnModuleInit {
return lastValueFrom(this.authService.AuthGetSession({ session }));
}
async oauthSignIn(data: { username: string; token: string }) {
const { username, token } = data;
return lastValueFrom(this.authService.AuthOauthSignIn({ token, username }));
async oauthSignIn(data: AuthOauthSignInRequest) {
return lastValueFrom(this.authService.AuthOauthSignIn(data));
}
}
@@ -0,0 +1,45 @@
import {
Strategy as Oauth2Strategy,
StrategyOptions,
VerifyCallback,
VerifyFunction,
} from 'passport-oauth2';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable } from '@nestjs/common';
import { OauthSecrets } from 'src/utils/OauthSecrets';
import { Request } from 'express';
import jwt from 'jsonwebtoken';
@Injectable()
export class MagaluIdStrategy extends PassportStrategy(
Oauth2Strategy,
'magalu-id-login',
) {
redirect_uri: string;
constructor() {
const options: StrategyOptions = {
clientID: process.env.MAGALU_ID_CLIENT_ID,
clientSecret: process.env.MAGALU_ID_CLIENT_SECRET,
callbackURL: process.env.MAGALU_ID_CALLBACK_URL,
scope: ['openid'],
authorizationURL: 'https://id.magalu.com/login',
tokenURL: 'https://id.magalu.com/oauth/token',
};
const verify: VerifyFunction = (
accessToken: string,
refreshToken: string,
profile: any,
verified: VerifyCallback,
) => {
return verified(null, profile, { accessToken, refreshToken });
};
super(options, verify);
}
authenticate(req: Request, options: Record<string, any>) {
const language = req.headers['dadosfera-lang'] || req.query.language;
options.state = jwt.sign({ language }, process.env.JWT_PRIVATE_KEY);
super.authenticate(req, options);
}
}
+2 -3
View File
@@ -51,12 +51,11 @@ class CatalogService implements OnModuleInit {
const cloud_environment = process.env.CLOUD_ENVIRONMENT || 'aws';
if ((process.env.ENV === 'prd') && (cloud_environment === 'aws')) {
if (process.env.ENV === 'prd' && cloud_environment === 'aws') {
return `https://nimbus-${customer}.dadosfera.ai`;
}
if ((process.env.ENV === 'prd' && (cloud_environment === 'mgc'))) {
if (process.env.ENV === 'prd' && cloud_environment === 'mgc') {
return `https://nimbus-${customer}.dadosfera.com`;
}