How do I store the logged in users in my own DB?

HI @ markd

Sounds like a good idea as if the upsert into our DB fails we could just throw away the access token and avoid logging the user in, asking them to retry. This would then guarantee every logged in user has a user record in our DB.

Having said that, our applications are all SPAs currently so we wouldn’t reliably be able to deny the login if the upsert into our DB failed as the access token would have already been sent to the browser.

I guess this is a good use case for rules then e.g.

function syncUser(__user, __context, __callback) {
  const fetch = require('node-fetch');

  const API_GATEWAY_HOST = 'https://example.com/api';

  const main = async (user, context) => {
    // *upsert* the user into our DB
    const response = await fetch(`${API_GATEWAY_HOST}/users/`, {
      method: 'PUT',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
       Authorization: 'Bearer ${ACCESS_TOKEN}'
      },
      body: JSON.stringify({
        id: user.user_id,
        roles: user.roles,
        email: user.email,
        emailVerified: user.email_verified,
        name: user.name,
        firstName: user.first_name,
        lastName: user.last_name,
        nickname: user.nickname,
        picture: user.picture,
        locale: user.locale,
        updatedAt: user.updated_at,
        createdAt: user.created_at,
      }),
    });
    if (!response.ok) {
      throw new Error(`Failed to sync user: ${response.status}`);
    }
    return [user, context];
  };

  main(__user, __context)
    .then(([user, context]) => __callback(null, user, context))
    .catch(ex => __callback(ex));
}
1 Like