1 | |
2 | import * as wmill from "windmill-client" |
3 | type COauthCredentials = { |
4 | nonce: string, |
5 | scope: string, |
6 | resource: string, |
7 | client_id: string, |
8 | token_url: string, |
9 | expires_in: string, |
10 | token_type: string, |
11 | access_token: string, |
12 | client_secret: string, |
13 | not_before_policy: string, |
14 | refresh_expires_in: string |
15 | } |
16 |
|
17 | |
18 | * Creates an OAuth 2.0 access token using the client credentials flow |
19 | * @param oauthResource - OAuth resource containing client_id and client_secret |
20 | * @param tokenUrl - The OAuth token endpoint URL (optional if provided in resource) |
21 | * @param scope - Optional scope for the token request |
22 | * @returns Object containing the access token and additional token information |
23 | */ |
24 | export async function main( |
25 | resourcepath:string ='', |
26 | variablepath:string = '' |
27 | ) { |
28 | var oauthResource : COauthCredentials = await wmill.getResource(resourcepath); |
29 | |
30 | const requestBody = new URLSearchParams({ |
31 | grant_type: 'client_credentials', |
32 | client_id: oauthResource.client_id, |
33 | client_secret: oauthResource.client_secret |
34 | }); |
35 |
|
36 |
|
37 | try { |
38 | |
39 | const response = await fetch(oauthResource.token_url, { |
40 | method: 'POST', |
41 | headers: { |
42 | 'Content-Type': 'application/x-www-form-urlencoded', |
43 | 'Accept': 'application/json' |
44 | }, |
45 | body: requestBody.toString() |
46 | }); |
47 |
|
48 | if (!response.ok) { |
49 | const errorText = await response.text(); |
50 | throw new Error(`Token request failed: ${response.status} ${response.statusText} - ${errorText}`); |
51 | } |
52 |
|
53 | const tokenData = await response.json(); |
54 | |
55 | oauthResource.expires_in = tokenData.expires_in; |
56 | oauthResource.token_type = tokenData.token_type; |
57 | oauthResource.refresh_expires_in = tokenData.refresh_expires_in; |
58 | oauthResource.not_before_policy = tokenData['not-before-policy']; |
59 | oauthResource.access_token = tokenData.access_token; |
60 | await wmill.setResource(oauthResource,resourcepath); |
61 | await wmill.setVariable(variablepath,oauthResource.access_token ); |
62 |
|
63 | return { |
64 | token_type: tokenData.token_type, |
65 | expires_in: tokenData.expires_in, |
66 | message: 'Token updated successfully' |
67 | }; |
68 | |
69 | } catch (error) { |
70 | throw new Error(`Failed to create OAuth token: ${error.message}`); |
71 | } |
72 | } |
73 |
|