开发者

What a base controller that will look for a session cookie, and if present, set the User object

I want to use a custom base controller for my wep application that has a User object as a property, and a boolean IsLoggedIn property.

In the constructor of the base controller (or whatever event I need to do this in??) I want to look for a session cookie, if present, load the user and set the User obj开发者_StackOverflow社区ect and set the IsLoggedIn property to true.

I'm very new to pylons so any guidance would be appreciated.


Also you can use before method of controller like this:

class MyControllerWithUserProperty(BaseController):

   def __before__(self, action, **params):
       # check the cookies
       # ...

       self.user = <user object>

       # set others properties
       # ...


In your code that is responsible for logging user in, after verification of user name and password you can store user id in session and make redirect:

session['user_id'] = authenticated_user.id
session.save()
h.redirect_to('/')

and then, in BaseController.init assign user instance to controller's property like this:

self.user = session.get('user_id') and Session.query(User).get(session['user_id'])

This way if user is authenticated you get his instance in self.user. Otherwise self.user is going to be None.

And to logout someone just remove 'user_id' from Pylons' session:

del session['user_id']

PS: I've made some assumptions such as that you are using SQLAlchemy for database backend, but you get the point

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜