login

login(pxRequest, options)

Establishes a session, either by recovering one that already exists or by obtaining a new identity. What that means depends on the platform:

  • In a browser, this recovers a session from local/session storage or via postMessage from the auth origin if possible; otherwise it sends the user through the auth origin’s login/authorization pages, which redirect back to the current page once complete.

  • On Node.js (and other non-browser platforms), this has no UI to redirect through. It uses whatever setDefault() was called with (or the –dcp-identity= command-line flag, which calls setDefault for you); failing that, it loads id.keystore from the resource directory (~/.dcp by default) if present; failing that, it generates a brand new identity and persists it there for next time. Proxy-key negotiation (pxRequest/expiry options) isn’t supported through this path – only ‘$login’ (the default) is accepted.

Arguments:
  • pxRequest – The access this application is requesting – see normalizePxRequest() for the accepted shapes. Defaults to ‘$login’ (full access, tied to the user’s own identity). Browser only; must be ‘$login’ (or omitted) on other platforms.

  • options – Optional. A plain number is shorthand for { pxExpireSeconds: options }; a Date is shorthand for { pxExpireDate: options }.

  • options.nextUrl (string) – Browser only. Page to redirect back to once authorization completes. Defaults to the current page.

  • options.sessionOrigin (string) – Browser only. Origin allowed to receive the session back over postMessage. Defaults to the current origin.

  • options.pxExpireSeconds (number) – Browser only. How long the resulting proxy key should remain valid for, in seconds. Defaults to 86400 (one day) if neither this nor pxExpireDate is given.

  • options.pxExpireDate (Date) – Browser only. Absolute expiry for the resulting proxy key, instead of a duration.

Return type:

Promise<void>

Note

In a browser, this function’s own source comments warn that the page may reload during this process: when a fresh login is required, login() navigates away to the auth origin and back rather than resolving in place, so any state your application needs to survive that round trip should be saved (e.g. to storage) before calling it, and restored after DOMContentLoaded on return.

Example (browser)

const identity = require('dcp/identity');

await identity.login('job.exec');
console.log('Logged in as', identity.get().address);

Example (Node.js)

const identity = require('dcp/identity');

identity.setDefault('<api-key>'); // or a keystore filename, or a JSON-encoded keystore string
await identity.login();
console.log('Logged in as', identity.get().address);