Class: User

User

Represents a user of your application on Built.io Backend. User inherts from Object.

new User(uid){User}

user.js, line 14
Creates a user with initial value
Name Type Description
uid String | Object The uid of this object or a user with inital values.
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
// 'blt111sample2423b' is uid of an user on Built.io Backend
var User = Built.App('blt5d4sample2633b').User; 
// Example demonstrating the constructor taking a user's uid as argument
var user = User('blt111sample2423b');
// Example demonstrating the constructor taking a initial value
var user = User({
   email:'abc@email.com'
});

Methods

staticUser.anyAuth(fnUrl, reqBody, reqHeaders){Promise.<User>}

user.js, line 286
This is a helper function for AnyAuth feature. This method requires an extension function implementing AnyAuth login.
Name Type Description
fnUrl String The name of the AnyAuth function that needs to be executed
reqBody object The request body that needs to be sent with the request (Optional)
reqHeaders object Headers that need to be sent along with the request (Optional)
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
 
Built.App('blt5d4sample2633b').User
.anyAuth('/submit',{
   access_token:'dummy_access_token'
},{
   dummy_header:'value'
})
.then(function(user){
   console.log(user.toJSON()); // Logged-in user's details
});

staticUser.clearSession(){App}

user.js, line 235
Clears the session based on the persistence option
Fires:
  • user:clear-session event of Events
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var User = Built.App('blt5d4sample2633b').User; 
// Would clear session based on the persistence option set for the application
User.clearSession()

staticUser.generateAccessToken(query, upsert, updateObject){Promise.<User>}

user.js, line 251
This method allows you to login as any user without requiring the credentials. This is only possible if a master key is set up on the app instance. Master Key overrides usual restrictions, thereby enabling you to work as a privileged user. This method should to be used on the server side, where Master Key is not exposed to the client. Thus, it can be safely used in Built Extensions code.
Name Type Description
query Query Query to find the user
upsert Boolen Set this to true if a new user is to created if not found
updateObject Object Updates to be made in user object
Throws:
  • new Error('Master key not found in headers');
  • new Error('Query instance inappropriate');
  • new Error('Upsert argument should be a boolean value');
  • new Error('Update object inappropriate');
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
 
var app = Built.App('blt5d4sample2633b').setMasterKey('bltdb28sample4f1b8');
var User = app.User; 
// our query for an existing user with the username
var query = app.Class(Built.Constants.APPLICATION_USER).Query();
query = query.where('username', request.params.username);

User.generateAccessToken(
   query,
   // we *don't* want to create a new user if he doesn't exist
   false,
   // update the user with the following parameters
   {
      username: 'new-name'
   }
)
		

staticUser.getCurrentUser()(forceFetch){Promise.<User>}

user.js, line 180
Fetches the user profile based on the current persist session option. The behaviour of each persist session option is explained below.
1) When a session is persisted using cookie(browser side cookie), access_token would be extracted from it and a call to Built.io Backend would be made to fetch the whole user profile.
2) When a session is persisted using localStorage, the user profile would be fetched from it and returned.
3) When forceFetch flag is set as true, the user's profile would be forcefully fetched from built.(Ignores persist session option)
Name Type Description
forceFetch Boolean Set the flag to true if you want to forcefully fetch the user's profile from Built.io Backend (Optional and defaults to false)
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var User = Built.App('blt5d4sample2633b').User;  
User.getCurrentUser()
.then(function(user){
   console.log(user.toJSON();
})

 OR 

User.getSession()
.then(function(user){
   console.log(user.toJSON())
})

staticUser.getCurrentUserPresence(){Promise.<Presence>}

realtime.js, line 1605

[Only avaliable with realtime plugin]

Fetches the currently logged-in user's presence details
Throws:
new Error("Uid not found");
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User returns a 'User' constructor
var app = Built.App('blt5d4sample2633b').enableRealtime();
var User =  app.User

User
.getCurrentUserPresence()
.then(function(presence){
   console.log(presence.toJSON()); // Currently logged in user's presence
   // Refer presence module for more methods
});
	

staticUser.isAuthenticated(){Boolean}

user.js, line 166
Checks whether the user is currently logged in. The method returns 'true' if 'access_token' is already set.
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var User = Built.App('blt5d4sample2633b').User;
User.isAuthenticated(); // returns true/false

staticUser.off(event, callback){User}

realtime.js, line 1755

[Only avaliable with realtime plugin]

This function unregisters one or all event listener(s) from User constructor.

Name Type Description
event String The event whose listener needs to be unregistered [Optional]
callback function The callback function used while registering [Optional]
Throws:
  • new Error('Callback function to be removed is missing')
  • new Error('Event name is missing');
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User returns a 'User' constructor
var app = Built.App('blt5d4sample2633b').enableRealtime();
var User = app.User;

function cb(data){
   console.log(data);
}
// Sets up a listener for create event
User.on('delete',cb);   

// Sets up a listener for broadcast event
User.on('broadcast',cb);  

// Specifically removes the delete listener
User.off('delete',cb); 

// Removes all listeners on Person
User.off();           

// Removes all callbacks attached for delete event on this resource
User.off('delete');  

// Throws "Event name is missing"
User.off(cb)            

staticUser.on(event, callback){User}

realtime.js, line 1410

[Only avaliable with realtime plugin]

This function registers an event listener on User constructor.

Given below is the list of supported events.

  • Create
  • Create event is triggered when a new application user is created on this application. Registered callback is invoked with the created user's details.

  • Update
  • Update event is triggered whe the content or the ACL of any user object on this application is modified. Registered callback is invoked with the updated user's details.

  • Delete
  • Delete event is triggered when any user object on this application is deleted. Registered callback is invoked with the deleted user's details.

  • Broadcast
  • Broadcast event is triggered when a message is broadcast across all user objects. Registered callback is invoked with the broadcast message.

  • Presence
  • Presence event is triggered when a user's state is changed, i.e. when the user logs in or logs out

Name Type Description
event String The event on which listener should be registered
callback function The callback function to be invoked on event trigger
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User returns a 'User' constructor
var app = Built.App('blt5d4sample2633b').enableRealtime();
var User =  app.User;

User.on('create', function(jsonObject) {
   // newly created user's details
});
User.on('update', function(jsonObject) {
   // updated user's details
});
User.on('delete', function(jsonObject) {
   // deleted user's details
});
User.on('broadcast', function(message) {
   // The message broadcasted across all user objects
});
User.on('presence', function(presence){
   console.log(presence.toJSON()); // Currently logged-in users presence details
});
		

staticUser.refreshAccessToken(refresh_token){Promise.<User>}

user.js, line 311
This method allows you to refresh the access_token using the refresh_token
Name Type Description
refresh_token String Refresh token of the user
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
 
var app = Built.App('blt5d4sample2633b');
var User = app.User; 

User.refreshAccessToken(refresh_token)

staticUser.setSession(userJSON){App}

user.js, line 210
In scenario where developer opt to maintain session manually. He can use to method to set session in SDK. e.g In node envirnoment persist options such as localStorage, cookies etc are not avaliable. Developer can store session manually in database and restore it again using this method.
Name Type Description
userJSON object Plain JavaScript object containing user profile
Fires:
  • user:save-session event of Events
Throws:
new Error("access_token not found in user object");
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var User = Built.App('blt5d4sample2633b').User
User.setSession({     // user object
   uid:'blt111sample233b',
   email: 'abc@raweng.com',
   first_name: 'ABC',
   last_name: 'PQR',
   access_token: 'XYZ'
});

activate(activationToken){Promise.<null>}

user.js, line 329
Activates an application user on Built.io Backend
Name Type Description
activationToken String The user's activation token
Fires:
  • user:activate event of Events
Throws:
new Error("Uid not logged in");
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
// 'blt111sample2423b' is uid of an User on Built.io Backend
var user = Built.App('blt5d4sample2633b').User('blt111sample2423b');
user.activate('bltbc060sample6cd7e373a834')
.then(function(res){
   // do something here
});

deactivate(){Promise.<null>}

user.js, line 361
Deletes a application user from Built.io Backend
Fires:
  • user:deactivate event of Events
Throws:
  • new Error('Authentication token not found in headers');
  • new Error("Uid not found");
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
// 'blt111sample2423b' is uid of an user on Built.io Backend 
var user = Built.App('blt5d4sample2633b').User('blt111sample2423b');
user.deactivate()
.then(function(res){
   // do something here
});

fetchUserUidByEmail(email){Promise.<User>}

user.js, line 395
Fetches the user's uid based on email address
Name Type Description
email String The email address of the user whose uid needs to be fetched
Throws:
new Error("Email not found");
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var user = Built.App('blt5d4sample2633b').User();
user.fetchUserUidByEmail('abc@email.com')
.then(function(user){
   // do something here
});

fetchUserUidByFacebookUserId(user_id){Promise.<User>}

user.js, line 430
Fetches the user's uid based on his Facebook user id
Name Type Description
user_id String Facebook's user id
Throws:
new Error("User id not found");
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var user = Built.App('blt5d4sample2633b').User();
user.fetchUserUidByFacebookUserId('abc123')
.then(function(user){
   // do something here
});

fetchUserUidByGoogleEmail(email){Promise.<User>}

user.js, line 455
Fetches the user's uid based on gmail address
Name Type Description
email String Gmail address
Throws:
new Error("Email address not found");
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance

var user = Built.App('blt5d4sample2633b').User();
user.fetchUserUidByGoogleEmail('abc123@gmail.com')
.then(function(user){
   // do something here
});

fetchUserUidByTwitter(userId){Promise.<User>}

user.js, line 480
Fetches the user's uid based on Twitter user id
Name Type Description
userId String Twitter's user id
Throws:
new Error("Twitter user_id not found");
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance

var user = Built.App('blt5d4sample2633b').User();
user.fetchUserUidByTwitterUserId('abc123')
.then(function(user){
   // do something here
});

forgotPassword(email){Promise.<User>}

user.js, line 572
Sends a reset password request on the given email address
Name Type Description
email String Valid email address
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var user = Built.App('blt5d4sample2633b').User();
user.forgotPassword('test@email.com')
.then(function(){
   // do something here
});

getLastLoginAt(){Promise.<User>}

user.js, line 809
Gets the value for last_login_at property.
Example
// 'blt5d4sample2633b' is a dummy Application API key
// 'blt111sample992b' is uid of an existing user

// app.User() returns a 'User' instance
var user = Built.App('blt5d4sample2633b').User('blt111sample992b');
user.fetch()
.then(function(user){
	 console.log(user.getLastLoginAt())
   // do something here
});

getPresence(forceFetch){Promise.<Presence>}

realtime.js, line 1629

[Only avaliable with realtime plugin]

In chat applications, you can see someone else's presence details such as "last seen" timestamp. Similar functionality could be achieved using this method. The user object on which the method is invoked retrieves that user's presence details. .
Name Type Description
forceFetch Boolean When set to true would forcesfully fetch presence details from server.
Throws:
new Error("Uid not found");
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns an instance of application user class
// 'blt111sample2211r' is uid of an object on Built.io Backend
var app = Built.App('blt5d4sample2633b').enableRealtime();
var user = app.User('blt111sample2211r');

//Fetches presence from server
user.getPresence(true) 
.then(function(presence){
   console.log(presence.toJSON()); // this user's presences details
});

var app = Built.App('blt5d4sample2633b').enableRealtime();
var user = app.User('blt111sample2211r'); // blt111sample2211r is the user's uid
user.fetch()
.then(function(user){
   console.log(user.getPresence()); 
   // Extracts '_presence' property from user object
})
	

initiateSSO(){Promise}

user.js, line 846
Initiate the SSO login mechanism

[Only avaliable in Browser]

Example
// 'blt5d4sample2633b' is a dummy Application API key
var user = Built.App('blt5d4sample2633b').User();
user.initiateSSO()

login(email, password){Promise.<User>}

user.js, line 50
Logs in the user in Built.io Backend and saves the user's session based on the chosen persist session option.
Name Type Description
email String Valid email address
password String Valid password
Fires:
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var user = Built.App('blt5d4sample2633b').User();
user.login('abc@email.com','password')
.then(function(user){
   // logged in user
});

loginWithFacebook(access_token){Promise.<User>}

user.js, line 745
Performs federated login via Facebook
Name Type Description
access_token String Access token from Facebook
Fires:
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var user = Built.App('blt5d4sample2633b').User();
user.loginWithFacebook('ya29.AHES6ZSvSaMpLeToKeNVowjHEZrJA_J0k8')
.then(function(user){
   // do something here
});

loginWithGoogle(access_token){Promise.<User>}

user.js, line 717
Performs federated login via Google
Name Type Description
access_token String Access token from Google
Fires:
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var user = Built.App('blt5d4sample2633b').User();
user.loginWithGoogle('ya29.AHES6ZSvSaMpLeToKeNVowjHEZrJA_J0k8')
.then(function(user){
   //do something here
});

loginWithSSO(ssotoken){Promise.<User>}

user.js, line 877
Login the user in backend using sso token
Name Type Description
ssotoken String ssotoken of the user
Fires:
Example
// 'blt5d4sample2633b' is a dummy Application API key
var user = Built.App('blt5d4sample2633b').User();
user.loginWithSSO(ssotoken)
.then(function(user){
   // logged in user
});

loginWithTwitter(token, token_secret, consumer_key, consumer_secret){Promise.<User>}

user.js, line 774
Performs federated login via Twitter
Name Type Description
token String Token from Twitter used to identify user
token_secret String Secret Token from Twitter used to identify user
consumer_key String Consumer key used to identify application
consumer_secret String Consumer secret key used to identify application
Fires:
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var user = Built.App('blt5d4sample2633b').User();
user.loginWithTwitter('ya29.AHES6ZSvSaMpLeToKeNVowjHEZrJA_J0k8','aMpLeToKeNVowjHEZrJA_J0k8','aMpLeToKeNVowjHEZrJA_J0k8kjfs78','aMpLeToKeNVowjHEZrJA_J0kfd878')
.then(function(user){
   // do something here
});

loginWithUsername(username, password){Promise.<User>}

user.js, line 91
Logs in the user in Built.io Backend and saves the user's session based on the chosen persist session option.
Name Type Description
username String Valid username
password String Valid password
Fires:
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var user = Built.App('blt5d4sample2633b').User();
user.loginWithUsername('username','password')
.then(function(user){
   // logged in user
});

logout(){Promise.<null>}

user.js, line 128
Logs out the user from Built.io Backend and clears the user's session
Fires:
Throws:
new Error("User not logged in");
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var user = Built.App('blt5d4sample2633b').User();
user.logout().then(function(res){
   // do something here
});

off(event, callback){User}

realtime.js, line 1800

[Only avaliable with realtime plugin]

This function unregisters one or all event listener(s) from User instance.

Name Type Description
event String The event whose listener needs to be unregistered [Optional]
callback function The callback function used while registering [Optional]
Throws:
  • new Error('Callback function to be removed is missing')
  • new Error('Event name is missing');
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns an instance of application user class
// 'blt111sample2211r' is uid of an object on Built.io Backend
var app = Built.App('blt5d4sample2633b').enableRealtime();
var user = app.User('blt111sample2211r');

function cb(data){
   console.log(data);
}
// Sets up a listener for create event
user.on('delete',cb);   
// Sets up a listener for broadcast event
user.on('broadcast',cb);  
// Specifically removes the delete listener
user.off('delete',cb); 
// Removes all listeners on Person
user.off();           
// Removes all callbacks attached for delete event on this resource
user.off('delete');  
// Throws "Event name is missing"
user.off(cb)            
	

on(event, callback){User}

realtime.js, line 1465

[Only avaliable with realtime plugin]

This function registers an event listener on User instance.

Given below is the list of supported events.

  • Update
  • Update event is triggered when the content and/or the ACL of a user object on this application is modified. Registered callback is invoked with the updated user's details.

  • Delete
  • Delete event is triggered when a user object on this application is deleted. Registered callback is invoked with the deleted user's details.

  • Broadcast
  • Broadcast event is triggered when a message is broadcast over this user object. Registered callback is invoked with the broadcast message.

Name Type Description
event String The event on which listener should be registered
callback function The callback function to be invoked on event trigger
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns an instance of application user class
// 'blt111sample2211r' is uid of an object on Built.io Backend
var app = Built.App('blt5d4sample2633b').enableRealtime();
var user = app.User('blt111sample2211r'); 

user.on('update', function(jsonObject) {
   // updated user's details
});
user.on('delete', function(jsonObject) {
   // deleted user's details
});
user.on('broadcast', function(message) {
   // The message broadcasted across this user object
});
		

refreshAccessToken(refresh_token){Promise.<User>}

app.js, line 501
Refresh the user access_token in backend using refresh_token
Name Type Description
refresh_token String refresh_token of the user
Example
// 'blt5d4sample2633b' is a dummy Application API key
var user = Built.App('blt5d4sample2633b').User();
return user.refreshAccessToken(refresh_token)
.then(function(user){
   // logged in user
});
OR
var builtApp = Built.App('blt5d4sample2633b').persistRefreshToken()
var user     = builtApp.User();
return user.refreshAccessToken()
.then(function(user){
   // logged in user
});

register(email, password, password_confirm, extra_fields){Promise.<User>}

user.js, line 518
Registers the user on Built.io Backend
Name Type Description
email String Valid email address
password String Valid password
password_confirm String Valid password
extra_fields Object Extra field that need to be set on user registration (Optional)
Fires:
  • user:register event of Events
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
 
var user = Built.App('blt5d4sample2633b').User();

user.register("John@email.com","password","password",{
   username: "John" 
})
.then(function(user) {
   console.log(user.toJSON())
});

Setting extra fields
user.register("John@email.com","password","password", {
   first_name: 'John',
   last_name: 'Gates'
})
.then(function(user) {
   console.log(user.toJSON())
});

resetPassword(password, confirmPassword, resetToken){Promise.<null>}

user.js, line 604
Use this method to reset the application user's password
Name Type Description
password String New password
confirmPassword String Same password for confirmation
resetToken String Reset token received on forgot password request
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
var user = Built.App('blt5d4sample2633b').User();
user.resetPassword('abc123', 'abc123', 'bltadummy390b5fbb4e')
.then(function(){
   // do something here
});

updateUserProfile(updateObject){Promise.<User>}

user.js, line 643
Updates the user profile
Name Type Description
updateObject Object Javascript object containing updated values
Throws:
new Error('Uid not found');
Example
// 'blt5d4sample2633b' is a dummy Application API key
// app.User() returns a 'User' instance
// 'bltba9asample9e741' is uid of an User on Built.io Backend
var user = Built.App('blt5d4sample2633b').User('bltba9asample9e741');
user.updateUserProfile({
   email      : "john@email.com",
   first_name : "john",
   last_name  : "joseph",
})
.then(function(user) {
   //do something here
});