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
|
# -*- coding: utf-8 -*-
from functools import wraps
from flask import flash, request, redirect, render_template, session, url_for
from random import randint
from Crypto.Cipher import AES
from werkzeug.exceptions import Forbidden
# 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 'username' not in session:
raise Forbidden
return f(*args, **kwargs)
return login_required_
def login_user(username, password):
# if not ldap_bind():
# return False
session['username'] = username
session['password'] = encrypt_password(password)
#ldap_unbind()
return True
def logout_user():
session.pop('username', None)
session.pop('password', 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(app.config['PASSWORD_ENCRYPTION_KEY']) == 32
iv = ''.join(chr(randint(0, 0xff)) for i in range(16))
encryptor = AES.new(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(app.config['PASSWORD_ENCRYPTION_KEY'], AES.MODE_CBC, iv)
return encryptor.decrypt(ciphertext[16:]).rstrip('\0')
# circular import
from app import app
|