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 level methods such as fetch and save apply.

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.getCurrentUser().

Explicit vs. Implicit

There are two ways to set the active user in the library:

  • An explicitly set active user is one that your application will log in using a regular username and password on a log in form, or via a social log in through Facebook, Google, Twitter, LinkedIn.
  • An implicitly set active user is created and logged in by the library. This automatic action happens upon the first backend call that the app makes from a device and only if an explicit user is not set. The username and password of the implicit user are randomly generated.

Apps that have no explicit notion of user registration and identity, like mobile single-player games, can simply skip logging in a user. The library then follows the implicit flow and handles the user setup transparently.

For all other practical purposes the implicit user is the same as any other user; the complete user entity is cached locally, it can have custom attributes and it can be a destination for push notifications.

Kinvey.User object

The Kinvey.User class is used to represent a user, and is a subclass of Kinvey.Entity. Therefore, user attributes can be modified in the same way as regular entities. The Kinvey.User class does however expose an additional method to obtain the username - myUser.getUsername().

The following fields have specific semantics in the backend:

Sign up

Use Kinvey.User.create to create a new user. The created user is automatically logged in and stored as the current user. An error will occur when the username is already taken.

Kinvey.User.create({
    username: 'johndoe',
    password: 'secret',
    name: 'John Doe'
}, {
    success: function(user) {
        // user is the created user, which is now logged in.
    },
    error: function(e) {
        // Failed to create the user.
        // e holds information about the nature of the error.
    }
});

Removing the User from the System

Use Kinvey.User.destroy to delete the current user. This operation cannot be undone, and should be used with care.

var user = Kinvey.getCurrentUser();
if(null !== user) {
    user.destroy({
        success: function() {
            // user was deleted.
        },
        error: function(e) {
            // Failed to delete user.
              // e holds information about the nature of the error.
        }
    });
}

If you delete a current user using the 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 code. You can fix this by clearing the locally stored user, by calling Kinvey.User._logout (note the underscore).

Login

Use Kinvey.User.login to login an existing user by username and password. Upon authentication, the user is logged in and becomes the current user.

var myUser = new Kinvey.User();
myUser.login('johndoe', 'secret', {
    success: function(user) {
        // user is the logged in user instance.
    },
    error: function(e) {
        // Failed to login the user.
        // e holds information about the nature of the error.
    }
});

Logout

Use Kinvey.User.logout to log out the current user. The current user will be reset.

var user = Kinvey.getCurrentUser();
if(null !== user) {
    user.logout({
        success: function() {
            // user is now logged out.
        },
        error: function(e) {
            // Failed to logout user.
            // e holds information about the nature of the error.
        }
    });
}

User Management

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

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.

To request email verification, use Kinvey.User.verifyEmail. The user must have a valid email set in the email attribute. For example, to send a confirmation email to the active user:

var user = Kinvey.getCurrentUser();
if(null !== user) {
    Kinvey.User.verifyEmail(user.getUsername(), {
        success: function() {
            // Email was sent.
        },
        error: function(e) {
            // Failed to send verification email.
            // e holds information about the nature of the error.
        }
    });
}

This request will send an email to the user requesting they confirm their email address by clicking on a link in the account. 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. The workflow sends a final email to the user letting them know that their email was successfully confirmed.

Email Verification Completed

To test whether the user has clicked the verify link, use Kinvey.User.isVerified:

var user = Kinvey.getCurrentUser();
if(null !== user) {
    if(user.isVerified()) {
        // The active user has verified its email address.
    }
    else {
        // Email has not yet been verified, show a button to resend.
    }
}

Email Confirmation 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 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

Password Reset

Users can request that our system send them an email 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 email set in the email attribute.

Kinvey.User.resetPassword('username', {
    success: function() {
        // Email was sent.
    },
    error: function(e) {
        // Failed to initiate a password reset.
        // e holds information about the nature of the error.
    }
});

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.

If the user knows his current password and is logged in, but wants to change the password, use Kinvey.User.setPassword followed by saving the user:

var user = Kinvey.getCurrentUser()
user.setPassword('secret');
user.save({
    success: function(user) {
        // Password is now "secret".
    },
    error: function(e) {
        // Failed to change the password.
        // e holds information about the nature of the error.
    }
});

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 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.

Facebook

Instead of explicitly creating a user with a username and password, you can create a user and log in using a Facebook access token. The first time this will generate a new user with a unique, default username and associate it with a valid Facebook token. Subsequent log-ins with a Facebook token that is associated with the user will log in-in with that same user.

Obtaining a Facebook access token

Before the app can log in to Kinvey, it first has to obtain a token from Facebook. There are two ways in which to obtain the token:

  • Use the Facebook SDK

    Facebook’s JavaScript SDK allows you to easily obtain an access token. After you have initialized the SDK, you can use the following code to obtain an access token:

      // Login the user.
      FB.login(function(response) {
          if(response.authResponse) {
              // User is now logged in via Facebook.
              console.log('My access token is: ' + response.authResponse.accessToken);
              console.log('My access token expiry is: ' + response.authResponse.expiresIn);
    
              // Here, you want to call "Kinvey.User.loginWithFacebook" (see below).
          }
          else {
              // User cancelled login or did not fully authorize.
          }
      });
  • Use Kinvey

    You can also use Kinvey to obtain a Facebook access token. This way, you do not need Facebook’s JavaScript SDK. This method however requires some additional set-up. A step-by-step tutorial on how to do this is available here. This approach is recommended especially if you also make use of other Social Identities.

    Once you have obtained the Facebook access token, use Kinvey.User.loginWithFacebook to login the user. Kinvey will verify the access token with Facebook and if it is authenticated, the method will successfully return a Kinvey.User:

      // Create a new user object, and login using a Facebook access token. The second
      // argument can be used to set additional user properties (in this case: "name").
      var user = new Kinvey.User();
      user.loginWithFacebook({
          access_token: '<access-token>',
          expires_in: '<access-token-expiry>'
      }, { name: 'John Doe' }, {
          success: function(user) {
              // The Facebook account is now linked to a Kinvey.User.
              // user.getIdentity() will return the users Facebook identity.
          },
          error: function(e) {
              // Failed to login with Facebook.
              // e holds information about the nature of the error.
          }
      });

Google+

An app can have users login using their Google+ accounts. This allows an app to establish user identity using Google+ identities. To obtain the Google access token needed, implement the OAuth 2.0 for Client-side Applications flow in your app. Alternatively, you can also let Kinvey perform this flow for you. A step-by-step tutorial on how to do this is available here.

Once you have obtained the Google+ access token, use Kinvey.User.loginWithGoogle to login the user. Kinvey will verify the access token with Google and if it is authenticated, the method will successfully return a Kinvey.User:

// Create a new user object, and login using a Google+ access token. The second
// argument can be used to set additional user properties (in this case: "name").
var user = new Kinvey.User();
user.loginWithGoogle({
    access_token: '<access-token>',
    expires_in: '<access-token-expiry>'
}, { name: 'John Doe' }, {
    success: function(user) {
        // The Google+ account is now linked to a Kinvey.User.
        // user.getIdentity() will return the users Google+ identity.
    },
    error: function(e) {
        // Failed to login with Google+.
        // e holds information about the nature of the error.
    }
});

LinkedIn

You can also use LinkedIn to obtain OAuth credentials for a user and use those to log them in to Kinvey. To obtain a LinkedIn access token, implement the LinkedIn Authentication Flow in your app. Alternatively, you can also let Kinvey perform this flow for you. A step-by-step tutorial on how to do this is available here.

Once you have obtained the LinkedIn access tokens, use Kinvey.User.loginWithLinkedIn to login the user. Kinvey will verify the access token with LinkedIn and if it is authenticated, the method will successfully return a Kinvey.User:

// Create a new user object, and login using a LinkedIn access token. The second
// argument can be used to set additional user properties (in this case: "name").
var user = new Kinvey.User();
user.loginWithLinkedIn({
    access_token: '<access-token>',
    access_token_secret: '<access-token-secret>',
    consumer_key: '<consumer-key>',
    consumer_secret: '<consumer-secret>'
}, { name: 'John Doe' }, {
    success: function(user) {
        // The LinkedIn account is now linked to a Kinvey.User.
        // user.getIdentity() will return the users LinkedIn identity.
    },
    error: function(e) {
        // Failed to login with LinkedIn.
        // e holds information about the nature of the error.
    }
});

Never embed the consumer key and consumer secret in publicly accessible code. Instead, follow the OAuth tutorial for a safe set-up.

Twitter

Finally, you can also use Twitter to obtain OAuth credentials for a user and use those to log them in to Kinvey. To obtain a Twitter access token, implement the Twitter Sign-In Flow in your app. Alternatively, you can also let Kinvey perform this flow for you. A step-by-step tutorial on how to do this is available here.

Once you have obtained the Twitter access tokens, use Kinvey.User.loginWithTwitter to login the user. Kinvey will verify the access token with Twitter and if it is authenticated, the method will successfully return a Kinvey.User:

// Create a new user object, and login using a Twitter access token. The second
// argument can be used to set additional user properties (in this case: "name").
var user = new Kinvey.User();
user.loginWithTwitter({
    access_token: '<access-token>',
    access_token_secret: '<access-token-secret>',
    consumer_key: '<consumer-key>',
    consumer_secret: '<consumer-secret>'
}, { name: 'John Doe' }, {
    success: function(user) {
        // The Twitter account is now linked to a Kinvey.User.
        // user.getIdentity() will return the users Twitter identity.
    },
    error: function(e) {
        // Failed to login with Twitter.
        // e holds information about the nature of the error.
    }
});

Never embed the consumer key and consumer secret in publicly accessible code. Instead, follow the OAuth tutorial for a safe set-up.

Get in touch