Skip to content

Commit

Permalink
refactor(next-drupal): add getAuthorizationHeader method to DrupalClient
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnAlbin committed Feb 27, 2024
1 parent 7e0637f commit 510ac07
Show file tree
Hide file tree
Showing 7 changed files with 656 additions and 804 deletions.
121 changes: 44 additions & 77 deletions packages/next-drupal/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,79 +246,10 @@ export class DrupalClient {
},
}

// Using the auth set on the client.
// TODO: Abstract this to a re-usable.
if (withAuth) {
this.debug(`Using authenticated request.`)

if (withAuth === true) {
if (typeof this._auth === "undefined") {
throw new Error(
"auth is not configured. See https://next-drupal.org/docs/client/auth"
)
}

// By default, if withAuth is set to true, we use the auth configured
// in the client constructor.
if (typeof this._auth === "function") {
this.debug(`Using custom auth callback.`)

init["headers"]["Authorization"] = this._auth()
} else if (typeof this._auth === "string") {
this.debug(`Using custom authorization header.`)

init["headers"]["Authorization"] = this._auth
} else if (typeof this._auth === "object") {
this.debug(`Using custom auth credentials.`)

if (isBasicAuth(this._auth)) {
const basic = Buffer.from(
`${this._auth.username}:${this._auth.password}`
).toString("base64")

init["headers"]["Authorization"] = `Basic ${basic}`
} else if (isClientIdSecretAuth(this._auth)) {
// Use the built-in client_credentials grant.
this.debug(`Using default auth (client_credentials).`)

// Fetch an access token and add it to the request.
// Access token can be fetched from cache or using a custom auth method.
const token = await this.getAccessToken(this._auth)
if (token) {
init["headers"]["Authorization"] = `Bearer ${token.access_token}`
}
} /* c8 ignore next 4 */ else if (isAccessTokenAuth(this._auth)) {
init["headers"]["Authorization"] =
`${this._auth.token_type} ${this._auth.access_token}`
}
}
} else if (typeof withAuth === "string") {
this.debug(`Using custom authorization header.`)

init["headers"]["Authorization"] = withAuth
} /* c8 ignore next 4 */ else if (typeof withAuth === "function") {
this.debug(`Using custom authorization callback.`)

init["headers"]["Authorization"] = withAuth()
} else if (isBasicAuth(withAuth)) {
this.debug(`Using basic authorization header.`)

const basic = Buffer.from(
`${withAuth.username}:${withAuth.password}`
).toString("base64")

init["headers"]["Authorization"] = `Basic ${basic}`
} else if (isClientIdSecretAuth(withAuth)) {
// Fetch an access token and add it to the request.
// Access token can be fetched from cache or using a custom auth method.
const token = await this.getAccessToken(withAuth)
if (token) {
init["headers"]["Authorization"] = `Bearer ${token.access_token}`
}
} /* c8 ignore next 4 */ else if (isAccessTokenAuth(withAuth)) {
init["headers"]["Authorization"] =
`${withAuth.token_type} ${withAuth.access_token}`
}
init.headers["Authorization"] = await this.getAuthorizationHeader(
withAuth === true ? this._auth : withAuth
)
}

if (this.fetcher) {
Expand All @@ -332,6 +263,41 @@ export class DrupalClient {
return await fetch(input, init)
}

async getAuthorizationHeader(auth: DrupalClientAuth) {
let header: string

if (isBasicAuth(auth)) {
const basic = Buffer.from(`${auth.username}:${auth.password}`).toString(
"base64"
)
header = `Basic ${basic}`
this.debug("Using basic authorization header.")
} else if (isClientIdSecretAuth(auth)) {
// Fetch an access token and add it to the request. getAccessToken()
// throws an error if it fails to get an access token.
const token = await this.getAccessToken(auth)
header = `Bearer ${token.access_token}`
this.debug(
"Using access token authorization header retrieved from Client Id/Secret."
)
} else if (isAccessTokenAuth(auth)) {
header = `${auth.token_type} ${auth.access_token}`
this.debug("Using access token authorization header.")
} else if (typeof auth === "string") {
header = auth
this.debug("Using custom authorization header.")
} else if (typeof auth === "function") {
header = auth()
this.debug("Using custom authorization callback.")
} else {
throw new Error(
"auth is not configured. See https://next-drupal.org/docs/client/auth"
)
}

return header
}

async createResource<T extends JsonApiResource>(
type: string,
body: JsonApiCreateResourceBody,
Expand Down Expand Up @@ -1410,10 +1376,11 @@ export class DrupalClient {

this.debug(`Fetching new access token.`)

const basic = Buffer.from(`${auth.clientId}:${auth.clientSecret}`).toString(
"base64"
)

// Use BasicAuth to retrieve the access token.
const credentials: DrupalClientAuthUsernamePassword = {
username: auth.clientId,
password: auth.clientSecret,
}
let body = `grant_type=client_credentials`

if (opts?.scope) {
Expand All @@ -1425,7 +1392,7 @@ export class DrupalClient {
const response = await this.fetch(url.toString(), {
method: "POST",
headers: {
Authorization: `Basic ${basic}`,
Authorization: await this.getAuthorizationHeader(credentials),
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,196 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`fetch() allows fetching custom url 1`] = `
{
"data": {
"attributes": {
"body": {
"format": "basic_html",
"processed": "<p>There's nothing like having your own supply of fresh herbs, readily available and close at hand to use while cooking. Whether you have a large garden or a small kitchen window sill, there's always enough room for something home grown.</p>
<h2>Outdoors</h2>
<h3>Mint</h3>
<p>Mint is a great plant to grow as it's hardy and can grow in almost any soil. Mint can grow wild, so keep it contained in a pot or it might spread and take over your whole garden.</p>
<h3>Sage</h3>
<p>Like mint, sage is another prolific growing plant and will take over your garden if you let it. Highly aromatic, the sage plant can be planted in a pot or flower bed in well drained soil. The best way to store the herb is to sun dry the leaves and store in a cool, dark cupboard in a sealed container.</p>
<h3>Rosemary</h3>
<p>Rosemary plants grow into lovely shrubs. Easily grown from cuttings, rosemary plants do not like freezing temperatures so keep pots or planted bushes near the home to shelter them from the cold. It grows well in pots as it likes dry soil, but can survive well in the ground too. If pruning rosemary to encourage it into a better shape, save the branches and hang them upside down to preserve the flavor and use in food.</p>
<h2>Indoors</h2>
<h3>Basil</h3>
<p>Perfect in sunny spot on a kitchen window sill. Basil is an annual plant, so will die off in the autumn, so it's a good idea to harvest it in the summer if you have an abundance and dry it. Picked basil stays fresh longer if it is placed in water (like fresh flowers). A great way to store basil is to make it into pesto!</p>
<h3>Chives</h3>
<p>A versatile herb, chives can grow well indoors. Ensure the plant is watered well, and gets plenty of light. Remember to regularly trim the chives. This prevents the flowers from developing and encourages new growth.</p>
<h3>Coriander (Cilantro)</h3>
<p>Coriander can grow indoors, but unlike the other herbs, it doesn't like full sun. If you have a south facing kitchen window, this isn't the place for it. Although not as thirsty as basil, coriander doesn't like dry soil so don't forget to water it! Cut coriander is best stored in the fridge.</p>
",
"summary": null,
"value": "<p>There's nothing like having your own supply of fresh herbs, readily available and close at hand to use while cooking. Whether you have a large garden or a small kitchen window sill, there's always enough room for something home grown.</p>
<h2>Outdoors</h2>
<h3>Mint</h3>
<p>Mint is a great plant to grow as it's hardy and can grow in almost any soil. Mint can grow wild, so keep it contained in a pot or it might spread and take over your whole garden.</p>
<h3>Sage</h3>
<p>Like mint, sage is another prolific growing plant and will take over your garden if you let it. Highly aromatic, the sage plant can be planted in a pot or flower bed in well drained soil. The best way to store the herb is to sun dry the leaves and store in a cool, dark cupboard in a sealed container.</p>
<h3>Rosemary</h3>
<p>Rosemary plants grow into lovely shrubs. Easily grown from cuttings, rosemary plants do not like freezing temperatures so keep pots or planted bushes near the home to shelter them from the cold. It grows well in pots as it likes dry soil, but can survive well in the ground too. If pruning rosemary to encourage it into a better shape, save the branches and hang them upside down to preserve the flavor and use in food.</p>
<h2>Indoors</h2>
<h3>Basil</h3>
<p>Perfect in sunny spot on a kitchen window sill. Basil is an annual plant, so will die off in the autumn, so it's a good idea to harvest it in the summer if you have an abundance and dry it. Picked basil stays fresh longer if it is placed in water (like fresh flowers). A great way to store basil is to make it into pesto!</p>
<h3>Chives</h3>
<p>A versatile herb, chives can grow well indoors. Ensure the plant is watered well, and gets plenty of light. Remember to regularly trim the chives. This prevents the flowers from developing and encourages new growth.</p>
<h3>Coriander (Cilantro)</h3>
<p>Coriander can grow indoors, but unlike the other herbs, it doesn't like full sun. If you have a south facing kitchen window, this isn't the place for it. Although not as thirsty as basil, coriander doesn't like dry soil so don't forget to water it! Cut coriander is best stored in the fridge.</p>
",
},
"changed": "2022-03-21T10:52:42+00:00",
"content_translation_outdated": false,
"content_translation_source": "und",
"created": "2022-03-21T10:52:42+00:00",
"default_langcode": true,
"drupal_internal__nid": 10,
"drupal_internal__vid": 20,
"langcode": "en",
"moderation_state": "published",
"path": {
"alias": "/articles/give-it-a-go-and-grow-your-own-herbs",
"langcode": "en",
"pid": 85,
},
"promote": true,
"revision_log": null,
"revision_timestamp": "2022-03-21T10:52:42+00:00",
"revision_translation_affected": null,
"status": true,
"sticky": false,
"title": "Give it a go and grow your own herbs",
},
"id": "52837ad0-f218-46bd-a106-5710336b7053",
"links": {
"self": {
"href": "https://tests.next-drupal.org/en/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053?resourceVersion=id%3A20",
},
},
"relationships": {
"field_media_image": {
"data": {
"id": "e5091a16-134e-400d-8393-cfe4eccbcaa2",
"meta": {
"drupal_internal__target_id": 10,
},
"type": "media--image",
},
"links": {
"related": {
"href": "https://tests.next-drupal.org/en/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053/field_media_image?resourceVersion=id%3A20",
},
"self": {
"href": "https://tests.next-drupal.org/en/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053/relationships/field_media_image?resourceVersion=id%3A20",
},
},
},
"field_tags": {
"data": [
{
"id": "dcd81647-71b7-48cb-b555-e20322bcb7a7",
"meta": {
"drupal_internal__target_id": 14,
},
"type": "taxonomy_term--tags",
},
{
"id": "60d20a4c-9d42-4b25-b717-3af3cba6abe8",
"meta": {
"drupal_internal__target_id": 23,
},
"type": "taxonomy_term--tags",
},
{
"id": "57a1d9f6-23a6-4215-a8a9-582202cd938d",
"meta": {
"drupal_internal__target_id": 16,
},
"type": "taxonomy_term--tags",
},
],
"links": {
"related": {
"href": "https://tests.next-drupal.org/en/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053/field_tags?resourceVersion=id%3A20",
},
"self": {
"href": "https://tests.next-drupal.org/en/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053/relationships/field_tags?resourceVersion=id%3A20",
},
},
},
"node_type": {
"data": {
"id": "a145b65a-e660-4f5d-ac0d-bd2ff9e3f0b0",
"meta": {
"drupal_internal__target_id": "article",
},
"type": "node_type--node_type",
},
"links": {
"related": {
"href": "https://tests.next-drupal.org/en/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053/node_type?resourceVersion=id%3A20",
},
"self": {
"href": "https://tests.next-drupal.org/en/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053/relationships/node_type?resourceVersion=id%3A20",
},
},
},
"revision_uid": {
"data": {
"id": "dd9c916d-4d66-4bff-a851-eeba0cf7673a",
"meta": {
"drupal_internal__target_id": 5,
},
"type": "user--user",
},
"links": {
"related": {
"href": "https://tests.next-drupal.org/en/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053/revision_uid?resourceVersion=id%3A20",
},
"self": {
"href": "https://tests.next-drupal.org/en/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053/relationships/revision_uid?resourceVersion=id%3A20",
},
},
},
"uid": {
"data": {
"id": "dd9c916d-4d66-4bff-a851-eeba0cf7673a",
"meta": {
"drupal_internal__target_id": 5,
},
"type": "user--user",
},
"links": {
"related": {
"href": "https://tests.next-drupal.org/en/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053/uid?resourceVersion=id%3A20",
},
"self": {
"href": "https://tests.next-drupal.org/en/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053/relationships/uid?resourceVersion=id%3A20",
},
},
},
},
"type": "node--article",
},
"jsonapi": {
"meta": {
"links": {
"self": {
"href": "http://jsonapi.org/format/1.0/",
},
},
},
"version": "1.0",
},
"links": {
"self": {
"href": "https://tests.next-drupal.org/jsonapi/node/article/52837ad0-f218-46bd-a106-5710336b7053",
},
},
}
`;

exports[`getIndex() fetches the JSON:API index 1`] = `
{
"data": [],
Expand Down
Loading

0 comments on commit 510ac07

Please sign in to comment.