Users

User management is central to any application and central to Kinvey's backend-as-a-service.

The user management API has methods for handling typical user actions such as signup, login and logout. Using the API is as simple as calling each of those methods from the respective form and button in your app. An active user provides context for each interaction with your backend, ensuring that security is enforced and unauthorized access is disallowed. By default, a user's data is readable but not writable by other users.

A user object and its properties such as first name, last name and email are represented in the backend as an entity, and as such, most of the entity methods such as fetch and save apply.

User Model

The library represents users by an object literal.

{
    _id      : 'user-id',
    _acl     : { /* ACL */ },
    _kmd     : { /* Metadata */ },
    username : 'username',
    password : 'password',
    email    : 'email'
}

Similarly to the Data Store, the library does not provide any built-in classes to represent users.

If you are using Backbone.js, we recommend you use Kinvey’s Backbone library which provides tighter intregation between Kinvey and Backbone.js.

Active User

The library has a concept of an active user which represents the person using your app. There can only be one active user at a time. All backend API calls are made with the credentials of the active user, enforcing the corresponding access control.

The active user can be obtained by calling Kinvey.getActiveUser(). Note that the object literal returned may not necessarily reflect the latest user data on Kinvey. To refresh the active user, call me.

var user = Kinvey.getActiveUser();
var promise = Kinvey.User.me({
    success: function(response) {
        ...
    }
});

Active User Lifecycle

When the application launches there is initially no active user. The active user is set when one of the following happens:

  • If there is a user stored from a previous visit, this user is restored.
  • If there is no user stored, but a user is available in the backend, then a successful call to login will set the active user.
  • If there is no user stored, and no user is available in the backend, you can create a new active user.

Prior to version 1.1.0, a user would be implicitly created on the first call to the backend if there was no logged-in user. If a particular method requires user credentials, the client will now reject with a NO_ACTIVE_USER error instead.

Signup

To create a new user, call signup. The created user is automatically logged in and stored as the active user. The username and password field are optionally, and automatically generated by Kinvey if omitted.

var promise = Kinvey.User.signup({
    username : 'username',
    password : 'password'
}, {
    success: function(response) {
        ...
    }
});

If you are looking to login with a social identity (e.g. Facebook or Twitter), read the section on Using Social Identities.

Removing the User from the System

To delete a user from the system, call destroy. By default, this will disable the user. Disabled users can no longer access the app and will receive errors on all requests.

var promise = Kinvey.User.destroy('user-id', {
    success: function(response) {
        ...
    }
});

Re-enabling disabled users can only be done using the Master Secret. Therefore, this should never be done through your client-side app.

To permanently remove the user without the ability to re-enable it, add the hard option.

var promise = Kinvey.User.destroy('user-id', {
    hard    : true,
    success : function() {
        ...
    }
});

If you delete the active user using the Kinvey console, another API, or another device, that users credentials will still be stored locally on the app. This will cause all subsequent requests to return a InsufficientCredentials error. You can fix this by calling Kinvey.User.logout({ force: true });.

Login

The login method is used to login a user by its username and password.

var promise = Kinvey.User.login('username', 'password', {
    success: function(response) {
        ...
    }
});

Alternatively, you can pass in an object containing the username and password.

var promise = Kinvey.User.login({
    username : 'username',
    password : 'password'
}, {
    success: function(response) {
        ...
    }
});

Upon authentication, the response holds the user object.

If you are looking to login with a social identity (e.g. Facebook or Twitter), read the section on Using Social Identities.

Logout

The logout method is used to logout the active user.

var user = Kinvey.getActiveUser();
if(null !== user) {
    var promise = Kinvey.User.logout({
        success: function() {
            ...
        }
    });
}

User Management

User management features provide fully automated workflows that can be used to easily manage and secure user account information.

Updating

To update a user, call Kinvey.User.update. Make sure that you have write permissions for the user. The example below demonstrates how to update the active user.

// Update the active users’ age.
var user = Kinvey.getActiveUser();
user.age = 21;

var promise = Kinvey.User.update(user, {
    success: function() {
        ...
    }
});

Email Verification

Building email verification into your app ensures that your users provide you with correct and valid email addresses that they own during sign-up.

Configuration

The Console exposes several options that control how email verification is handled for your app. These options can be reached by opening the Users addon and selecting the Settings pane from the menu on the left, or by clicking here. The following settings are available:

  • Enforce email verification: by default, new apps do not enforce email verification. This means that while your users can go through the email verification process, any user can log into your app -- regardless of whether or not their email address is verified. In order to restrict access only to those users who have successfully verified their email addresses, enable the Enforce email verification option. Note that when this option is enabled, you will not be able to create a new user that does not have an email address.

    • Always allow access to users created before date: this option will become available when you turn on Enforce email verification. If enabled, any users created before the date you specify will be able to log into your app regardless of whether or not their email is verified. This option is intended to support apps with an existing user base in which users were not previously required to verify their email. The option will allow these existing users to log in, but require email verification from all new users created after the specified date.
  • Automatically send verification email: if this option is enabled, a verification email will automatically be sent when users are created, or when they change their email address. If this option is not enabled, you will need to manually initiate the email verification process (as described below) for each user in order to verify their email address.

Workflow

To request email verification, call verifyEmail. The user must have a valid e-mail address set in the email attribute.

var promise = Kinvey.User.verifyEmail('username', {
    success: function() {
        ...
    }
});

This request will start the email verification process, and will cause an email to be sent to the user requesting they confirm their email address by clicking on a link included in the email body. The link is served by Kinvey and is valid for five days from the time of the email. The email address for a user must be stored in a property named email in the user object.

Email Verification Request

The workflow completes when the user opens and clicks on the link in the email, thus confirming their email address. A final email is then sent to the user letting them know that their email address was successfully confirmed.

Email Verification Completed

You can obtain the status of the email verification for a particular user by creating a metadata object and calling metadata.getEmailVerification(). Please note that you have to refresh the active user first using Kinvey.User.me if you are directly obtaining the status after calling Kinvey.User.verifyEmail.

var user     = Kinvey.getActiveUser();
var metadata = new Kinvey.Metadata(user);
var status   = metadata.getEmailVerification();

The verification workflow exposes the following states in the status property:

  • sent: an email was sent in response to a verification initiate request
  • resent: multiple emails were sent in response to verification initiate requests
  • delivered: the email was successfully delivered to the user's mailbox (as reported by the remote server)
  • bounce: an email previously sent was bounced back by the remote server and couldn't be delivered
  • deferred: the mail system ran into transient problems delivering the email and deferred further attempts
  • dropped: the mail system dropped the email because of errors
  • confirmed: the user opened the email and clicked on the link enclosed in the email.

Each time the status changes, the time of change is recorded in the lastStateChangeAt property.

Customization of verification emails

You have the option of customizing the contents and appearance of the emails that are sent to your app users. To customize these emails, navigate to the Email Templates addon under the Messaging category of the addon menu. You may modify the from and reply-to email fields, as well as the subjects and bodies of both the first email and the confirmation email.

Email Verification Customization

The From Address and Reply-To Address can be in the form: Display Name <account@server.com> or just account@server.com. Be aware that even if you change these fields, the email will still be sent from support@kinvey.com, and this might cause the message to be flagged by some mail clients.

The Subject and Email fields support mustache templates (tags within double curly-brackets). The email field supports HTML bodies, but a plain-text version will be generated and sent along in the message as well.

The available tags vary by email type. The available tags are:

Verification Email:

  • appname - the application name
  • fname - the user's first name, as specified by the first_name field in the user collection.
  • username - the user's username, as specified by the username field in the user collection. The first two lines of the default template are a switch that uses first name if available, and username if one is not.
  • url - the link the user needs to click to verify the email and show the verification page
  • expirationTimeDays - how many days the link is valid for (from generation time)
  • expirationDate - the exact date the link will expire

Congratulations Email:

  • appname - the application name
  • fname - the user's first name, as specified by the first_name field in the user collection.
  • username - the user's username, as specified by the username field in the user collection. The first two lines of the default template are a switch that uses first name if available, and username if one is not.
  • lastChangedAt - the time the user submitted a new password

Customization of successful verification page

You have the option of customizing the HTML "success" page that is displayed when a used has successfully verified their email by clicking the link sent to them.

Email Verification Success Page

To customize this page, navigate to the HTML Templates addon under the Messaging category of the addon menu or click here. The page supports mustache templates (tags within double curly-brackets). The available tags are:

  • appname - the application name
  • fname - the user's first name, as specified by the first_name field in the user collection
  • username - the user's username, as specified by the username field in the user collection
  • lastChangedAt - the time the user submitted a new password

Password Reset

Users can request that our system send them an e-mail with a temporary password reset link. This link will open a web page where they can set a new password. The user must have a valid e-mail address set in the email attribute.

var promise = Kinvey.User.resetPassword('username', {
    success: function() {
        ...
    }
});

This request will send an email containing a secure time-bound link to the email address on record for the user. The link is served by Kinvey and is valid for twenty minutes from the time of the email. A link can be used for only one reset. Submitting the form will update the password for the user. The user will also receive a confirmation email when they complete the password reset.

Password Reset

Until the password reset is complete, the old password remains active and valid. This allows the user to ignore the request if he remembers the old password. If too much time has passed, the email link will no longer be valid, and the user will have to initiate a new password reset.

Changing the Password

If the user is already logged in but wants to change the password, simply call update with the new password.

var user = Kinvey.getActiveUser();
user.password = 'new-password';
var promise = Kinvey.User.update(user, {
    success: function(response) {
        ...
    }
});

Password Reset Email Customization

You have the option of customizing how the email is presented to your app users by specifying the from and reply-to email fields as well as the subjects and bodies of the first email and the congratulations email.

Email Verification Customization

The From Address and Reply-To Address can be in the form: Display Name <account@server.com> or just account@server.com. Be aware that even if you change these fields will still be sent from support@kinvey.com, and this might cause the message to be flagged by some mail clients.

The Subject and Email fields support mustache templates (tags within double curly-brackets). The email field supports HTML bodies, but a plain-text version will be generated and sent along in the message as well.

The available tags vary by email type. The available tags are:

Reset Email:

  • appname - the application name
  • fname - the user's first name, as specified by the first_name field in the user collection.
  • username - the user's username, as specified by the username field in the user collection. The first two lines of the default template are a switch that uses first name if available, and username if one is not.
  • reseturl - the link the user needs to click to go to the reset password page
  • expirationTimeMins - how many minutes the link is valid for (from generation time)
  • expirationDate - the exact date the link will expire

Congratulations Email:

  • appname - the application name
  • fname - the user's first name, as specified by the first_name field in the user collection.
  • username - the user's username, as specified by the username field in the user collection. The first two lines of the default template are a switch that uses first name if available, and username if one is not.
  • lastChangedAt - the time the user submitted a new password

Using a Custom Password Reset Page

Rather than using the default password reset page hosted on Kinvey, you may optionally host a password reset page on your server. A link to this page will be included in the email sent to your app's users when they reset their password. Typically, you would select this option if you want your users to see a link pointing to your domain rather than to kinvey.com, and/or brand the page in any way you like to better fit your app's visual style.

Background and Process

In order to understand where your custom page fits in, it's helpful to understand the general password reset process:

  1. A user attempts to reset their password. Your app makes a request to the password reset endpoint, either directly or via a client library.

  2. Kinvey sends an email to the user, with a link to baas.kinvey.com/rpc/:kid/:usernameOrEmail/user-password-reset-process (including parameters such as time, nonce and sig).

  3. When the user clicks the link, your app's password reset page is dynamically generated by Kinvey's servers and displayed to the user.

  4. When the user submits the form on the password reset page, their browser requests baas.kinvey.com/rpc/:kid/:usernameOrEmail/user-password-reset-complete (again, with some additional parameters), which resets their password, and displays a confirmation page.

The custom password reset page that you will host will essentially replace the third step described above. A link to your page will appear in the email sent to the user, and your page will then be responsible for parsing the required parameters from the email's link and passing them, along with the new password, onto the Kinvey endpoint mentioned in step 3.

Template

The first step in creating your custom password reset page is downloading our template:

Download Template

The template contains a very simple password reset page that is modeled after our own. It contains a few lines of JavaScript code which parse the parameters from incoming URL, as well as a form allowing the user to input his new password. When the submit button is clicked, the form will send the required parameters to the Kinvey endpoint mentioned in step 3 above.

You are free to customize this form as you wish. Be aware that the Kinvey endpoint that completes the password reset process expects the data to be presented in a certain format, and you should be careful when modifying the JavaScript code or the form elements. After you have made your changes, always make sure that the newly modified page still works as expected by trying to reset a user's password through the Kinvey Console.

When you have finished customizing your password reset page, upload it to your server and make note of the URL. You will need to enter the page's URL in the next step.

Console Configuration

Once you have customized your page and uploaded it to your server, it is time to configure Kinvey so that it uses your page instead of the default one. To do so, open the Kinvey Console and navigate to the Users Setting page by opening the Users addon and selecting the Settings pane from the menu on the left, or by clicking here.

Once in the Users Settings page, scroll down to the section titled Custom Password Reset Page. Enter the URL for your custom page in the input field, and press the Save Changes button. This will complete the setup process, and your new page will now be used for all future password reset requests from your app.

It is highly recommended that you now test the password reset process in order to make sure that the changes you have made to the page are compatible.

Forgot Username

Users can request that our system send them an email with their username. The user must have a valid e-mail address set in the email attribute.

var promise = Kinvey.User.forgotUsername('email', {
    success: function() {
        ...
    }
});

Using Social Identities

You can use social identities to simplify user management in your app. By offering options for your users to login using their Facebook, Twitter, Google+, or LinkedIn accounts, you eliminate a source of friction by not requiring that users create app specific usernames and passwords just for your app.

With Kinvey you can register multiple social identities against the same Kinvey user and switch between them as needed. This allows you to offer multiple login options (e.g.: Login with Facebook and Login with Twitter) in your app.

Alternatively, if you already have possession of the required tokens, you can use the signupWithProvider and loginWithProvider methods to signup or login directly:

var promise = Kinvey.User.loginWithProvider('facebook', {
    access_token : '<access_token>',
    expires_in   : '<expires_in>'
})

Facebook

To link a Facebook identity to a user, you’ll need to obtain an access_token and expires_in. You can obtain these by integrating Facebook Login in your app.

var promise = Kinvey.User.loginWithProvider('facebook', {
    access_token : 'facebook-access-token',
    expires_in   : 'expires_in'
}, {
    success: function(response) {
        ...
    }
});

Kinvey will validate credentials with Facebook and retrieve the corresponding user’s identity from Facebook. Use the login method to login an existing user by its Facebook identity.

var promise = Kinvey.User.loginWithProvider('facebook', {
    access_token : 'facebook-access-token',
    expires_in   : 'expires_in'
}, {
    success: function(response) {
        ...
    }
});

To unlink a Facebook identity from a user, set the facebook property to null and update the user.

var user = Kinvey.getActiveUser();
user._socialIdentity.facebook = null;// Unlink.
var promise = Kinvey.User.update(user, {
    success: function(response) {
        ...
    }
});

Google+

To link a Google+ identity to a user, you’ll need to obtain an access_token and expires_in. You can obtain these by integrating the Google OAuth2.0 workflow in your app.

var promise = Kinvey.User.signupWithProvider('google', {
    access_token : 'google-access-token',
    expires_in   : 'expires_in'
}, {
    success: function(response) {
        ...
    }
});

Kinvey will validate credentials with Google+ and retrieve the corresponding user’s identity from Google+. Use the login method to login an existing user by its Google+ identity.

var promise = Kinvey.User.loginWithProvider('google', {
    access_token : 'google-access-token',
    expires_in   : 'expires_in'
}, {
    success: function(response) {
        ...
    }
});

To unlink a Google+ identity from a user, set the google property to null and update the user.

var user = Kinvey.getActiveUser();
user._socialIdentity.google = null;// Unlink.
var promise = Kinvey.User.update(user, {
    success: function(response) {
        ...
    }
});

LinkedIn

To link a LinkedIn identity to a user, you’ll need to obtain an access_token and access_token_secret. You can obtain these by integrating the LinkedIn Authentication workflow in your app. Furthermore, you need your consumer_key and consumer_secret. To create a user on Kinvey, call the signup function.

var promise = Kinvey.User.signupWithProvider('linkedIn', {
    access_token        : 'access-token',
    access_token_secret : 'access-token-secret',
    consumer_key        : 'consumer-key',
    consumer_secret     : 'consumer-secret'
}, {
    success: function(response) {
        ...
    }
});

Kinvey wil validate credentials with LinkedIn and retrieve the corresponding user’s identity from LinkedIn. Use the login method to login an existing user by its LinkedIn identity.

var promise = Kinvey.User.loginWithProvider('linkedIn', {
    access_token        : 'access-token',
    access_token_secret : 'access-token-secret',
    consumer_key        : 'consumer-key',
    consumer_secret     : 'consumer-secret'
}, {
    success: function(response) {
        ...
    }
});

To unlink a LinkedIn identity from a user, set the linkedIn property to null and update the user.

var user = Kinvey.getActiveUser();
user._socialIdentity.linkedIn = null;// Unlink.
var promise = Kinvey.User.update(user, {
    success: function(response) {
        ...
    }
});

Make sure to capitalize the second i in linkedIn.

Twitter

To link a Twitter identity to a user, you’ll need to obtain an access_token and access_token_secret. You can obtain these by integrating the Twitter Authentication workflow in your app. Furthermore, you need your consumer_key and consumer_secret. To create a user on Kinvey, call the signup function.

var promise = Kinvey.User.signupWithProvider('twitter', {
    access_token        : 'access-token',
    access_token_secret : 'access-token-secret',
    consumer_key        : 'consumer-key',
    consumer_secret     : 'consumer-secret'
}, {
    success: function(response) {
        ...
    }
});

Kinvey wil validate credentials with Twitter and retrieve the corresponding user’s identity from Twitter. Use the login method to login an existing user by its Twitter identity.

var promise = Kinvey.User.loginWithProvider('twitter', {
    access_token        : 'access-token',
    access_token_secret : 'access-token-secret',
    consumer_key        : 'consumer-key',
    consumer_secret     : 'consumer-secret'
}, {
    success: function(response) {
        ...
    }
});

To unlink a Twitter identity from a user, set the twitter property to null and update the user.

var user = Kinvey.getActiveUser();
user._socialIdentity.twitter = null;// Unlink.
var promise = Kinvey.User.update(user, {
    success: function(response) {
        ...
    }
});

User Discovery

Often times, depending on your apps user permission level, users cannot access another user’s data. If that’s the case, querying users will not work. However, keeping user data hidden prevents users from discovering other users, thus reducing the social value of the app. User Discovery allows an app to respect user privacy but enable user discovery at the same time.

Using User Discovery, you can query for exact matches for fields:

  • _id
  • username
  • first_name
  • last_name
  • email
  • _socialIdentity.facebook.id

The example below discovers users with first name “John”. Note that you can only use the equalTo method on the fields listed above.

var query = new Kinvey.Query();
query.equalTo('first_name', 'John');

var promise = Kinvey.User.find(query, {
    discover : true,
    success  : function(response) {
        ...
    }
});

The response will only contain the six fields (if set) listed above. Any other user fields are hidden.

If your user permission settings are not private, you can use the querying interface to find users.

Username Existence Check

To quickly check whether a specific username already exists within your app, call exists. The response will be true if the username already exists, and false otherwise.

var promise = Kinvey.User.exists('usernameToCheck', {
    success: function(usernameExists) {
        ...
    }
});
Got a question?