Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Suggestion to simplifying the user or customer getting #469

Merged
merged 5 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## [2.15.1-develop.1](https://github.com/cheqd/credential-service/compare/2.15.0...2.15.1-develop.1) (2024-01-11)


### Bug Fixes

* Fix error handling on tracking operations [DEV-3527] ([#461](https://github.com/cheqd/credential-service/issues/461)) ([53d7dfd](https://github.com/cheqd/credential-service/commit/53d7dfdcc23d90dba85a681f39ebc724b7fbdcc2))

## [2.15.0](https://github.com/cheqd/credential-service/compare/2.14.0...2.15.0) (2024-01-05)


Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@cheqd/credential-service",
"version": "2.15.0",
"version": "2.15.1-develop.1",
"description": "cheqd Credential Service Backend",
"source": "src/index.ts",
"main": "dist/index.js",
Expand Down
53 changes: 20 additions & 33 deletions src/controllers/account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,41 +111,28 @@ export class AccountController {
}

const identityStrategySetup = new IdentityServiceStrategySetup(response.locals.customer.customerId);
let apiKey = await identityStrategySetup.agent.getAPIKey(response.locals.customer, response.locals.user);
// If there is no API key for the customer - create it
if (!apiKey) {
apiKey = await identityStrategySetup.agent.setAPIKey(
request.session.idToken,
response.locals.customer,
response.locals.user
);
} else if (apiKey.isExpired()) {
// If API key is expired - update it
apiKey = await identityStrategySetup.agent.updateAPIKey(apiKey, request.session.idToken);
}
return response.status(StatusCodes.OK).json({
idToken: apiKey?.apiKey,
});
}

public async setupDefaultRole(request: Request, response: Response) {
if (request.body) {
const { body } = request;
if (!body.user.isSuspended) {
const logToHelper = new LogToHelper();
const _r = await logToHelper.setup();
if (_r.status !== StatusCodes.OK) {
return response.status(StatusCodes.BAD_GATEWAY).json({
error: _r.error,
});
}
const resp = await logToHelper.setDefaultRoleForUser(body.user.id as string);
return response.status(resp.status).json({
error: resp.error,
});
try {
// Get the API key for the customer
let apiKey = await identityStrategySetup.agent.getAPIKey(response.locals.customer, response.locals.user);
// If there is no API key for the customer - create it
if (!apiKey) {
apiKey = await identityStrategySetup.agent.setAPIKey(
request.session.idToken,
response.locals.customer,
response.locals.user
);
} else if (apiKey.isExpired()) {
// If API key is expired - update it
apiKey = await identityStrategySetup.agent.updateAPIKey(apiKey, request.session.idToken);
}
return response.status(StatusCodes.OK).json({
idToken: apiKey?.apiKey,
});
} catch (error) {
return response.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
error: `Internal error: ${(error as Error)?.message || error}`,
});
}
return response.status(StatusCodes.BAD_REQUEST).json({});
}

public async bootstrap(request: Request, response: Response) {
Expand Down
45 changes: 24 additions & 21 deletions src/controllers/credential-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -562,13 +562,14 @@ export class CredentialStatusController {
},
} as ITrackOperation;

const trackResult = await identityServiceStrategySetup.agent.trackOperation(trackResourceInfo);
const trackResult = await identityServiceStrategySetup.agent
.trackOperation(trackResourceInfo)
.catch((error) => {
return { error };
});
if (trackResult.error) {
return response
.status(StatusCodes.INTERNAL_SERVER_ERROR)
.json(trackResult as CreateEncryptedStatusListUnsuccessfulResponseBody);
console.error(`Tracking Error: ${trackResult.error}`);
}

// return result
return response.status(StatusCodes.OK).json({ ...result, encrypted: undefined });
} catch (error) {
Expand Down Expand Up @@ -695,14 +696,14 @@ export class CredentialStatusController {
feePaymentNetwork: CheqdNetwork.Testnet,
},
} as ITrackOperation;
const trackResult = await identityServiceStrategySetup.agent.trackOperation(trackResourceInfo);

const trackResult = await identityServiceStrategySetup.agent
.trackOperation(trackResourceInfo)
.catch((error) => {
return { error };
});
if (trackResult.error) {
return response
.status(StatusCodes.INTERNAL_SERVER_ERROR)
.json(trackResult as CreateEncryptedStatusListUnsuccessfulResponseBody);
console.error(`Tracking Error: ${trackResult.error}`);
}

// return result
return response.status(StatusCodes.OK).json({ ...result, encrypted: undefined });
} catch (error) {
Expand Down Expand Up @@ -873,12 +874,13 @@ export class CredentialStatusController {
symmetricKey: '',
},
} as ITrackOperation;
const trackResult = await identityServiceStrategySetup.agent.trackOperation(trackResourceInfo);
const trackResult = await identityServiceStrategySetup.agent
.trackOperation(trackResourceInfo)
.catch((error) => {
return { error };
});
if (trackResult.error) {
return response.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
updated: false,
error: trackResult.error,
} as UpdateUnencryptedStatusListUnsuccessfulResponseBody);
console.error(`Tracking Error: ${trackResult.error}`);
}
}

Expand Down Expand Up @@ -1072,12 +1074,13 @@ export class CredentialStatusController {
feePaymentNetwork: CheqdNetwork.Testnet,
},
} as ITrackOperation;
const trackResult = await identityServiceStrategySetup.agent.trackOperation(trackResourceInfo);
const trackResult = await identityServiceStrategySetup.agent
.trackOperation(trackResourceInfo)
.catch((error) => {
return { error };
});
if (trackResult.error) {
return response.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
updated: false,
error: trackResult.error,
} as UpdateUnencryptedStatusListUnsuccessfulResponseBody);
console.error(`Tracking Error: ${trackResult.error}`);
}
}

Expand Down
30 changes: 18 additions & 12 deletions src/controllers/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,11 +331,13 @@ export class CredentialController {
} as ITrackOperation;

// Track operation
const trackResult = await identityServiceStrategySetup.agent.trackOperation(trackInfo);
if (trackResult.error) {
return response.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
error: trackResult.error,
const trackResult = await identityServiceStrategySetup.agent
.trackOperation(trackInfo)
.catch((error) => {
return { error };
});
if (trackResult.error) {
console.error(`Tracking Error: ${trackResult.error}`);
}
}
// Return Ok response
Expand Down Expand Up @@ -435,11 +437,13 @@ export class CredentialController {
} as ITrackOperation;

// Track operation
const trackResult = await identityServiceStrategySetup.agent.trackOperation(trackInfo);
if (trackResult.error) {
return response.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
error: trackResult.error,
const trackResult = await identityServiceStrategySetup.agent
.trackOperation(trackInfo)
.catch((error) => {
return { error };
});
if (trackResult.error) {
console.error(`Tracking Error: ${trackResult.error}`);
}
}

Expand Down Expand Up @@ -537,11 +541,13 @@ export class CredentialController {
} as ITrackOperation;

// Track operation
const trackResult = await identityServiceStrategySetup.agent.trackOperation(trackInfo);
if (trackResult.error) {
return response.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
error: trackResult.error,
const trackResult = await identityServiceStrategySetup.agent
.trackOperation(trackInfo)
.catch((error) => {
return { error };
});
if (trackResult.error) {
console.error(`Tracking Error: ${trackResult.error}`);
}
}
// Return Ok response
Expand Down
10 changes: 6 additions & 4 deletions src/controllers/resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,11 +190,13 @@ export class ResourceController {
},
} as ITrackOperation;

const trackResult = await identityServiceStrategySetup.agent.trackOperation(trackResourceInfo);
if (trackResult.error) {
return response.status(StatusCodes.INTERNAL_SERVER_ERROR).json({
error: `${trackResult.error}`,
const trackResult = await identityServiceStrategySetup.agent
.trackOperation(trackResourceInfo)
.catch((error) => {
return { error };
});
if (trackResult.error) {
console.error(`Tracking Error: ${trackResult.error}`);
}

return response.status(StatusCodes.CREATED).json({
Expand Down
2 changes: 0 additions & 2 deletions src/middleware/auth/base-auth-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,6 @@ export class BaseAuthHandler extends BaseAPIGuard implements IAuthHandler {
this.setUserInfoStrategy(new APITokenUserInfoFetcher(token));
} else {
this.setUserInfoStrategy(new M2MTokenUserInfoFetcher(token));
const customerId = request.headers['customer-id'];
if (typeof customerId === 'string') this.setCustomerId(customerId);
}
} else {
this.setUserInfoStrategy(new SwaggerUserInfoFetcher());
Expand Down
4 changes: 4 additions & 0 deletions src/middleware/auth/user-info-fetcher/m2m-token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export class M2MTokenUserInfoFetcher extends AuthReturn implements IUserInfoFetc
}

async fetchUserInfo(request: Request, oauthProvider: IOAuthProvider): Promise<IAuthResponse> {
// Get customerId from header
const customerId = request.headers['customer-id'];
if (typeof customerId === 'string') this.setCustomerId(customerId);
// Verify M2M token
return this.verifyJWTToken(this.token as string, oauthProvider);
}

Expand Down
25 changes: 16 additions & 9 deletions src/middleware/authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,12 @@ export class Authentication {
});
}
// Only for rules when it's not allowed for unauthorized users
// we need to find customer and assign it to the response.locals
// we need to find customer or user and assign them to the response.locals
if (!_resp.data.isAllowedUnauthorized) {
let customer;
let user;
if (_resp.data.userId !== '') {
const user = await UserService.instance.get(_resp.data.userId);
user = await UserService.instance.get(_resp.data.userId);
if (!user) {
return response.status(StatusCodes.NOT_FOUND).json({
error: `Looks like user with logToId ${_resp.data.userId} is not found`,
Expand All @@ -149,18 +151,23 @@ export class Authentication {
error: `Looks like user with logToId ${_resp.data.userId} is not assigned to any CredentialService customer`,
});
}
response.locals.customer = user.customer;
response.locals.user = user;
} else if (!(['/account/create'].includes(request.path) && _resp.data.customerId == '')) {
// allow bootstrap apis to create a customer if there is not customerId
const customer = await CustomerService.instance.get(_resp.data.customerId);
customer = user.customer;
}
if (_resp.data.customerId !== '' && !customer) {
customer = await CustomerService.instance.get(_resp.data.customerId);
if (!customer) {
return response.status(StatusCodes.NOT_FOUND).json({
error: `Looks like user with logToId ${_resp.data.customerId} is not found`,
error: `Looks like customer with id ${_resp.data.customerId} is not found`,
});
}
response.locals.customer = customer;
}
if (!customer && !user) {
return response.status(StatusCodes.UNAUTHORIZED).json({
error: `Looks like customer and user are not found in the system or they are not registered yet. Please contact administrator.`,
})
}
response.locals.customer = customer;
response.locals.user = user;
}
next();
} catch (err) {
Expand Down
Loading