source: mauRepo/dj_security_middleware/trunk/dj_security_middleware/__init__.py @ 8813

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/mauRepo/dj_security_middleware/trunk/dj_security_middleware/__init__.py@8813
Revision 8813, 2.9 KB checked in by mnagni, 6 years ago (diff)

Reverted to 0.0.13 and moved to 0.0.14

  • Property svn:mime-type set to text/plain
Line 
1__version__ = '0.0.14'
2
3from django.conf import settings
4from paste.auth.auth_tkt import AuthTicket
5import logging
6import socket
7import urlparse
8from dj_security_middleware.exception import DJMiddlewareException
9
10LOGIN_SERVICE_ERROR = 'No LOGIN_SETTING parameter is defined in the \
11application settings.py file. Please define a proper URL to the \
12authenticating service'
13
14# Get an instance of a logger
15LOGGER = logging.getLogger(__name__)
16
17def login_service():
18    try:
19        return getattr(settings, 'SECURITY_LOGIN_SERVICE')
20    except AttributeError:
21        raise DJMiddlewareException(LOGIN_SERVICE_ERROR)
22
23def auth_tkt_name():
24    return getattr(settings, 'AUTH_TKT_NAME', 'auth_tkt')
25
26def cookie_domain():
27    try:
28        return getattr(settings, 'COOKIE_DOMAIN')
29    except AttributeError:
30        netloc = urlparse.urlparse(login_service()).netloc
31        if netloc.find(':') > 0:
32            return netloc[:netloc.index(':')]
33        return netloc
34
35def reset_password():
36    return getattr(settings, 'CC_RESET_PASSWORD', [])
37
38def redirect_field_name():
39    return getattr(settings, 'REDIRECT_FIELD_NAME', 'r')
40
41def token_field_name():
42    return getattr(settings, 'TOKEN_FIELD_NAME', 't')
43
44def security_filter():
45    return getattr(settings, 'DJ_SECURITY_FILTER', [])
46
47def shared_secret():
48    return getattr(settings, 'SECURITY_SHAREDSECRET', 'sharedsecret')
49
50def _calculate_remote_ip(url_path):   
51    remote_url = urlparse.urlparse(url_path)
52    LOGGER.debug("calculating remote_ip for %s" % (str(remote_url)))
53    port = 80
54    host = None
55    if remote_url.netloc:
56        host = remote_url.netloc
57    elif remote_url.path:
58        host = remote_url.path
59       
60    if not host:
61        return None
62   
63    if ':' in host:
64        host, port = host.split(':')
65    addrinfo = socket.getaddrinfo(host, int(port))
66    LOGGER.debug("%s has remote_ip %s" % (url_path, addrinfo[0][-1][0]))
67    for remote_url in addrinfo:
68        if not remote_url[-1][0].startswith('127'):
69            return remote_url[-1][0]
70    return None
71
72def _get_host_ip():
73    if getattr(settings, 'DJ_MIDDLEWARE_IP', None):
74        return settings.DJ_MIDDLEWARE_IP
75       
76    return _calculate_remote_ip(socket.getfqdn())
77
78def generate_auth_cookie(user, response, remote_ip = _get_host_ip()):
79    token = AuthTicket(
80            getattr(settings, 'SHARED_SECRET', 'sharedsecret'),
81            user.accountid,
82            remote_ip,
83            user_data = '{"userkey": "%s", "accountid": "%s"}'
84            % (user.userkey, getattr("user", "accountid", "NotAssigned")))               
85    LOGGER.info("Created authTicket for %s from %s" % (user.accountid, remote_ip))
86    response.set_cookie(auth_tkt_name(),
87                        token.cookie_value(),
88                        domain = cookie_domain())
89    LOGGER.debug("Set authTicket in response for %s from %s to domain %s"
90                 % (user.accountid, remote_ip, cookie_domain()))
91    return response
Note: See TracBrowser for help on using the repository browser.