<commit_before>import axios from 'axios';
import qs from 'querystring';
import config from 'config';
import models from '../models';
import errors from '../lib/errors';
import roles from '../constants/roles';

const AUTHORIZE_URI = 'https://connect.stripe.com/oauth/authorize';
const TOKEN_URI = 'https://connect.stripe.com/oauth/token';

const checkIfUserIsHost = UserId =>
  models.UserGroup.find({
    where: {
      UserId,
      role: roles.HOST
    }
  })
  .then(userGroup => {
    if (!userGroup) throw new errors.BadRequest(`User ${UserId} is not a host`);
  });

const getToken = code => () => axios
  .post(TOKEN_URI, {
    grant_type: 'authorization_code',
    client_id: config.stripe.clientId,
    client_secret: config.stripe.secret,
    code
  })
  .then(res => res.data);

const createStripeAccount = data => models.StripeAccount.create({
  accessToken: data.access_token,
  refreshToken: data.refresh_token,
  tokenType: data.token_type,
  stripePublishableKey: data.stripe_publishable_key,
  stripeUserId: data.stripe_user_id,
  scope: data.scope
});

/**
 * Ask stripe for authorization OAuth
 */
export const authorize = (req, res, next) => {
  checkIfUserIsHost(req.remoteUser.id)
    .then(() => {
      const params = qs.stringify({
        response_type: 'code',
        scope: 'read_write',
        client_id: config.stripe.clientId,
        redirect_uri: config.stripe.redirectUri,
        state: req.remoteUser.id
      });

      res.send({
        redirectUrl: `${AUTHORIZE_URI}?${params}`
      });
    })
    .catch(next);
};

/**
 * Callback for the stripe OAuth
 */
export const callback = (req, res, next) => {
  const UserId = req.query.state;

  if (!UserId) {
    return next(new errors.BadRequest('No state in the callback'));
  }

  let host;
  checkIfUserIsHost(UserId)
    .then(() => models.User.findById(UserId))
    .tap(h => host = h)
    .then(getToken(req.query.code))
    .then(createStripeAccount)
    .then(stripeAccount => host.setStripeAccount(stripeAccount))
    .then(() => res.redirect(`${config.host.webapp}/?stripeStatus=success`))
    .catch(next);
};<commit_msg>redirect stripe oauth to website, instead of app (#821)<commit_after>import axios from 'axios';
import qs from 'querystring';
import config from 'config';
import models from '../models';
import errors from '../lib/errors';
import roles from '../constants/roles';

const AUTHORIZE_URI = 'https://connect.stripe.com/oauth/authorize';
const TOKEN_URI = 'https://connect.stripe.com/oauth/token';

const checkIfUserIsHost = UserId =>
  models.UserGroup.find({
    where: {
      UserId,
      role: roles.HOST
    }
  })
  .then(userGroup => {
    if (!userGroup) throw new errors.BadRequest(`User ${UserId} is not a host`);
  });

const getToken = code => () => axios
  .post(TOKEN_URI, {
    grant_type: 'authorization_code',
    client_id: config.stripe.clientId,
    client_secret: config.stripe.secret,
    code
  })
  .then(res => res.data);

const createStripeAccount = data => models.StripeAccount.create({
  accessToken: data.access_token,
  refreshToken: data.refresh_token,
  tokenType: data.token_type,
  stripePublishableKey: data.stripe_publishable_key,
  stripeUserId: data.stripe_user_id,
  scope: data.scope
});

/**
 * Ask stripe for authorization OAuth
 */
export const authorize = (req, res, next) => {
  checkIfUserIsHost(req.remoteUser.id)
    .then(() => {
      const params = qs.stringify({
        response_type: 'code',
        scope: 'read_write',
        client_id: config.stripe.clientId,
        redirect_uri: config.stripe.redirectUri,
        state: req.remoteUser.id
      });

      res.send({
        redirectUrl: `${AUTHORIZE_URI}?${params}`
      });
    })
    .catch(next);
};

/**
 * Callback for the stripe OAuth
 */
export const callback = (req, res, next) => {
  const userId = req.query.state;

  if (!userId) {
    return next(new errors.BadRequest('No state in the callback'));
  }
  let host;

  checkIfUserIsHost(userId)
    .then(() => models.User.findById(userId))
    .tap(h => host = h)
    .then(getToken(req.query.code))
    .then(createStripeAccount)
    .then(stripeAccount => host.setStripeAccount(stripeAccount))
    .then(() => res.redirect(`${config.host.website}/${host.username}/settings?stripeStatus=success`))
    .catch(next);
};
{'fraction_non_alphanumeric': 0.14958256029684602, 'fraction_numerical': 0.0006957328385899814, 'mean_word_length': 3.450980392156863, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 29, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1181178', 'n_tokens_mistral': 1450, 'n_tokens_neox': 1437, 'n_words': 302}