planning
All checks were successful
Publish To Prod / deploy_and_publish (push) Successful in 35s

This commit is contained in:
2024-10-14 09:15:30 +02:00
parent bcba00a730
commit 6e64e138e2
21059 changed files with 2317811 additions and 1 deletions

4
node_modules/gotrue-js/.babelrc generated vendored Normal file
View File

@@ -0,0 +1,4 @@
{
"presets": ["@babel/preset-env"],
"plugins": ["@babel/plugin-proposal-object-rest-spread"]
}

10
node_modules/gotrue-js/.editorconfig generated vendored Normal file
View File

@@ -0,0 +1,10 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
max_line_length = 120
trim_trailing_whitespace = true
insert_final_newline = true

1
node_modules/gotrue-js/.eslintcache generated vendored Normal file
View File

@@ -0,0 +1 @@
[{"/Users/erezrokah/Code/github/netlify/gotrue-js/src/admin.js":"1","/Users/erezrokah/Code/github/netlify/gotrue-js/src/index.js":"2","/Users/erezrokah/Code/github/netlify/gotrue-js/src/user.js":"3","/Users/erezrokah/Code/github/netlify/gotrue-js/tests/user.js":"4"},{"size":855,"mtime":1591536403762,"results":"5","hashOfConfig":"6"},{"size":3735,"mtime":1611859798902,"results":"7","hashOfConfig":"6"},{"size":5782,"mtime":1611863798601,"results":"8","hashOfConfig":"6"},{"size":1053,"mtime":1611863798602,"results":"9","hashOfConfig":"6"},{"filePath":"10","messages":"11","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"1s3mbll",{"filePath":"12","messages":"13","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"14","messages":"15","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},{"filePath":"16","messages":"17","errorCount":0,"warningCount":0,"fixableErrorCount":0,"fixableWarningCount":0},"/Users/erezrokah/Code/github/netlify/gotrue-js/src/admin.js",[],"/Users/erezrokah/Code/github/netlify/gotrue-js/src/index.js",[],"/Users/erezrokah/Code/github/netlify/gotrue-js/src/user.js",[],"/Users/erezrokah/Code/github/netlify/gotrue-js/tests/user.js",[]]

3
node_modules/gotrue-js/.eslintignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
node_modules
lib
browser

75
node_modules/gotrue-js/.eslintrc.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
const { overrides } = require('@netlify/eslint-config-node');
module.exports = {
extends: '@netlify/eslint-config-node',
parserOptions: {
sourceType: 'module',
},
env: {
browser: true,
node: true,
es6: true,
},
rules: {
// eslint-plugin-ava needs to know where test files are located
'ava/no-ignored-test-files': [2, { files: ['tests/**/*.js'] }],
// TODO: enable these rules
'consistent-this': 0,
'func-style': 0,
'no-throw-literal': 0,
'no-param-reassign': 0,
'no-magic-numbers': 0,
'fp/no-mutation': 0,
'fp/no-let': 0,
'fp/no-class': 0,
'fp/no-this': 0,
'fp/no-loops': 0,
'fp/no-delete': 0,
'fp/no-mutating-assign': 0,
'no-console': ['warn', { allow: ['warn', 'error'] }],
'no-unused-vars': ['error', { vars: 'all', args: 'none', ignoreRestSiblings: true }],
'no-underscore-dangle': 0,
complexity: 0,
'max-depth': 0,
'max-lines': 0,
'promise/prefer-await-to-then': 0,
'promise/no-return-wrap': 0,
'promise/no-nesting': 0,
'node/no-unsupported-features/es-syntax': 0,
camelcase: 0,
},
overrides: [
...overrides,
{
files: ['*.ts'],
parser: '@typescript-eslint/parser',
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'prettier/@typescript-eslint',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:import/typescript',
],
},
{
files: ['tests/**/*.js'],
rules: {
'node/no-unpublished-import': 0,
},
},
{
// TODO: remove this
files: ['README.md'],
rules: {
'node/no-missing-import': 0,
'no-console': 0,
'promise/always-return': 0,
'require-await': 0,
'node/exports-style': 0,
'no-shadow': 0,
},
},
],
};

1
node_modules/gotrue-js/.gitattributes generated vendored Normal file
View File

@@ -0,0 +1 @@
* text=auto eol=lf

1
node_modules/gotrue-js/.github/CODEOWNERS generated vendored Normal file
View File

@@ -0,0 +1 @@
* @netlify/netlify-dev

View File

@@ -0,0 +1,40 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,19 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

22
node_modules/gotrue-js/.github/workflows/babelify.yml generated vendored Normal file
View File

@@ -0,0 +1,22 @@
name: babelify
on:
# Workaround for syncing browser/gotrue.js on release-please PRs
push:
branches:
- release-*
jobs:
babelify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
token: ${{ secrets.NODE_PKG_RELEASE_TOKEN }}
- uses: actions/setup-node@v2
with:
node-version: 15
- name: Install dependencies
run: npm ci
- run: npm run babelify
- uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: 'chore: sync browser/gotrue.js'

31
node_modules/gotrue-js/.github/workflows/fossa.yml generated vendored Normal file
View File

@@ -0,0 +1,31 @@
name: Dependency License Scanning
on:
push:
branches:
- master
defaults:
run:
shell: bash
jobs:
fossa:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Fossa init
run: |-
curl -H 'Cache-Control: no-cache' https://raw.githubusercontent.com/fossas/fossa-cli/master/install.sh | bash
fossa init
- name: Set env
run: echo "line_number=$(grep -n "project" .fossa.yml | cut -f1 -d:)" >> $GITHUB_ENV
- name: Configuration
run: |-
sed -i "${line_number}s|.*| project: git@github.com:${GITHUB_REPOSITORY}.git|" .fossa.yml
cat .fossa.yml
- name: Upload dependencies
run: fossa analyze --debug
env:
FOSSA_API_KEY: ${{ secrets.FOSSA_API_KEY }}

30
node_modules/gotrue-js/.github/workflows/labeler.yml generated vendored Normal file
View File

@@ -0,0 +1,30 @@
name: Label PR
on:
pull_request:
types: [opened, edited]
jobs:
label-pr:
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false
runs-on: ubuntu-latest
steps:
- uses: erezrokah/pr-labeler-action@v1.0.0
if: startsWith(github.event.pull_request.title, 'fix')
with:
token: '${{ secrets.GITHUB_TOKEN }}'
label: 'type: bug'
- uses: erezrokah/pr-labeler-action@v1.0.0
if: startsWith(github.event.pull_request.title, 'chore')
with:
token: '${{ secrets.GITHUB_TOKEN }}'
label: 'type: chore'
- uses: erezrokah/pr-labeler-action@v1.0.0
if: startsWith(github.event.pull_request.title, 'feat')
with:
token: '${{ secrets.GITHUB_TOKEN }}'
label: 'type: feature'
- uses: erezrokah/pr-labeler-action@v1.0.0
if: startsWith(github.event.pull_request.title, 'security')
with:
token: '${{ secrets.GITHUB_TOKEN }}'
label: 'type: security'

47
node_modules/gotrue-js/.github/workflows/node.yml generated vendored Normal file
View File

@@ -0,0 +1,47 @@
name: GoTrueJS CI
on:
push:
branches:
- master
tags:
- '*'
pull_request:
types: [opened, synchronize, reopened]
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [macos-latest, windows-latest, ubuntu-latest]
node-version: [15.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- name: log versions
run: node --version && npm --version
- name: Install dependencies
run: npm ci
- name: compile code
run: npm run babelify
- name: Linting
run: npm run format:ci
- name: Tests
run: npm run test:ci
- name: Get test coverage flags
id: test-coverage-flags
run: |-
os=${{ matrix.os }}
node=${{ matrix.node-version }}
echo "::set-output name=os::${os/-latest/}"
echo "::set-output name=node::node_${node//./}"
shell: bash
- uses: codecov/codecov-action@v1
with:
file: coverage/coverage-final.json
flags: ${{ steps.test-coverage-flags.outputs.os }},${{ steps.test-coverage-flags.outputs.node }}

View File

@@ -0,0 +1,17 @@
name: release-please
on:
push:
branches:
- master
jobs:
release-please:
runs-on: ubuntu-latest
steps:
- uses: GoogleCloudPlatform/release-please-action@v2
id: release
with:
# We can't rely on the GITHUB_TOKEN as we need to trigger
# further actions and the GITHUB_TOKEN doesn't allow it
token: ${{ secrets.NODE_PKG_RELEASE_TOKEN }}
release-type: node
package-name: 'gotrue-js'

View File

@@ -0,0 +1 @@
{}

View File

@@ -0,0 +1 @@
{}

View File

@@ -0,0 +1 @@
{"parent":"d14f88ea-8b82-434a-a594-5cf76f4ee717","pid":41740,"argv":["/usr/local/Cellar/node/14.9.0/bin/node","/Users/erezrokah/Code/github/netlify/gotrue-js/node_modules/ava/lib/worker/subprocess.js"],"execArgv":[],"cwd":"/Users/erezrokah/Code/github/netlify/gotrue-js","time":1611856858825,"ppid":41738,"coverageFilename":"/Users/erezrokah/Code/github/netlify/gotrue-js/.nyc_output/3962e035-17bd-420a-9bb4-71eb1673b81c.json","externalId":"","uuid":"3962e035-17bd-420a-9bb4-71eb1673b81c","files":[]}

View File

@@ -0,0 +1 @@
{"parent":null,"pid":41738,"argv":["/usr/local/Cellar/node/14.9.0/bin/node","/Users/erezrokah/Code/github/netlify/gotrue-js/node_modules/.bin/ava"],"execArgv":[],"cwd":"/Users/erezrokah/Code/github/netlify/gotrue-js","time":1611856855842,"ppid":41737,"coverageFilename":"/Users/erezrokah/Code/github/netlify/gotrue-js/.nyc_output/d14f88ea-8b82-434a-a594-5cf76f4ee717.json","externalId":"","uuid":"d14f88ea-8b82-434a-a594-5cf76f4ee717","files":[]}

View File

@@ -0,0 +1 @@
{"processes":{"3962e035-17bd-420a-9bb4-71eb1673b81c":{"parent":"d14f88ea-8b82-434a-a594-5cf76f4ee717","children":[]},"d14f88ea-8b82-434a-a594-5cf76f4ee717":{"parent":null,"children":["3962e035-17bd-420a-9bb4-71eb1673b81c"]}},"files":{},"externalIds":{}}

5
node_modules/gotrue-js/.prettierrc generated vendored Normal file
View File

@@ -0,0 +1,5 @@
{
"trailingComma": "all",
"singleQuote": true,
"printWidth": 100
}

1
node_modules/gotrue-js/.prettierrc.json generated vendored Normal file
View File

@@ -0,0 +1 @@
"@netlify/eslint-config-node/.prettierrc.json"

12
node_modules/gotrue-js/.vscode/settings.json generated vendored Normal file
View File

@@ -0,0 +1,12 @@
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true
},
"[markdown]": {
"editor.formatOnSave": false,
"editor.codeActionsOnSave": {
"source.fixAll": false
}
}
}

28
node_modules/gotrue-js/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,28 @@
## [0.9.28](https://github.com/netlify/gotrue-js/compare/v0.9.27...v0.9.28) (2020-12-07)
### Bug Fixes
* **docs-readme:** add note about using admin methods with Netlify CLI ([#234](https://github.com/netlify/gotrue-js/issues/234)) ([5f3d504](https://github.com/netlify/gotrue-js/commit/5f3d504b3694610d56027bf40ef7fbf2f1f37eaa))
### [0.9.29](https://www.github.com/netlify/gotrue-js/compare/v0.9.28...v0.9.29) (2021-01-28)
### Bug Fixes
* **security:** don't log token on parsing errors ([#279](https://www.github.com/netlify/gotrue-js/issues/279)) ([1334f52](https://www.github.com/netlify/gotrue-js/commit/1334f5289a53f226defdea99d694788cfae290b5))
## [0.9.27](https://github.com/netlify/gotrue-js/compare/v0.9.26...v0.9.27) (2020-09-07)
### Bug Fixes
* **types:** make signup data argument optional ([#165](https://github.com/netlify/gotrue-js/issues/165)) ([d1565a7](https://github.com/netlify/gotrue-js/commit/d1565a7d0576ff613b1c37c46a42d1fcbd720c7c))
## [0.9.26](https://github.com/netlify/gotrue-js/compare/v0.9.25...v0.9.26) (2020-06-30)
### Bug Fixes
* **docs:** format readme file and add some missing arguments ([#110](https://github.com/netlify/gotrue-js/issues/110)) ([738998e](https://github.com/netlify/gotrue-js/commit/738998eb212b7a4bb0b6dfb86a958fab7450b40d))
* return a rejected promise when inner token is null or undefined ([#83](https://github.com/netlify/gotrue-js/issues/83)) ([2ae4de5](https://github.com/netlify/gotrue-js/commit/2ae4de5317c0a9962ee027346fdf611aba4ae566))

21
node_modules/gotrue-js/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Netlify
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

880
node_modules/gotrue-js/README.md generated vendored Normal file
View File

@@ -0,0 +1,880 @@
# gotrue-js library
[![Build Status](https://travis-ci.org/netlify/gotrue-js.svg?branch=master)](https://travis-ci.org/netlify/gotrue-js)
This is a JavaScript client library for the [GoTrue](https://github.com/netlify/gotrue) API.
It lets you create and authenticate users and is a building block for constructing
the UI for signups, password recovery, login and logout.
Play around the methods via the [demo site](https://gotruejs-playground.netlify.com/).
## Installation
```bash
yarn add gotrue-js
```
## Usage
```js
import GoTrue from 'gotrue-js';
// Instantiate the GoTrue auth client with an optional configuration
auth = new GoTrue({
APIUrl: 'https://<your domain name>/.netlify/identity',
audience: '',
setCookie: false,
});
```
### GoTrue configuration
APIUrl: The absolute path of the GoTrue endpoint. To find the `APIUrl`, go to `Identity` page of your Netlify site dashboard.
audience(optional): `audience` is one of the pre-defined [JWT payload](https://tools.ietf.org/html/rfc7519#section-4.1.3) claims. It's an optional attribute which is set to be empty by default. If you were hosting your own identity service and wanted to support [multitenancy](https://en.wikipedia.org/wiki/Multitenancy), you would need `audience` to separate the users.
setCookie(optional): set to be `false` by default. If you wish to implement the `remember me` functionality, set the value to be `true`.
### Error handling
If an error occurs during the request, the promise may be rejected with an Error, `HTTPError`, `TextHTTPError`, or `JSONHTTPError`. See [micro-api-client-lib error types](https://github.com/netlify/micro-api-client-lib#class-httperror-extends-error).
## Authentication examples
### Create a new user
Create a new user with the specified email and password
```js
auth.signup(email, password);
```
Example usage:
```js
auth
.signup(email, password)
.then((response) => console.log('Confirmation email sent', response))
.catch((error) => console.log("It's an error", error));
```
Example response object:
```json
{
"id": "example-id",
"aud": "",
"role": "",
"email": "example@example.com",
"confirmation_sent_at": "2018-04-27T22:36:59.636416916Z",
"app_metadata": { "provider": "email" },
"user_metadata": null,
"created_at": "2018-04-27T22:36:59.632133283Z",
"updated_at": "2018-04-27T22:37:00.061039863Z"
}
```
Also, make sure the `Registration preferences` under `Identity settings` in your Netlify dashboard are set to `Open`.
![registration preferences](src/images/identity-settings-registration.png)
If the registration preferences is set to be `Invite only`, you'll get an error message like this:
`{code: 403, msg: 'Signups not allowed for this instance'}`
### Confirm a new user signup
This function confirms a user sign up via a unique confirmation token
```js
auth.confirm(token, remember);
```
When a new user signed up, a confirmation email will be sent to the user if `Autoconfirm` isn't turned on under the [identity settings](https://www.netlify.com/docs/identity/#adding-users).
In the email, there's a link that says "Confirm your email address".
When a user clicks on the link, it'll be redirected to the site with a [fragment identifier](https://en.wikipedia.org/wiki/Fragment_identifier) `#confirmation_token=Iyo9xHvsGVbW-9A9v4sDmQ` in the URL.
For all good reasons, the `confirmation_token` is hidden from the browser via a redirect.
If you wish to manually confirm a user using the `auth.confirm(token, remember)` method,
you can copy the link location of the email and use the `curl -I` script to get the `confirmation_token` from your terminal. E.g.,
```bash
$ curl -I https://mandrillapp.com/track/click/30002868/example.netlify.com?p=example-token
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.12.2
Date: Tue, 15 May 2018 21:19:13 GMT
Content-Type: text/html; charset=utf-8
Set-Cookie: PHPSESSID=77c421bf85fa412e5f994f28a6b30956; expires=Wed, 16-May-2018 07:19:13 GMT; path=/; secure; HttpOnly
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: PHPSESSID=77c421bf85fa412e5f994f28a6b30956; expires=Wed, 16-May-2018 07:19:13 GMT; path=/; secure; httponly
Location: https://example.netlify.com/#confirmation_token=Iyo9xHvsGVbW-9A9v4sDmQ
```
Example usage:
```js
auth
.confirm(token, true)
.then((response) => {
console.log('Confirmation email sent', JSON.stringify({ response }));
})
.catch((error) => {
console.log(error);
});
```
_This method requires usage of browser window object `localStorage`. Test the usage in your front end code._
Example response object:
```json
{
"response": {
"api": {
"apiURL": "https://example.netlify.com/.netlify/identity",
"_sameOrigin": true,
"defaultHeaders": {}
},
"url": "https://example.netlify.com/.netlify/identity",
"token": {
"access_token": "example-jwt-token",
"token_type": "bearer",
"expires_in": 3600,
"refresh_token": "example-refresh_token",
"expires_at": 1526110512000
},
"id": "example-id",
"aud": "",
"role": "",
"email": "example@netlify.com",
"confirmed_at": "2018-05-12T06:35:13Z",
"confirmation_sent_at": "2018-05-12T06:34:35Z",
"app_metadata": {
"provider": "email"
},
"user_metadata": {},
"created_at": "2018-05-12T06:34:35Z",
"updated_at": "2018-05-12T06:34:35Z"
}
}
```
### Login a user
Handles user login via the specified email and password
`auth.login(email, password, remember)`
Example usage:
```js
auth
.login(email.value, password.value, true)
.then((response) => {
showMessage(`Success! Response: ${JSON.stringify({ response })}`, form);
})
.catch((error) => showMessage(`Failed :( ${JSON.stringify(error)}`, form));
```
Example response object:
```json
{
"response": {
"api": {
"apiURL": "https://example.netlify.com/.netlify/identity",
"_sameOrigin": true,
"defaultHeaders": {}
},
"url": "https://example.netlify.com/.netlify/identity",
"token": {
"access_token": "example-jwt-token",
"token_type": "bearer",
"expires_in": 3600,
"refresh_token": "example-refresh_token",
"expires_at": 1526062471000
},
"id": "example-id",
"aud": "",
"role": "",
"email": "example@netlify.com",
"confirmed_at": "2018-05-04T23:57:17Z",
"app_metadata": {
"provider": "email"
},
"user_metadata": {},
"created_at": "2018-05-04T23:57:17Z",
"updated_at": "2018-05-04T23:57:17Z"
}
}
```
### Request password recover email
This function sends a request to GoTrue API and triggers a password recovery email to the specified email address.
Similar to `confirmation_token`, the `recovery_token` is baked in the link of the email. You can also copy the link location from the email and run `curl -I` in the command line to grab the token.
`auth.requestPasswordRecovery(email)`
Example usage:
```js
auth
.requestPasswordRecovery(email)
.then((response) => console.log('Recovery email sent', { response }))
.catch((error) => console.log('Error sending recovery mail: %o', error));
```
Example response object:
`{}`
### Recover a user account
This function recovers a user account via a recovery token
`auth.recover(recoveryToken, remember)`
Example usage:
```js
auth
.recover(token, true)
.then((response) => console.log('Logged in as %s', JSON.stringify({ response })))
.catch((error) => console.log('Failed to verify recover token: %o', error));
```
Example response object:
```json
{
"response": {
"api": {
"apiURL": "https://example.netlify.com/.netlify/identity",
"_sameOrigin": true,
"defaultHeaders": {}
},
"url": "https://example.netlify.com/.netlify/identity",
"token": {
"access_token": "example-jwt-token",
"token_type": "bearer",
"expires_in": 3600,
"refresh_token": "example-refresh_token",
"expires_at": 1526107729000
},
"id": "example-id",
"aud": "",
"role": "",
"email": "example@netlify.com",
"confirmed_at": "2018-05-12T05:48:49Z",
"invited_at": "2018-05-04T23:40:00Z",
"recovery_sent_at": "2018-05-12T05:48:13Z",
"app_metadata": {
"provider": "email"
},
"user_metadata": {},
"created_at": "2018-05-04T23:40:00Z",
"updated_at": "2018-05-04T23:40:00Z"
}
}
```
### Get current user
This function returns the current user object when a user is logged in
`auth.currentUser()`
Example usage:
```js
const user = auth.currentUser();
```
Example response object:
```json
{
"api": {
"apiURL": "https://example.netlify.com/.netlify/identity",
"_sameOrigin": true,
"defaultHeaders": {}
},
"url": "https://example.netlify.com/.netlify/identity",
"token": {
"access_token": "example-jwt-token",
"token_type": "bearer",
"expires_in": 3600,
"refresh_token": "example-refresh_token",
"expires_at": 1525214326000
},
"id": "example-id",
"aud": "",
"role": "",
"email": "example@example.com",
"confirmed_at": "2018-05-01T19:21:00Z",
"app_metadata": {
"provider": "email"
},
"user_metadata": {},
"created_at": "2018-05-01T19:21:00Z",
"updated_at": "2018-05-01T19:21:00Z"
}
```
### Update a user
This function updates a user object with specified attributes
`user.update(attributes)`
Users can update their `user_metadata` field. To do this, pass an object to the `attributes.data` key with the fields you want to update. Updates to a users `app_metadata` must be performed from a secure environment, such as a [Lambda function](https://www.netlify.com/docs/functions/). For examples on updating user and app metadata, see [netlify/identity-update-user-data](https://github.com/netlify/identity-update-user-data).
Example usage:
```js
const user = auth.currentUser();
user
.update({ email: 'example@example.com', password: 'password' })
.then((user) => console.log('Updated user %s', user))
.catch((error) => {
console.log('Failed to update user: %o', error);
throw error;
});
```
Example response object:
```json
{
"api": {
"apiURL": "https://example.netlify.com/.netlify/identity",
"_sameOrigin": true,
"defaultHeaders": {}
},
"url": "https://example.netlify.com/.netlify/identity",
"token": {
"access_token": "example-jwt-token",
"token_type": "bearer",
"expires_in": 3600,
"refresh_token": "example-refresh_token",
"expires_at": 1525215471000
},
"id": "example-id",
"aud": "",
"role": "",
"email": "example@example.com",
"confirmed_at": "2018-05-01T19:21:00Z",
"app_metadata": {
"provider": "email"
},
"user_metadata": {},
"created_at": "2018-05-01T19:21:00Z",
"updated_at": "2018-05-01T22:04:07.923944421Z",
"new_email": "new-example@example.com",
"email_change_sent_at": "2018-05-01T22:04:07.49197052Z"
}
```
### Get a JWT token
This function retrieves a JWT token from a currently logged in user
`user.jwt(forceRefresh)`
Example usage:
```js
const user = auth.currentUser();
const jwt = user.jwt();
jwt
.then((response) => console.log('This is a JWT token', response))
.catch((error) => {
console.log('Error fetching JWT token', error);
throw error;
});
```
Example response object:
```bash
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MjUyMTk4MTYsInN1YiI6ImE5NG.98YDkB6B9JbBlDlqqef2nme2tkAnsi30QVys9aevdCw debugger eval code:1:43
```
### Logout a user
This function removes the current session of the user and log out the user
`user.logout()`
Example usage:
```js
const user = auth.currentUser();
user
.logout()
.then(response => console.log("User logged out");)
.catch(error => {
console.log("Failed to logout user: %o", error);
throw error;
});
```
## Admin methods
The following admin methods are currently not available to be used directly. You can access `context.clientContext.identity` and get a short lived admin token through a Lambda function and achieve the same goals, e.g., update user role, create or delete user etc. See [Functions and Identity](https://docs.netlify.com/functions/functions-and-identity/) for more info.
> For users of [Netlify CLI](https://github.com/netlify/cli) - functions using admin methods will _not_ work locally - they need to be deployed to your site in order to work as intended.
Let's create a simple login form in HTML and JavaScript to interact with a lambda function and test out the admin methods.
1. Create an HTML form for user login
```html
<h2>Log in</h2>
<form name="login">
<div class="message"></div>
<p>
<label>Email<br /><input type="email" name="email" required /></label>
</p>
<p>
<label>Password<br /><input type="password" name="password" required /></label>
</p>
<button type="submit">Log in</button>
</form>
```
2. Invoke lambda function. (In this example our function is names as `hello.js`)
```js
document.querySelector("form[name='login']").addEventListener("submit", e => {
e.preventDefault();
const form = e.target;
const { email, password } = form.elements;
auth
.login(email.value, password.value, true)
.then(response => {
const myAuthHeader = "Bearer " + response.token.access_token; //creates the bearer token
fetch("/.netlify/functions/hello", {
headers: { Authorization: myAuthHeader },
credentials: "include"
})
.then(response => {
console.log({ response });
})
.catch(error => {...});
})
.catch(error => {...});
});
```
### Get a user
This function retrieves a user object with the specified user id
```js
getUser(user) {
return this.user.\_request(`/admin/users/${user.id}`);
}
```
Example usage:
```js
import fetch from 'node-fetch';
exports.handler = async (event, context) => {
const { identity, user } = context.clientContext;
const userID = user.sub;
const userUrl = `${identity.url}/admin/users/{${userID}}`;
const adminAuthHeader = `Bearer ${ identity.token}`;
try {
return fetch(userUrl, {
method: 'GET',
headers: { Authorization: adminAuthHeader },
})
.then((response) => response.json())
.then((data) => {
console.log('data', JSON.stringify(data));
return { statusCode: 204 };
})
.catch((error) => {
console.log('Failed to get user! 500! Internal.');
return {
statusCode: 500,
body: `Internal Server Error: ${ error}`,
};
});
} catch (error) {
console.log('GOT HERE! 500! outer');
return { statusCode: 500, body: `Internal Server Error: ${ error}` };
}
};
```
Example response object:
```json
{
"id": "example-id",
"aud": "",
"role": "",
"email": "example@netlify.com",
"confirmed_at": "2018-05-09T06:28:46Z",
"app_metadata": {
"provider": "email"
},
"user_metadata": {},
"created_at": "2018-05-09T06:28:46Z",
"updated_at": "2018-05-09T06:28:46Z"
}
```
### Update a user
This function updates the an existing user with the specified attributes
```js
updateUser(user, attributes = {}) {
return this.user._request(`/admin/users/${user.id}`, {
method: "PUT",
body: JSON.stringify(attributes)
});
}
```
Example usage:
```js
import fetch from "node-fetch";
exports.handler = async (event, context) => {
const { identity, user } = context.clientContext;
const userID = user.sub;
const userUrl = `${identity.url}/admin/users/${userID}`;
const adminAuthHeader = "Bearer " + identity.token;
try {
return fetch(userUrl, {
method: "PUT",
headers: { Authorization: adminAuthHeader },
body: JSON.stringify({ app_metadata: { roles: ["superstar"] } })
})
.then(response => {
return response.json();
})
.then(data => {
console.log("Updated a user! 204!");
console.log(JSON.stringify({ data }));
return { statusCode: 204 };
})
.catch(e => return {...});
} catch (e) { return e; }
};
```
Example response object:
```json
{
"data": {
"id": "example-id",
"aud": "",
"role": "",
"email": "example@netlify.com",
"confirmed_at": "2018-05-09T06:52:58Z",
"app_metadata": {
"provider": "email",
"roles": [
"superstar"
]
},
"user_metadata": {},
"created_at": "2018-05-09T06:52:58Z",
"updated_at": "2018-05-11T00:26:27.668465915Z"
}
}
```
### Invite a user
To invite a user using the admin token, do a `POST` request to `/invite` endpoint. It's not possible to set `user_metadata` or `app_metadata` until a user has been created.
Example usage:
```js
import fetch from 'node-fetch';
exports.handler = async (event, context) => {
const { identity } = context.clientContext;
const inviteUrl = `${identity.url}/invite`;
const adminAuthHeader = "Bearer " + identity.token;
try {
return fetch(inviteUrl, {
method: "POST",
headers: { Authorization: adminAuthHeader },
body: JSON.stringify({ email: "example@example.com" })
})
.then(response => {
return response.json();
})
.then(data => {
console.log("Invited a user! 204!");
console.log(JSON.stringify({ data }));
return { statusCode: 204 };
})
.catch(e => return {...});
} catch (e) { return e; };
};
```
Example response:
```json
{
"id": "example-id",
"aud": "",
"role": "",
"email": "example@example.com",
"invited_at": "2018-05-25T20:28:04.436230023Z",
"app_metadata": {
"provider": "email"
},
"user_metadata": null,
"created_at": "2018-05-25T20:28:03.684905861Z",
"updated_at": "2018-05-25T20:28:04.862592451Z"
}
```
### Create a new user
This function creates a new user object with the specified new email and password and other optional attributes. User will not be confirmed unless `confirm` parameter is set to true.
```js
createUser(email, password, attributes = {}) {
attributes.email = email;
attributes.password = password;
return this.user.\_request("/admin/users", {
method: "POST",
body: JSON.stringify(attributes)
});
}
```
Example usage:
```js
import fetch from "node-fetch";
exports.handler = async (event, context) => {
const { identity, user } = context.clientContext;
const userID = user.sub;
const usersUrl = `${identity.url}/admin/users`;
const adminAuthHeader = "Bearer " + identity.token;
try {
return fetch(usersUrl, {
method: "POST",
headers: { Authorization: adminAuthHeader },
body: JSON.stringify({ email: "new-email@netlify.com", password: "newpw", confirm: true })
})
.then(response => {
return response.json();
})
.then(data => {
console.log("Created a user! 204!");
console.log(JSON.stringify({ data }));
return { statusCode: 204 };
})
.catch(e => {...};
});
} catch (e) {
return e;
}
};
```
Example response object:
```json
{
"data": {
"id": "new-id",
"aud": "",
"role": "",
"email": "new-email@netlify.com",
"app_metadata": {
"provider": "email"
},
"user_metadata": null,
"created_at": "2018-05-11T00:37:34.475713996Z",
"updated_at": "2018-05-11T00:37:34.481743781Z"
}
}
```
### Delete a user
This function deletes an existing user object
```js
deleteUser(user) {
return this.user.\_request(`/admin/users/${user.id}`, {
method: "DELETE"
});
}
```
Example usage:
```js
import fetch from 'node-fetch';
exports.handler = async (event, context) => {
const { identity, user } = context.clientContext;
const userID = user.sub;
const userUrl = `${identity.url}/admin/users/{${userID}}`;
const adminAuthHeader = `Bearer ${identity.token}`;
try {
return fetch(userUrl, {
method: 'DELETE',
headers: { Authorization: adminAuthHeader },
})
.then((response) => {
console.log('Deleted a user!');
return response.json();
})
.then((data) => {
console.log({ data });
return { statusCode: 204 };
})
.catch((error) => ({
statusCode: 500,
body: `Internal Server Error: ${error}`,
}));
} catch (error) {
return error;
}
};
```
Example response object:
```json
{ "data": {} }
```
### Get a list of users
This function retrieves an array of user objects. The `audience` param is optional. It's for when you are hosting your own identity service and want to support [multitenancy](https://en.wikipedia.org/wiki/Multitenancy).
```js
listUsers(aud) {
return this.user._request("/admin/users", {
method: "GET",
audience: aud
});
}
```
Example usage:
```js
import fetch from 'node-fetch';
exports.handler = async (event, context) => {
const { identity, user } = context.clientContext;
const usersUrl = `${identity.url}/admin/users`;
const adminAuthHeader = `Bearer ${identity.token}`;
try {
return fetch(usersUrl, {
method: 'GET',
headers: { Authorization: adminAuthHeader },
})
.then((response) => response.json())
.then((data) => {
console.log('data', JSON.stringify(data));
return { statusCode: 204 };
})
.catch((error) => ({
statusCode: 500,
body: `Internal Server Error: ${error}`,
}));
} catch (error) {
return error;
}
};
```
Example response object:
```json
{
"aud": "",
"users": [
{
"id": "example-id-01",
"aud": "",
"role": "",
"email": "example-email-01@netlify.com",
"app_metadata": {
"provider": "email"
},
"user_metadata": {},
"created_at": "2018-05-09T18:14:51Z",
"updated_at": "2018-05-09T18:14:51Z"
},
{
"id": "example-id-02",
"aud": "",
"role": "",
"email": "example-email-02@netlify.com",
"confirmed_at": "2018-05-09T06:52:58Z",
"app_metadata": {
"provider": "email"
},
"user_metadata": {},
"created_at": "2018-05-09T06:52:58Z",
"updated_at": "2018-05-09T06:52:58Z"
},
{
"id": "example-id-03",
"aud": "",
"role": "",
"email": "example-email-03@netlify.com",
"confirmed_at": "2018-05-09T06:28:46Z",
"app_metadata": {
"provider": "email",
"roles": [
"admin"
]
},
"user_metadata": {},
"created_at": "2018-05-09T06:28:46Z",
"updated_at": "2018-05-09T06:28:46Z"
}
]
}
```
## Oauth providers supported by Netlify
Currently we support Google, GitHub, GitLab, and BitBucket as directly supported in the Netlify app UI (other oauth providers require serverless functions to be set up correctly, but these don't.)
[`acceptInviteExternalUrl`](https://github.com/netlify/gotrue-js/blob/6dda47191dac9194658c5899272fc962d96f8cd6/index.d.ts#L21) and [`loginExternalUrl`](https://github.com/netlify/gotrue-js/blob/6dda47191dac9194658c5899272fc962d96f8cd6/index.d.ts#L26) are useful for that. You can see example usage in [`netlify-identity-widget`](https://github.com/netlify/netlify-identity-widget/blob/ece08ed2a3653adcad87cf3998277362e362da60/src/state/store.js#L99-L119)
## See also
- [gotrue](https://github.com/netlify/gotrue)
- [netlify-identity-widget](https://github.com/netlify/netlify-identity-widget/)
- [micro-api-client-library](https://github.com/netlify/micro-api-client-lib)
- [Netlify identity docs](https://www.netlify.com/docs/identity/)

4
node_modules/gotrue-js/RELEASE.md generated vendored Normal file
View File

@@ -0,0 +1,4 @@
# Releasing
1. Merge the release PR
2. Publish the package `npm publish`

8
node_modules/gotrue-js/ava.config.js generated vendored Normal file
View File

@@ -0,0 +1,8 @@
const config = {
files: ['tests/*.js'],
verbose: true,
babel: true,
require: ['esm'],
};
export default config;

1
node_modules/gotrue-js/commitlint.config.js generated vendored Normal file
View File

@@ -0,0 +1 @@
module.exports = { extends: ['@commitlint/config-conventional'] };

1
node_modules/gotrue-js/coverage/coverage-final.json generated vendored Normal file
View File

@@ -0,0 +1 @@
{}

0
node_modules/gotrue-js/coverage/lcov.info generated vendored Normal file
View File

107
node_modules/gotrue-js/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,107 @@
declare class Admin {
constructor(user: User);
createUser(email: string, password: string, attributes?: any): Promise<UserData>;
deleteUser(user: UserData): Promise<void>;
getUser(user: UserData): Promise<UserData>;
listUsers(aud: string): Promise<UserData[]>;
updateUser(user: UserData, attributes?: any): Promise<void>;
}
export interface GoTrueInit {
APIUrl?: string;
audience?: string;
setCookie?: boolean;
}
declare class GoTrue {
constructor(init?: GoTrueInit);
acceptInvite(token: string, password: string, remember?: boolean): Promise<User>;
acceptInviteExternalUrl(provider: string, token: string): string;
confirm(token: string, remember?: boolean): Promise<User>;
createUser(tokenResponse: any, remember?: boolean): Promise<User>;
currentUser(): User | null;
login(email: string, password: string, remember?: boolean): Promise<User>;
loginExternalUrl(provider: string): string;
recover(token: string, remember?: boolean): Promise<User>;
requestPasswordRecovery(email: string): Promise<void>;
settings(): Promise<Settings>;
signup(email: string, password: string, data?: any): Promise<User>;
verify(type: string, token: string, remember?: boolean): Promise<User>;
}
export interface Settings {
autoconfirm: boolean;
disable_signup: boolean;
external: {
bitbucket: boolean;
email: boolean;
facebook: boolean;
github: boolean;
gitlab: boolean;
google: boolean;
}
}
export interface Token {
access_token: string;
expires_at: number;
expires_in: number;
refresh_token: string;
token_type: 'bearer';
}
export declare class User implements UserData {
constructor(api: any, tokenResponse: any, audience: string);
static removeSavedSession(): void;
static recoverSession(api: any): User | null;
admin: Admin;
// Must be copied from UserData :(
app_metadata: any;
aud: string;
audience: string;
confirmed_at: string;
created_at: string;
email: string;
id: string;
role: string;
token: Token;
updated_at: string;
url: string;
user_metadata: any;
clearSession(): void;
getUserData(): Promise<UserData>;
jwt(forceRefresh?: boolean): Promise<string>;
logout(): Promise<void>;
tokenDetails(): Token;
update(attributes: any): Promise<User>;
}
export interface UserData {
app_metadata: any;
aud: string;
audience: string;
confirmed_at: string;
created_at: string;
email: string;
id: string;
role: string;
token: Token;
updated_at: string;
url: string;
user_metadata: any;
}
export default GoTrue;
declare global {
interface Window {
GoTrue: typeof GoTrue;
}
}

67
node_modules/gotrue-js/lib/admin.js generated vendored Normal file
View File

@@ -0,0 +1,67 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var Admin = /*#__PURE__*/function () {
function Admin(user) {
_classCallCheck(this, Admin);
this.user = user;
} // Return a list of all users in an audience
_createClass(Admin, [{
key: "listUsers",
value: function listUsers(aud) {
return this.user._request('/admin/users', {
method: 'GET',
audience: aud
});
}
}, {
key: "getUser",
value: function getUser(user) {
return this.user._request("/admin/users/".concat(user.id));
}
}, {
key: "updateUser",
value: function updateUser(user) {
var attributes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return this.user._request("/admin/users/".concat(user.id), {
method: 'PUT',
body: JSON.stringify(attributes)
});
}
}, {
key: "createUser",
value: function createUser(email, password) {
var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
attributes.email = email;
attributes.password = password;
return this.user._request('/admin/users', {
method: 'POST',
body: JSON.stringify(attributes)
});
}
}, {
key: "deleteUser",
value: function deleteUser(user) {
return this.user._request("/admin/users/".concat(user.id), {
method: 'DELETE'
});
}
}]);
return Admin;
}();
exports["default"] = Admin;

222
node_modules/gotrue-js/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,222 @@
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _microApiClient = _interopRequireWildcard(require("micro-api-client"));
var _user = _interopRequireDefault(require("./user.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var HTTPRegexp = /^http:\/\//;
var defaultApiURL = "/.netlify/identity";
var GoTrue = /*#__PURE__*/function () {
function GoTrue() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$APIUrl = _ref.APIUrl,
APIUrl = _ref$APIUrl === void 0 ? defaultApiURL : _ref$APIUrl,
_ref$audience = _ref.audience,
audience = _ref$audience === void 0 ? '' : _ref$audience,
_ref$setCookie = _ref.setCookie,
setCookie = _ref$setCookie === void 0 ? false : _ref$setCookie;
_classCallCheck(this, GoTrue);
if (APIUrl.match(HTTPRegexp)) {
console.warn('Warning:\n\nDO NOT USE HTTP IN PRODUCTION FOR GOTRUE EVER!\nGoTrue REQUIRES HTTPS to work securely.');
}
if (audience) {
this.audience = audience;
}
this.setCookie = setCookie;
this.api = new _microApiClient["default"](APIUrl);
}
_createClass(GoTrue, [{
key: "_request",
value: function _request(path) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
options.headers = options.headers || {};
var aud = options.audience || this.audience;
if (aud) {
options.headers['X-JWT-AUD'] = aud;
}
return this.api.request(path, options)["catch"](function (error) {
if (error instanceof _microApiClient.JSONHTTPError && error.json) {
if (error.json.msg) {
error.message = error.json.msg;
} else if (error.json.error) {
error.message = "".concat(error.json.error, ": ").concat(error.json.error_description);
}
}
return Promise.reject(error);
});
}
}, {
key: "settings",
value: function settings() {
return this._request('/settings');
}
}, {
key: "signup",
value: function signup(email, password, data) {
return this._request('/signup', {
method: 'POST',
body: JSON.stringify({
email: email,
password: password,
data: data
})
});
}
}, {
key: "login",
value: function login(email, password, remember) {
var _this = this;
this._setRememberHeaders(remember);
return this._request('/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: "grant_type=password&username=".concat(encodeURIComponent(email), "&password=").concat(encodeURIComponent(password))
}).then(function (response) {
_user["default"].removeSavedSession();
return _this.createUser(response, remember);
});
}
}, {
key: "loginExternalUrl",
value: function loginExternalUrl(provider) {
return "".concat(this.api.apiURL, "/authorize?provider=").concat(provider);
}
}, {
key: "confirm",
value: function confirm(token, remember) {
this._setRememberHeaders(remember);
return this.verify('signup', token, remember);
}
}, {
key: "requestPasswordRecovery",
value: function requestPasswordRecovery(email) {
return this._request('/recover', {
method: 'POST',
body: JSON.stringify({
email: email
})
});
}
}, {
key: "recover",
value: function recover(token, remember) {
this._setRememberHeaders(remember);
return this.verify('recovery', token, remember);
}
}, {
key: "acceptInvite",
value: function acceptInvite(token, password, remember) {
var _this2 = this;
this._setRememberHeaders(remember);
return this._request('/verify', {
method: 'POST',
body: JSON.stringify({
token: token,
password: password,
type: 'signup'
})
}).then(function (response) {
return _this2.createUser(response, remember);
});
}
}, {
key: "acceptInviteExternalUrl",
value: function acceptInviteExternalUrl(provider, token) {
return "".concat(this.api.apiURL, "/authorize?provider=").concat(provider, "&invite_token=").concat(token);
}
}, {
key: "createUser",
value: function createUser(tokenResponse) {
var remember = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
this._setRememberHeaders(remember);
var user = new _user["default"](this.api, tokenResponse, this.audience);
return user.getUserData().then(function (userData) {
if (remember) {
userData._saveSession();
}
return userData;
});
}
}, {
key: "currentUser",
value: function currentUser() {
var user = _user["default"].recoverSession(this.api);
user && this._setRememberHeaders(user._fromStorage);
return user;
}
}, {
key: "verify",
value: function verify(type, token, remember) {
var _this3 = this;
this._setRememberHeaders(remember);
return this._request('/verify', {
method: 'POST',
body: JSON.stringify({
token: token,
type: type
})
}).then(function (response) {
return _this3.createUser(response, remember);
});
}
}, {
key: "_setRememberHeaders",
value: function _setRememberHeaders(remember) {
if (this.setCookie) {
this.api.defaultHeaders = this.api.defaultHeaders || {};
this.api.defaultHeaders['X-Use-Cookie'] = remember ? '1' : 'session';
}
}
}]);
return GoTrue;
}();
exports["default"] = GoTrue;
if (typeof window !== 'undefined') {
window.GoTrue = GoTrue;
}

315
node_modules/gotrue-js/lib/user.js generated vendored Normal file
View File

@@ -0,0 +1,315 @@
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _microApiClient = _interopRequireWildcard(require("micro-api-client"));
var _admin = _interopRequireDefault(require("./admin.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var ExpiryMargin = 60 * 1000;
var storageKey = 'gotrue.user';
var refreshPromises = {};
var currentUser = null;
var forbiddenUpdateAttributes = {
api: 1,
token: 1,
audience: 1,
url: 1
};
var forbiddenSaveAttributes = {
api: 1
};
var isBrowser = function isBrowser() {
return typeof window !== 'undefined';
};
var User = /*#__PURE__*/function () {
function User(api, tokenResponse, audience) {
_classCallCheck(this, User);
this.api = api;
this.url = api.apiURL;
this.audience = audience;
this._processTokenResponse(tokenResponse);
currentUser = this;
}
_createClass(User, [{
key: "update",
value: function update(attributes) {
var _this = this;
return this._request('/user', {
method: 'PUT',
body: JSON.stringify(attributes)
}).then(function (response) {
return _this._saveUserData(response)._refreshSavedSession();
});
}
}, {
key: "jwt",
value: function jwt(forceRefresh) {
var token = this.tokenDetails();
if (token === null || token === undefined) {
return Promise.reject(new Error("Gotrue-js: failed getting jwt access token"));
}
var expires_at = token.expires_at,
refresh_token = token.refresh_token,
access_token = token.access_token;
if (forceRefresh || expires_at - ExpiryMargin < Date.now()) {
return this._refreshToken(refresh_token);
}
return Promise.resolve(access_token);
}
}, {
key: "logout",
value: function logout() {
return this._request('/logout', {
method: 'POST'
}).then(this.clearSession.bind(this))["catch"](this.clearSession.bind(this));
}
}, {
key: "_refreshToken",
value: function _refreshToken(refresh_token) {
var _this2 = this;
if (refreshPromises[refresh_token]) {
return refreshPromises[refresh_token];
}
return refreshPromises[refresh_token] = this.api.request('/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: "grant_type=refresh_token&refresh_token=".concat(refresh_token)
}).then(function (response) {
delete refreshPromises[refresh_token];
_this2._processTokenResponse(response);
_this2._refreshSavedSession();
return _this2.token.access_token;
})["catch"](function (error) {
delete refreshPromises[refresh_token];
_this2.clearSession();
return Promise.reject(error);
});
}
}, {
key: "_request",
value: function _request(path) {
var _this3 = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
options.headers = options.headers || {};
var aud = options.audience || this.audience;
if (aud) {
options.headers['X-JWT-AUD'] = aud;
}
return this.jwt().then(function (token) {
return _this3.api.request(path, _objectSpread({
headers: Object.assign(options.headers, {
Authorization: "Bearer ".concat(token)
})
}, options))["catch"](function (error) {
if (error instanceof _microApiClient.JSONHTTPError && error.json) {
if (error.json.msg) {
error.message = error.json.msg;
} else if (error.json.error) {
error.message = "".concat(error.json.error, ": ").concat(error.json.error_description);
}
}
return Promise.reject(error);
});
});
}
}, {
key: "getUserData",
value: function getUserData() {
return this._request('/user').then(this._saveUserData.bind(this)).then(this._refreshSavedSession.bind(this));
}
}, {
key: "_saveUserData",
value: function _saveUserData(attributes, fromStorage) {
for (var key in attributes) {
if (key in User.prototype || key in forbiddenUpdateAttributes) {
continue;
}
this[key] = attributes[key];
}
if (fromStorage) {
this._fromStorage = true;
}
return this;
}
}, {
key: "_processTokenResponse",
value: function _processTokenResponse(tokenResponse) {
this.token = tokenResponse;
try {
var claims = JSON.parse(urlBase64Decode(tokenResponse.access_token.split('.')[1]));
this.token.expires_at = claims.exp * 1000;
} catch (error) {
console.error(new Error("Gotrue-js: Failed to parse tokenResponse claims: ".concat(error)));
}
}
}, {
key: "_refreshSavedSession",
value: function _refreshSavedSession() {
// only update saved session if we previously saved something
if (isBrowser() && localStorage.getItem(storageKey)) {
this._saveSession();
}
return this;
}
}, {
key: "_saveSession",
value: function _saveSession() {
isBrowser() && localStorage.setItem(storageKey, JSON.stringify(this._details));
return this;
}
}, {
key: "tokenDetails",
value: function tokenDetails() {
return this.token;
}
}, {
key: "clearSession",
value: function clearSession() {
User.removeSavedSession();
this.token = null;
currentUser = null;
}
}, {
key: "admin",
get: function get() {
return new _admin["default"](this);
}
}, {
key: "_details",
get: function get() {
var userCopy = {};
for (var key in this) {
if (key in User.prototype || key in forbiddenSaveAttributes) {
continue;
}
userCopy[key] = this[key];
}
return userCopy;
}
}], [{
key: "removeSavedSession",
value: function removeSavedSession() {
isBrowser() && localStorage.removeItem(storageKey);
}
}, {
key: "recoverSession",
value: function recoverSession(apiInstance) {
if (currentUser) {
return currentUser;
}
var json = isBrowser() && localStorage.getItem(storageKey);
if (json) {
try {
var data = JSON.parse(json);
var url = data.url,
token = data.token,
audience = data.audience;
if (!url || !token) {
return null;
}
var api = apiInstance || new _microApiClient["default"](url, {});
return new User(api, token, audience)._saveUserData(data, true);
} catch (error) {
console.error(new Error("Gotrue-js: Error recovering session: ".concat(error)));
return null;
}
}
return null;
}
}]);
return User;
}();
exports["default"] = User;
function urlBase64Decode(str) {
// From https://jwt.io/js/jwt.js
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0:
break;
case 2:
output += '==';
break;
case 3:
output += '=';
break;
default:
throw 'Illegal base64url string!';
} // polifyll https://github.com/davidchambers/Base64.js
var result = window.atob(output);
try {
return decodeURIComponent(escape(result));
} catch (error) {
return result;
}
}

73
node_modules/gotrue-js/package.json generated vendored Normal file
View File

@@ -0,0 +1,73 @@
{
"name": "gotrue-js",
"description": "GoTrue API client for JavaScript",
"version": "0.9.29",
"author": "Mathias Biilmann Christensen",
"bugs": "https://github.com/netlify/micro-api-client-lib/issues",
"dependencies": {
"micro-api-client": "^3.2.1"
},
"devDependencies": {
"@ava/babel": "^1.0.1",
"@babel/cli": "^7.11.6",
"@babel/core": "^7.11.6",
"@babel/plugin-proposal-object-rest-spread": "^7.11.0",
"@babel/preset-env": "^7.11.5",
"@netlify/eslint-config-node": "^2.2.5",
"@typescript-eslint/eslint-plugin": "^4.0.1",
"@typescript-eslint/parser": "^4.0.1",
"ava": "^3.15.0",
"babelify": "^10.0.0",
"browserify": "^16.0.0",
"esm": "^3.2.25",
"nyc": "^15.1.0",
"sinon": "^9.2.4",
"typescript": "^4.0.0",
"uglify-js": "^3.0.0"
},
"homepage": "https://github.com/netlify/gotrue-js",
"keywords": [
"api",
"gotrue",
"identity",
"netlify"
],
"license": "MIT",
"main": "lib/index.js",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/netlify/gotrue-js.git"
},
"scripts": {
"babelify": "browserify src/index.js -t [ babelify --presets [ @babel/preset-env ] --plugins [ @babel/plugin-proposal-object-rest-spread ] ] | uglifyjs > browser/gotrue.js",
"prepare": "run-s compile",
"prepublishOnly": "run-s prepublishOnly:*",
"prepublishOnly:checkout": "git checkout master",
"prepublishOnly:pull": "git pull",
"prepublishOnly:install": "npm ci",
"prepublishOnly:test": "npm test",
"compile": "babel src -d lib",
"test": "run-s format test:dev",
"format": "run-s format:check-fix:*",
"format:ci": "run-s format:check:*",
"format:check-fix:lint": "run-e format:check:lint format:fix:lint",
"format:check:lint": "cross-env-shell eslint $npm_package_scriptsArgs_eslint",
"format:fix:lint": "cross-env-shell eslint --fix $npm_package_scriptsArgs_eslint",
"format:check-fix:prettier": "run-e format:check:prettier format:fix:prettier",
"format:check:prettier": "cross-env-shell prettier --check $npm_package_scriptsArgs_prettier",
"format:fix:prettier": "cross-env-shell prettier --write $npm_package_scriptsArgs_prettier",
"test:dev": "ava",
"test:ci": "nyc -r lcovonly -r text -r json ava"
},
"scriptsArgs": {
"eslint": "--ignore-path .gitignore --cache --format=codeframe --max-warnings=0 \"{src,tests,.github}/**/*.{js,md,html}\"",
"prettier": "--ignore-path .gitignore --loglevel=warn \"{src,tests,.github}/**/*.{js,md,yml,json,html}\" \"*.{js,yml,json,html}\" \".*.{js,yml,json,html}\" \"!package-lock.json\" \"!CHANGELOG.md\""
},
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
"pre-push": "npm run format"
}
}
}

6
node_modules/gotrue-js/renovate.json generated vendored Normal file
View File

@@ -0,0 +1,6 @@
{
"extends": ["github>netlify/renovate-config:default"],
"ignorePresets": [":prHourlyLimit2"],
"semanticCommits": true,
"masterIssue": true
}

42
node_modules/gotrue-js/tests/user.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
import { Buffer } from 'buffer';
import test from 'ava';
import sinon from 'sinon';
import User from '../src/user.js';
// mock window
global.window = { atob: (base64) => Buffer.from(base64, 'base64').toString('ascii') };
test('should parse token in ctor', (t) => {
//
// {
// "sub": "1234567890",
// "name": "John Doe",
// "iat": 1516239022,
// "exp": 1000
// }
//
const tokenResponse = {
access_token:
'header.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjEwMDB9.secret',
};
const user = new User({}, tokenResponse, '');
t.is(user.token.expires_at, 1000000);
});
test.serial('should not log token on error', (t) => {
const spy = sinon.spy(console, 'error');
const tokenResponse = {
access_token: 'header.invalid.secret',
};
// eslint-disable-next-line no-new
new User({}, tokenResponse, '');
t.assert(spy.calledOnce);
const [error] = spy.getCall(0).args;
t.true(error instanceof Error);
t.false(error.message.includes(tokenResponse.access_token));
});