Code Monkey home page Code Monkey logo

rules's Introduction

Auth0 Rule Templates

CircleCI

This repo contains Rule templates that appear in the Auth0 Dashboard when you create a new Rule.

Table of Contents

Documentation

Contributing

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

If you're considering developing a new Rule template, please submit an Issue to discuss with our team. If you'd like to write an integration for the Auth0 Marketplace, please see our Partners page to get started.

  1. Read the Contributing guidelines above
  2. Make your changes in src/rules by changing an existing template or by adding a new file for a new template
  3. If you're adding a new Rule, include the following metadata at the top:
  • @title 3-5 word title of the rule
  • @overview brief, one-sentence description of the rule.
  • @gallery set to true
  • @category use "access control", "enrich profile", "multifactor", "guardian", "debugging", "saml", or "default"
  • A detailed, multi-line, Markdown-enabled description of the rule, including any required configuration keys
  1. Ensure tests run in both Node v8 and Node v12 using a tool like nvm
  2. Make sure to test your Rule in Auth0 directly to make sure it can be saved without errors and that it does what you expect during login
  3. Submit your PR following the "fork and pull" workflow described here
  4. Fill out the PR template completely and our team will review as soon as we're able

Support + Feedback

  • Use the Support Center for questions on implementation and issues with a Rule installed in your tenant
  • Use Issues here for code-level support and bug reports within the templates

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 helps you to easily:

  • implement authentication with multiple identity providers, including social (e.g., Google, Facebook, Microsoft, LinkedIn, GitHub, Twitter, etc), or enterprise (e.g., Windows Azure AD, Google Apps, Active Directory, ADFS, SAML, etc.)
  • log in users with username/password databases, passwordless, or multi-factor authentication
  • link multiple user accounts together
  • generate signed JSON Web Tokens to authorize your API calls and flow the user identity securely
  • access demographics and analytics detailing how, when, and where users are logging in
  • enrich user profiles from other data sources using customizable JavaScript rules

Why Auth0?

License

These Rule templates are licensed under MIT - LICENSE

rules's People

Contributors

adam-auth0 avatar amaanc avatar cristiandouce avatar dafortune avatar dschenkelman avatar eugeniop avatar fyockm avatar glena avatar jfromaniello avatar joshbetz avatar joshcanhelp avatar lobo avatar marygreenleeauth0 avatar mcidw avatar mgonto avatar nicosabena avatar ntotten avatar pose avatar rolodato avatar rrexford avatar saltukalakus avatar sandrinodimattia avatar shawnmclean avatar siacomuzzi avatar tehsis avatar thameera avatar tophermarie avatar twistedstream avatar woloski avatar zxan1285 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rules's Issues

Merge identites by email overrides the original user_id

I am using the rule to merge identites by email. However, when merge occurs, the user changes its user_id to the last recently identity added.

Such behavior causes a lot of identity issues - for example, when you try to get the user in a database using the user_id as search key.

Instead of overriding the original user_id, this rule should just add the new identity to the original one, and keep it's user_id

Broken relative links

Any link here that includes .md in it is likely broken.

We should use absolute links instead of relative ones to support Dashboard templates and the documentation pages at the same time.

Link Accounts with Same Email Address not working as expected

Scenario1: this logic works fine if user firstly sign up with email and then use social(fb/twitter etc)for signup, by this it will link all the accounts properly

Scenario2: if we firstly use social(fb/twitter etc) and then use simple email signup it will create two different account which is not desired instead it should give warning that this email is already registered

Note: in scenario 2 if user verified his id and again login it will be merge then but it keeps two different account before that.

IMP if you try to change the password after signing up with social provider you will get an error that user does not exist on the auth0 dashboard

Type | Failed Change Password
Description | User does not exist.
Connection | Username-Password-Authentication

This is does not happen in any real world application i don't know what's the intent please guide if i understood it wrongly.

Linking accounts takes all user details from the primaryUser and overrides all modified attributes of the current user

One of my rule added some extra attributes to the user, like given_name and family_name, and I can see these attributes returned from Auth0 after the authentication.

However, If I added a rule for linking accounts before the existing rule, and set up the primaryUser attribute in context, even though the next rule still adds the extra attributes, the payload returned by Auth0 only contains those owned by the primary user stored on Auth0.

Is this an expected behaviour? Or did I missed something?

Thanks.

Doesn't work for mobile app (OAuth) users

As far as we can see Auth0 doesn't detect OAuth connections (using a refresh token) as a login. Neither the login count is updated nor are other props of a users updated (devices for instance or last login date are not reflecting a user which uses a mobile app over a web browser). Is there a solution for this available (can mobile logins be detected) or is it a change in the design to get this fixed?

Yubico-MFA doesn't receive OTP code

When the user provides the OTP code the form is correctly submitted with the otp code, however it doesn't appear in either the context or req parameters. This means 'undefined' is passed through to the Yubico validation servers and the auth fails.

I can't find any way of getting the otp value other than sending it through as a GET parameter instead.

What are the contexts in which I can use rules

The very definition Rules are code snippets written in JavaScript that are executed as part of the authentication pipeline in Auth0 makes rules one of the most powerful feature in Auth0 platform. However, the statement Create authorization rules based on complex logic (anything that can be written with node.js). written on the page at https://auth0.com/docs/rules indicates that one can use rules only of the app is hosted on node.js.

I think that Auth0 should be completely platform agnostic so I would like to know how can I use rules in an angular app hosted by ASP.NET

Encapsulating code in different files that can be required by the rules

Hi,

I'd like to know if it there is a way for the rules to load code via requires so I can reuse, encapsulate and test the core validation functions.

I've tried to create a structure similar to:

|---rules
|      |------email-domain-validation.js
|
|---core
       |------domain.js
       |------whitelist.js

In my approach /rules/email-domain-validation.js tries to load code from /core/domain.js via require('../core/domain.js') as you normally would do in a node.js project.

However, when auth0 runs the email-domain-validation.js rule: I can see in the logs the following error: "description": "Cannot find module '../core/domain'",.

I haven't put core under rules since that would be taken by auth0 as if they were rules where they aren't (my first approach was to place the core folder under rules).

Is there any way for solving this?

User properties when changing `context.primaryUser`

So we have this rule that merges a user logging-in into a previously existing identity. As explained in #71, context.primaryUser must be update accordingly in that particular case.

But it is kinda wiered and unclear what happens next when calling callback(null, user, context) with user being the user that was merged into the previous account (the original user that was used to call the rule).

  • More specifically, what will be the user_id of the user in the next rule ?
  • Do we need to update all the properties of user (user.app_metadata, user.user_metadata, user.first_name, etc.) with those of the primary user before calling the next rule, or will Auth0 automatically reload the properties of user if context.primaryUser has changed ?
  • Why shouldn't we call callback(null, otherPrimaryUser, context) (I have the impression that this will cause an Unable to construct sso user. error in some cases, but I can't figure out when) ?

redirect-rules/simple - Still valid?

I'm following all the steps here:
https://github.com/auth0/rules/tree/master/redirect-rules/simple

Using the following URL:

https://DOMAIN.auth0.com/authorize?response_type=token&scope=openid%20profile&client_id=CLIENT_ID&redirect_uri=http://jwt.io&connection=Username-Password-Authentication

I'm redirected to

https://nasbnation.auth0.com/login/callback?state=S7dScBNwLS1HVt_D9DqIQ5NIXtOlBtQ8

I get the following response:

Invalid redirect URL https://wt-peter-auth0_com-0.run.webtask.io/simple-redirect-rule-consent-form';var CONSENT_FORM_URL = 'https://wt-peter-auth0_com-0.run.webtask.io/simple-redirect-rule-consent-form?auth0_domain=nasbnation.auth0.com

My real-time Webtask Logs return:

9:36:59 PM: new webtask request 1507167419882.564674
9:36:59 PM: finished webtask request 1507167419882.564674 with HTTP 200 in 107ms

Am I missing something? Perhaps the library has changed?

Dynamics CRM

create a rule to feed dynamics CRM contacts based on signups/logins

How to use replyWithError with return reject using nock?

I am making https request from my js file like:

function createProfile(accessToken) {
       return new Promise(function (resolve, reject) {
           var payLoad = JSON.stringify({
               Name: user.name,
               Email: user.email
           });

           request({
               url: "{mydomain}/profile",
               headers: {
                   'Authorization': 'Bearer ' + accessToken,
                   'content-type': 'application/json'
               },
               body: payLoad,
               method: "POST"

           }, function (error, response, body) {
               if (error) {
                   return reject(error);
               }
               if (response.statusCode === 200) {
                   var profile = JSON.parse(body);
                   return resolve(profile);
               }
               else
                   return reject();


           });
       });
   }

Now when I am using nock for this method like this:

nock("{mydomain}", { reqheaders: { 'Authorization': 'Bearer ' + accessToken } })
            .post('/profile',
                function(body) {
                    const expectations = {
                        Name: user.name,
                        Email: user.email,
                    };
                    expect(body).toEqual(expectations);
                    return true;
                })
            .replyWithError('profile error');

This is throwing error 'profile error' in cmd. If I change return reject(error) with return callback(error) then it it is working fine and my test case is passing. How can I reply error for return reject(error)

Salesforce

create a rule that create a new lead using Salesforce API

Has this worked for anyone?

I am having problems with this against parse running on AWS.
Issue is described here
but short summary is that if I do get post it fails. Individual get or post work just fine. on the server I get )
Connection refused: AH00957: HTTP: attempt to connect to 127.0.0.1:1337 (127.0.0.1) failed [Sat Dec 03 02:10:18.478083 2016] [proxy_http:error] [pid 1149] ...

on parse server I get exception around line 390 in ParseServer.js address in use... but only when post is after get failure.

Document *all* variables available in rules.

Is there any complete documentation about the variables available within rules? I can find no reference in documentation to the auth0 object, but yet it's used here

https://github.com/auth0/rules/blob/2392ea11601ec0b220e4b3c3a2408cd3a1f50233/redirect-rules/simple/rule.js

as auth0.baseUrl. (this is very helpful for instance, if i need to do a client-credentials grant against the current auth0 account without hardcoding)

As a user - having undocumented variables in examples is incredibly confusing. i'd love to see the documentation updated to include all the variables that are available within a rule (including global).

Linting rules

Hi! Rules are awesome - currently sinking my teeth into them.

I'm sure someone has had this question before but I can't find it: Is there an easy way to set up linting for Rules functions?

Specifically, when running eslint over a Rule, it's hitting Parsing error: unexpected token ( at function ( user, context, callback ) { - because the function both is anonymous, and isn't assigned to something like module.exports.

Account linking rule should handle invalid email error and allow login

if (response.statusCode !== 200) return callback(new Error(body));

For some IdP user.email will be undefined or empty (fb/twitter won't return user email for privacy settings or if user signed up with phone). In such cases it would be ideal to skip account linking and continue the login flow (previously with user search api, it returned an empty array. However /users-by-email endpoint returns a query validation error.

Possible fix

if (!user.email_verified || !user.email) {
    return callback(null, user, context);
  }

Link account w/ metadata merge can cause loss of primary user metadata

The Link Accounts with Same Email Address while Merging Metadata rule as written will cause metadata on the original/primary user to be deleted if the current/secondary user has no metadata. This is because PATCH /api/v2/users/{id} effectively treats user_metadata: {}, app_metadata: {} as a delete of those fields.

In these cases the rule should skip the updateAppMetadata() calls to avoid the loss.

Convert sms-mfa redirect rule sample into email mfa

The sms-mfa redirect rule sample is now obsolete since Auth0 now offers build-in support for SMS MFA. However, we don't yet offer an email equivalent for MFA (send a magic link in an email as a second factor), so this sample could be changed to do that instead, since the configuration is very similar. The one nice thing about email Passwordless is that it doesn't require the setup of a Twilio account.

Can I Require?

Not sure if this is the correct place for this, but your canirequire page is broken, due to a problem with JQuery.

On page load it receives this error:

auth0-extensions.github.io/:48 GET https://code.jquery.com/jquery-3.3.1.min.js net::ERR_SSL_VERSION_INTERFERENCE

Rule that collects user's e-mail on twitter is incorrect

This line should have the "long function" shown here instead of the following two lines:

user.app_metadata = user.app_metadata || {};
var email = user.email || user.app_metadata.social_email;

These two lines are wrongly added as a rule when the user clicks on Get e-mail address from Twitter template rule on our dashboard.

link-users-by-email won't work with github

Original account: google-oauth-2
New account: github

If I try this combination I get a Bad Request response and the following hash response:

#error=access_denied&error_description=Error%20linking%20account%3A%20Bad%20Request&state=G8I.4LschBFHZeY0G_UBFy.ddl4c7KLH

Rules not applied when impersonating user

Is it correct that rules are not applied when I logon as another user, by using the impersonation feature.

If so, then how are we supposed to be able to use rules to their full potential. I add extra claims during login, those are missing when I'm impersonating the user.

Firebase token rule is 404

The rule for generating Firebase tokens in the readme is gone. It's highlighted in the readme as Get a Firebase Session Token. I'd be interested to see it. Can it come back?

Logic in send mail with mailgun is incorrect

The rule mailgun.md contains this at the start

function(user, context, callback) {  
  user.app_metadata = user.app_metadata || {};  
  if (!user.app_metadata.signedUp) {  
    return callback(null, user, context);  
  }

but the logic in the if statement is wrong and should not have the !

if (user.app_metadata.signedUp) {

Linking user account logic not aligned with documentation

Documentation states

Note, that if the primary account changes during the authorization transaction (for example, the account the user has logged in with, becomes a secondary account to some other primary account), you could get an error in the Authorization Code flow or an id_token with the wrong sub claim in the token flow. To avoid this, set context.primaryUser = 'auth0|user123' in the rule after account linking. This will tell the authorization server to use the user with id auth0|user123 for the rest of the flow.

This would be our desired behavior. However when actually using this rule I'm not seeing this logic applied: the sub is still the user id of the secondary (to be removed) account.

Parse session token

Hi,

Once I logout from Parse using Parse.User.logout() and try login again with Auth0, session token seems no longer valid and is not updated.

ParseError {code: 209, message: "invalid session token"}

Adding another query param when setting context.redirect.url

I'd like to redirect users after they register to our service and pass the state and a JWT we created in the rule that contains things like their user id, email, etc... Essentially the problem we're trying to solve is that we want to kick off a bunch of tasks when a new user registers.

When I add a ?token=${token} state is not passed anymore, so it appears I can't pass both in. There are no docs for how rules work under the hood as far as I can tell, so it appears it just doesn't work.

Is there a better way to do this? Am I missing something?

Thanks,
Matt

Feedback: Maybe use a named function in all examples

It looks like Auth0 encourages to write rules like this in current docs:

function (user, context, callback) {
  context.idToken["http://mynamespace/hello"] = "world";
  console.log('===> set "hello" for ' + user.name);
  callback(null, user, context);
}

As you probably know this code snippet alone throws an SyntaxError:

image

I guess you save this function into a variable internally...?

image

It would be nice however to use named functions in all docs instead.

image

This will help with tooling compatibility. For example I can now prettify my rules 👍 This will also help when I want to preprocess my rules (e.g. with TypeScript) before uploading them.

Issue with targetUserId in link-users-by-email rule

Hi,

i was playing arround with this rule today and noticed some strange behavior. My user god all users from a specific connection assigned to his identity. This was the case with ADFS connection whose user id consists of three parts, not just two:

provider|ConnectionName|userid

As far as I can tell it is related to this piece of code:

 var aryTmp = targetUser.user_id.split('|');
 var provider = aryTmp[0];
 var targetUserId = aryTmp[1];

In the end i replaced it with a function like this:

  function getUserIdFromFullId(fullId)
  {
    var parts = fullId.split('|');
    var userId = parts[1];
    
    for(var i=2; i< parts.length; i++)
    {
      userId += '|' + parts[i];
    }
    
    return userId;
  }

? auth0 redirection is not available on /oauth/token endpoint

The sms-mfa example is slick, and I seemed to have gotten implemented for use as part of a non-hosted login scenario. However, when it tries to do the redirect to the webtask, auth0 errors out with the error "auth0 redirection is not available on /oauth/token endpoint".

Is there a config somewhere that needs to be set as well for this to work in that case?

How to write unit tests for Auth0 rules

I have multiple rules in my tenant and now I want to write unit tests for my rules. Now the issue is in the docs (https://auth0.com/docs/support/testing) it’s written that we can use https://www.npmjs.com/package/auth0-rules-testharness module for unit test our rules but I think the explanation is old and it’s not updated because in the sample project (https://github.com/tawawa/auth0-rules-testharness-sample) we need to add webtask token and sandbox url and now we can’t find webtask token in Auth0 dashboard (https://manage.auth0.com/#/account/webtasks) and also where can I get this sandbox url? Any help?

Rules to link accounts by email are case-sensitive

I've encountered an issue in which a user signs up with multiple connections associated with the same email address and the automatic account linking rule fails to link them. Eventually I tracked this down to the fact that the users-by-email endpoint performs a case-sensitive search, which is very surprising. The user signed up for an email/password account as [email protected], but their Google account has [email protected] as the associated email address.

In practice, email addresses are treated in a case-insensitive manner, and the Auth0 web console performs case-insensitive search for email addresses. It seems like anyone using these rules to link accounts with matching emails would want it handle differing case, since some providers will report differing case for a given email address (i.e. not everyone normalizes addresses to lower-case).

NewRelic

feed newrelic with logins/signup events

Splunk

feed splunk with signup/login events

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.