Skip to content
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

Routine maintenance 2023-07 #111

Merged
merged 14 commits into from
Aug 7, 2023
Merged
23 changes: 23 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Publish
run-name: ${{ github.actor }} published a new release
on:
release:
types: [published]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Check out latest code
uses: actions/checkout@v3
- name: Set up node
uses: actions/setup-node@v3
with:
node-version: '18.x'
registry-url: 'https://registry.npmjs.org'
scope: '@launchpadlab'
- name: Install dependencies
run: HUSKY=0 yarn --frozen-lockfile
- name: Publish package on NPM
run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

yarn run docs && git add docs.md
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
18
3 changes: 1 addition & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
language: node_js
node_js:
- '8'
dist: focal
cache: yarn
before_script:
- 'yarn lint'
Expand Down
151 changes: 73 additions & 78 deletions docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,28 @@

### Table of Contents

- [api][1]
- [Examples][2]
- [configureApi][3]
- [Parameters][4]
- [Examples][5]
- [configureHttp][6]
- [Parameters][7]
- [Examples][8]
- [composeMiddleware][9]
- [Parameters][10]
- [Examples][11]
- [http][12]
- [Parameters][13]
- [Examples][14]
- [HttpError][15]
- [Parameters][16]
- [Examples][17]
- [isAuthenticated][18]
- [Parameters][19]
- [Examples][20]
- [getAuthenticationContext][21]
- [Examples][22]
* [api][1]
* [Examples][2]
* [configureApi][3]
* [Parameters][4]
* [Examples][5]
* [configureHttp][6]
* [Parameters][7]
* [Examples][8]
* [composeMiddleware][9]
* [Parameters][10]
* [Examples][11]
* [http][12]
* [Parameters][13]
* [Examples][14]
* [HttpError][15]
* [Parameters][16]
* [Examples][17]
* [isAuthenticated][18]
* [Parameters][19]
* [Examples][20]
* [getAuthenticationContext][21]
* [Examples][22]

## api

Expand All @@ -32,12 +32,12 @@ Provides functions to make API requests with specified HTTP methods.

The functions are as follows:

- `get(url, options)` sends a `'GET'` request
- `patch(url, body, options)` sends a `'PATCH'` request
- `post(url, body, options)` sends a `'POST'` request
- `put(url, body, options)` sends a `'PUT'` request
- `destroy(url, body, options)` sends a `'DELETE'` request
- `call(url, method, body, options)` sends a request with specified method
* `get(url, options)` sends a `'GET'` request
* `patch(url, body, options)` sends a `'PATCH'` request
* `post(url, body, options)` sends a `'POST'` request
* `put(url, body, options)` sends a `'PUT'` request
* `destroy(url, body, options)` sends a `'DELETE'` request
* `call(url, method, body, options)` sends a request with specified method

Each function can be passed an `options` object, which will eventually be forwarded
to the [Fetch API][24].
Expand Down Expand Up @@ -66,8 +66,8 @@ Note: This configuration can always be overridden by passing in options manually

### Parameters

- `config` **[Object][26]** An api configuration object
- `baseApi` **[Object][26]?** An existing api instance to extend with the configuration
* `config` **[Object][26]** An api configuration object
* `baseApi` **[Object][26]?** An existing api instance to extend with the configuration

### Examples

Expand All @@ -88,8 +88,8 @@ Note: This configuration can always be overridden by passing in options manually

### Parameters

- `config` **[Object][26]** An http configuration object
- `baseHttp` **[Object][26]?** An existing http instance to extend with the configuration
* `config` **[Object][26]** An http configuration object
* `baseHttp` **[Object][26]?** An existing http instance to extend with the configuration

### Examples

Expand All @@ -108,7 +108,7 @@ This can be used to create more complex `before` hooks for [http][23].

### Parameters

- `middlewares` **...[Function][27]** Functions that receive and return request options
* `middlewares` **...[Function][27]** Functions that receive and return request options

### Examples

Expand Down Expand Up @@ -156,27 +156,29 @@ Any one of these settings can be overriden using the passed-in config object.

In addition to the normal Fetch API settings, the config object may also contain these special settings just for `http`:

- `url`: The url for the request. This can also be passed in directly as the first argument (see shorthand example).
- `root`: A path to be appended to the given url (default=`''`).
- `crsf`: The name of the `meta` tag containing the CSRF token (default=`'csrf-token'`). This can be set to `false` to prevent a token from being sent.
- `before`: A function that's called before the request executes. This function is passed the request options and its return value will be added to those options.
It can also return a promise that resolves to a new options object.
- `bearerToken`: A token to use for bearer auth. If provided, `http` will add the header `"Authorization": "Bearer <bearerToken>"` to the request.
- `onSuccess`: A function that will be called if the request succeeds. It will be passed the successful response. If it returns a value, `http` will resolve with this value instead of the response.
- `onFailure`: A function that will be called if the request fails. It will be passed the error that was thrown during the request. If it returns a value, `http` will reject with this value instead of the default error.
- `successDataPath`: A path to response data that the promise will resolve with.
- `failureDataPath`: A path to the errors that will be included in the HttpError object (default=`'errors'`)
- `query`: An object that will be transformed into a query string and appended to the request URL.
- `overrideHeaders`: A boolean flag indicating whether or not default headers should be included in the request (default=`false`).
- `camelizeResponse`: A boolean flag indicating whether or not to camelize the response keys (default=`true`). The helper function that does this is also exported from this library as `camelizeKeys`.
- `decamelizeBody`: A boolean flag indicating whether or not to decamelize the body keys (default=`true`). The helper function that does this is also exported from this library as `decamelizeKeys`.
- `decamelizeQuery`: A boolean flag indicating whether or not to decamelize the query string keys (default=`true`).
- `parseJsonStrictly`: A boolean flag indicating whether or not to return the text of the response body if JSON parsing fails (default=`true`). If set to `true` and invalid JSON is received in the response, then `null` will be returned instead.
- `auth`: An object with the following keys `{ username, password }`. If present, `http` will use [basic auth][28], adding the header `"Authorization": "Basic <authToken>"` to the request, where `<authToken>` is a base64 encoded string of `username:password`.
* `url`: The url for the request. This can also be passed in directly as the first argument (see shorthand example).
* `root`: A path to be appended to the given url (default=`''`).
* `crsf`: The name of the `meta` tag containing the CSRF token (default=`'csrf-token'`). This can be set to `false` to prevent a token from being sent.
* `before`: A function that's called before the request executes. This function is passed the request options and its return value will be added to those options.
It can also return a promise that resolves to a new options object.
* `bearerToken`: A token to use for bearer auth. If provided, `http` will add the header `"Authorization": "Bearer <bearerToken>"` to the request.
* `onSuccess`: A function that will be called if the request succeeds. It will be passed the successful response. If it returns a value, `http` will resolve with this value instead of the response.
* `onFailure`: A function that will be called if the request fails. It will be passed the error that was thrown during the request. If it returns a value, `http` will reject with this value instead of the default error.
* `successDataPath`: A path to response data that the promise will resolve with.
* `failureDataPath`: A path to the errors that will be included in the HttpError object (default=`'errors'`)
* `query`: An object that will be transformed into a query string and appended to the request URL.
* `overrideHeaders`: A boolean flag indicating whether or not default headers should be included in the request (default=`false`).
* `camelizeResponse`: A boolean flag indicating whether or not to camelize the response keys (default=`true`). The helper function that does this is also exported from this library as `camelizeKeys`.
* `decamelizeBody`: A boolean flag indicating whether or not to decamelize the body keys (default=`true`). The helper function that does this is also exported from this library as `decamelizeKeys`.
* `decamelizeQuery`: A boolean flag indicating whether or not to decamelize the query string keys (default=`true`).
* `parseJsonStrictly`: A boolean flag indicating whether or not to return the text of the response body if JSON parsing fails (default=`true`). If set to `true` and invalid JSON is received in the response, then `null` will be returned instead.
* `auth`: An object with the following keys `{ username, password }`. If present, `http` will use [basic auth][28], adding the header `"Authorization": "Basic <authToken>"` to the request, where `<authToken>` is a base64 encoded string of `username:password`.

Type: [Function][27]

### Parameters

- `config` **[Object][26]** An object containing config information for the `Fetch` request, as well as the extra keys noted above.
* `config` **[Object][26]** An object containing config information for the `Fetch` request, as well as the extra keys noted above.

### Examples

Expand Down Expand Up @@ -209,17 +211,17 @@ An error class that is thrown by the [http][23] module when a request fails.

In addition to the standard [Error][30] attributes, instances of `HttpError` include the following:

- `status`: the status code of the response
- `statusText`: the status text of the response
- `response`: the full response object
- `message`: A readable error message with format `<status> - <statusText>`
* `status`: the status code of the response
* `statusText`: the status text of the response
* `response`: the full response object
* `message`: A readable error message with format `<status> - <statusText>`

### Parameters

- `status` **[Number][31]** the status code of the response
- `statusText` **[String][32]** the status text of the response
- `response` **[Object][26]** the full response object
- `errors` **[Object][26]** an object containing error messages associated with the response (optional, default `{}`)
* `status` **[Number][31]** the status code of the response
* `statusText` **[String][32]** the status text of the response
* `response` **[Object][26]** the full response object
* `errors` **[Object][26]** an object containing error messages associated with the response (optional, default `{}`)

### Examples

Expand All @@ -237,17 +239,14 @@ http('/bad-route').catch(err => console.log(err.name)) // -> "HttpError"
A helper function to determine if the current user is authenticated.
This function accepts an object argument with a `context` key.

This returns true when the LP Auth Api cookie exists and contains a
token.
If the `context` key is present, this function returns true if the user is
both authenticated and the specified context is present.
*Note, this does not **validate** the token, it only checks for
presence, validation must be done on the server.*

Note, this does not **validate** the token, it only checks for
presence, validation must be done on the server.
Type: [Function][27]

### Parameters

- `options` **[Object][26]** config object containing the context (optional, default `{}`)
* `options` **[Object][26]** config object containing the context (optional, default `{}`)

### Examples

Expand All @@ -273,35 +272,29 @@ isAuthenticated({ context: 'admin' }) // false
isAuthenticated({ context: 'non-admin' }) // false
```

Returns **[Boolean][33]**
Returns **[Boolean][33]** True when the LP Auth Api cookie exists and contains a token.
If the `context` key is present, this function returns true if the user is
both authenticated and the specified context is present.

## getAuthenticationContext

A helper function to retrieve the authentication context for the
A helper function to retrieve the authentication context for the
authenticated user.

This function returns the context string when the LP Auth Api cookie exists,
contains a valid token, and contains a context.

This function returns `undefined` when there is no context present,
or if the LP Auth API cookie does not exist.

### Examples

```javascript
// After an 'admin' signs in
getAuthenticationContext() // 'admin'

// After a user with no context signs in
getAuthenticationContext() // undefined
getAuthenticationContext() // undefined

// After sign out
getAuthenticationContext() // undefined

*
```

Returns **[String][32]**
Returns **([String][32] | [Undefined][34])** The context string when the LP Auth Api cookie exists, contains a valid token, and contains a context. Returns `undefined` when there is no context present, or if the LP Auth API cookie does not exist.

[1]: #api

Expand Down Expand Up @@ -368,3 +361,5 @@ Returns **[String][32]**
[32]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

[33]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean

[34]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/undefined
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
module.exports = {
testEnvironment: 'jsdom',
chawes13 marked this conversation as resolved.
Show resolved Hide resolved
'setupFiles': [
'./test/setup.js',
],
Expand Down
26 changes: 13 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@launchpadlab/lp-requests",
"version": "4.2.2",
"version": "4.3.0",
"description": "Request helpers",
"main": "lib/index.js",
"scripts": {
Expand All @@ -9,12 +9,11 @@
"build:development": "mkdir -p lib && babel src --watch --out-dir lib",
"clean": "rm -rf lib",
"docs": "documentation build src/index.js -f md -o docs.md",
"prepare": "husky install && yarn run lint && yarn run clean && yarn run build",
"lint": "eslint src",
"precommit": "yarn run docs && git add docs.md",
"prepublish": "yarn run lint && yarn run clean && yarn run build",
"report-coverage": "codeclimate-test-reporter < coverage/lcov.info",
"test": "jest --coverage",
"test:coverage": "jest --coverage",
"report-coverage": "codeclimate-test-reporter < coverage/lcov.info"
"test:coverage": "jest --coverage"
},
"repository": "launchpadlab/lp-requests",
"homepage": "https://github.com/launchpadlab/lp-requests",
Expand All @@ -33,21 +32,22 @@
"@babel/core": "^7.5.5",
"@babel/polyfill": "^7.4.4",
"@launchpadlab/babel-preset": "^2.1.0",
"@launchpadlab/eslint-config": "^2.2.3",
"@launchpadlab/eslint-config": "^3.0.1",
"codeclimate-test-reporter": "^0.5.0",
"documentation": "^12.1.1",
"eslint": "^6.1.0",
"husky": "^3.0.3",
"jest": "^24.8.0"
"documentation": "^14.0.2",
"eslint": "^8.46.0",
"husky": "^8.0.0",
"jest": "^29.6.2",
"jest-environment-jsdom": "^29.6.2"
chawes13 marked this conversation as resolved.
Show resolved Hide resolved
},
"dependencies": {
"Base64": "^1.0.1",
"humps": "^2.0.0",
"is-promise": "^2.1.0",
"is-promise": "^4.0.0",
"isomorphic-fetch": "^3.0.0",
"js-cookie": "^2.1.4",
"js-cookie": "^3.0.5",
"lodash": "^4.17.4",
"query-string": "^5.0.0",
"query-string": "^7.1.3",
"url-join": "^4.0.0"
}
}
23 changes: 10 additions & 13 deletions src/get-authentication-context.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,25 @@
import { getLpAuthCookie, parseObject } from './utils'

/**
* A helper function to retrieve the authentication context for the
* A helper function to retrieve the authentication context for the
* authenticated user.
*
* This function returns the context string when the LP Auth Api cookie exists,
* contains a valid token, and contains a context.
*
* This function returns `undefined` when there is no context present,
* or if the LP Auth API cookie does not exist.
*
* @returns {String}
* @name getAuthenticationContext
* @type Function
* @returns {String|Undefined} The context string when the LP Auth Api cookie exists, contains a valid token, and contains a context. Returns `undefined` when there is no context present, or if the LP Auth API cookie does not exist.
*
* @example
*
*
* // After an 'admin' signs in
* getAuthenticationContext() // 'admin'
*
*
* // After a user with no context signs in
* getAuthenticationContext() // undefined
* getAuthenticationContext() // undefined
*
* // After sign out
* getAuthenticationContext() // undefined
*
**/
*
*/

export default function getAuthenticationContext () {
const lpAuthCookie = getLpAuthCookie()
Expand Down
Loading