File: httpbasicauth.py

package info (click to toggle)
python-werkzeug 0.8.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 2,940 kB
  • sloc: python: 16,194; makefile: 143; pascal: 66; xml: 16
file content (45 lines) | stat: -rw-r--r-- 1,529 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# -*- coding: utf-8 -*-
"""
    HTTP Basic Auth Example
    ~~~~~~~~~~~~~~~~~~~~~~~

    Shows how you can implement HTTP basic auth support without an
    additional component.

    :copyright: (c) 2009 by the Werkzeug Team, see AUTHORS for more details.
    :license: BSD.
"""
from werkzeug.serving import run_simple
from werkzeug.wrappers import Request, Response


class Application(object):

    def __init__(self, users, realm='login required'):
        self.users = users
        self.realm = realm

    def check_auth(self, username, password):
        return username in self.users and self.users[username] == password

    def auth_required(self, request):
        return Response('Could not verify your access level for that URL.\n'
                        'You have to login with proper credentials', 401,
                        {'WWW-Authenticate': 'Basic realm="%s"' % self.realm})

    def dispatch_request(self, request):
        return Response('Logged in as %s' % request.authorization.username)

    def __call__(self, environ, start_response):
        request = Request(environ)
        auth = request.authorization
        if not auth or not self.check_auth(auth.username, auth.password):
            response = self.auth_required(request)
        else:
            response = self.dispatch_request(request)
        return response(environ, start_response)


if __name__ == '__main__':
    application = Application({'user1': 'password', 'user2': 'password'})
    run_simple('localhost', 5000, application)