Esempio n. 1
0
def login_user(request,
               service='google',
               save_redirect=None,
               token=None,
               is_force=None):
    if service and len(service) > 32:
        # Probably some injection spam -_-
        raise httpexceptions.HTTPBadRequest(detail="invalid service")

    user_id = get_user_id(request)

    if user_id and not is_force:
        return user_id

    if token and request.features.get('token_login'):
        # Only enabled during testing
        u = get(token=token)
        if u:
            login_user_id(request, u.id)
            return u.id

    request.session['next'] = save_redirect
    request.session.save()

    oauth = service_registry[service or 'google'](request)
    next, state = oauth.auth_url()  # is_force=is_force
    request.session['oauth_state'] = state
    raise httpexceptions.HTTPSeeOther(next)
Esempio n. 2
0
    def pricing(self):
        self.c.user = api.account.get_user(self.request)

        p = self.c.user and self.c.user.payment
        if p and p.id == 'namecheap':
            return httpexceptions.HTTPSeeOther(
                'https://www.namecheap.com/apps/subscriptions')

        monthly = ('monthly', 'Pay Monthly', [
            Plan.get('starter'),
            PlanGroup.get('agency-10'),
            PlanGroup.get('enterprise'),
        ])
        yearly = ('yearly', 'Pay Yearly (2 month discount)', [
            Plan.get('starter-yr'),
            PlanGroup.get('agency-10-yr'),
            PlanGroup.get('enterprise-yr'),
        ])

        self.c.plans = []

        if self.c.user and self.c.user.payment and self.c.user.payment.id == 'namecheap':
            self.c.plans.append(yearly)
        else:
            self.c.plans.append(monthly)

        if 'yearly' in self.request.params:
            self.c.plans = [yearly, monthly]

        return self._render('pricing.mako')
Esempio n. 3
0
def index(request):
    """ The only app-routed view which delegates the rest of the API-related
    functionality. Collates the API result into the final payload and response
    object.

    This is bypassed if the API method is processed through a @handle_api view.
    """
    data = {
        'status': 'ok',
        'code': 200,
        'messages': [],
        'result': {},
    }

    format = request.params.get('format', 'json')
    if format not in ('json', 'redirect'):
        return httpexceptions.HTTPBadRequest('Invalid format requested: %s' %
                                             format)

    encode_settings = {'cls': SchemaEncoder}
    if request.params.get('pretty'):
        encode_settings['sort_keys'] = True
        encode_settings['indent'] = 4

    next = request.params.get('next') or request.referer

    try:
        r = api_controller(request)
        if r is not None:
            data['result'] = r

    except APIControllerError as e:
        data['messages'] += [e.message]
        data['code'] = e.code
        data['status'] = 'error'

    except (APIControllerError, LoginRequired) as e:
        data['messages'] += [e.message]
        data['code'] = e.code
        data['status'] = 'error'

        if isinstance(e, LoginRequired):
            next = e.next_url(request, next=next)

    data['messages'] += request.pop_flash()

    if format == 'redirect':
        for message in data['messages']:
            # Copy request-level messages to session storage to be displayed on
            # redirect.
            request.session.flash(message)
        return httpexceptions.HTTPSeeOther(next or '/')

    body = json.dumps(data, **encode_settings).encode()
    return Response(body, content_type='application/json', status=data['code'])
Esempio n. 4
0
        def wrapped(self):
            if 'method' not in self.request.params:
                return fn(self)

            try:
                api_controller(self.request, method_whitelist=method_whitelist)

            except APIControllerError as e:
                self.request.flash(e.message)
                return fn(self)

            finally:
                # FIXME: This is repeated
                for message in self.request.pop_flash():
                    # Copy request-level messages to session storage.
                    self.request.session.flash(message)

            next = self.request.params.get(
                'next') or self.request.referer or '/'
            return httpexceptions.HTTPSeeOther(next)
Esempio n. 5
0
def connect_oauth(request, oauth, user_required=False):
    user, account = get_account(request,
                                service=oauth.id,
                                user_required=user_required)

    code = request.params.get('code')
    if not code:
        raise httpexceptions.HTTPBadRequest('Missing code.')

    error = request.params.get('error')
    if error:
        raise APIError('Failed to connect: %s' % error)

    url = request.current_route_url().replace(
        'http://', 'https://')  # We lie, because honeybadger.

    try:
        token = oauth.auth_token(url)
    except InvalidGrantError:
        # Try again.
        raise httpexceptions.HTTPSeeOther(
            request.route_path('account_login', service=oauth.id))
    except OAuth2Error as e:
        raise APIError(
            "Unexpected authentication error, please try again: %s" %
            e.description)
    except ValueError as e:
        raise APIError("Unexpected response error, please try again: %s" % e)

    remote_id, email, display_name, remote_data = oauth.query_user()
    if not user:
        # New user
        user = get_or_create(
            email=email,
            service=oauth.id,
            token=token,
            display_name=display_name,
            remote_id=remote_id,
            remote_data=remote_data,
        )
        account = user.accounts[0]
    elif not account:
        # New account
        account = model.Account.create(
            display_name=display_name or user.display_name,
            user=user,
            oauth_token=token,
            service=oauth.id,
            remote_id=remote_id,
            remote_data=remote_data,
        )
    else:
        # Update account
        account.oauth_token = token
        account.remote_id = remote_id
        account.remote_data = remote_data
        force_skip = oauth.is_autocreate and Session.query(
            model.Report).filter_by(account_id=account.id).limit(1).count()
        if force_skip:
            # Already exists, skip autocreate.
            oauth.is_autocreate = False

    Session.commit()

    return account
Esempio n. 6
0
 def _redirect(self, *args, **kw):
     "Shortcut for returning HTTPSeeOther"
     return httpexceptions.HTTPSeeOther(*args, **kw)