UNPKG

@rdfc/http-utils-processor-ts

Version:
50 lines (49 loc) 1.75 kB
import { HttpUtilsError } from "../../error.js"; export class OAuth2PasswordAuth { username; password; endpoint; constructor(username, password, endpoint) { this.username = username; this.password = password; this.endpoint = endpoint; } async authorize(req) { const authRequest = new Request(this.endpoint, { body: new URLSearchParams({ grant_type: "password", username: this.username, password: this.password, }), method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, }); const authResponse = await fetch(authRequest); if (!authResponse.ok) { throw HttpUtilsError.oAuth2TokenError(authResponse.status); } const authData = (await authResponse.json()); const token = authData["access_token"]; if (!token) { throw HttpUtilsError.unauthorizedError(); } req.headers.set("Authorization", `Bearer ${authData.access_token}`); } check() { throw new Error("Method not implemented."); } static from(auth) { if (!auth.username) { throw HttpUtilsError.illegalParameters("Username is required for OAuth2.0 Password Grant."); } if (!auth.password) { throw HttpUtilsError.illegalParameters("Password is required for OAuth2.0 Password Grant."); } if (!auth.endpoint) { throw HttpUtilsError.illegalParameters("Endpoint is required for OAuth2.0 Password Grant."); } return new OAuth2PasswordAuth(auth.username, auth.password, auth.endpoint); } }