本文介绍了如何使用flask-security在登录时运行自定义代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的烧瓶,但适度python娴熟 - 我有一个烧瓶的应用程序使用瓶安全性用户身份验证。我想添加一些额外的功能,用户登录过程。具体而言,我需要在登录时将用户的auth_token(我已经设置为一次性使用标记)保存到数据库,并在注销时将其删除。问题的出现是因为瓶颈安全并没有(据我所知)直接向开发者公开登录机制。据我可以告诉代码,它进口flask-login,它使用login_user函数。我开始试图通过导入flask.ext.login(通常,我不需要这样做)重写这个函数,并重新定义函数如下: / p>

 导入flask.ext.login作为
def new_login_user():
...现有的副本函数在这里...
...加上新的东西与current_user.get_auth_token()...
a.login_user = new_login_user


我认为可能有一种方法可以用装饰器来实现,但是我是新的装饰器,而且不用多少装饰器。



处理这个问题的最好方法是什么?对于上下文,我想在数据库中的auth_token,因为我需要将网站身份验证传递给另一个进程,这也访问数据库。另一个进程是使用websockets的API服务器。我不想将这些过程结合在一起。

解决方案

我认为使用信号装饰器似乎是最简单的下面的例子 on_user_logged_in 应该在用户登录到应用程序时调用。更多信息中。

  from flask.ext.login import user_logged_in 

@ user_logged_in.connect_via(app)
def on_user_logged_in(sender,user):
log_auth_token(user.get_auth_token())#或其他。


I am new to flask, but moderately proficient in python - I have a flask app that uses flask-security for user authentication. I would like to add some additional functionality to the user login process. Specifically, I need to save the user's auth_token (which I have set up to be a one-time-use token) to the db when they login, and remove it when they log out. The issue comes because flask-security does not (to my knowledge) expose the machinery of logging in directly to the developer. As far as I can tell from the code, it imports flask-login, which uses a login_user function.

I started out by trying to override this function by importing flask.ext.login (which normally, I would not need to do) and redefining the function as follows:

import flask.ext.login as a
def new_login_user():
    ...copy of existing function goes here...
    ...Plus new stuff with current_user.get_auth_token()...
a.login_user = new_login_user

however, I got hit with all sorts of namespace issues, and it seems like a really ugly way to do it.

I was thinking there might be a way to do it with a decorator, but I am new to flask, and have not used decorators much regardless.

Any ideas on what the best way to approach this might be? for context, I want the auth_token in the db, because I need to pass off the website authentication to another process, which also accesses the db. The other process is an API server using websockets. I don't want to combine the processes.

解决方案

I think using a signal decorator seems to be the easiest-- in the following example on_user_logged_in should be called when a user logs into your app. More info in the docs.

from flask.ext.login import user_logged_in

@user_logged_in.connect_via(app)
def on_user_logged_in(sender, user):
    log_auth_token(user.get_auth_token()) # or whatever.

这篇关于如何使用flask-security在登录时运行自定义代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 02:03