Devise Token Auth Client
Installation
yarn add devise-token-auth-client
Usage
This client is based on Axios. See the Axios Docs for basic usage instructions.
The instructions that follow show the usage of this client with Devise Token Auth.
Initialization
The ApiClient
during the setup phase of your app.
import ApiClient from 'devise-token-auth-client';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
async function render = Component => {
// create the client instance
const client = new ApiClient({
baseUrl: 'https://my-api.com'
});
// wait for the client to initialize before use. this will ensure that the
// user session is available for the initial render.
await client.isInitialized;
ReactDOM.render(
<Component client={client} />,
document.getElementById('app')
);
}
render(App);
Usage
Client Instance Methods
emailSignUp
Create a new user account.
When email confirmation is not enabled, this will also authenticate the new user.
Usage |
|
||||||||||||
Params |
|
||||||||||||
Return |
This method returns a Promise . The success and error resolutions are
described below.
|
||||||||||||
Success |
|
||||||||||||
Error |
|
emailSignIn
Authenticate an existing user.
Usage |
|
|||||||||
Params |
|
|||||||||
Return |
This method returns a Promise . The success and error resolutions are
described below.
|
|||||||||
Success |
|
|||||||||
Error |
|
oAuthSignIn
Sign in using a 3rd party OAuth provider (i.e. Github, Facebook, etc.). This method will open a popup window that allows the user to authenticate using the 3rd party service. Once the 3rd party authentication is complete, the user will be signed in to our own API and a session will be created in the browser. A new user will be created if no user exists matching the ID and provider of the 3rd party account.
Usage |
|
||||||
Params |
|
||||||
Return |
This method returns a Promise . The success and error resolutions are
described below.
|
||||||
Success |
|
||||||
Error |
|
signOut
Clear the current user's session and user state. This method attempts to sign out with the API, but the browser session and state is always cleared, even in the case of API failure.
Usage |
|
Params | None |
Return |
This method returns a Promise . This promise should always
resolve with no payload.
|
Success |
|
passwordResetRequest
Sends an email to a user that has forgotten their password. The email will contain a link that allows them to reset their password.
Usage |
|
||||||
Params |
|
||||||
Return |
This method returns a Promise . The success and error resolutions are
described below.
|
||||||
Success |
|
||||||
Error |
|
Dispatch Actions
When configured to work with a dispatch
action, the following actions will be
dispatched at the given times.
Action Type | Example |
---|---|
AUTH_INITIALIZED
Dispatched after the client has initialized. At this point, the
|
|
UPDATE_AUTH_CREDSDispatched whenever the client credentials have been updated. |
|
CLEAR_AUTH_CREDSDispatched when the auth creds are cleared. This will happen on sign-out, or when a token is returned as invalid. |
|
INVALID_CREDS
Dispatched when a |
|
UPDATE_USERDispatched when the current user data is updated. This will happen on login. |
|
VALIDATE_TOKEN_STARTDispatched before the request to validate the user's session credentials with the API starts. |
|
VALIDATE_TOKEN_SUCCESSDispatched when the user's session credentials are successfully validated with the API. |
|
VALIDATE_TOKEN_ERRORDispatched when the user's session credentials are rejected by the API. |
|
EMAIL_SIGNUP_START
Dispatched at the start of an |
|
EMAIL_SIGNUP_SUCCESS
Dispatched when the |
|
EMAIL_SIGNUP_ERROR
Dispatched when the |
|
EMAIL_SIGNUP_CONFIRMATION_SUCCESSDispatched when a user arrives from an email confiramtion link, and the confirmation is successful. |
|
EMAIL_SIGNUP_CONFIRMATION_ERRORDispatched when a user arrives from an email confiramtion link, and the confirmation fails. |
|
EMAIL_SIGNIN_START
Dispatched at the start of the |
|
EMAIL_SIGNIN_SUCCESS
Dispatched when |
|
EMAIL_SIGNIN_ERROR
Dispatched when |
|
SIGN_OUT_START
Dispatched when the |
|
SIGN_OUT_SUCCESS
Dispatched at the end of a successful |
|
SIGN_OUT_ERROR
Dispatched when a |
|
PASSWORD_RESET_REQUEST_START
Dispatched at the start of the |
|
PASSWORD_RESET_REQUEST_SUCCESS
Dispatched at the end of a successful
|
|
PASSWORD_RESET_REQUEST_ERROR
Dispatched on failure of the |
|
PASSWORD_RESET_CONFIRMATION_SUCCESSDispatched when a user arrives from a password reset link, and the confirmation is successful. |
|
PASSWORD_RESET_CONFIRMATION_ERRORDispatched when a user arrives from a password reset link, and the confirmation fails. |
|
OAUTH_SIGNIN_START
Dispatched at the start of |
|
OAUTH_SIGNIN_SUCCESSDispatched when the user has successfully authenticated with a 3rd party OAuth provider and the new user session has been created. |
|
OAUTH_SIGNIN_ERROR
Dispatched on failed |
|
PERSIST_THROUGH_REDIRECTDispatched when the client visits a confirmation redirect with the auth creds appended to the URL as querystring params. The auth creds are stored into the current session, and the browser is redirected to the same url without the auth querystring params. |
|
LOAD_AFTER_REDIRECT
Dispatched following a confirmation redirect. See the PERSIST_THROUGH_REDIRECT action
above.
|
|
Advanced Configuration
Redux
To sync with a redux store, simply pass the dispatch
and getState
methods
to the initializer.
import { createStore } from 'redux';
import ApiClient from 'devise-token-auth-client';
import reducers from './reducers';
// ...
const store = createStore(reducers);
const client = new ApiClient({
baseUrl: 'https://my-api.com',
dispatch: store.dispatch,
getState: store.getState
});
Server Side Rendering
The goal of SSR is to pre-render the initial page load of a single-page app (SPA). This is helpful to search engine crawlers that can't parse SPAs, and in some cases it offers better performance and a better user experience.
Devise Token Client supports server-side rendering (SSR). But SSR does complicate the setup. We will need to pass additional configuration params to the initializer on both the server and the client.
SSR Step 1: Initialize on the server
The server needs the following additional params for SSR:
| param | type | description |
|===|===|===|
| location
| (string) | The url for the initial render |
| redirect
| (function) | A function used by the server to redirect to a new page |
| requestCookies
| (object) | An object representation of the cookies contained in the initial request |
| setResponseCookie
| (function) | A method used to set response cookies on the server |
| clearResponseCookie
| (function) | A method used to clear a response cookie on the server |
SSR Server Config Example
This example uses Express. This example is also not sufficient to set up an actual SSR app - it only calls out the steps necessary for authentication. See [here] for a complete, working setup.
import Express from 'express';
import cookieParser from 'cookie-parser';
import { renderToStaticMarkup } from 'react-dom/server';
import { StaticRouter } from 'react-router';
import createStore from './create-store';
import ApiClient from 'devise-token-auth-client';
import HTML from './html';
import App from './app';
// init the app
const app = new Express();
// this middleware will convert the cookie string into an object
app.use(cookieParser());
app.use(async (req, res) => {
// if this is the result of an OAuth redirect, don't render anything
if (req.query.blank) {
return res.send(`<!doctype html>\nAUTHENTICATING...`);
}
const store = createStore();
const client = new ApiClient({
baseUrl: 'https://my-api.com/api',
dispatch: store.dispatch,
getState: store.getState
// SSR-specific params
requestCookies: req.cookies,
setResponseCookie: (key, val) => res.cookie(key, val),
clearResponseCookie: key => res.clearCookie(key),
redirect: url => { context.url = url },
});
// wait until auth session has loaded before rendering the page
await client.isInitialized;
// do an initial render to check for redirects
const { state: serverState, html: content } = await renderToString(
<Provider store={store} key="provider">
<StaticRouter location={req.originalUrl} context={context}>
<App />
</StaticRouter>
</Provider>,
);
// if the redirect was called anywhere in the initial render, actually
// perform the redirect here
if (context.url) {
return res.redirect(context.url);
}
// serve the rendered content to the browser
return res.send(`<!doctype html>\n${html}`);
});
SSR Step 2: Initialize on the client
The client needs the following additional params for SSR:
| param | type | description |
|===|===|===|
| location
| (string) | The url for the initial render |
| redirect
| (function) | A function used by the browser to redirect to a new page |
SSR Client Config Example
import { createStore } from 'redux';
import ApiClient from 'devise-token-auth-client';
import reducers from './reducers';
// ...
const store = createStore(reducers);
const client = new ApiClient({
baseUrl: 'https://my-api.com/api',
dispatch: store.dispatch,
getState: store.getState
});