python flask应用 Principal 授权认证

'''
Created on 2012-6-14

@author: wenwen
'''

from flask import Flask, make_response, request, session, render_template, redirect, abort, current_app
from flask_principal import Principal, Permission, UserNeed, RoleNeed, Identity, AnonymousIdentity, identity_changed, identity_loaded
import simplejson as json
from bson import json_util
from datetime import datetime, timedelta
from logging import Formatter
import logging.handlers
import traceback
import paramiko

LOG_FILENAME = 'logs/admin.log'
handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=100000000, backupCount=5)
handler.setFormatter(Formatter('%(asctime)s - %(name)s - %(levelname)s - %(process)d - Line:%(lineno)d - %(message)s'))


# application
app = Flask(__name__)

app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

# load the extension
principals = Principal(app)

# Create a permission with a single Need, in this case a RoleNeed.
all_permission = Permission(RoleNeed('admin'),RoleNeed('operator'))
admin_permission = Permission(RoleNeed('admin'))


@app.before_request
def before_request():
    print "----------------------------------------------------------------"


@identity_loaded.connect_via(app)
def on_identity_loaded(sender, identity):
    identity.user = session.get("userinfo")
    if session.get("userinfo"):
        identity.provides.add(UserNeed(session.get("userinfo")['account']))
        identity.provides.add(RoleNeed(session.get("userinfo")['roles']))
    else:
    	print "***************"

@app.route("/logout", methods=['GET'])
def logout():
    try:
        session.pop("userinfo")
        # Remove session keys set by Flask-Principal
        for key in ('identity.name', 'identity.auth_type'):
            session.pop(key, None)
            identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity())
    except Exception,e:
        print e	
    return "logout"



@app.route("/auth", methods=['GET'])
def auth():
    try:
    	user_info = {"account":"peng.zhou","roles":"admin"}
    	session["userinfo"] = user_info
    	identity_changed.send(current_app._get_current_object(),identity=Identity(user_info['account']))
        return "login"
    except Exception, e:
        print e

@app.route("/cooler", methods=['GET'])
@admin_permission.require(http_exception=401)
def getAdminUserList():
    return "hello"
#
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080)


你可能感兴趣的:(python)