UNPKG

35.6 kBMarkdownView Raw
1[![NPM version][npm-image]][npm-url]
2[![Build status][circleci-image]][circleci-url]
3[![Dependency Status][david-image]][david-url]
4[![License][license-image]][license-url]
5[![Downloads][downloads-image]][downloads-url]
6[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fauth0%2Flock.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fauth0%2Flock?ref=badge_shield)
7
8# Lock
9
10[Auth0](https://auth0.com) is an authentication broker that supports both social and enterprise identity providers, including Active Directory, LDAP, Google Apps, and Salesforce.
11
12## Table of Contents
131. [Install](#install)
142. [Cross Origin Authentication](#cross-origin-authentication)
153. [API](#api)
164. [Browser Compatibility](#browser-compatibility)
175. [Issue Reporting](#issue-reporting)
186. [Author](#author)
197. [License](#license)
20
21## Install
22
23From CDN
24
25```html
26<!-- Latest patch release (recommended for production) -->
27<script src="https://cdn.auth0.com/js/lock/11.30.5/lock.min.js"></script>
28```
29
30From [npm](https://npmjs.org)
31
32```sh
33npm install auth0-lock
34```
35
36Then you can import `Auth0Lock` or `Auth0LockPasswordless` like this:
37
38```js
39import Auth0Lock from 'auth0-lock';
40// OR
41import { Auth0Lock } from 'auth0-lock';
42import { Auth0LockPasswordless } from 'auth0-lock';
43```
44
45After installing the `auth0-lock` module, you'll need to bundle it up along with all of its dependencies. See examples for [browserify](examples/bundling/browserify/) and [webpack](examples/bundling/webpack/).
46
47> It is expected that you use the development mode when working on your app, and the production mode when deploying your app to the users.
48> You can find instructions for building your app for production with different module bundlers [here](https://reactjs.org/docs/optimizing-performance.html#use-the-production-build).
49
50If you are targeting mobile audiences, we recommended that you add:
51
52```html
53<meta name="viewport" content="width=device-width, initial-scale=1"/>
54```
55## Cross-Origin Authentication
56
57Lock uses **Cross-Origin Authentication**, make sure you understand the considerations you need to take into account by reading the [Cross-Origin Authentication documentation](https://auth0.com/docs/cross-origin-authentication).
58
59## API
60
61### new Auth0Lock(clientID, domain, options)
62
63Initializes a new instance of `Auth0Lock` configured with your application `clientID` and your account's `domain` at [Auth0](https://manage.auth0.com/). You can find this information in your [application settings](https://manage.auth0.com/#/applications).
64
65- **clientId {String}**: Your application _clientId_ in Auth0.
66- **domain {String}**: Your Auth0 _domain_. Usually _your-account.auth0.com_.
67- **options {Object}**: Allows you to customize the dialog's appearance and behavior. See [below](#customization) for the details.
68
69#### Example
70
71```js
72var clientId = "YOUR_AUTH0_APP_CLIENTID";
73var domain = "YOUR_DOMAIN_AT.auth0.com";
74var lock = new Auth0Lock(clientId, domain);
75var accessToken = null;
76var profile = null;
77
78lock.on("authenticated", function(authResult) {
79 lock.getUserInfo(authResult.accessToken, function(error, profileResult) {
80 if (error) {
81 // Handle error
82 return;
83 }
84
85 accessToken = authResult.accessToken;
86 profile = profileResult;
87
88 // Update DOM
89 });
90});
91```
92
93### new Auth0LockPasswordless(clientID, domain, options)
94
95Initializes a new instance of `Auth0LockPasswordless` configured with your application `clientID` and your account's `domain` at [Auth0](https://manage.auth0.com/). You can find this information in your [application settings](https://manage.auth0.com/#/applications).
96
97- **clientId {String}**: Your application _clientId_ in Auth0.
98- **domain {String}**: Your Auth0 _domain_. Usually _your-account.auth0.com_.
99- **options {Object}**: Allows you to customize the dialog's appearance and behavior. See [below](#customization) for the details.
100
101If both SMS and email passwordless connections are enabled [in the dashboard](https://manage.auth0.com/#/connections/passwordless), Lock will pick email by default. If you want to conditionally pick email or SMS, use the [`allowedConnections`](#ui-options) option, for example: `allowedConnections: ['sms']`.
102
103If using an [additional passwordless connection](#additional-passwordless-connections) that has been created through the Management API, you must specify the connection in `allowedConnections` and also enable the `useCustomPasswordlessConnection` flag in the options.
104
105For more information, read our [passwordless docs](https://auth0.com/docs/connections/passwordless).
106
107#### Example
108
109```js
110var clientId = "YOUR_AUTH0_APP_CLIENTID";
111var domain = "YOUR_DOMAIN_AT.auth0.com";
112var lock = new Auth0LockPasswordless(clientId, domain);
113var accessToken = null;
114var profile = null;
115
116lock.on("authenticated", function(authResult) {
117 lock.getUserInfo(authResult.accessToken, function(error, profileResult) {
118 if (error) {
119 // Handle error
120 return;
121 }
122
123 accessToken = authResult.accessToken;
124 profile = profileResult;
125
126 // Update DOM
127 });
128});
129```
130
131### getUserInfo(accessToken, callback)
132
133Once the user has logged in and you are in possession of an access token, you can obtain the profile with `getUserInfo`.
134
135- **accessToken {String}**: User access token.
136- **callback {Function}**: Will be invoked after the user profile has been retrieved.
137
138#### Example
139
140```js
141lock.getUserInfo(accessToken, function(error, profile) {
142 if (!error) {
143 alert("hello " + profile.name);
144 }
145});
146```
147
148### on(event, callback)
149
150Lock will emit events during its lifecycle.
151
152- `show`: emitted when Lock is shown. Has no arguments.
153- `hide`: emitted when Lock is hidden. Has no arguments.
154- `unrecoverable_error`: emitted when there is an unrecoverable error, for instance when no connection is available. Has the error as the only argument.
155- `authenticated`: emitted after a successful authentication. Has the authentication result as the only argument.
156- `authorization_error`: emitted when authorization fails. Has the error as the only argument.
157- `hash_parsed`: every time a new Auth0Lock object is initialized in redirect mode (the default), it will attempt to parse the hash part of the URL looking for the result of a login attempt. This is a _low-level_ event for advanced use cases and _authenticated_ and _authorization_error_ should be preferred when possible. After that, this event will be emitted with `null` if it couldn't find anything in the hash. It will be emitted with the same argument as the `authenticated` event after a successful login or with the same argument as `authorization_error` if something went wrong. This event won't be emitted in popup mode because there is no need to parse the URL's hash part.
158- `forgot_password ready`: emitted when the "Forgot password" screen is shown.
159- `forgot_password submit`: emitted when the user clicks on the submit button of the "Forgot password" screen.
160- `signin submit`: emitted when the user clicks on the submit button of the "Login" screen.
161- `signup submit`: emitted when the user clicks on the submit button of the "Sign up" screen.
162- `signup success`: emitted when the user successfully signs up.
163- `signup error`: emitted when signup fails. Has the error as an argument.
164- `federated login`: emitted when the user clicks on a social connection button. Has the connection name and the strategy as arguments.
165- `sso login`: emitted when the user clicks on an enterprise SSO connection button. Has the lock ID, connection object, and field name as arguments.
166- `ssodata fetched`: emitted when the SSOData endpoint was called, usually as a result of an internal `checkSession` call. Has the error and the SSOData object as arguments.
167
168### show(options)
169
170Displays the widget, allowing you to override some options.
171
172- **options {Object}**: Allows you to customize some aspect of the dialog's appearance and behavior. The options allowed in here are a subset of the options allowed in the constructor and will override them: `allowedConnections`, `auth.params`, `allowLogin`, `allowSignUp`, `allowForgotPassword`, `initialScreen`, `rememberLastLogin`, `flashMessage` and `languageDictionary`. See [below](#customization) for the details. Keep in mind that `auth.params` will be fully replaced and not merged.
173
174#### Example
175
176```js
177// without options
178lock.show();
179
180// will override the allowedConnections option passed to the constructor, if any
181lock.show({allowedConnections: ["twitter", "facebook"]})
182
183// will override the entire auth.params object passed to the constructor, if any
184lock.show({auth: {params: {state: 'auth_state'}}})
185```
186
187### resumeAuth(hash, callback)
188
189If you set the [auth.autoParseHash](#authentication-options) option to `false`, you'll need to call this method to complete the authentication flow. This method is useful when you're using a client-side router that uses a `#` to handle URLs (angular2 with `useHash` or react-router with `hashHistory`).
190- **hash {String}**: The hash fragment received from the redirect.
191- **callback {Function}**: Will be invoked after the parse is done. Has an error (if any) as the first argument and the authentication result as the second one. If there is no hash available, both arguments will be `null`.
192
193#### Example
194
195```js
196lock.resumeAuth(hash, function(error, authResult) {
197 if (error) {
198 alert("Could not parse hash");
199 }
200 console.log(authResult.accessToken);
201});
202```
203
204### logout(options)
205
206Logs out the user.
207
208- **options {Object}**: This is optional and follows the same rules as [this](https://auth0.com/docs/libraries/auth0js#logout).
209
210#### Example
211
212```js
213lock.logout({ returnTo: 'https://myapp.com/bye-bye' });
214```
215
216### checkSession(params, callback)
217
218The checkSession method allows you to acquire a new token from Auth0 for a user who is already authenticated against the universal login page for your domain. The method accepts any valid OAuth2 parameters that would normally be sent to authorize. In order to use this method, you have to enable Web Origins for your application. For more information, see [Using checkSession to acquire new tokens](https://auth0.com/docs/libraries/auth0js#using-checksession-to-acquire-new-tokens).
219- **params {Object}**: OAuth2 params object to send to Auth0's servers.
220- **callback {Function}**: Will be invoked after the response from the server is returned. Has an error (if any) as the first argument and the authentication result as the second one.
221
222#### Example
223
224```js
225lock.checkSession({}, function (error, authResult) {
226 if (error || !authResult) {
227 lock.show();
228 } else {
229 // user has an active session, so we can use the accessToken directly.
230 lock.getUserInfo(authResult.accessToken, function (error, profile) {
231 console.log(error, profile);
232 });
233 }
234});
235```
236
237### Customization
238
239The appearance of the widget and the mechanics of authentication can be customized with an `options` object which has one or more of the following properties. Each method that opens the dialog can take an `options` object as its first argument.
240
241#### UI options
242
243- **allowedConnections {Array}**: List of connection that will be available to perform the authentication. It defaults to all enabled connections.
244- **autoclose {Boolean}**: Determines whether or not the Lock will be closed automatically after a successful sign in. If the Lock is not `closable` it won't be closed even if this option is set to `true`. Defaults to `false`.
245- **autofocus {Boolean}**: Determines whether or not the first input on the screen, that is the email or phone number input, should have focus when the Lock is displayed. Defaults to `false` when a `container` option is provided or the Lock is being rendered on a mobile device. Otherwise, it defaults to `true`.
246- **avatar {Object}**: Determines whether or not an avatar and a username should be displayed on the Lock's header once an email or username has been entered and how to obtain it. By default avatars are fetched from [Gravatar](https://gravatar.com/). Supplying `null` will disable the functionality. To fetch avatar from other provider see [below](#avatar-provider).
247- **container {String}**: The `id` of the HTML element where the Lock will be rendered. This makes the Lock appear inline instead of in a modal window.
248- **language {String}**: Specifies the language of the widget. Defaults to `"en"`. Supported languages are:
249 - `de`: German
250 - `en`: English
251 - `es`: Spanish
252 - `it`: Italian
253 - `nb`: Norwegian bokmål
254 - `pt-BR`: Brazilian Portuguese
255 - `ru`: Russian
256 - `zh`: Chinese
257 - `ja`: Japanese
258 - [Check all the available languages](https://github.com/auth0/lock/tree/master/src/i18n)
259- **languageDictionary {Object}**: Allows you to customize every piece of text displayed in the Lock. Defaults to `{}`. See below [Language Dictionary Specification](#language-dictionary-specification) for the details.
260- **closable {Boolean}**: Determines whether or not the Lock can be closed. When a `container` option is provided its value is always `false`, otherwise it defaults to `true`.
261- **popupOptions {Object}**: Allows you to customize the location of the popup in the screen. Any [position and size feature](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#Position_and_size_features) allowed by `window.open` is accepted. Defaults to `{}`.
262- **rememberLastLogin {Boolean}**: Determines whether or not to show a screen that allows you to quickly log in with the account you used the last time when the `initialScreen` option is set to `"login"` (the default). Defaults to `true`.
263- **flashMessage {Object}**: Shows an `error` or `success` flash message when Lock is shown.
264 + **type {String}**: The message type, it should be `error` or `success`.
265 + **text {String}**: The text to show.
266- **allowAutocomplete {Boolean}**: Determines whether or not the email or username inputs will allow autocomplete (`<input autocomplete />`). Defaults to `false`.
267- **scrollGlobalMessagesIntoView {Boolean}**: Determines whether or not a globalMessage should be scrolled into the user's viewport. Defaults to `true`.
268- **allowShowPassword {Boolean}**: Determines whether or not add a checkbox to show the password when typing it. Defaults to `false`.
269- **allowPasswordAutocomplete {Boolean}**: Determines whether the password field will allow autocomplete; setting this to `true` is required for password manager support and to avoid many cases of adverse behavior. Defaults to `false`.
270- **preferConnectionDisplayName {Boolean}**: If true, Lock will try to use the connection display name as configured in the manage dashboard, if available.
271
272
273#### Theming options
274
275Theme options are grouped in the `theme` property of the `options` object.
276
277```js
278var options = {
279 theme: {
280 labeledSubmitButton: false,
281 logo: "https://example.com/assets/logo.png",
282 primaryColor: "green",
283 authButtons: {
284 connectionName: {
285 displayName: "...",
286 primaryColor: "...",
287 foregroundColor: "...",
288 icon: "https://.../logo.png"
289 }
290 }
291 }
292};
293```
294
295- **labeledSubmitButton {Boolean}**: Indicates whether or not the submit button should have a label. Defaults to `true`. When set to `false` an icon will be shown. The labels can be customized through the `languageDictionary`.
296- **logo {String}**: Url for an image that will be placed in the Lock's header. Defaults to Auth0's logo.
297- **primaryColor {String}**: Defines the primary color of the Lock, all colors used in the widget will be calculated from it. This option is useful when providing a custom `logo` to ensure all colors go well together with the logo's color palette. Defaults to `"#ea5323"`.
298- **authButtons {Object}**: Allows the customization of the custom oauth2 login buttons.
299 + **displayName {String}**: The name to show instead of the connection name.
300 + **primaryColor {String}**: The button's background color. Defaults to `"#eb5424"`.
301 + **foregroundColor {String}**: The button's text color. Defaults to `"#FFFFFF"`.
302 + **icon {String}**: The icon's url for the connection. For example:`"https://site.com/logo.png"`.
303
304#### Authentication options
305
306Authentication options are grouped in the `auth` property of the `options` object. The default scope used by Lock is `openid profile email`.
307
308```js
309var options = {
310 auth: {
311 params: {
312 param1: "value1",
313 scope: "openid profile email"
314 },
315 autoParseHash: true,
316 redirect: true,
317 redirectUrl: "some url",
318 responseMode: "form_post",
319 responseType: "token",
320 sso: true,
321 connectionScopes: {
322 connectionName: [ 'scope1', 'scope2' ]
323 }
324 }
325};
326```
327
328- **params {Object}**: Specifies extra parameters that will be sent when starting a login. Defaults to `{}`.
329- **autoParseHash {Boolean}**: When set to `true`, Lock will parse the `window.location.hash` string when instantiated. If set to `false`, you'll have to manually resume authentication using the [resumeAuth](#resumeauthhash-callback) method.
330- **redirect {Boolean}**: When set to `true`, the default, _redirect mode_ will be used. Otherwise, _popup mode_ is chosen. See [below](#popup-mode) for more details.
331- **redirectUrl {String}**: The URL Auth0 will redirect back to after authentication. Defaults to the empty string `""` (no redirect URL).
332- **responseMode {String}**: Should be set to `"form_post"` if you want the code or the token to be transmitted via an HTTP POST request to the `redirectUrl` instead of being included in its query or fragment parts. Otherwise, it should be omitted.
333- **responseType {String}**: Should be set to `"token"` for Single Page Applications, and `"code"` otherwise. Also, `"id_token"` is supported for the first case. Defaults to `"code"` when `redirectUrl` is provided, and to `"token"` otherwise.
334- **sso {Boolean}**: Determines whether Single Sign-On is enabled or not in **Lock**. The Auth0 SSO session will be created regardless of this option if SSO is enabled for your application or tenant.
335- **connectionScopes {Object}**: Allows you to set scopes to be sent to the oauth2/social/enterprise connection for authentication.
336
337#### Database options
338
339- **additionalSignUpFields {Array}**: Allows you to provide extra input fields during sign up. See [below](#additional-sign-up-fields) more for details. Defaults to `[]`.
340- **allowLogin {Boolean}**: When set to `false` the widget won't display the _login screen_. This is useful if you want to use the widget just for signups (the _login and sign up tabs_ in the _sign up screen_ will be hidden) or to reset passwords (the _back button_ in the _forgot password screen_ will be hidden). In such cases you may also need to specify the `initialScreen`, `allowForgotPassword` and `allowSignUp` options. It defaults to `true`.
341- **allowForgotPassword {Boolean}**: When set to `false` hides the _"Don't remember your password?"_ link in the _login screen_, making the _forgot password screen_ unreachable. Defaults to `true`. Keep in mind that if you are using a database connection with a _custom database_ which doesn't have a _change password script_ the forgot password screen won't be available.
342- **allowSignUp {Boolean}**: When set to `false` hides the _login and sign up tabs_ in the _login screen_, making the _sign up screen_ unreachable. Defaults to `true`. Keep in mind that if the database connection has sign ups _disabled_ or you are using a _custom database_ which doesn't have a _create script_, then the sign up screen won't be available.
343- **defaultDatabaseConnection {String}**: Specifies the database connection that will be used when there is more than one available.
344- **initialScreen {String}**: Name of the screen that will be shown when the widget is opened. Valid values are `"login"`, `"signUp"`, and `"forgotPassword"`. If this option is left unspecified, the widget will pick the first screen that is available from the previous list. If you set `initialScreen` to `"forgotPassword"` we recommend that you set `allowLogin` to `"false"`, otherwise a back button will be shown in the forgot password screen and it might not be clear to the user where that back button will take them.
345- **loginAfterSignUp {Boolean}**: Determines whether or not the user will be automatically signed in after a successful sign up. Defaults to `true`.
346- **forgotPasswordLink {String}**: URL for a page that allows the user to reset her password. When set to a non-empty string, the user will be linked to the provided URL when clicking the _"Don't remember your password?"_ link in the _login screen_.
347- **showTerms {Boolean}**: When set to `true` displays the `languageDictionary.signUpTerms` string. Defaults to `true`.
348- **mustAcceptTerms {Boolean}**: When set to `true` displays a checkbox input along with the terms and conditions that must be checked before signing up. The terms and conditions can be specified via the `languageDictionary` option, see the example below. Defaults to `false`.
349- **prefill {Object}**: Allows you to set the initial value for the _email_ and/or _username_ inputs, e.g. `{prefill: {email: "someone@auth0.com", username: "someone"}}`. When omitted no initial value will be provided.
350- **signUpLink {String}**: URL for a page that allows the user to sign up. When set to a non-empty string, the user will be linked to the provided URL when clicking the _sign up_ tab in the _login screen_.
351- **usernameStyle {String}**: Determines what will be used to identify the user for a Database connection that has the `requires_username` flag set, otherwise it will be ignored. Possible values are `"username"` and `"email"` and by default both `username` and `email` are allowed.
352- **signUpHideUsernameField {Boolean}**: When set to `true` hides the _username_ input during sign up for a Database connection that has the `requires_username` flag set. Defaults to `false`.
353- **signUpFieldsStrictValidation {Boolean}**: When set to `true`, the _email_ input on the sign-up page is validated using [`validator`](https://www.npmjs.com/package/validator). Otherwise, a very loose check is made on the format before being fully validate on the server. Defaults to `false`.
354
355#### Enterprise options
356
357- **defaultEnterpriseConnection {String}**: Specifies the enterprise connection which allows you to log in using a username and a password that will be used when there is more than one available or there is a database connection. If a `defaultDatabaseConnection` is provided the database connection will be used and this option will be ignored.
358
359#### Example
360
361```js
362var options = {
363 container: "myContainer",
364 closable: false,
365 languageDictionary: {
366 signUpTerms: "I agree to the <a href='/terms' target='_new'>terms of service</a> and <a href='/privacy' target='_new'>privacy policy</a>.",
367 title: "My Company",
368 },
369 autofocus: false
370};
371```
372
373#### Passwordless options
374
375- **passwordlessMethod {String}**: When using `Auth0LockPasswordless` with an email connection, you can use this option to pick between sending a [code](https://auth0.com/docs/connections/passwordless/spa-email-code) or a [magic link](https://auth0.com/docs/connections/passwordless/spa-email-link) to authenticate the user. Available values for email connections are `code` and `link`. Defaults to `code`. SMS passwordless connections will always use `code`.
376- **useCustomPasswordlessConnection {Boolean}**: Enables the use of a custom passwordless connection (see below).
377
378#### Additional passwordless connections
379
380By default, only two passwordless connections are available: `email` and `sms`. However, it is possible to create additional passwordless connections that employ the `email` or `sms` strategy through the Management API. To use these connections in Lock, you must:
381
3821. Specify the custom connection in the `allowedConnections` option, and
3832. Enable the `useCustomPasswordlessConnection` flag in the options
384
385Users logging in using this connection should then be associated with the correct passwordless connection and this can be verified in [the logs](https://manage.auth0.com/#/logs).
386
387**Note:** If you specify more than one connection in `allowedConnections`, the first one will always be used.
388
389#### Hooks
390
391Lock supports hooks that can be used to integrate into various procedures within Lock.
392
393| Name | Description |
394|----|-----|
395| `loggingIn` | Called when the user presses the login button; after validating the login form, but before calling the login endpoint |
396| `signingUp` | Called when the user presses the button on the sign-up page; after validating the signup form, but before calling the sign up endpoint |
397
398**API**
399Both hooks accept two arguments:
400
401| Name | Description |
402|----|----|
403| `context` | this argument is currently always `null` but serves as a future-proofing mechanism to support providing additional data without us requiring breaking changes to the library |
404| `cb` | a callback function to call when the hook is finished. Execution of the user journey is blocked until this function is called by the hook |
405
406**API**
407
408Specify your hooks using a new `hooks` configuration item when setting up the library:
409
410```js
411new Auth0Lock('client ID', 'domain', {
412 hooks: {
413 loggingIn: function(context, cb) {
414 console.log('Hello from the login hook!');
415 cb();
416 },
417 signingUp: function(context, cb) {
418 console.log('Hello from the sign-up hook!');
419 cb();
420 }
421});
422```
423
424**Error handling**
425
426The developer can throw an error to block the login or sign-up process. The developer can either specify a specific object and show the error on the page, or throw a generic error which causes Lock to show a fallback error:
427
428```js
429new Auth0Lock('client ID', 'domain', {
430 hooks: {
431 loggingIn: function(context, cb) {
432 // Throw an object with code: `hook_error` to display this on the Login screen
433 throw { code: 'hook_error', description: 'There was an error in the login hook!' };
434
435 // Throw something generic to show a fallback error message
436 throw "Some error happened";
437 },
438});
439```
440
441**Note:** The error's `description` field is not sanitized by the SDK and so any content that reflects user input or could otherwise display dangerous HTML should be sanitized by your hook.
442
443#### Other options
444
445- **configurationBaseUrl {String}**: Overrides application settings base URL. By default it uses Auth0's CDN URL when the `domain` has the format `*.auth0.com`. Otherwise, it uses the provided `domain`.
446- **languageBaseUrl {String}**: Overrides the language source URL for Auth0's provided translations. By default it uses to Auth0's CDN URL `https://cdn.auth0.com`.
447- **hashCleanup {Boolean}**: When enabled, it will remove the hash part of the callback URL after the user authentication. Defaults to `true`.
448- **connectionResolver {Function}**: When in use, provides an extensibility point to make it possible to choose which connection to use based on the username information. Has `username`, `context`, and `callback` as parameters. The callback expects an object like: `{type: 'database', name: 'connection name'}`. **This only works for database connections.** Keep in mind that this resolver will run in the form's `onSubmit` event, so keep it simple and fast. **This is a beta feature. If you find a bug, please open a GitHub [issue](https://github.com/auth0/lock/issues/new).**
449
450```js
451var options = {
452 connectionResolver: function (username, context, cb) {
453 var domain = username.includes('@') && username.split('@')[1];
454 if (domain) {
455 // If the username is test@auth0.com, the connection used will be the `auth0.com` connection.
456 // Make sure you have a database connection with the name `auth0.com`.
457 cb({ type: 'database', name: domain });
458 } else {
459 // Use the default approach to figure it out the connection
460 cb(null);
461 }
462 }
463}
464```
465
466#### Language Dictionary Specification
467
468A language dictionary is an object that allows you to customize every piece of text the Lock needs to display. For instance, the following code will change the title displayed in the header and the placeholder for the email field.
469
470```js
471var options = {
472 languageDictionary: {
473 emailInputPlaceholder: "Please enter your email",
474 title: "My Company"
475 },
476};
477```
478
479#### Additional sign up fields
480
481Extra input fields can be added to the sign up screen with the `additionalSignUpFields` option. Every input must have a `name` and a `placeholder`, and an `icon` URL can also be provided. Also, the initial value can be provided with the `prefill` option, which can be a **string** with the value or a **function** that obtains it. Other options depend on the type of the field, which is defined via the `type` option and defaults to `"text"`.
482
483Additional sign up fields are rendered below the default fields in the order they are provided.
484
485##### Text field
486
487A `validator` function can also be provided.
488
489```js
490var options = {
491 additionalSignUpFields: [{
492 name: "address",
493 placeholder: "enter your address",
494 // The following properties are optional
495 ariaLabel: "Address",
496 icon: "https://example.com/assets/address_icon.png",
497 prefill: "street 123",
498 validator: function(address) {
499 return {
500 valid: address.length >= 10,
501 hint: "Must have 10 or more chars" // optional
502 };
503 }
504 }]
505};
506```
507
508If you don't provide a `validator` function a default validator is applied, which requires the text field to contain some value (be non-empty). You can make a field optional by using a validator that always return `true`:
509
510```js
511var options = {
512 additionalSignUpFields: [{
513 name: "address",
514 placeholder: "enter your address (optional)",
515 validator: function() {return true;}
516 }]
517};
518```
519
520If you want to save the value of the attribute in the root of your profile, use `storage: 'root'`. Only a subset of values can be stored this way. The list of attributes that can be added to your root profile is [here](https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id). By default, every additional sign up field is stored inside the `user_metadata` object.
521
522```js
523var options = {
524 additionalSignUpFields: [{
525 name: "name",
526 storage: "root"
527 }]
528};
529```
530
531##### Select field
532
533To specify a select field `type: "select"` needs to be provided along with the `options` property.
534
535```js
536var options = {
537 additionalSignUpFields: [{
538 type: "select",
539 name: "location",
540 placeholder: "choose your location",
541 options: [
542 {value: "us", label: "United States"},
543 {value: "fr", label: "France"},
544 {value: "ar", label: "Argentina"}
545 ],
546 // The following properties are optional
547 ariaLabel: "Location",
548 icon: "https://example.com/assets/location_icon.png",
549 prefill: "us"
550 }]
551}
552```
553
554The `options` and the `prefill` value can be provided through a function.
555
556```js
557var options = {
558 additionalSignUpFields: [{
559 type: "select",
560 name: "location",
561 placeholder: "choose your location",
562 options: function(cb) {
563 // obtain options, in case of error you call cb with the error in the
564 // first arg instead of null
565 cb(null, options);
566 },
567 ariaLabel: "Location",
568 icon: "https://example.com/assets/location_icon.png",
569 prefill: function(cb) {
570 // obtain prefill, in case of error you call cb with the error in the
571 // first arg instead of null
572 cb(null, prefill);
573 }
574 }]
575}
576```
577
578##### Checkbox field
579
580To specify a checkbox field use: `type: "checkbox"`
581The `prefill` value can determine the default state of the checkbox and it is required.
582
583```js
584var options = {
585 additionalSignUpFields: [{
586 type: "checkbox",
587 name: "newsletter",
588 prefill: "true",
589 placeholder: "I hereby agree that I want to receive marketing emails from your company",
590 // placeholderHTML - is an optional field and overrides the value of placeholder
591 // do not use user inputted data for HTML fields as they are vulnerable to XSS
592 placeholderHTML: "<b>I hereby agree that I want to receive marketing emails from your company</b>",
593 // ariaLabel - is an optional field
594 ariaLabel: "Activate Newsletter"
595 }]
596}
597```
598
599##### Hidden field
600
601To specify a hidden field use: `type: "hidden"`. Both the `value` and `name` properties are required.
602
603```js
604var options = {
605 additionalSignUpFields: [{
606 type: "hidden",
607 name: "signup_code",
608 value: "foobar123"
609 }]
610}
611```
612
613#### Avatar provider
614
615Lock can show avatars fetched from anywhere. A custom avatar provider can be specified with the `avatar` option by passing an object with the keys `url` and `displayName`. Both properties are functions that take an email and a callback function.
616
617```js
618var options = {
619 avatar: {
620 url: function(email, cb) {
621 // obtain URL for email, in case of error you call cb with the error in
622 // the first arg instead of null
623 cb(null, url);
624 },
625 displayName: function(email, cb) {
626 // obtain displayName for email, in case of error you call cb with the
627 // error in the first arg instead of null
628 cb(null, displayName);
629 }
630 }
631};
632```
633
634### Popup mode
635
636A popup window can be displayed instead of redirecting the user to a social provider website. While this has the advantage of preserving page state, it has some issues. Often times users have popup blockers that prevent the login page from even displaying. There are also known issues with mobile browsers. For example, in recent versions of Chrome on iOS, the login popup does not [close properly](https://github.com/auth0/lock/issues/71) after login. For these reasons, we encourage developers to avoid this mode, even with Single Page Apps.
637
638If you decide to use popup mode you can activate it by passing the option `auth: {redirect: false}` when constructing `Auth0Lock`.
639
640```js
641var clientId = "YOUR_AUTH0_APP_CLIENTID";
642var domain = "YOUR_DOMAIN_AT.auth0.com";
643var options = {
644 auth: {
645 redirect: false
646 }
647};
648
649var lock = new Auth0Lock(clientId, domain, options);
650lock.show();
651```
652
653More information can be found in [Auth0's documentation](https://auth0.com/docs/libraries/lock/v11/authentication-modes#popup-mode).
654
655## Browser Compatibility
656
657We ensure browser compatibility in Chrome, Safari, Firefox and IE >= 10. We currently use [zuul](https://github.com/defunctzombie/zuul) along with [Saucelabs](https://saucelabs.com) to run integration tests on each push.
658
659## Issue Reporting
660
661If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.
662
663## Author
664
665[Auth0](https://auth0.com)
666
667## License
668
669This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.
670
671
672[circleci-image]: https://img.shields.io/circleci/project/github/auth0/lock.svg?style=flat-square
673[circleci-url]: https://circleci.com/gh/auth0/lock/tree/master
674[npm-image]: https://img.shields.io/npm/v/auth0-lock.svg?style=flat-square
675[npm-url]: https://npmjs.org/package/auth0-lock
676[license-image]: https://img.shields.io/npm/l/auth0-lock.svg?style=flat-square
677[license-url]: #license
678[downloads-image]: https://img.shields.io/npm/dm/auth0-lock.svg?style=flat-square
679[downloads-url]: https://npmjs.org/package/auth0-lock
680[david-image]: https://david-dm.org/auth0/lock/status.svg?style=flat-square
681[david-url]: https://david-dm.org/auth0/lock
682
683
684[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fauth0%2Flock.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fauth0%2Flock?ref=badge_large)