bottle authentication 插件

By admin at 2013-12-03 22:27 • 3436次点击


Cork provides a simple set of methods to implement Authentication and Authorization in web applications based on Bottle.
code 3


import bottle

def check(user, passwd):
    if user == 'ben':
        return True
    return False

def index():
    print 'auth', bottle.request.auth
    print 'remote_addr', bottle.request.remote_addr
    return "Yay - you made it!"

if __name__ == '__main__':
    print "Starting server"'', port=8080, reloader=True) 

import urllib2, base64

(user, password) = ('ben', 'xyz')
request = urllib2.Request("http://localhost:8080/")
base64string = base64.encodestring('%s:%s' % (user, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string) 
result = urllib2.urlopen(request)

摘菜 2

基于 cookie 的

def require_uid(fn):
    def check_uid(**kwargs):   
        cookie_uid = request.get_cookie('cookieName', secret='cookieSignature')

        if cookie_uid:
            //do stuff with a user object
            return fn(**kwargs)

    return check_uid

@route('/userstuff', method='GET')
def app_userstuff():
    //doing things is what i like to do
    return dict(foo="bar")

摘菜 1

bottle, authentication, 插件


def auth_basic(check, realm="private", text="Access denied"):
    ''' Callback decorator to require HTTP auth (basic).
        TODO: Add route(check_auth=...) parameter. '''
    def decorator(func):
      def wrapper(*a, **ka):
        user, password = request.auth or (None, None)
        if user is None or not check(user, password):
          response.headers['WWW-Authenticate'] = 'Basic realm="%s"' % realm
          return HTTPError(401, text)
        return func(*a, **ka)
      return wrapper
    return decorator

admin at 2013-12-03 22:35


from bottle import *
from bottle_user_auth import User

def index_page(): #displays index page
    user = User() #here and below - creates an instance of User class
    if user.loggedin:
        return 'You are an authenticated user'
def login_page():
    #assume you have a login page with two fields: 
    #"email" and "password" and submit button'/login')
def user_login(): #getting credentials from POST request from login page
    user = User()

    if user.authenticate( 
            request.POST.get( 'email' ),
            request.POST.get( 'password' )
        #if authentication has been successful module will assing a cookie
        #with encripted user id from database to user

    redirect('/login/error') 1

admin at 2013-12-11 18:38
登录 后发表评论