Exemplo n.º 1
0
def login(api, config, api_root=None, analytics=True):
    """Authenticate to your Transcriptic account."""
    if api_root is None:
        # Always default to the pre-defined api-root if possible, else use
        # the secure.transcriptic.com domain
        try:
            api_root = api.api_root
        except ValueError:
            api_root = "https://secure.transcriptic.com"

    email = click.prompt('Email')
    password = click.prompt('Password', hide_input=True)
    try:
        r = api.post(
            routes.login(api_root=api_root),
            data=json.dumps({
                'user': {
                    'email': email,
                    'password': password,
                },
            }),
            headers={
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            status_response={
                '200': lambda resp: resp,
                '401': lambda resp: resp,
                'default': lambda resp: resp
            }
        )

    except requests.exceptions.RequestException:
        click.echo("Error logging into specified host: {}. Please check your "
                   "internet connection and host name".format(api_root))
        sys.exit(1)

    if r.status_code != 200:
        click.echo("Error logging into Transcriptic: %s" % r.json()['error'])
        sys.exit(1)
    user = r.json()
    token = (user.get('authentication_token') or
             user['test_mode_authentication_token'])
    user_id = user.get("id")
    feature_groups = user.get('feature_groups')
    organization = org_prompt(user['organizations'])

    r = api.get(
        routes.get_organization(api_root=api_root, org_id=organization),
        headers={
            'X-User-Email': email,
            'X-User-Token': token,
            'Accept': 'application/json'},
        status_response={
            '200': lambda resp: resp,
            'default': lambda resp: resp}
    )

    if r.status_code != 200:
        click.echo("Error accessing organization: %s" % r.text)
        sys.exit(1)
    api = Connection(email=email, token=token,
                     organization_id=organization, api_root=api_root,
                     user_id=user_id, analytics=analytics,
                     feature_groups=feature_groups)
    api.save(config)
    click.echo('Logged in as %s (%s)' % (user['email'], organization))