从Pyramid(Python)中的cookie获取用户名信息

时间:2015-06-02 21:59:43

标签: python authentication cookies pyramid

我正在编写一个金字塔应用程序,允许在数据库表中注册任意数量的用户。这是我的登录代码:

@view_config(route_name='login', renderer='templates/login.jinja2')
def login(request):
    username = request.params.get('username', '')
    error = ''
    if request.method == 'POST':
        error = 'Login Failed'
        authenticated = False
        try:
            authenticated = do_login(request)
        except ValueError as e:
            error = str(e)
        if authenticated:
            headers = remember(request, username)
            return HTTPFound(request.route_url('home'), headers=headers)
    return {'error': error, 'username': username}

,其中

def do_login(request):
    username = request.params.get('username', None)
    password = request.params.get('password', None)
    if not (username and password):
        raise ValueError('both username and password required')
    manager = BCRYPTPasswordManager()
    cur = request.db.cursor()
    try:
        cur.execute("SELECT password FROM users WHERE username=%s", [username])
    except psycopg2.Error:
        raise ValueError("That username already exists!")
    actual_password = cur.fetchall()[0][0]  # Extrrrract the data
    return manager.check(actual_password, password)

我希望在给定用户通过身份验证后在所有视图上显示用户名。我的理解是认证信息存储在cookie中,并且该cookie看起来像(auth_tkt ="")。我如何获得"当前"这个cookie的用户名?

或者我比我意识到的更困惑?

1 个答案:

答案 0 :(得分:0)

您可以致电request.authenticated_userid获取经过身份验证的用户名。您可以在official docs中找到有关此内容的更多信息。

我也倾向于将整个user对象(和dbsession)存储在request中,如下所示:

def includeme(config):
    from .models.user import User

    settings = config.get_settings()
    dbsession_factory = get_dbsession_factory(settings)
    config.add_request_method(
        lambda request: dbsession_factory(),
        'dbsession',
        reify=True)
    config.add_request_method(
        lambda request: User.get_by_username(
            request.dbsession,
            request.authenticated_userid),
        'user',
        reify=True)

def get_dbsession_factory(settings):
    engine = engine_from_config(settings, 'sqlalchemy.')
    dbsession_factory = sessionmaker()
    register(dbsession_factory)
    dbsession_factory.configure(bind=engine)
    return dbsession_factory 

然后,您只需在应用config.include('your_app.models')中拨打__init__