Skip to content

Commit

Permalink
Merge pull request #131 from infinitybase/staging
Browse files Browse the repository at this point in the history
Staging
  • Loading branch information
guimroque authored Jun 26, 2024
2 parents 7d579a7 + 95bf515 commit c861d0e
Show file tree
Hide file tree
Showing 23 changed files with 236 additions and 145 deletions.
3 changes: 3 additions & 0 deletions packages/api/src/config/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ const test: ConnectionOptions = {
entities: [entitiesDir],
migrations: [migrationsDir, seedersDir],
synchronize: false,
ssl: {
rejectUnauthorized: false,
},
migrationsRun: true,
};

Expand Down
23 changes: 10 additions & 13 deletions packages/api/src/middlewares/auth/index.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,36 @@
import { Request, Response, NextFunction } from 'express';
import { request } from 'http';

import { RecoverCode, RecoverCodeType } from '@src/models';
import { PermissionRoles, Workspace } from '@src/models/Workspace';
import { TokenUtils } from '@src/utils';
import { validatePermissionGeneral } from '@src/utils/permissionValidate';

import { ErrorTypes } from '@utils/error';
import { Unauthorized, UnauthorizedErrorTitles } from '@utils/error/Unauthorized';

import { IAuthRequest } from './types';
import app from '@src/server/app';

async function authMiddleware(req: Request, res: Response, next: NextFunction) {
try {
const requestAuth: IAuthRequest = req;
const signature = requestAuth?.headers?.authorization;
const signerAddress = requestAuth.get('signerAddress');
const isRecoverCode = !!signature && signature.includes('code');

if (!signature || !signerAddress) {
if (!signature) {
throw new Unauthorized({
type: ErrorTypes.Unauthorized,
title: UnauthorizedErrorTitles.MISSING_CREDENTIALS,
detail: 'Some required credentials are missing',
});
}

if (isRecoverCode) return connectorMiddleware(req, res, next)

const token = await TokenUtils.recoverToken(signature);
await TokenUtils.renewToken(token);
if (isRecoverCode) return connectorMiddleware(req, res, next);
const token = await app._sessionCache.getSession(signature);

requestAuth.user = await TokenUtils.checkUserExists(signerAddress);
requestAuth.userToken = token;
requestAuth.workspace = await TokenUtils.findLoggedWorkspace(token);

requestAuth.user = token.user;
requestAuth.workspace = token.workspace;

return next();
} catch (e) {
return next(e);
Expand All @@ -46,7 +42,8 @@ function authPermissionMiddleware(permission?: PermissionRoles[]) {
return async function (req: Request, res: Response, next: NextFunction) {
try {
const requestAuth: IAuthRequest = req;



if (!permission || permission.length === 0) return next();
const { user, workspace } = requestAuth;

Expand Down
1 change: 1 addition & 0 deletions packages/api/src/mocks/networks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const networks: { [key: string]: string } = {
beta5: 'https://beta-5.fuel.network/graphql',
beta4: 'https://beta-4.fuel.network/graphql',
local: 'http://127.0.0.1:4000/v1/graphql',
devnet: 'https://devnet.fuel.network/v1/graphql/',
};

export const providers: { [key: string]: () => Promise<Provider> } = {
Expand Down
8 changes: 5 additions & 3 deletions packages/api/src/modules/addressBook/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import {
} from './types';
import { IconUtils } from '@utils/icons';

const {
API_DEFAULT_NETWORK
} = process.env;

export class AddressBookController {
private addressBookService: IAddressBookService;
private userService: IUserService;
Expand All @@ -32,7 +36,6 @@ export class AddressBookController {
try {
const { address, nickname } = req.body;
const { workspace, user } = req;

const duplicatedNickname = await new AddressBookService()
.filter({
owner: [workspace.id],
Expand Down Expand Up @@ -65,10 +68,9 @@ export class AddressBookController {
if (!savedUser) {
savedUser = await this.userService.create({
address,
provider: user.provider,
provider: user.provider,// ?? API_DEFAULT_NETWORK,// ?? networks['devnet'],
avatar: IconUtils.user(),
type: TypeUser.FUEL,

active: true,
});
}
Expand Down
5 changes: 0 additions & 5 deletions packages/api/src/modules/addressBook/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,6 @@ export class AddressBookService implements IAddressBookService {
),
);

//todo: add new subquery to order by, because the select is required distinct mode
// console.log('this._filter', this._filter, this._ordination);
// hasOrdination &&
// queryBuilder.orderBy(`ab.${this._ordination.orderBy}`, this._ordination.sort);

return hasPagination
? Pagination.create(queryBuilder)
.paginate(this._pagination)
Expand Down
16 changes: 9 additions & 7 deletions packages/api/src/modules/auth/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
ICreateRecoverCodeRequest,
ISignInRequest,
} from './types';
import app from '@src/server/app';

export class AuthController {
private authService: IAuthService;
Expand All @@ -36,13 +37,14 @@ export class AuthController {
try {
const { digest, encoder, signature } = req.body;

const userToken = await TokenUtils.createAuthToken(
const {userToken, signin} = await TokenUtils.createAuthToken(
signature,
digest,
encoder,
);

return successful(userToken, Responses.Ok);
await app._sessionCache.addSession(userToken.token, userToken);
return successful(signin, Responses.Ok);
} catch (e) {
if (e instanceof GeneralError) throw e;

Expand All @@ -56,7 +58,7 @@ export class AuthController {

return successful(response, Responses.Ok);
} catch (e) {
return error(e.error[0], e.statusCode);
return error(e.error, e.statusCode);
}
}

Expand All @@ -75,7 +77,7 @@ export class AuthController {

return successful(response, Responses.Ok);
} catch (e) {
return error(e.error[0], e.statusCode);
return error(e.error, e.statusCode);
}
}

Expand All @@ -96,14 +98,14 @@ export class AuthController {

const isUserMember = workspace.members.find(m => m.id === user);

const token = await this.authService.findToken({
userId: user,
});
const token = await TokenUtils.getTokenBySignature(req.headers.authorization);

if (isUserMember) {
token.workspace = workspace;
}

await app._sessionCache.addSession(token.token, token);

return successful(
await token.save().then(({ workspace, token, user }: UserToken) => {
return {
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/modules/auth/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export class AuthService implements IAuthService {
avatar: data.user.avatar,
address: data.user.address,
user_id: data.user.id,
expiredAt: data.expired_at,
workspace: {
id: data.workspace.id,
name: data.workspace.name,
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/modules/auth/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export interface IFindTokenParams {

export interface ISignInResponse {
accessToken: string;
expiredAt: Date;
avatar: string;
user_id: string;
workspace: {
Expand Down
12 changes: 5 additions & 7 deletions packages/api/src/modules/predicate/__tests__/predicate.tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,14 @@ describe('[PREDICATE]', () => {
'Create predicate without version code',
async () => {
const {
data: data_workspace,
data_user1,
data_user2,
USER_5,
} = await generateWorkspacePayload(api);
const members = [data_user1.address, data_user2.address];
const { predicatePayload } = await PredicateMock.create(1, members);
const { data } = await api.axios.post('/predicate', predicatePayload);

const { data: workspace, status: status_find } = await api.axios.get(
const { data: workspace } = await api.axios.get(
`/workspace/${api.workspace.id}`,
);

Expand Down Expand Up @@ -184,7 +182,7 @@ describe('[PREDICATE]', () => {
});
});

test('Find predicate by id', async () => {
test('Find predicate by id', async () => {
const auth = new AuthValidations(networks['local'], accounts['USER_3']);
await auth.create();
await auth.createSession();
Expand All @@ -201,15 +199,15 @@ describe('[PREDICATE]', () => {
//create a new nicknames
const { data: n_data5 } = await auth.axios.post('/address-book/', {
address: USER_5.address,
nickname: `[TESTE]${USER_5.address}`,
nickname: `[TESTE]${USER_5.address}${new Date().getTime()}`,
});
const { data: n_data1 } = await auth.axios.post('/address-book/', {
address: data_user1.address,
nickname: `[TESTE]${data_user1.address}`,
nickname: `[TESTE]${data_user1.address}${new Date().getTime()}`,
});
const { data: n_data2 } = await auth.axios.post('/address-book/', {
address: data_user2.address,
nickname: `[TESTE]${data_user2.address}`,
nickname: `[TESTE]${data_user2.address}${new Date().getTime()}`,
});

//create a vault
Expand Down
39 changes: 19 additions & 20 deletions packages/api/src/modules/predicate/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,13 +152,9 @@ export class PredicateController {

async findByAddress({ params: { address } }: IFindByHashRequest) {
try {
const response = await this.predicateService
.filter({
address,
})
.paginate(undefined)
.list()
.then((data: Predicate[]) => data[0]);
const response = await Predicate.findOne({
where: { predicateAddress: address },
})

const _response = await this.predicateService.findById(
response.id,
Expand All @@ -174,16 +170,15 @@ export class PredicateController {
async findByName(req: IFindByNameRequest) {
const { params, workspace } = req;
const { name } = params;

try {
const response = await this.predicateService
.filter({
name,
workspace: [workspace.id],
})
.paginate(undefined)
.list()
.then((data: Predicate[]) => data[0]);
if(!name || name.length === 0) return successful(false, Responses.Ok);

const response = await Predicate.createQueryBuilder('p')
.leftJoin('p.workspace', 'w')
.addSelect(['w.id', 'w.name'])
.where('p.name = :name', { name })
.andWhere('w.id = :workspace', { workspace: workspace.id })
.getOne();

return successful(!!response, Responses.Ok);
} catch (e) {
Expand Down Expand Up @@ -270,23 +265,27 @@ export class PredicateController {
})
.list()
.then((response: Workspace[]) => response[0]);


const allWk = await new WorkspaceService()
const hasSingle = singleWorkspace.id === workspace.id;

const _wk = hasSingle
? await new WorkspaceService()
.filter({
user: user.id,
})
.list()
.then((response: Workspace[]) => response.map(wk => wk.id));
.then((response: Workspace[]) => response.map(wk => wk.id))
: [workspace.id];

const hasSingle = singleWorkspace.id === workspace.id;

const response = await this.predicateService
.filter({
address: predicateAddress,
provider,
owner,
q,
workspace: hasSingle ? allWk : [workspace.id],
workspace: _wk,
signer: hasSingle ? user.address : undefined,
})
.ordination({ orderBy, sort })
Expand Down
34 changes: 19 additions & 15 deletions packages/api/src/modules/transaction/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -463,21 +463,25 @@ export class TransactionController {
const { workspace, user } = req;

const singleWorkspace = await new WorkspaceService()
.filter({
user: user.id,
single: true,
})
.list()
.then((response: Workspace[]) => response[0]);

const allWk = await new WorkspaceService()
.filter({
user: user.id,
})
.list()
.then((response: Workspace[]) => response.map(wk => wk.id));
.filter({
user: user.id,
single: true,
})
.list()
.then((response: Workspace[]) => response[0]);


const hasSingle = singleWorkspace.id === workspace.id;

const _wk = hasSingle
? await new WorkspaceService()
.filter({
user: user.id,
})
.list()
.then((response: Workspace[]) => response.map(wk => wk.id))
: [workspace.id];

const hasSingle = singleWorkspace.id === workspace.id;

const result = await new TransactionService()
.filter({
Expand All @@ -486,7 +490,7 @@ export class TransactionController {
status: status ?? undefined,
createdBy,
name,
workspaceId: hasSingle ? allWk : [workspace.id],
workspaceId: _wk,
signer: hasSingle ? user.address : undefined,
predicateId: predicateId ?? undefined,
})
Expand Down
5 changes: 0 additions & 5 deletions packages/api/src/modules/transaction/services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,6 @@ export class TransactionService implements ITransactionService {
}),
);
// =============== specific for workspace ===============
//console.log('[transaction_FILTER]: ', this._filter);

// =============== specific for home ===============
(this._filter.workspaceId || this._filter.signer) &&
Expand Down Expand Up @@ -403,8 +402,6 @@ export class TransactionService implements ITransactionService {
return resume;
})
.catch(e => {
console.log('[ERRO_SEND_TOCHAIN]: ', e);

throw new Internal({
type: ErrorTypes.Internal,
title: 'Error on transaction sendToChain',
Expand Down Expand Up @@ -472,8 +469,6 @@ export class TransactionService implements ITransactionService {
}
}
}

//console.log('[DENTRO_ELSE_IF]', _api_transaction, resume, a);
return resume;
}

Expand Down
Loading

0 comments on commit c861d0e

Please sign in to comment.