summaryrefslogtreecommitdiffstats
path: root/utils.py
blob: 6ab7ed43be71c31fa6c3f0f0a15559e8adfd9aa0 (plain)
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
# -*- coding: utf-8 -*-
import hmac
import ldap
import pickle
import re
import struct
import subprocess
from base64 import urlsafe_b64encode, urlsafe_b64decode
from Crypto.Cipher import AES
from email.mime.text import MIMEText
from functools import wraps
from flask import current_app, flash, g, redirect, render_template, request, session, url_for
from hashlib import sha1
from random import randint
from time import time
from werkzeug.exceptions import Forbidden



_username_re = re.compile(r'^[a-z]{2,16}')

# using http://flask.pocoo.org/docs/patterns/viewdecorators/
def templated(template=None):
    def templated_(f):
        @wraps(f)
        def templated__(*args, **kwargs):
            template_name = template
            if template_name is None:
                template_name = request.endpoint \
                    .replace('.', '/') + '.html'
            ctx = f(*args, **kwargs)
            if ctx is None:
                ctx = {}
            elif not isinstance(ctx, dict):
                return ctx
            return render_template(template_name, **ctx)
        return templated__
    return templated_

def login_required(f):
    @wraps(f)
    def login_required_(*args, **kwargs):
        if not g.user:
            raise Forbidden(u'Bitte einloggen!')
        return f(*args, **kwargs)
    return login_required_

def logout_required(f):
    @wraps(f)
    def logout_required_(*args, **kwargs):
        if g.user:
            raise Forbidden(u'Diese Seite ist nur für nicht eingeloggte Benutzer gedacht!')
        return f(*args, **kwargs)
    return logout_required_


def login_user(username, password):
    try:
        g.user = g.ldap.auth(username, password)
    except ldap.INVALID_CREDENTIALS:
        return False

    session['username'] = username
    session['password'] = encrypt_password(password)

    return True


def logout_user():
    session.pop('username', None)
    session.pop('password', None)
    g.user = None


def pad(s, numbytes=32, padding='\0'):
    return s + (numbytes - len(s) % numbytes) * padding

def encrypt_password(password):
    """
    Encrypt the given password with `config.PASSWORD_ENCRYPTION_KEY`.
    The key must be 32 bytes long.
    """
    assert len(current_app.config['PASSWORD_ENCRYPTION_KEY']) == 32

    if isinstance(password, unicode):
        password = password.encode('utf8')

    iv = ''.join(chr(randint(0, 0xff)) for i in range(16))
    encryptor = AES.new(current_app.config['PASSWORD_ENCRYPTION_KEY'], AES.MODE_CBC, iv)
    return iv + encryptor.encrypt(pad(password))

def decrypt_password(ciphertext):
    """
    Decrypt the given password with `config.PASSWORD_ENCRYPTION_KEY`.
    """
    iv = ciphertext[:16]
    encryptor = AES.new(current_app.config['PASSWORD_ENCRYPTION_KEY'], AES.MODE_CBC, iv)
    return encryptor.decrypt(ciphertext[16:]).rstrip('\0')


def make_confirmation(realm, data):
    """
    Create a confirmation token e.g. for confirmation mails.

    Expects as input a realm to distinguish data for several applications and
    some data (pickle-able).
    """
    key = '\0'.join((current_app.config['SECRET_KEY'], realm))
    payload = ''.join((struct.pack('>i', time()), pickle.dumps(data)))
    mac = hmac.new(key, payload, sha1)
    return urlsafe_b64encode(''.join((mac.digest(), payload))).rstrip('=')

class ConfirmationInvalid(ValueError):
    """Raised by `verify_confirmation` on invalid input data"""

class ConfirmationTimeout(ValueError):
    """Raised by `verify_confirmation` when the input data is too old"""

def verify_confirmation(realm, token, timeout=None):
    """
    Verify a confirmation token created by `make_confirmation` and, if it is
    valid, return the original data.
    If `timeout` is given, only accept the token if it is less than `timeout`
    seconds old.
    """
    key = '\0'.join((current_app.config['SECRET_KEY'], realm))

    token = urlsafe_b64decode(token + '=' * (4 - len(token) % 4))
    mac = token[:20]
    tokentime = struct.unpack('>i', token[20:24])[0]
    payload = token[24:]

    if mac != hmac.new(key, token[20:], sha1).digest():
        raise ConfirmationInvalid('MAC does not match')

    print '%d+%d=%d <> %d' % (tokentime, timeout, tokentime+timeout, time())
    if timeout is not None and time() > tokentime + timeout:
        raise ConfirmationTimeout('Token is too old')

    return pickle.loads(payload)

def http_verify_confirmation(*args, **kwargs):
    """
    Like `verify_confirmation`, but raise HTTP exceptions with appropriate
    messages instead of `Confirmation{Invalid,Timeout}`.
    """

    try:
        return verify_confirmation(*args, **kwargs)
    except ConfirmationInvalid:
        raise Forbidden(u'Ungültiger Bestätigungslink.')
    except ConfirmationTimeout:
        raise Forbidden(u'Bestätigungslink ist zu alt.')


def send_mail(recipient, subject, body, sender=None):
    if sender is None:
        sender = current_app.config['MAIL_DEFAULT_SENDER']

    safe = lambda s: s.split('\n', 1)[0]

    msg = MIMEText(body, _charset='utf-8')
    msg['Subject'] = safe(subject)
    msg['To'] = safe(recipient)
    msg['From'] = safe(sender)

    p = subprocess.Popen([current_app.config['SENDMAIL_COMMAND'], '-t'],
                         stdin=subprocess.PIPE)
    p.stdin.write(msg.as_string())
    p.stdin.close()

    if p.wait() != 0:
        raise RuntimeError('sendmail terminated with %d' % p.returncode)


class Service(object):
    def __init__(self, id, name, url):
        self.id = id
        self.name = name
        self.url = url
        self.changed = None # used by settings view

    def __repr__(self):
        return '<Service %s>' % self.id