forked from Shared/esg
feat: add car inquiries with resilience, ownership privacy, and retry visibility
Introduce plate, chassis, and third-party car endpoints, a wall-clock inquiry deadline with transport-only retries, and ownership-safe no-match errors so another person's identity never leaks. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,33 +1,151 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import axios from 'axios';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Model } from 'mongoose';
|
||||
import { mergeOutboundAxiosConfig } from '../../common/helpers/http-client.helper';
|
||||
import {
|
||||
AUTH_MAX_ATTEMPTS,
|
||||
AUTH_RETRY_DELAY_MS,
|
||||
isAuthTransportRetryable,
|
||||
} from '../../common/helpers/provider-resilience.helper';
|
||||
import { withRetry } from '../../common/helpers/retry.helper';
|
||||
import { GeneralToken, GeneralTokenDocument } from '../schemas/general-token.schema';
|
||||
import { TejaratNouConfig } from '../interfaces/tejaratnou-config.interface';
|
||||
|
||||
export interface OAuthTokenResponse {
|
||||
accessToken: string;
|
||||
tokenType: string;
|
||||
scope: string;
|
||||
expiresIn: number;
|
||||
}
|
||||
|
||||
/** Refresh tokens this many seconds before actual expiry. */
|
||||
const TOKEN_EXPIRY_BUFFER_SECONDS = 60;
|
||||
|
||||
@Injectable()
|
||||
export class GeneralTokenService {
|
||||
private readonly logger = new Logger(GeneralTokenService.name);
|
||||
|
||||
constructor(
|
||||
@InjectModel(GeneralToken.name)
|
||||
private readonly generalTokenModel: Model<GeneralTokenDocument>,
|
||||
) {}
|
||||
|
||||
async getLatestToken(serviceProvider = 'TejaratNou'): Promise<GeneralTokenDocument | null> {
|
||||
return this.generalTokenModel
|
||||
.findOne({ serviceProvider })
|
||||
.sort({ createdAt: -1 })
|
||||
.exec();
|
||||
async getLatestToken(serviceProvider: string): Promise<GeneralTokenDocument | null> {
|
||||
return this.generalTokenModel.findOne({ serviceProvider }).sort({ createdAt: -1 }).exec();
|
||||
}
|
||||
|
||||
async create(
|
||||
data: Omit<GeneralToken, 'createdAt'>,
|
||||
): Promise<GeneralTokenDocument> {
|
||||
async isTokenExpired(
|
||||
token: GeneralTokenDocument,
|
||||
bufferSeconds = TOKEN_EXPIRY_BUFFER_SECONDS,
|
||||
): Promise<boolean> {
|
||||
if (!token.expiresAt) return true;
|
||||
const refreshAt = token.expiresAt.getTime() - bufferSeconds * 1000;
|
||||
return Date.now() >= refreshAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a valid access token — reuses MongoDB-stored token when not expired,
|
||||
* otherwise fetches a new one via the supplied OAuth fetcher.
|
||||
*/
|
||||
async getValidAccessToken(
|
||||
serviceProvider: string,
|
||||
fetchNewToken: () => Promise<OAuthTokenResponse>,
|
||||
persistContext: {
|
||||
url: string;
|
||||
clientId: string;
|
||||
username: string;
|
||||
},
|
||||
): Promise<string> {
|
||||
const latest = await this.getLatestToken(serviceProvider);
|
||||
if (latest && !(await this.isTokenExpired(latest))) {
|
||||
this.logger.debug(`Reusing ${serviceProvider} token ${latest._id}`);
|
||||
return latest.accessToken;
|
||||
}
|
||||
|
||||
const fresh = await fetchNewToken();
|
||||
const expiresAt = new Date(Date.now() + fresh.expiresIn * 1000);
|
||||
|
||||
await this.generalTokenModel.create({
|
||||
serviceProvider,
|
||||
tokenType: fresh.tokenType,
|
||||
url: persistContext.url,
|
||||
clientId: persistContext.clientId,
|
||||
username: persistContext.username,
|
||||
scope: fresh.scope,
|
||||
accessToken: fresh.accessToken,
|
||||
expiresIn: fresh.expiresIn,
|
||||
expiresAt,
|
||||
});
|
||||
|
||||
this.logger.log(`Stored new ${serviceProvider} token, expires at ${expiresAt.toISOString()}`);
|
||||
return fresh.accessToken;
|
||||
}
|
||||
|
||||
/** Persist a provider token (AMITIS and other non-OAuth flows). Credentials stay in env. */
|
||||
async persistToken(data: {
|
||||
serviceProvider: string;
|
||||
tokenType: string;
|
||||
url: string;
|
||||
clientId: string;
|
||||
username: string;
|
||||
scope: string;
|
||||
accessToken: string;
|
||||
refreshToken?: string;
|
||||
expiresIn: number;
|
||||
expiresAt: Date;
|
||||
}): Promise<GeneralTokenDocument> {
|
||||
return this.generalTokenModel.create(data);
|
||||
}
|
||||
|
||||
async isTokenExpired(token: GeneralTokenDocument): Promise<boolean> {
|
||||
if (!token.expiresAt) {
|
||||
return true;
|
||||
}
|
||||
const now = new Date();
|
||||
return now >= token.expiresAt;
|
||||
/** OAuth2 password grant for Tejarat No identity gateway. */
|
||||
async getTejaratNouAccessToken(config: TejaratNouConfig): Promise<string> {
|
||||
return this.getValidAccessToken(
|
||||
'TejaratNou',
|
||||
async () => {
|
||||
const response = await withRetry(
|
||||
() =>
|
||||
axios.post(
|
||||
`${config.baseUrl}/connect/token`,
|
||||
new URLSearchParams({
|
||||
grant_type: 'password',
|
||||
client_id: config.clientId,
|
||||
client_secret: config.clientSecret,
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
scope: 'api-gateway access-management',
|
||||
}),
|
||||
mergeOutboundAxiosConfig({
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
timeout: config.timeout,
|
||||
}),
|
||||
),
|
||||
{
|
||||
maxAttempts: AUTH_MAX_ATTEMPTS,
|
||||
delayMs: AUTH_RETRY_DELAY_MS,
|
||||
shouldRetry: isAuthTransportRetryable,
|
||||
},
|
||||
);
|
||||
|
||||
const body = response.data as {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
scope: string;
|
||||
expires_in: number;
|
||||
};
|
||||
|
||||
return {
|
||||
accessToken: body.access_token,
|
||||
tokenType: body.token_type,
|
||||
scope: body.scope,
|
||||
expiresIn: body.expires_in,
|
||||
};
|
||||
},
|
||||
{
|
||||
url: config.baseUrl,
|
||||
clientId: config.clientId,
|
||||
username: config.username,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user