Search…
Accounts

Accounts

Adds custom account registration, authentication, and verification. Import
1
const Accounts = org.objects.accounts;
2
// or import Accounts from 'accounts';
3
4
// find first readable account.
5
Accounts.find().paths('email').next().email;
6
7
// script principal is an Account instance.
8
script.principal.update('name.first', 'Myself');
Copied!
Methods

failAuth()

Record an audit record failed authentication attempt in the logs. Developers should call this after a custom authentication failure. This will increment the auth attempts counter and lock the account if required. Always throws either kInvalidCredentials or kAccountLocked.
Additionally, an account locked notification is sent to the account holder if the account is locked.
Arguments
  • email (String) The account login email address.

login(payload, options)

Enables account login through a script. Use in conjunction with preAuth and failAuth to use the built-in authentication failure lock-out mechanism.
Arguments
  • payload (Object) Uses the same options as the Login endpoint. Though password may be omitted if the passwordLess options is set.
  • options (Object)
    • passwordLess (Bool) If true, skips password check.
    • verifyLocation (Bool) Defaults to true. When false, 2fa based on location md.fingerprint is completely ignored. Useful for SSO scenarios where 2fa would presumably be handled by the identify provider.
Returns
principal (Object)
  • _id (ObjectId) The identifier of the principal who called the script
  • email (String) The principal's email address
  • name (Object)
    • first (String) The principal's first name
    • last (String) The principal's last name
  • roles (ObjectId[]) A list of the principal's assigned org roles
accounts.login() is only available in Route scripts.

preAuth(email)

Checks to ensure the account exists and is not locked. throws kInvalidCredentials or kAccountLocked.
Arguments
  • email (String) The account login email address.
Returns
  • account (Account) The Account object as read by the account itself.

register(payload, options)

Enables account provisioning through a script, bypassing the org's self-registration setting.
This version requires that a request be present and must be called from a route.
Arguments
  • payload (Object) Uses the same options as the Registration endpoint.
  • options (Object)
    • skipVerification (Bool) Set new account state to 'verified'. Normally, initial account state is 'unverified' and an account is verified through an email link that includes a verification token. Unverified accounts cannot create connections or be connection targets.
    • skipActivation (Bool) Skip activation when an org is configured to require activation prior to login.
    • skipNotification (Bool) Suppress provisioned account password reset welcome email for newly provisioned accounts.
    • requireMobile (Bool) Defaults to true. If false, an account can be created without a mobile number.
    • requireMobile (Bool) Defaults to true. If false, an account can be created without a mobile number.
    • verifyLocation (Bool) When provisioning an account whose caller is the target of the account creation, the md.fingerprint cookie will be created and the current location verified automatically.
Returns
  • account (Account) The account object as read by the newly registered account holder.

provision(payload, options)

Offline account provisioning.
Arguments
  • payload (Object) Uses the same options as the Registration endpoint.
  • options (Object)
    • skipActivation (Bool) Skip activation when an org is configured to require activation prior to login.
    • sendWelcomeEmail (Bool) Set to false to suppress provisioned account password reset welcome email.
Returns
  • account (Account) The account object as read by the newly registered account holder.

createAuthToken(apiKey, subject, options)

See Token Authentication and Scoping for more information about scopes and jwt claims.
Creates a JWT access token used for scoped access the api.
Arguments
  • apiKey (String) The api key of the issuing application. Generate API Key
  • subject (String|ObjectID) The account identifier or email address for which the token is issued. Using the token will authenticate the caller as the subject.
  • options (Object)
    • activatesIn (Number) Optional number of seconds until the token activates. Incompatible with validAt, and expiresIn must exist to use this option.
    • validAt (Date) The date when the token activates. Incompatible with activatesIn, and expiresIn must exist to use this option.
    • expiresIn (Number) Optional number of seconds the token will be active, between 1 and the app's authDuration setting (typically 900). Incompatible with permanent, and defaults to authDuration.
    • grant (Number) Increases the grant level for all operations. Use with extreme care.
    • maxUses (Number) Limits the number of times the token can be authorized. Sets the 'jti' claim, so limited-use tokens can be revoked.
    • permanent (Bool) If true, creates an auth token that can be used forever and can be revoked by token id or by regenerating the app's RSA key pair. Incompatible with expiresIn.
    • roles (ObjectID[]) Additional roles granted to the token subject at runtime.
    • scope (String[]) Scopes to which the token is limited. If no scopes are passed, [] is assumed, which renders the token next to useless unless there are scoped roles.
    • skipAcl (Bool) Set to true to bypass Object defaultAcl for matching objects. A grant is still required to allow property access. Use with extreme care.
    • bypassCreateAcl (Bool) Set to true to bypass an Object createAcl. Use with extreme care.

decodeAuthToken(token)

Decodes an auth token into a human-readable JSON document.
Arguments
  • token (String) The JWT access token.
Returns token (Object) The decoded JWT access tokenJSON
1
{
2
"aud": "https://api.dev.medable.com/example/v2",
3
"cortex/gnt": 4,
4
"cortex/scp": [
5
"object.read.account.58ffcf06f0d11f3788826fcf.name",
6
"object.read.c_messages.*.c_subject"
7
],
8
"cortex/skp": true,
9
"exp": 1498674945,
10
"iat": 1498674045,
11
"iss": "H2gFRtKGyLKvSEdOf5aYpf",
12
"sub": "58ffcf06f0d11f3788826fcf"
13
}
Copied!

authorizeToken(token)

Authorizes an access token and returns the resulting account principal. Typically, calls into the api are already authenticated (using the Authorization request header). This method exists mainly for developer use in debugging token authentication and scoping.
Arguments
  • token (String) The JWT access token.
Returns principal (Object)

revokeAuthToken(tokenOrId)

Revoke a permanent or limited-use auth token by token or jti. Only tokens creates using the permanent or maxUses options can be revoked.
Arguments
  • tokenOrId (String|ObjectID) The JWT access token or jti claim value.
Returns revoked (Bool) True is revoked, false if the token does not exist.

getSubjectTokens(apiKey, subject)

Retrieves details of active permanent and limited-use auth tokens for a subject.
Arguments
  • apiKey (String) The api key of the issuing application.
  • subject (String|ObjectID) The account identifier or email address for which the token was issued.
Returns details[] (Object[])
  • jti (String) The unique token identifier
  • last_accessed (Date) The date the token was last authorized (does not exist until the first access)
  • times_accessed (Number) The number of times the token was authorized (does not exist for limited-use tokens)
  • uses_remaining (Number) The remaining number of times the token can be authorized
JSON
1
[
2
{
3
"_id": "59486e7f53c603e8688cb5f7",
4
"last_authorized": "2017-06-28T17:10:26.249Z",
5
"times_authorized": 304
6
},
7
{
8
"_id": "5953ebc9749219f1a2eedc57",
9
"times_authorized": 0
10
},
11
{
12
"_id": "595415684cffa322569c4820",
13
"expires_at": "2017-06-28T21:00:28.000Z",
14
"uses_remaining": 3
15
}
16
]
Copied!

revokeSubjectTokens(apiKey, subject)

Revokes all permanent or limited-use tokens for a subject.
Arguments
  • apiKey (String) The api key of the issuing application.
  • subject (String|ObjectID) The account identifier or email address for which the token was issued.
Returns revoked (Number) The count of revoked tokens.

inAuthScope(compiledScope, scopeString, matchPrefix)

Checks if a scope string is within the purview of a compiled scope.
Arguments
  • compiledScope (Object[]) The compiled principal scope. Can be retrieved through script.principal.scope or org.objects.accounts.authorizeToken(token).scope.
  • scopeString (String) The scope string to check (eg. object.read.c_messages).
  • matchPrefix (String) Defaults to true. If false, requires an exact match all the way down the chain. For example, object.read.c_messages will not match a compiled scope with object.read.c_messages.*.c_subject when false.
Returns in_scope (Boolean) True if the scopeString is within the compiled scope.
Examples
Creating and testing auth scope.JavaScript
1
require('should');
2
3
const token = org.objects.account.createAuthToken(
4
'H2gFRtKGyLKvSEdOf5aYpf',
6
{
7
scope: [
8
"object.read.c_messages.*.c_subject"
9
]
10
}
11
)
12
13
const principal = org.objects.account.authorizeToken(token);
14
15
org.objects.account.inAuthScope(principal.scope, 'object.read.c_messages', true).should.equal(true);
16
17
org.objects.account.inAuthScope(principal.scope, 'object.read.c_messages', false).should.equal(false);
Copied!
Custom registration: Here we have an example custom registration script. It takes a request body that contains the necessary properties to register an account, registers that account, logs that user in, and returns the account object.Custom Registration
1
import accounts from 'accounts';
2
import request from 'request';
3
4
/* example request body
5
{
6
7
name: {
8
first: 'Gordon',
9
last: 'Downie'
10
},
11
mobile: '+15555555555',
12
password: 'new orleans is sinking, man, and i don\'t wanna swim',
13
roles:[customRoleId]
14
}
15
*/
16
17
const options = {
18
skipVerification: true,
19
skipActivation: true,
20
skipNotification: true,
21
verifyLocation: true
22
};
23
24
let account = accounts.register(request.body, options);
25
26
// verifyLocation ensures the caller is logged in without a kNewLocation fault.
27
let principal = accounts.login({
28
email: account.email
29
}, {
30
passwordLess: true
31
});
32
33
return account;
Copied!
Custom authentication: Here we have a custom authentication script that checks with a third-party authentication system, and if successful authenticates the user. This type of custom authentication can be useful for single sign-on use cases or where user identity is managed via an external provider.Custom Authentication
1
import req from 'request';
2
import accounts from 'accounts';
3
import http from 'http';
4
5
const payload = {
6
email: req.body.email
7
};
8
9
// this checks for account existence and lock. should be called prior to custom authentication.
10
let account = accounts.preAuth(req.body.email);
11
12
// custom authentication here (token is some sort of 3rd party auth token).
13
let response = http.post('https://my.login.com/auth_me', {token: req.body.token});
14
15
// if authentication fails, increment attempts, fail and throw.
16
if (response.body.err) {
17
accounts.failAuth(req.body.email, response.body.err);
18
}
19
20
// was there a 2fa location verification code attached?
21
if (req.body.code) {
22
payload.location = {
23
verificationToken: req.body.code
24
};
25
}
26
27
// login without a password. note that the account 'clientKey' cannot be attached when no password is used.
28
return accounts.login(payload, {
29
passwordLess: true
30
});
Copied!
Last modified 2mo ago