Skip to content

YEP-2933 Implement cached access token endpoint for yepcode run #8

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all 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
23 changes: 13 additions & 10 deletions src/api/yepcodeApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export class YepCodeApi {
private teamId?: string;
private accessToken?: string;
private timeout: number;
private apiToken?: string;

constructor(config: YepCodeApiConfig = {}) {
if (typeof fetch !== "function") {
Expand All @@ -73,9 +74,6 @@ export class YepCodeApi {
...envConfig,
...config,
};
if (!finalConfig.authUrl) {
finalConfig.authUrl = `${finalConfig.apiHost}/auth/realms/yepcode/protocol/openid-connect/token`;
}

if (
!finalConfig.accessToken &&
Expand Down Expand Up @@ -122,13 +120,14 @@ export class YepCodeApi {
this.apiHost = finalConfig.apiHost;
this.clientId = finalConfig.clientId;
this.clientSecret = finalConfig.clientSecret;
this.authUrl = finalConfig.authUrl;
this.apiToken = finalConfig.apiToken;
this.teamId = finalConfig.teamId;
this.accessToken = finalConfig.accessToken;
this.timeout = finalConfig.timeout;
if (!this.teamId) {
this.initTeamId();
}
this.authUrl = finalConfig.authUrl ?? this.getAuthURL();
}

getTeamId(): string {
Expand Down Expand Up @@ -163,8 +162,12 @@ export class YepCodeApi {
return `${this.apiHost}/api/${this.teamId}/rest`;
}

private getAuthURL(): string {
return `${this.getBaseURL()}/auth/token`;
}

private async getAccessToken(): Promise<string> {
if (!this.clientId || !this.clientSecret) {
if (!this.apiToken && (!this.clientId || !this.clientSecret)) {
throw new Error(
"AccessToken has expired. Provide a new one or enable automatic refreshing by providing an apiToken or clientId and clientSecret."
);
Expand All @@ -174,12 +177,12 @@ export class YepCodeApi {
const response = await fetch(this.authUrl, {
method: "POST",
headers: {
authorization: `Basic ${Buffer.from(
`${this.clientId}:${this.clientSecret}`
).toString("base64")}`,
"Content-Type": "application/x-www-form-urlencoded",
"x-api-token":
this.apiToken ??
`sk-${Buffer.from(`${this.clientId}:${this.clientSecret}`).toString(
"base64"
)}`,
},
body: "grant_type=client_credentials",
});

if (!response.ok) {
Expand Down