~wgrant/canonical-identity-provider/lp-xmlrpc

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# Copyright 2010 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

import binascii
import hashlib
import httplib
import random
import re
import urllib
import urllib2
import socket
import xmlrpclib

from email.Header import Header
from email.Utils import formataddr

from django.core.exceptions import ObjectDoesNotExist
from django.utils.log import getLogger
from django.utils.translation import ugettext as _

SALT_LENGTH = 20


def canonical_url(
    obj, request=None, rootsite=None, path_only_if_possible=False,
    view_name=None):
    """ Very dumb implementation of canonical_url() """
    from identityprovider.models import Person
    if isinstance(obj, Person):
        if view_name is None:
            return 'https://launchpad.net/~%s' % obj.name
        else:
            return 'https://launchpad.net/~%s/%s' % (obj.name, view_name)
    else:
        return None


def encrypt_launchpad_password(plaintext, salt=None):
    plaintext = str(plaintext)
    if salt is None:
        salt = generate_salt()
    v = binascii.b2a_base64(hashlib.sha1(plaintext + salt).digest() + salt)
    return v[:-1]


def format_address(address, name=None):
    r"""Formats a name and address to be used as an email header.

        >>> format_address('foo@bar.com', 'Name')
        'Name <foo@bar.com>'
        >>> format_address('foo@bar.com', '')
        'foo@bar.com'
        >>> format_address(u'foo@bar.com')
        'foo@bar.com'

    It handles unicode and characters that need quoting as well.

        >>> format_address('foo.bar@canonical.com', u'F\xf4\xf4 Bar')
        '=?utf-8?b?RsO0w7QgQmFy?= <foo.bar@canonical.com>'

        >>> format_address('foo.bar@canonical.com', 'Foo [Baz] Bar')
        '"Foo \\[Baz\\] Bar" <foo.bar@canonical.com>'

    Really long names doesn't get folded, since we're not constructing
    an e-mail header here.

        >>> formatted_address = format_address(
        ...     'long.name@example.com',
        ...     'a '*100)
        >>> '\n' in formatted_address
        False
    """
    if not name:
        return str(address)
    name = str(Header(unicode(name)))
    # Using Header to encode the name has the side-effect that long
    # names are folded, so let's unfold it again.
    name = ''.join(name.splitlines())
    return str(formataddr((name, address)))


def generate_openid_identifier():
    # import here to avoid circular imports
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("SELECT generate_openid_identifier();")
    row = cursor.fetchone()
    return row[0]


def generate_salt():
    """ From lib/canonical/launchpad/webapp/authentication.py """
    # Salt can be any length, but not more than about 37 characters
    # because of limitations of the binascii module.
    # All 256 characters are available.
    salt = ''
    for n in range(SALT_LENGTH):
        salt += chr(random.randrange(256))
    return salt


def password_policy_compliant(password):
    if len(password) < 8:
        return False
    has_upper = False
    has_number = False
    has_punctuation = False
    if re.search(r'[A-Z]', password):
        has_upper = True
    if re.search(r'[0-9]', password):
        has_number = True
    search_string = '[\.\?\!\,\-\_\[\]\(\)"#$%&\'\*\+/:;\<\>=\^`\{\}\|~ ]'
    if re.search(search_string, password):
        has_punctuation = True
    return ((int(has_upper) + int(has_number) + int(has_punctuation)) >= 2)


def polite_form_errors(errors):
    if 'email' in errors:
        if errors['email'][0] == _("Enter a valid e-mail address."):
            errors['email'][0] = _("Please enter a valid email address.")


def validate_launchpad_password(plaintext, encrypted):
    encrypted = str(encrypted)
    plaintext = str(plaintext)
    try:
        ref = binascii.a2b_base64(encrypted)
    except binascii.Error:
        # Not valid base64.
        return False
    salt = ref[20:]
    v = binascii.b2a_base64(
        hashlib.sha1(plaintext + salt).digest() + salt)[:-1]
    pw1 = (v or '').strip()
    pw2 = (encrypted or '').strip()
    return pw1 == pw2


def http_request_with_timeout(url, data=None, headers=None, timeout=5):
    if data is not None:
        data = urllib.urlencode(data)
    if headers is None:
        headers = {}
    request = urllib2.Request(url, headers=headers, data=data)
    old_timeout = socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(timeout)
        datafile = urllib2.urlopen(request)
        data = datafile.read()
        headers = datafile.info()
    except urllib2.URLError:
        data, headers = None, None
    finally:
        socket.setdefaulttimeout(old_timeout)
    return data, headers


def get_object_or_none(qs_or_model, **kwargs):
    if hasattr(qs_or_model, 'objects'):
        qs_or_model = qs_or_model.objects.all()
    try:
        return qs_or_model.get(**kwargs)
    except ObjectDoesNotExist:
        return None


class HTTP(httplib.HTTP):
    """A version of httplib.HTTP with a timeout argument."""

    def __init__(self, host='', port=None, strict=None,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        self._setup(
            self._connection_class(host, port, strict, timeout=timeout))


class Transport(xmlrpclib.Transport):
    """An xmlrpclib transport that supports a timeout argument.

    Use by passing into the "transport" argument of the xmlrpclib.ServerProxy
    initialization.
    """

    def __init__(self,
                 use_datetime=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        xmlrpclib.Transport.__init__(self, use_datetime)
        self.timeout = timeout

    def make_connection(self, host):
        return HTTP(host, timeout=self.timeout)


def get_launchpad_details_for_user(user):
    endpoint = 'http://xmlrpc-private.launchpad.dev:8087/canonicalsso'
    proxy = xmlrpclib.ServerProxy(
        endpoint, transport=Transport(timeout=0.5))
    try:
        details = proxy.getPersonByOpenIDIdentifier(
            user.openid_identifier.split('/')[-1])
    except socket.error:
        getLogger().exception("Failed to retrieve details from Launchpad.")
        details = None
    return details