This repository has been archived by the owner on Jan 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.ts
199 lines (171 loc) · 5.87 KB
/
api.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import { BaseClient, Issuer, TokenSet, generators } from "npm:openid-client";
import {
CookieJar,
wrapFetch,
} from "https://deno.land/x/[email protected]/mod.ts";
// Per la permanenza dei cookies
const cookieJar = new CookieJar();
const fetch = wrapFetch({ cookieJar });
export class ArgoAPI {
username: string;
password: string;
schoolCode: string;
#tokenSet?: TokenSet;
#authToken?: string;
#client?: BaseClient;
static baseApiUrl = "https://www.portaleargo.it/appfamiglia/api/rest";
static endpoints = {
dashboard: `${ArgoAPI.baseApiUrl}/dashboard/dashboard`,
};
constructor(username: string, password: string, schoolCode: string) {
this.username = username;
this.password = password;
this.schoolCode = schoolCode;
}
async login() {
const argoIssuer = await Issuer.discover("https://auth.portaleargo.it");
const authenticationUrl = "https://www.portaleargo.it/auth/sso/login";
const tokenUrl = "https://auth.portaleargo.it/oauth2/token";
const loginUrl = "https://www.portaleargo.it/appfamiglia/api/rest/login";
this.#client = new argoIssuer.Client({
client_id: "72fd6dea-d0ab-4bb9-8eaa-3ac24c84886c",
client_secret: "superdupersecret",
redirect_uris: ["it.argosoft.didup.famiglia.new://login-callback"],
response_types: ["code"],
});
const code_verifier = generators.codeVerifier();
const code_challenge = generators.codeChallenge(code_verifier);
const state = generators.state();
const authorizationUrl = this.#client.authorizationUrl({
scope: "openid offline profile user.roles argo",
code_challenge: code_challenge,
state: state,
code_challenge_method: "S256",
});
let response: Response;
response = await fetch(authorizationUrl, { redirect: "manual" });
response = await fetch(response.headers.get("location")!, {
redirect: "manual",
});
const challenge = new URL(response.url).searchParams.get("login_challenge");
const urlEncodedData = new URLSearchParams({
client_id: this.#client.metadata.client_id,
username: this.username,
password: this.password,
famiglia_customer_code: this.schoolCode,
challenge: challenge!,
prefill: "false",
login: "true",
});
response = await fetch(authenticationUrl, {
method: "POST",
redirect: "manual",
body: urlEncodedData,
});
response = await fetch(response.headers.get("location")!, {
redirect: "manual",
});
response = await fetch(response.headers.get("location")!, {
redirect: "manual",
});
response = await fetch(response.headers.get("location")!, {
method: "POST",
redirect: "manual",
body: new URL(response.url).searchParams,
});
response = await fetch(tokenUrl, {
method: "POST",
redirect: "manual",
body: new URLSearchParams({
code: new URL(response.headers.get("location")!).searchParams.get(
"code"
)!,
grant_type: "authorization_code",
redirect_uri: this.#client.metadata.redirect_uris![0],
code_verifier: code_verifier,
client_id: this.#client.metadata.client_id,
}),
});
const jsonBody = await response.json();
this.#tokenSet = new TokenSet({
access_token: jsonBody.access_token,
token_type: "Bearer",
id_token: jsonBody.id_token,
refresh_token: jsonBody.refresh_token,
expires_at: jsonBody.expires_at,
session_state: jsonBody.session_state,
});
const userInfo = await this.#client.userinfo(this.#tokenSet.access_token!);
console.log(
`Accesso eseguito
\tNome: «${userInfo.full_name}»
\tTipo di profilo: «${userInfo.user_type}» / «${userInfo.roles}»`
);
// Ottenimento del token d'autenticazione
// (procedura specifica, fine flow standard OpenID Connect)
response = await fetch(loginUrl, {
redirect: "manual",
method: "POST",
body: JSON.stringify({
clientId: this.#client.metadata.client_id,
}),
headers: {
authorization: `Bearer ${this.#tokenSet.access_token!}`,
"content-type": "text/json",
},
});
this.#authToken = (await response.json()).data[0].token;
console.log(`Ottenuto token d'auteticazione: ${this.#authToken}`);
}
async dashboard() {
if (this.#tokenSet && this.#authToken) {
return (
await (
await this.#getResource(
ArgoAPI.endpoints.dashboard,
this.#authToken,
this.#tokenSet.access_token!,
this.schoolCode,
{
dataultimoaggiornamento: "2023-01-01 12:25:51.496648", // TODO: Salvare i dati ed evitare di richiedere sempre tutto
}
)
).json()
).data.dati[0]; // La risposta arriva in un formato strano, estraggo solo i dati utili
// Esempio di risposta: ({ success: true | false, msg: any, data: { dati: [<dati utili>] } })
}
throw new Error("tokenSet and authToken haven't been set yet", {
cause: "You need to call login() before doing anything else",
});
}
async reminders() {
return (await this.dashboard()).promemoria;
}
/**
* Accede ad una risorsa che richiede l'autenticazione
*/
async #getResource(
url: URL | string | Request,
authToken: string,
accessToken: string,
schoolCode: string,
body?: Record<string, string>
): Promise<Response> {
if (this.#tokenSet!.expired()) {
this.#tokenSet = await this.#client!.refresh(
this.#tokenSet!.refresh_token!
);
}
const headers: Record<string, string> = {
"x-cod-min": schoolCode,
"x-auth-token": authToken,
Authorization: `Bearer ${accessToken}`,
};
body ? (headers["content-type"] = "text/json") : null;
return fetch(url, {
method: body ? "POST" : "GET",
headers: headers,
body: body ? JSON.stringify(body) : undefined,
});
}
}