summaryrefslogtreecommitdiffstats
path: root/app.py
blob: 15434bfe44b3c3bc10f7deaac526a52b10ca43ec (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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# -*- coding: utf-8 -*-

import flaskext_compat
flaskext_compat.activate()

import account
import ldap
import os
from copy import deepcopy
from flask import flash, Flask, g, redirect, request, session
from utils import *
from uuid import uuid4




app = Flask(__name__)
app.config.from_object('default_settings')
if 'SPLINE_ACCOUNT_WEB_SETTINGS' in os.environ:
    app.config.from_envvar('SPLINE_ACCOUNT_WEB_SETTINGS')

app.all_services = account.SERVICES #TODO: take that from our json file or so

@app.before_request
def session_permanent():
    if app.config.get('PERMANENT_SESSION_LIFETIME'):
        session.permanent = True
    else:
        session.permanent = False

@app.before_request
def ldap_connect():
    g.ldap = account.AccountService(app.config['LDAP_HOST'], app.config['LDAP_BASE_DN'],
        app.config['LDAP_ADMIN_USER'], app.config['LDAP_ADMIN_PASS'], app.all_services)

@app.before_request
def initialize_user():
    g.user = None

    if 'username' in session and 'password' in session:
        username = ensure_utf8(session['username'])
        password = ensure_utf8(decrypt_password(session['password']))
        try:
            g.user = g.ldap.auth(username, password)
        except ldap.INVALID_CREDENTIALS:
            # we had crap in the session, delete it
            logout_user()

@app.before_request
def read_blacklist():
    app.username_blacklist = None

    # use @before_first_request as soon as we require flask 0.8
    if app.username_blacklist is None and app.config.get('USERNAME_BLACKLIST_FILE'):
        with open(app.config['USERNAME_BLACKLIST_FILE']) as f:
            app.username_blacklist = f.read().split('\n')

@app.context_processor
def template_default_context():
    return {
        'app': app
    }


@app.route('/', methods=['GET', 'POST'])
@templated('index.html')
def index():
    if not g.user:
        form = LoginForm(request.form, csrf_enabled=False)
        if request.method == 'POST' and form.validate():
            if login_user(form.username.data, form.password.data):
                flash(u'Erfolgreich eingeloggt', 'success')
                return redirect(url_for('settings'))
            else:
                flash(u'Ungültiger Benutzername und/oder Passwort', 'error')
    else:
        return redirect(url_for('settings'))

    return {'form': form}


@app.route('/register', methods=['GET', 'POST'])
@templated('register.html')
@logout_required
def register():
    form = RegisterForm(request.form, csrf_enabled=False)
    if request.method == 'POST' and form.validate():
        send_register_confirmation_mail(form.username.data, form.mail.data)

        flash(u'Es wurde eine E-Mail an die angegebene Adresse geschickt, '
              u'um diese zu überprüfen. Bitte folge den Anweisungen in der '
              u'E-Mail.', 'success')

        return redirect(url_for('index'))

    return {'form': form}


@app.route('/register/<token>', methods=['GET', 'POST'])
@templated('register_complete.html')
@logout_required
def register_complete(token):
    #TODO: check for double uids and mail
    username, mail = http_verify_confirmation('register', token.encode('ascii'), timeout=3*24*60*60)

    try:
        g.ldap.get_by_uid(username)
        g.ldap.get_by_mail(mail)
    except account.NoSuchUserError:
        pass
    else:
        flash(u'Du hast den Benutzer bereits angelegt! Du kannst dich jetzt einfach einloggen:')
        return redirect(url_for('index'))

    form = RegisterCompleteForm(request.form, csrf_enabled=False)
    if request.method == 'POST' and form.validate():
        password = form.password.data

        user = account.Account(username, mail, password=form.password.data)
        g.ldap.register(user)

        # populate request context and session
        assert login_user(user.uid, user.password)

        if app.config.get('MAIL_REGISTER_NOTIFY'):
            send_mail(
                app.config['MAIL_REGISTER_NOTIFY'],
                u'[accounts] Neuer Benutzer %s erstellt' % username,
                u'Benutzername: %s\nE-Mail:       %s\n\nSpammer? Deaktivieren: '
                u'%s\n' % (username, mail,
                    url_for('admin_disable_account', uid=username, _external=True))
            )

        flash(u'Benutzer erfolgreich angelegt.', 'success')
        return redirect(url_for('settings'))

    return {
        'form': form,
        'token': token,
        'username': username,
        'mail': mail,
    }


@app.route('/lost_password', methods=['GET', 'POST'])
@templated('lost_password.html')
@logout_required
def lost_password():
    form = LostPasswordForm(request.form, csrf_enabled=False)
    if request.method == 'POST' and form.validate():
        #TODO: make the link only usable once (e.g include a hash of the old pw)
        # atm the only thing we do is make the link valid for only little time
        confirm_token = make_confirmation('lost_password', (form.user.uid,))
        confirm_link = url_for('lost_password_complete', token=confirm_token, _external=True)

        body = render_template('mail/lost_password.txt', username=form.user.uid,
                               link=confirm_link)

        send_mail(form.user.attributes['mail'], u'Passwort vergessen', body,
                  sender=app.config.get('MAIL_CONFIRM_SENDER'))

        flash(u'Wir haben dir eine E-Mail mit einem Link zum Passwort ändern '
              u'geschickt. Bitte folge den Anweisungen in der E-Mail.', 'success')

        return redirect(url_for('index'))

    return {'form': form}


@app.route('/lost_password/<token>', methods=['GET', 'POST'])
@templated('lost_password_complete.html')
@logout_required
def lost_password_complete(token):
    username, = http_verify_confirmation('lost_password', token.encode('ascii'), timeout=4*60*60)

    form = RegisterCompleteForm(request.form, csrf_enabled=False)
    if request.method == 'POST' and form.validate():
        user = g.ldap.get_by_uid(username)
        user.change_password(form.password.data)
        g.ldap.update(user, as_admin=True)

        session['username'] = username
        session['password'] = encrypt_password(form.password.data)
        flash(u'Passwort geändert.', 'success')

        return redirect(url_for('settings'))

    return {
        'form': form,
        'token': token,
        'username': username,
    }


@app.route('/settings', methods=['GET', 'POST'])
@templated('settings.html')
@login_required
def settings():
    form = SettingsForm(request.form, mail=g.user.attributes['mail'])
    if request.method == 'POST' and form.validate():
        changed = False

        if request.form.get('submit_services'):
            for service in app.all_services:
                field = form.get_servicedelete(service.id)
                if(field.data):
                    g.user.reset_password(service.id)
                    changed = True

        elif request.form.get('submit_main'):
            if form.mail.data and form.mail.data != g.user.attributes['mail']:
                confirm_token = make_confirmation('change_mail', (g.user.uid, form.mail.data))
                confirm_link = url_for('change_mail', token=confirm_token, _external=True)

                body = render_template('mail/change_mail.txt', username=g.user.uid,
                                       mail=form.mail.data, link=confirm_link)

                send_mail(form.mail.data, u'E-Mail-Adresse bestätigen', body,
                          sender=app.config.get('MAIL_CONFIRM_SENDER'))

                flash(u'Es wurde eine E-Mail an die angegebene Adresse geschickt, '
                      u'um diese zu überprüfen. Bitte folge den Anweisungen in der '
                      u'E-Mail.', 'success')
                changed = True

            if form.password.data:
                g.user.change_password(form.password.data, form.old_password.data)
                session['password'] = encrypt_password(form.password.data)

                flash(u'Passwort geändert', 'success')
                changed = True

            for service in app.all_services:
                field = form.get_servicepassword(service.id)
                if field.data:
                    changed = True
                    g.user.change_password(field.data, None, service.id)

        if changed:
            g.ldap.update(g.user, as_admin=True) #XXX: as_admin wieder wegmachen sobald ACLs richtig gesetzt sind
            return redirect(url_for('settings'))
        else:
            flash(u'Nichts geändert.')


    services = deepcopy(app.all_services)
    for s in services:
        s.changed = s.id in g.user.services

    return {
        'form': form,
        'services': services,
    }

@app.route('/settings/change_mail/<token>')
@login_required
def change_mail(token):
    username, mail = http_verify_confirmation('change_mail', token.encode('ascii'), timeout=3*24*60*60)

    if g.user.uid != username:
        raise Forbidden(u'Bitte logge dich als der Benutzer ein, dessen E-Mail-Adresse du ändern willst.')

    results = g.ldap.find_by_mail(mail)
    for user in results:
        if user.uid != g.user.uid:
            raise Forbidden(u'Diese E-Mail-Adresse wird schon von einem anderen account benutzt!')

    g.user.change_email(mail)
    g.ldap.update(g.user)

    flash(u'E-Mail-Adresse geändert.', 'success')
    return redirect(url_for('settings'))


@app.route('/logout')
def logout():
    logout_user()
    flash(u'Erfolgreich ausgeloggt.', 'success')
    return redirect(url_for('index'))


@app.route('/about')
@templated('about.html')
def about():
    return {}


@app.route('/admin')
@templated('admin_index.html')
def admin():
    return {}


@app.route('/admin/create_account', methods=['GET', 'POST'])
@templated('admin_create_account.html')
@admin_required
def admin_create_account():
    form = AdminCreateAccountForm()
    if request.method == 'POST' and form.validate():
        send_register_confirmation_mail(form.username.data, form.mail.data)

        flash(u'Mail versandt.', 'success')
        return redirect(url_for('admin'))
    return {'form': form}

@app.route('/admin/view_blacklist')
@app.route('/admin/view_blacklist/<start>')
@templated('admin_view_blacklist.html')
@admin_required
def admin_view_blacklist(start=''):
    entries = app.username_blacklist
    if start:
        entries = [e for e in entries if e.startswith(start)]

    next_letters = set(e[len(start)] for e in entries if len(e) > len(start))

    return {
        'entries': entries,
        'start': start,
        'next_letters': next_letters,
    }


@app.route('/admin/disable_account', methods=['GET', 'POST'])
@templated('admin_disable_account.html')
@admin_required
def admin_disable_account():
    form = AdminDisableAccountForm()
    if 'uid' in request.args:
        form = AdminDisableAccountForm(username=request.args['uid'])
    if request.method == 'POST' and form.validate():
        random_pw = str(uuid4())
        form.user.change_password(random_pw)
        for service in app.all_services:
            form.user.reset_password(service.id)

        oldmail = form.user.attributes['mail']
        mail = app.config['DISABLED_ACCOUNT_MAILADDRESS_TEMPLATE'] % form.user.uid
        form.user.change_email(mail)

        g.ldap.update(form.user, as_admin=True)

        flash(u'Passwort auf ein zufälliges und Mailadresse auf %s '
              u'gesetzt.' % mail, 'success')

        if app.config.get('MAIL_REGISTER_NOTIFY'):
            send_mail(
                app.config['MAIL_REGISTER_NOTIFY'],
                u'[accounts] Benutzer %s deaktiviert' % form.user.uid,
                'Benutzername: %s\nE-Mail war:   %s\n\ndurch:        %s\n' % \
                (form.user.uid, oldmail, session['username'])
            )

        return redirect(url_for('admin'))

    return {'form': form}


@app.errorhandler(403)
@app.errorhandler(404)
def errorhandler(e):
    return render_template('error.html', error=e), e.code


@app.route('/debug')
def debug():
    raise Exception()


# we need the app to exist before initializing the forms
from forms import RegisterForm, RegisterCompleteForm, LoginForm, SettingsForm,\
                  LostPasswordForm, AdminCreateAccountForm,\
                  AdminDisableAccountForm


if __name__ == '__main__':
    app.run()