{"size": 1571, "ext": "js", "max_stars_repo_path": "packages/marko-web-identity-x/routes/login.js", "max_stars_repo_name": "parameter1/base-cms", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/marko-web-identity-x/routes/login.js", "max_issues_repo_name": "parameter1/base-cms", "max_issues_repo_issues_event_min_datetime": "2021-01-08T04:35:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:17:24.000Z", "max_forks_repo_path": "packages/marko-web-identity-x/routes/login.js", "max_forks_repo_name": "parameter1/base-cms", "max_forks_repo_forks_event_min_datetime": "2021-01-12T15:46:19.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-23T17:54:16.000Z"}
{"max_stars_count": null, "max_issues_count": 104, "max_forks_count": 8, "avg_line_length": 24.1692307692, "max_line_length": 97, "alphanum_fraction": 0.635264163}
const gql = require('graphql-tag');
const { asyncRoute } = require('@parameter1/base-cms-utils');
const callHooksFor = require('../utils/call-hooks-for');
const userFragment = require('../api/fragments/active-user');

const buildQuery = () => gql`
  query LoginCheckAppUser($email: String!) {
    appUser(input: { email: $email }) {
      ...ActiveUserFragment
    }
  }
  ${userFragment}
`;

const createUser = gql`
  mutation LoginCreateAppUser($email: String!) {
    createAppUser(input: { email: $email }) {
      ...ActiveUserFragment
    }
  }
  ${userFragment}
`;

const sendLoginLink = gql`
  mutation LoginSendLoginLink($input: SendAppUserLoginLinkMutationInput!) {
    sendAppUserLoginLink(input: $input)
  }
`;

module.exports = asyncRoute(async (req, res) => {
  const { identityX, body } = req;
  const {
    email,
    authUrl,
    redirectTo,
    appContextId,
  } = body;
  const variables = { email };
  const query = buildQuery();
  const { data } = await identityX.client.query({ query, variables });
  let { appUser } = data;


  if (!appUser) {
    // Create the user.
    const { data: newUser } = await identityX.client.mutate({ mutation: createUser, variables });
    appUser = newUser.createAppUser;
  }

  // Send login link.
  await identityX.client.mutate({
    mutation: sendLoginLink,
    variables: {
      input: {
        email: appUser.email,
        authUrl,
        redirectTo,
        appContextId,
      },
    },
  });
  await callHooksFor(identityX, 'onLoginLinkSent', { req, user: appUser });
  return res.json({ ok: true });
});
