summaryrefslogtreecommitdiffstats
path: root/accounts/utils/__init__.py
blob: e584e285b6a27b8352f7c03b1f36bb7e8077251e (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
# -*- coding: utf-8 -*-
import importlib
from functools import wraps
from flask import current_app, flash, g, redirect, render_template, request, session
from flask import url_for as flask_url_for
from flask.ext.login import current_user
from werkzeug.exceptions import Forbidden
from wtforms.validators import Regexp, ValidationError

from .confirmation import Confirmation


# 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 ensure_utf8(s):
    if isinstance(s, unicode):
        s = s.encode('utf8')
    return s


def send_register_confirmation_mail(username, mail):
    confirm_token = Confirmation('register').dumps((username, mail))
    confirm_link = url_for('default.register_complete', token=confirm_token, _external=True)

    body = render_template('mail/register.txt', username=username,
                           mail=mail, link=confirm_link)

    current_app.mail_backend.send(
        mail, u'E-Mail-Adresse bestätigen', body,
        sender=current_app.config.get('MAIL_CONFIRM_SENDER'))


class NotRegexp(Regexp):
    """
    Like wtforms.validators.Regexp, but rejects data that DOES match the regex.
    """
    def __call__(self, form, field):
        if self.regex.match(field.data or u''):
            if self.message is None:
                self.message = field.gettext(u'Invalid input.')

            raise ValidationError(self.message)


def url_for(endpoint, **values):
    """Wrap `flask.url_for` so that it always returns https links"""
    #XXX: Drop this in favor of config.PREFERRED_URL_SCHEME when we require Flask 0.9
    u = flask_url_for(endpoint, **values)
    if '_external' in values and u.startswith('http://') \
       and current_app.config['PREFERRED_URL_SCHEME'] == 'https':
        return 'https://' + u[7:]
    else:
        return u


def get_backend(path, app):
    module = path.rsplit(".", 1).pop()
    class_name = '%sBackend' % module.title()
    backend_class = getattr(importlib.import_module(path), class_name)
    return backend_class(app)