Code Monkey home page Code Monkey logo

node-auth0's Introduction

Node.js client library for Auth0

Release Codecov Downloads License

๐Ÿ“š Documentation - ๐Ÿš€ Getting Started - ๐Ÿ’ป API Reference - ๐Ÿ’ฌ Feedback

Documentation

  • Docs Site - explore our docs site and learn more about Auth0

Getting Started

Requirements

This library supports the following tooling versions:

  • Node.js: >=18

Installation

Using npm in your project directory run the following command:

npm install auth0

Configure the SDK

Authentication API Client

This client can be used to access Auth0's Authentication API.

import { AuthenticationClient } from 'auth0';

const auth0 = new AuthenticationClient({
  domain: '{YOUR_ACCOUNT}.auth0.com',
  clientId: '{OPTIONAL_CLIENT_ID}',
  clientSecret: '{OPTIONAL_CLIENT_SECRET}',
});

See more examples.

Management API Client

The Auth0 Management API is meant to be used by back-end servers or trusted parties performing administrative tasks. Generally speaking, anything that can be done through the Auth0 dashboard (and more) can also be done through this API.

Initialize your client class with a client ID, client secret and a domain.

import { ManagementClient } from 'auth0';

var management = new ManagementClient({
  domain: '{YOUR_TENANT_AND REGION}.auth0.com',
  clientId: '{YOUR_CLIENT_ID}',
  clientSecret: '{YOUR_CLIENT_SECRET}',
});

Or, initialize your client class with an API v2 token and a domain.

import { ManagementClient } from 'auth0';

var management = new ManagementClient({
  domain: '{YOUR_TENANT_AND REGION}.auth0.com',
  token: '{YOUR_API_V2_TOKEN}',
});

See more examples.

API Reference

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0?

Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

node-auth0's People

Contributors

adamjmcgrath avatar annyv2 avatar chenkie avatar cocojoe avatar crigot avatar damieng avatar davidpatrick avatar dependabot-preview[bot] avatar dependabot[bot] avatar dschenkelman avatar evansims avatar floppy avatar frederikprijck avatar gyaneshgouraw-okta avatar hzalaz avatar jfromaniello avatar jimmyjames avatar joshcanhelp avatar lbalmaceda avatar luisrudge avatar mgonto avatar ngonzalvez avatar ntotten avatar orangain avatar pose avatar siacomuzzi avatar snyk-bot avatar stevezau avatar vmartynets avatar wbhob avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-auth0's Issues

Wrap all calls to Node specific env

Some parts of the code tries to access process.version which is not defined in browser (or React Native) environment, so we need to check if its defined first.

Also the library rest-facade makes the follow requirement require('url'); which won't be outside node env, not sure how to fix this properly though

Reset password method

Hello. In current version, method for password reset not implemented.
I debug reset page from email, and found lo/reset request, it's can be used for custom reset page.
Why it not included to library?

nodejs api example outdated dependencies

*body-parser 1.10.2 -> 1.15.0
*cookie-parser 1.3.5 -> 1.4.1
*debug 2.1.3 -> 2.2.0
*express 4.11.2 -> 4.13.4
*jade 1.9.2 -> 1.11.0
*morgan 1.5.3 -> 1.7.0
*serve-favicon 2.2.1 -> 2.3.0

Docs link?

I know I've seen a node-specific docs page for the Management API before. I can't find it now. Is it in the Readme somewhere?

LICENSE?

you need the license text for the MIT license

Handle errors when body has error+error_description

Maybe we should put this logic inside ApiError, to use like this return done(new ApiError(body)).

   if (r.statusCode.toString()[0] !== '2') {
      var message = body.detail || body.error_description || body;
      var apiError = new ApiError(message, r.statusCode);
      apiError.code = body.error;
      return done(apiError);
    }

docs fail to build

21 error Tell the author that this fails on your system:
21 error jsdoc src/*/.js -d docs -t node_modules/latodoc -R README.md

Query params are not being processed in v2

A user brought this bug to my attention, it seems in the most recent v2 branch that passing parameters through auth0.getUsers does not work.

Even using the example in the documentation does not work:

// Pagination settings.
var params = {
  per_page: 10,
  page: 2
};

// Using auth0 instance.
auth0.getUsers(params, function (err, users) {
  console.log(users.length);
});

It will always return a list of every user, no matter the parameters requested.

The user did some debugging and this is where he thinks the issue resides:

Inside rest-facade's Client.js file you will find the followingrequest prototype function.

A careful reading of this function will show that unlessthis.options.query.convertCase is populated, no query params will ever be provided to the request:

Client.prototype.request = function (options, params, callback) { var headers = this.options.headers || {}; 
var selectedCase = this.options.query.convertCase; 
var queryParams = {}; 
var convertCase = null; 
var newKey = null; 
var value = null;

// If the user specified a convertion case (e.g. 'snakeCase') convert all the 
// query string params names to the given case. 
if (selectedCase) { 
convertCase = changeCase[selectedCase];

for (var prevKey in params) { 
newKey = convertCase(prevKey); 
value = params[prevKey];

// If the repeatParams flag is set to false, encode arrays in 
// the querystring as comma separated values. 
// e.g. ?a=1,2,3 
if (Array.isArray(value) && !this.options.query.repeatParams) { 
value = value.join(','); 
}

queryParams[newKey] = value; 
} 
}

var promise = new Promise(function (resolve, reject) { 
var method = options.method.toLowerCase();

// Set methods and attach the body of the request (if this is a POST request). 
var req = request[method](options.url).send(options.data);

// Add request headers. 
for (var header in headers) { 
req = req.set(header, headers[header]); 
}

// Add all the given parameters to the querystring. 
req = req.query(queryParams);

// Send the request. 
req 
.set('Accept', 'application/json') 
.end(function (err, res) { 
return err ? reject(err) : resolve(res.body); 
}); 
});

Inside the auth0 files, each endpoint sets their own options, but none
of them include convertCase, so the code to include the query params
is never executed inside the function above.

(actually, as near as I can tell, the only options that are even
respected are the ones set in TicketsManager.js, because that is the
last one setup in Auth0.js. Not 100% sure why it behaves this way)

I recognize that I could be wrong about all this, but by adding the
option in question to TicketsManager.js, I am able to have my query
parameters respected.

var TicketsManager = function (options){ 
var clientOptions = { 
headers: options.headers, 
query: { repeatParams: true, convertCase: 'snakeCase' } 
};

Zendesk Ticket: https://auth0.zendesk.com/agent/tickets/3851

Remove the examples directory from this repository

Read carefully.

Remove the examples directory from this repository because it is completely unrelated to this project:

  • examples/nodejs-regular-webapp is a passport-auth0 example, so it should go straight to the examples directory of passport-auth0.
  • examples/nodejs-api is an express-jwt example, but because this is a general purpose library and not only for auth0, move to express-jwt/examples/auth0.

Modify the example packager/seed project/docs etc with the new links.

Errors returned are not valid json

When creating a user via the management API the returned error object is not valid JSON.

authManager.createUser(data, function(err, responseData) { JSON.parse(err) }

Printing the error object returns this

{ [Bad Request: The user already exists.]
name: 'Bad Request',
message: 'The user already exists.',
statusCode: 400 }

Any idea why the error object can't be parsed?

Thanks.

Missing dependency in Relay API

Relay API seed project requires dotenv to work when downloaded from Auht0.com, so it should be included in the package.json file

getUserMetadata, patchUserMetadata and updateUserMetadata set the app_metadata

It's not a noticeable, but by doing

api.patchUserMetadata(req.user.id,{pilot:true}, function(err){
      console.log(err);
});

api.updateUserMetadata(req.user.id,{pilot:true},function(err,user){
    console.log(err,user);
});

api.getUserMetadata(req.user.id,function(err,metadata){
  console.log(err,metadata);
});

You're actually setting, patching and retrieving the app metadata, the functionality keeps untouched but it's quite confusing because by using the API directly via the https://auth0.com/docs/api/v2#!/Users/patch_users_by_id when you set the user_metadata, you actually set the user metadata; so it seems to be a mismatch.

Should be a simple fix.

Bad HTTP authentication header format

setup:

const auth0ManagementClient = new ManagementClient({
  domain: auth0.account,
  token: auth0.clientId
});
const updateRes = await auth0ManagementClient.users.updateUserMetadata(params, metadata);

headers:

   { Authorization: 'Bearer w3mBrhiXGsZZZZZZZpAz2bS6VzLhOyJ',
     'User-agent': 'node.js/6.3.0',
     'Content-Type': 'application/json' }

stack trace:

at Client.request (/Users/mk/Code/action2/node_modules/rest-facade/src/Client.js:250:17)
      at Client.patch (/Users/mk/Code/action2/node_modules/rest-facade/src/Client.js:150:15)
      at UsersManager.updateUserMetadata (/Users/mk/Code/action2/node_modules/auth0/src/management/UsersManager.js:211:21)

response:

name: 'Bad Request',
message: 'Bad HTTP authentication header format',
statusCode: 400 

Error messages are not descriptive

The error objects returned by the Node SDK seem to have less information than what is returned when calling the Authentication API directly.

How to reproduce:
Call Authentication API's /dbconnections/signup endpoint via Postman with an email that already exists in DB. The API responds with the following error:
{name: 'BadRequestError', code: 'user_exists', description: 'The user already exists', statusCode: 400}
Now perform this operation with Node SDK using same data. (Call auth0.database.signUp() where auth0 is an instance of AuthenticationClient). SDK returns following error:
{[BadRequestError] name: 'BadRequestError', message: undefined, statusCode: 400 }

Expected result:
The error message returned by SDK should contain all error information that the API returns. For example:
{[BadRequestError] name: 'BadRequestError', code: 'user_exists', description: 'The user already exists', statusCode: 400 }

This was reported by a customer: https://auth0.zendesk.com/agent/tickets/11110

Unable to use getUserMetadata (gets 404)

When I try to do:

  api.getUserMetadata('auth0|xyz', function(err, metadata) {
     ...
  })

I get this error:

{ [ApiError: Not Found] name: 'ApiError', statusCode: 404, code: undefined }

I can use patchUserMetadata but I'm not able to get the metadata.

Get user data after user create callback

Hi, I am currently used the node-auth0 and find it is difficult to get the user info in the user create callback:

UsersManager.prototype.create = function (data, cb) {
if (cb && cb instanceof Function) {
return this.users.create(data, cb);
}
return this.users.create(data);
};

How could I get the created user info in the cb? Thx a lot.

Error trying to use api.createUser(userData, callback) for connection:sms (passwordless)

Using node-auth 0.8.2

I may be using this method incorrectly but tried to follow the parameters mentioned in Passwordless Connections for the /users POST endpoint and I keep getting passed an error object with this message to my callback :

 ApiError: User must have one of the following identifier fields: user_id | _id | id

More details:

  • The SMS is being sent via Twillio and my phone received the verification code generated by Auth0. so the Twillio connection is correctly configured on Auth0 connections.
  • The user is not listed on Auth0 Dashboard for the app.
  • Even if I pass an attribute user_id, id, or _id on the userParams to api.createUser this error keeps coming with the same message.

The call to api.createUser is being made like this:

    // api = new Auth0({.....})
    api.createUser({
      connection: "sms",
      email_verified: false,
      phone_number: "+541155555555"
    }, function(err, user) {
      if (err) {
        var errorstring = util.format("Error creating user : %s", err.toString());
        return res.status(500).json({
          message: errorstring
        });
      }
      res.json(user);
    });

This only supports v1 of the API, how do I use v2?

I'll fall back to making REST calls myself, but it's really not clear anywhere in the documentation or the package on npm that this only works on v1 of the API.

Is there another project for v2? Is there a plan to have one?

getDelegationToken doesn't allow for usage of the refresh_token

At the moment the implementation of the getDelegationToken only allows for retrieving a new token using the old token. Though the Auth0 API also offers the possibility to get a new token using the refresh token, which one might get if the scope 'offline_access' is being used.

On top of that, the target is required, even though you don't always want to specify another target. Also the Auth0 API documentation allows for not specifying a target ('none' in the dropdown).

I've created a fork in which i've fixed these two issues. I can create a pull request for this, just let me know.

Link / unlink?

It doesn't appear that the link/unlink methods are available via this API. Will they be added?

Need rate limiting info returned by SDK

SDK should return the info that Auth0 returns on HTTP headers about rate limiting, so calling program can dynamically adjust the rate at which it makes subsequent API calls (that are rate limited)

Here is the documentation on what programs are supposed to do:
https://auth0.com/docs/rate-limits

SDK should return the info to enable that.

Save token to be used on the upcoming requests

Currently, if a client is created with clientSecret and clientID access token is not saved. So, for each of the API calls a new token is retrieved.

This can be improved by saving the access token and keep using it till expires instead of requesting a new one each time.

Missing step

Web app seed project readme is missing an instruction, tell the user to run "npm install"

Increase readmy clarity (refer to examples)

It took me a couple of minutes to figure out that there is no readme-like documentation on the API. I remembered reading docs on how to create a user through the node API only a couple of days ago, but it seems the recent updates have changed things around. That's no biggie, but perhaps you could explicitly refer users to the examples until proper docs are written.

Btw, I know you have a link to the examples in the readme, but I was explicitly looking for docs since I remembered reading those.

Any specific reason change password api is split into two methods?

Change Password API has an optional password parameter. If given, auth0 sets user password to this provided password after user clicks on the link received in email. If not given, user clicks on the email receive, enters his new password and then auth0 updates user password to this new password.

Nodejs sdk changePassword API password input is mandatory though. There is a separate method requestChangePasswordEmail to let user reset password after clicking link in received email.

Is there any specific reason for doing this way? Seems not consistent with the API docs and behavior of auth0 server.

Update Node API Example

Seed project uses express 3, it should be updated to use express 4.
Seed project uses deprecated version of express-jwt, should be updated to latest version (currently 3.3.0)

getUsers is forced to be serial

I was trying to use a parallel job to grab pages of users, it turns out you can't send in a page number option as I would have expected because it just gets removed in favor of "nextPageLink". I want to be able to grab page number X as I would have expected from the API docs https://auth0.com/docs/api/v2#!/Users/get_users.

lib/api.js

api.getUsers = function(accessToken, options, done) {
...
    if(options.page){
      nextPageLink = options.page;
      delete options.page;
    }

getUsers is double encoding the "q" parameter

When specifying a query using the "q" parameter to getUsers (along with search_engine: "v2"), I am getting back all results instead of the results I expect according to the q value. After tracing through exactly what URL is being requested, I believe the problem is due to this commit:

eeb8b21

The "q" parameter is being encoded here, but further down the line the params object is being passed to qs.stringify, which encodes it again.

If I remove the three lines of code that encode "q" I get the results I expect.

impersonate call in v2 doesn't seem to work

I tried to call the impersonate call in the v2 branch and I always get a 401. Looking at the code and at the documentation, it looks like it is missing the Bearer header.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.