Пример #1
0
def complete_login(request, consumer_token, cookie, rdb_session, root_path, api_log):
    # TODO: Remove or standardize the DEBUG option
    if DEBUG:
        identity = {'sub': 6024474,
                    'username': '******'}
    else:
        handshaker = Handshaker(WIKI_OAUTH_URL, consumer_token)

        with api_log.debug('load_login_cookie') as act:
            try:
                rt_key = cookie['request_token_key']
                rt_secret = cookie['request_token_secret']
            except KeyError:
                # in some rare cases, stale cookies are left behind
                # and users have to click login again
                act.failure('clearing stale cookie, redirecting to {}', root_path)
                cookie.set_expires()
                return redirect(root_path)

        req_token = RequestToken(rt_key, rt_secret)

        access_token = handshaker.complete(req_token,
                                           request.query_string)
        identity = handshaker.identify(access_token)

    userid = identity['sub']
    username = identity['username']
    user = rdb_session.query(User).filter(User.id == userid).first()
    now = datetime.datetime.utcnow()
    if user is None:
        user = User(id=userid, username=username, last_active_date=now)
        rdb_session.add(user)
    else:
        user.last_active_date = now

    # These would be useful when we have oauth beyond simple ID, but
    # they should be stored in the database along with expiration times.
    # ID tokens only last 100 seconds or so
    # cookie['access_token_key'] = access_token.key
    # cookie['access_token_secret'] = access_token.secret

    # identity['confirmed_email'] = True/False might be interesting
    # for contactability through the username. Might want to assert
    # that it is True.

    cookie['userid'] = identity['sub']
    cookie['username'] = identity['username']

    return_to_url = cookie.get('return_to_url')
    # TODO: Clean up
    if not DEBUG:
        del cookie['request_token_key']
        del cookie['request_token_secret']
        del cookie['return_to_url']
    else:
        return_to_url = '/'
    return redirect(return_to_url)
Пример #2
0
def add_entry_render(context, cookie, link_map):
    new_entry = context.get('new_entry')
    # cookie data added...
    if new_entry:
        cookie['new_entry_alias'] = new_entry.alias
        cookie.setdefault('aliases', []).insert(0, new_entry.alias)
    return redirect('/', code=303)
Пример #3
0
def create_app(consumer_key, consumer_secret):
    ui_redirector = lambda context: redirect('/userinfo')

    new_section_pdm = PostDataMiddleware({
        'page_title': unicode,
        'section_title': unicode,
        'text': unicode,
        'summary': unicode
    })

    new_section_route = POST('/new_section', post_new_section, render_basic, middlewares=[new_section_pdm])

    routes = [('/', home, render_basic),
              ('/userinfo', get_user_info, render_basic),
              ('/auth/authorize', authorize, render_basic),
              ('/auth/callback', authorize_complete, ui_redirector),
              new_section_route]

    resources = {'consumer_key': consumer_key,
                 'consumer_secret': consumer_secret,
                 'request_token_url': DEFAULT_REQ_TOKEN_URL,
                 'authorize_token_url': DEFAULT_AUTHZ_URL,
                 'access_token_url': DEFAULT_TOKEN_URL,
                 'api_url': DEFAULT_API_URL}

    middlewares = [GetParamMiddleware(['oauth_verifier', 'oauth_token']),
                   SignedCookieMiddleware(secret_key=consumer_secret),
                   SessionMiddleware()]
    return Application(routes, resources, middlewares=middlewares)
Пример #4
0
def logout(request, cookie, root_path):
    cookie.pop('userid', None)
    cookie.pop('username', None)

    return_to_url = request.args.get('next', root_path)

    return redirect(return_to_url)
Пример #5
0
def get_console_html(request, global_contexts, eval_context=None):
    if eval_context is None:
        return clastic.redirect(
            request.path + 'console/{0}'.format(len(global_contexts)))
    path, _, _ = request.path.rsplit('/', 2)
    callback = path + '/eval/{0}'.format(eval_context)
    return clastic.Response(
        CONSOLE_HTML.replace("CALLBACK_URL", callback), mimetype="text/html")
Пример #6
0
def fetch_entry(link_map, link_alias, request, local_static_app=None):
    try:
        target = link_map.get_entry(link_alias)
    except KeyError:
        return Forbidden()  # 404? 402?
    if target.startswith('/'):
        if local_static_app:
            return local_static_app.get_file_response(target, request)
        return Forbidden()
    return redirect(target, code=307)
Пример #7
0
def login(request, consumer_token, cookie, root_path):
    handshaker = Handshaker(WIKI_OAUTH_URL, consumer_token)

    redirect_url, request_token = handshaker.initiate()

    cookie['request_token_key'] = request_token.key
    cookie['request_token_secret'] = request_token.secret

    cookie['return_to_url'] = request.args.get('next', root_path)
    return redirect(redirect_url)
Пример #8
0
def logout(request, cookie, root_path):
    cookie.pop('userid', None)
    cookie.pop('username', None)
    cookie.pop('oauth_access_key', None)
    cookie.pop('oauth_access_secret', None)
    cookie.pop('request_token_secret', None)
    cookie.pop('request_token_key', None)

    return_to_url = request.args.get('next', root_path)

    return redirect(return_to_url)
Пример #9
0
def authorize(session, consumer_key, consumer_secret,
              authorize_token_url, request_token_url):
    req_token_key, req_token_secret = get_request_token(consumer_key,
                                                        consumer_secret,
                                                        request_token_url,
                                                        validate_certs=False)
    session['token_key'] = req_token_key
    session['token_secret'] = req_token_secret
    suffix = ('&oauth_token=%s&oauth_consumer_key=%s'
              % (req_token_key, consumer_key))
    redirect_url = authorize_token_url + suffix
    return redirect(redirect_url)
Пример #10
0
def redirect_today(lang=DEFAULT_LANG, project=DEFAULT_PROJECT):
    cur_date = datetime.today()
    days = 0
    while not check_issue(cur_date, days, lang, project):
        days += 1
    cur_date = cur_date - timedelta(days=days)
    today_file = HTML_FILE_TMPL.format(lang=DEFAULT_LANG,
                                       project=DEFAULT_PROJECT,
                                       year=cur_date.year,
                                       month=cur_date.month,
                                       day=cur_date.day)
    return redirect(today_file)
Пример #11
0
def redirect_today(lang=DEFAULT_LANG, project=DEFAULT_PROJECT):
    cur_date = datetime.today()
    days = 0
    while not check_issue(cur_date, days, lang, project):
        days += 1
    cur_date = cur_date - timedelta(days=days)
    today_file = HTML_FILE_TMPL.format(lang=DEFAULT_LANG,
                                       project=DEFAULT_PROJECT,
                                       year=cur_date.year,
                                       month=cur_date.month,
                                       day=cur_date.day)
    return redirect(today_file)
Пример #12
0
def add_entry(db, cookie, target_url, new_alias, expiry_time, max_count):
    try:
        entry = db.add_link(
            target_url=target_url,
            alias=new_alias,
            expiry_time=expiry_time,
            max_count=max_count,
        )
        cookie["new_entry_alias"] = entry["alias"]
        cookie["alias_available"] = "yes"
    except ValueError:
        cookie["new_entry_alias"] = new_alias
        cookie["alias_available"] = "no"
    return redirect("/", code=HTTPStatus.SEE_OTHER)
Пример #13
0
def use_entry(link_map, alias, request, local_static_app=None):
    entry = link_map.use_entry(alias)
    if not entry:
        return Forbidden(is_breaking=False)  # 404? 402?
    target = entry.target
    if target.startswith('/'):
        if local_static_app:
            rel_path = target[1:]
            link_map.save()
            return local_static_app.get_file_response(rel_path, request)
        else:
            m = 'This Erosion instance is not configured to host local files.'
            return Forbidden(m, is_breaking=False)
    else:
        link_map.save()
        return redirect(target, code=301)
Пример #14
0
def use_entry(link_map, alias, request, local_static_app=None):
    entry = link_map.use_entry(alias)
    if not entry:
        return Forbidden(is_breaking=False)  # 404? 402?
    target = entry.target
    if target.startswith('/'):
        if local_static_app:
            rel_path = target[1:]
            link_map.save()
            return local_static_app.get_file_response(rel_path, request)
        else:
            m = 'This Erosion instance is not configured to host local files.'
            return Forbidden(m, is_breaking=False)
    else:
        link_map.save()
        return redirect(target, code=301)
Пример #15
0
def view_obj(request, default_obj, obj_id=None):

    if obj_id is None:
        return clastic.redirect(
            request.path.rstrip('/') + '/{0}'.format(id(default_obj)))

    for obj in gc.get_objects():
        if id(obj) == obj_id:
            break
    else:
        raise ValueError("no Python object with id {0}".format(obj_id))

    path, _, _ = request.path.rpartition('/')
    return clastic.Response(render_html(obj,
                                        lambda id: path + '/{0}'.format(id)),
                            mimetype="text/html")
Пример #16
0
def view_obj(request, default_obj, obj_id=None):

    if obj_id is None:
        return clastic.redirect(
            request.path.rstrip('/') + '/{0}'.format(id(default_obj)))

    for obj in gc.get_objects():
        if id(obj) == obj_id:
            break
    else:
        raise ValueError("no Python object with id {0}".format(obj_id))

    path, _, _ = request.path.rpartition('/')
    return clastic.Response(
        render_html(
            obj, lambda id: path + '/{0}'.format(id)),
        mimetype="text/html")
Пример #17
0
def complete_login(request, consumer_token, cookie):
    handshaker = Handshaker(WIKI_OAUTH_URL, consumer_token)

    req_token = RequestToken(cookie['request_token_key'],
                             cookie['request_token_secret'])

    access_token = handshaker.complete(req_token, request.query_string)

    identity = handshaker.identify(access_token)

    userid = identity['sub']
    username = identity['username']

    cookie['userid'] = userid
    cookie['username'] = username
    # Is this OK to put in a cookie?
    cookie['oauth_access_key'] = access_token.key
    cookie['oauth_access_secret'] = access_token.secret

    return_to_url = cookie.get('return_to_url', '/')

    return redirect(return_to_url)
Пример #18
0
def complete_login(request, consumer_token, cookie, rdb_session):
    handshaker = Handshaker(WIKI_OAUTH_URL, consumer_token)

    req_token = RequestToken(cookie['request_token_key'],
                             cookie['request_token_secret'])

    access_token = handshaker.complete(req_token, request.query_string)
    identity = handshaker.identify(access_token)

    userid = identity['sub']
    username = identity['username']
    user = rdb_session.query(User).filter(User.id == userid).first()
    now = datetime.datetime.utcnow()
    if user is None:
        user = User(id=userid, username=username, last_login_date=now)
        rdb_session.add(user)
    else:
        user.last_login_date = now

    # These would be useful when we have oauth beyond simple ID, but
    # they should be stored in the database along with expiration times.
    # ID tokens only last 100 seconds or so
    # cookie['access_token_key'] = access_token.key
    # cookie['access_token_secret'] = access_token.secret

    # identity['confirmed_email'] = True/False might be interesting
    # for contactability through the username. Might want to assert
    # that it is True.

    cookie['userid'] = identity['sub']
    cookie['username'] = identity['username']

    return_to_url = cookie.get('return_to_url')
    del cookie['request_token_key']
    del cookie['request_token_secret']
    del cookie['return_to_url']
    return redirect(return_to_url)
Пример #19
0
def use_entry(alias, db):
    entry = db.use_link(alias)
    if entry is None:
        return NotFound()
    return redirect(entry["target"], code=HTTPStatus.MOVED_PERMANENTLY)
Пример #20
0
def add_entry_render(context, cookie, link_map):
    new_entry = context.get('new_entry')
    if new_entry:
        cookie['new_entry_alias'] = new_entry.alias
        cookie.setdefault('aliases', []).insert(0, new_entry.alias)
    return redirect('/', code=303)
Пример #21
0
def juror_camp_redirect(user_dao, campaign_id, correct_name=None):
    if not correct_name:
        correct_name = user_dao.get_campaign_name(campaign_id)
    correct_name = correct_name.replace(' ', '-')
    new_path = '/campaign/%s/%s' % (campaign_id, correct_name)
    return redirect(new_path)
Пример #22
0
def juror_round_redirect(user_dao, round_id, correct_name=None):
    if not correct_name:
        correct_name = user_dao.get_round_name(round_id)
    correct_name = correct_name.replace(' ', '-')
    new_path = '/round/%s/%s' % (round_id, correct_name)
    return redirect(new_path)