def decorated_function(env, csrf_clerk):
            get_vars = util.retrieve_get_vars(env)
            post_vars = util.retrieve_post_vars(env)
            session = turbo_session.get_session(env)
            account = turbo_session.retrieve_oauth_account(session)

            # Start OAuth
            cookie_set = int(get_vars.get('cookie_set', [0])[0])
            # Failed to set cookie, tell user to enable cookies
            if(account is None and min_access_level >= ACL.turbo and
               cookie_set == 1):
                return error_view('Login Error',
                                  'Failed to create session. Try to enable '
                                  ' cookies for this site.')

            elif(account is None and min_access_level >= ACL.turbo):
                # Show Auth Error in headless mode
                if(headless):
                    return error_view('Auth Error', 'You are not logged in.',
                                      nav, headless=True)

                redirect_uri = turbo_views['oauth-callback'].uri
                oauth = turbo_session.OAuth2Session(
                    config.mastodon.client_id,
                    redirect_uri=redirect_uri,
                    scope=config.mastodon.scope)
                authorization_url, state = oauth.authorization_url(
                    config.mastodon.authorize_url,
                    turbo_session.generate_state(env, csrf_clerk)
                )

                status = '307 Temporary Redirect'
                response_body = ''
                response_headers = [('Location', str(authorization_url))]

            # Redirect to url without cookie_set parameter
            elif(cookie_set == 1):
                status = '307 Temporary Redirect'
                response_body = ''
                response_headers = [
                    ('Location', util.build_url(env['PATH_INFO']))
                ]

            # Display View
            else:
                user = User.create(account)
                access_level = User.get_access_level(user)
                if access_level < min_access_level:
                    return error_view('Missing Privileges',
                                      'You do not have the required '
                                      'permissions to access this.',
                                      access_level=access_level)
                response_body, response_headers, status = func(
                    env, get_vars, post_vars, csrf_clerk, session, user
                )

            return response_body, response_headers, status
Example #2
0
def generate_state(env, csrf_clerk):
    # if redirect_to is set, remember that instead of the current location
    get_vars = retrieve_get_vars(env)
    location = get_vars.get('redirect_to', [env['PATH_INFO']])[0]

    csrf_token = csrf_clerk.register('oauth-authorization')

    # oauth state is a list of a csrf token and the location
    oauth_state = [csrf_token, location]

    # return oauth_state jsonified and encrypted
    return encrypt(json.dumps(oauth_state))
def oauth_callback_view(env, csrf_clerk):
    get_vars = util.retrieve_get_vars(env)
    redirect_uri = turbo_views['oauth-callback'].uri
    authorization_response = redirect_uri + '?' + env['QUERY_STRING']
    try:
        oauth = turbo_session.OAuth2Session(
            config.mastodon.client_id,
            redirect_uri=redirect_uri,
            scope=config.mastodon.scope
        )
        oauth_state = turbo_session.retrieve_oauth_state(
            get_vars.get('state', [''])[0]
        )
        if(oauth_state and
           csrf_clerk.validate('oauth-authorization', oauth_state[0])):
            token = oauth.fetch_token(
                config.mastodon.token_url,
                authorization_response=authorization_response,
                client_secret=config.mastodon.client_secret
            )
            session_token = turbo_session.create_session(token)

            if(session_token is not None):
                redirect_to = str(oauth_state[1])
                if redirect_to.startswith('/'):
                    redirect_to = util.build_url(redirect_to,
                                                 query={'cookie_set': 1})

                status = '307 Temporary Redirect'
                response_body = ''
                response_headers = [
                    util.set_cookie_header('TB_SESSION', session_token),
                    ('Location', redirect_to)
                ]
            else:
                return error_view('Internal Error',
                                  'Failed to create session.')
        else:
            return error_view('CSRF Verfication failed',
                              'Failed to authorize account due to a CSRF '
                              'verfication error, try again.')

    except OAuth2Error as error:
        # Might indicate a "deny" on granting access to the app
        util.print_exception('OAuth 2.0 Error occured: ', error)
        return error_view('OAuth Error',
                          'Failed to authorize account, try again.')
    else:
        # Normal function return without errors
        return response_body, response_headers, status
Example #4
0
def patreon_theatre_callback_view(env, csrf_clerk):
    redirect_uri = turbo_views['patreon-theatre-callback'].uri
    authorization_response = redirect_uri + '?' + env['QUERY_STRING']
    get_vars = util.retrieve_get_vars(env)
    try:
        oauth = turbo_session.OAuth2Session(config.patreon.client_id,
                                            redirect_uri=redirect_uri,
                                            scope=config.patreon.scope)
        oauth_state = turbo_session.retrieve_oauth_state(
            get_vars.get('state', [''])[0])
        if oauth_state and csrf_clerk.validate('oauth-authorization',
                                               oauth_state[0]):
            oauth.fetch_token(config.patreon.token_url,
                              authorization_response=authorization_response,
                              client_secret=config.patreon.client_secret)
            patreon_user = patreon.get_current_user(oauth)
            if patreon_user is not None and len(patreon_user) > 0:
                memberships = patreon_user[0].get('memberships', [])
                session_token = None
                for item in memberships:
                    cents = item.get('currently_entitled_amount_cents', 0)
                    campaign_id = item.get('campaign', [{}])[0].get('id', '')
                    if (cents >= config.patreon.theatre_cents
                            and campaign_id == config.patreon.campaign_id):
                        session_token = patreon.create_session()

                if session_token is None:
                    dollars = str(config.patreon.theatre_cents // 100)
                    return error_view(
                        'Insufficient pledge',
                        'We could not verify that you are '
                        'pledging $' + dollars + ' to the '
                        'Video Games AWESOME Patreon.')

                redirect_to = turbo_views['theatre'].uri

                status = '307 Temporary Redirect'
                response_body = ''
                response_headers = [
                    util.set_cookie_header('TB_PATREON_SESSION',
                                           session_token,
                                           max_age=config.expiration_interval),
                    ('Location', redirect_to)
                ]
            else:
                return error_view('Unexpected error',
                                  'Failed to retrieve Patreon user details.')
        else:
            return error_view(
                'CSRF Verfication failed',
                'Failed to authorize Patreon account due to a '
                'CSRF verfication error, try again.')

    except OAuth2Error as error:
        # Might indicate a "deny" on granting access to the app
        logger.info(f'OAuth 2.0 Error occured: {error}',
                    exc_info=config.debug_mode)
        return error_view('OAuth Error',
                          'Failed to authorize Patreon account, try again.')
    else:
        # Normal function return without errors
        return response_body, response_headers, status