File: admin.py

package info (click to toggle)
trac-accountmanager 0.6.1%2Bsvn18669-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,552 kB
  • sloc: python: 6,863; javascript: 175; makefile: 4
file content (1575 lines) | stat: -rw-r--r-- 75,072 bytes parent folder | download
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 Matthew Good <trac@matt-good.net>
# Copyright (C) 2010-2014 Steffen Hoffmann <hoff.st@web.de>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# Author: Matthew Good <trac@matt-good.net>

from datetime import datetime
import inspect
import re

from trac.admin import IAdminPanelProvider
from trac.config import BoolOption, Option
from trac.core import Component, ExtensionPoint, implements
from trac.perm import PermissionCache, PermissionSystem
from trac.util import as_int
from trac.util.datefmt import format_datetime, to_datetime
from trac.util.html import html as tag
from trac.util.presentation import Paginator
from trac.util.translation import dgettext, tagn_
from trac.util.text import cleandoc, exception_to_unicode
from trac.web.api import IAuthenticator
from trac.web.chrome import Chrome, add_ctxtnav, add_link, add_notice
from trac.web.chrome import add_script, add_stylesheet, add_warning
from trac.wiki.formatter import format_to_html

from .api import AccountManager, IUserIdChanger, _, gettext, ngettext, tag_
from .compat import iteritems, itervalues
from .guard import AccountGuard
from .model import (change_uid, del_user_attribute, email_verification_token,
                    email_verified, get_user_attribute, last_seen,
                    set_user_attribute)
from .notification import NotificationError
from .register import EmailVerificationModule, RegistrationError
from .util import i18n_tag, format_timespan
from .web_ui import AccountModule


def fetch_user_data(env, req, filters=None):
    acctmgr = AccountManager(env)
    guard = AccountGuard(env)
    accounts = {}
    for username in acctmgr.get_users():
        if 'ACCTMGR_USER_ADMIN' in req.perm:
            url = req.href.admin('accounts', 'users', username)
        else:
            url = None
        accounts[username] = {'username': username, 'url': url}
        if guard.user_locked(username):
            accounts[username]['locked'] = True
            t_lock = guard.lock_time(username)
            if t_lock > 0:
                t_release = guard.pretty_release_time(req, username)
                accounts[username]['release_hint'] = _(
                    "Locked until %(t_release)s",
                    t_release=t_release)
    verify_email = env.is_enabled(EmailVerificationModule) and \
                   EmailVerificationModule(env).email_enabled and \
                   EmailVerificationModule(env).verify_email
    for acct, status in iteritems(get_user_attribute(env, username=None,
                                                     authenticated=None)):
        account = accounts.get(acct)
        if account is not None and 1 in status:
            # Only use attributes related to authenticated
            # accounts.
            account['name'] = status[1].get('name')
            account['email'] = status[1].get('email')
            # Obfuscate email address if required.
            if account['email']:
                account['email'] = Chrome(env).format_author(req,
                                                             account['email'])
            approval = status[1].get('approval')
            approval = approval and set((approval,)) or set()
            if approval and filters and not approval.intersection(filters):
                del accounts[acct]
                continue
            if account['email'] and verify_email:
                if email_verified(env, account['username'], account['email']):
                    if approval:
                        account['approval'] = list(approval)
                elif approval:
                    account['approval'] = list(approval.union(['email']))
                elif not filters or 'email' in filters:
                    account['approval'] = ['email']
            elif approval:
                account['approval'] = list(approval)
    if filters and 'active' not in filters:
        inactive_accounts = {}
        for username in accounts:
            if 'approval' in accounts[username]:
                # Hint: This is 30 % faster than dict.update() here.
                inactive_accounts[username] = accounts[username]
        accounts = inactive_accounts
    ts_seen = last_seen(env)
    for username, last_visit in ts_seen:
        account = accounts.get(username)
        if account and last_visit:
            account['last_visit'] = to_datetime(last_visit)
    return sorted(itervalues(accounts), key=lambda acct: acct['username'])


def _getoptions(cls):
    opt_cls = isinstance(cls, Component) and cls.__class__ or cls
    options = [(name, value) for name, value in inspect.getmembers(opt_cls)
               if isinstance(value, Option)]
    index = 0
    for option in options:
        index += 1
        try:
            opt_val = option[1].__get__(cls, cls)
        except AttributeError:
            # Error will be raised again when parsing options list,
            # so don't care here.
            continue
        # Check, if option is a valid component (possibly with own options).
        opt_cls = isinstance(opt_val, Component) and opt_val.__class__ or None
        extents = _getoptions(opt_cls)
        for extent in extents:
            options.insert(index, extent)
            index += 1
    return options


def _setorder(req, components):
    """Pull the password store ordering out of the req object"""
    for c in components.get_all_components():
        components[c] = int(req.args.get(c.__class__.__name__, 0))
        continue


class ExtensionOrder(dict):
    """Keeps the order of components in OrderedExtensionsOption."""

    instance = 0

    def __init__(self, d=None, components=None, list=None):
        super(ExtensionOrder, self).__init__()
        self.instance += 1
        self.d = d or {}
        self.sxref = {}
        for c in components or []:
            self.d[c] = 0
            self[0] = c
            self.sxref[c.__class__.__name__] = c
            continue
        for i, c in enumerate(list or []):
            self.d[c] = i + 1
            self[i + 1] = c

    def __getitem__(self, key):
        """Lookup a component in the list."""
        return self.d[key]

    def __setitem__(self, key, value):
        if isinstance(key, Component):
            order = self.d[key]
            self.d[key] = value
            self.d[order].remove(key)
            self[value] = key
        elif isinstance(key, str):
            self.d[self.sxref[key]] = value
        elif isinstance(key, int):
            self.d.setdefault(key, [])
            self.d[key].append(value)
        else:
            raise KeyError("Invalid key type (%s) for ExtensionOrder" %
                           type(key))
        pass

    def get_enabled_components(self):
        """Return an ordered list of components.

        All components that are order 0 are dropped from the list.
        """
        keys = sorted(k for k in self.d if isinstance(k, int))
        component_list = []
        for k in keys[1:]:
            component_list.extend(self.d[k])
            continue
        return component_list

    def get_enabled_component_names(self):
        """Returns the class names of the enabled components."""
        components = self.get_enabled_components()
        return [c.__class__.__name__ for c in components]

    def get_all_components(self):
        return [k for k in self.d if isinstance(k, Component)]

    def component_count(self):
        return len(self.get_all_components())


class UserAdminPanel(Component):
    implements(IAdminPanelProvider)

    uid_changers = ExtensionPoint(IUserIdChanger)

    ACCTS_PER_PAGE = 20

    def __init__(self):
        self.acctmgr = AccountManager(self.env)
        self.guard = AccountGuard(self.env)

    # IAdminPanelProvider methods

    def get_admin_panels(self, req):
        if 'ACCTMGR_USER_ADMIN' in req.perm:
            yield 'accounts', _("Accounts"), 'users', _("Users")

    def render_admin_panel(self, req, cat, page, path_info):
        if path_info:
            return self._do_acct_details(req, path_info)
        return self._do_users(req)

    def _do_add(self, req):
        """Add new user account on verified request."""
        return _add_user_account(self.env, req)

    def _do_db_cleanup(self, req):
        if 'ACCTMGR_ADMIN' in req.perm:
            env = self.env
            changed = False
            # Get data for all authenticated users from 'session_attribute'.
            attr = get_user_attribute(self.env, username=None,
                                      authenticated=1)
            attrs = {}
            accounts = req.args.get('accounts')
            accounts = accounts and accounts.split(',') or []
            sel = req.args.getlist('sel')
            if req.args.get('purge') and sel:
                sel_len = len(sel)
                matched = []
                for acct, states in iteritems(attr):
                    for state in states['id']:
                        for elem, id in iteritems(states[state]['id']):
                            if id in sel:
                                if acct in attrs:
                                    if state in attrs[acct]:
                                        attrs[acct][state].append(elem)
                                    else:
                                        attrs[acct][state] = [elem]
                                else:
                                    attrs[acct] = {state: [elem]}
                                matched.append(id)
                                if len(matched) == sel_len:
                                    break
                        if len(matched) == sel_len:
                            break
                    if len(matched) == sel_len:
                        break
                for id in (frozenset(sel) - frozenset(matched)):
                    for acct, states in iteritems(attr):
                        for state, id_ in iteritems(states['id']):
                            if id == id_:
                                # Full account is marked, forget attributes.
                                if acct in attrs:
                                    attrs[acct][state] = []
                                else:
                                    attrs[acct] = {state: []}
                                matched.append(id)
                                if len(matched) == sel_len:
                                    break
                        if len(matched) == sel_len:
                            break
                # DEVEL: For Python>2.4 better use defaultdict for counters.
                del_count = {'acct': 0, 'attr': 0}
                for account, states in iteritems(attrs):
                    for state, elem in iteritems(states):
                        if len(elem) == 0:
                            del_user_attribute(env, account, state)
                            del_count['acct'] += 1
                        else:
                            for attribute in elem:
                                del_user_attribute(env, account, state,
                                                   attribute)
                                del_count['attr'] += 1
                    changed = True

            if changed:
                accounts_ = attributes = ''
                n_plural = del_count['acct']
                if n_plural > 0:
                    accounts_ = tag.li(ngettext("%(count)s account",
                                                "%(count)s accounts",
                                                n_plural, count=n_plural))
                n_plural = del_count['attr']
                if n_plural > 0:
                    attributes = tag.li(ngettext(
                        "%(count)s account attribute",
                        "%(count)s account attributes",
                        n_plural, count=n_plural))
                add_notice(req, tag_("Successfully deleted: %(account)s",
                                     account=tag.ul(accounts_, attributes)))
                # Update the dict after changes.
                attr = get_user_attribute(env, username=None,
                                          authenticated=1)
            if not accounts and sel:
                # Get initial account selection from account/user list.
                accounts = sel
            attr_sel = dict((account, states)
                            for account, states in iteritems(attr)
                            if account in accounts)

            if len(accounts) == 1:
                back_label = _("Back to Account")
                back_href = req.href.admin('accounts', 'users', accounts[0])
            else:
                back_label = _("Back to Accounts")
                back_href = req.href.admin('accounts', 'users')
            add_ctxtnav(req, back_label, href=back_href)
            add_stylesheet(req, 'acct_mgr/acctmgr.css')
            data = dict(i18n_tag=i18n_tag, accounts=accounts, attr=attr_sel)
            return 'account_db_cleanup.html', data

    def _do_acct_details(self, req, username):
        env = self.env
        acctmgr = self.acctmgr
        guard = self.guard

        if not (username and acctmgr.has_user(username)):
            add_warning(req, _(
                "Please choose account by username from the list to proceed."
            ))
            req.redirect(req.href.admin('accounts', 'users'))

        change_uid_enabled = self.uid_changers and True or False
        data = dict(i18n_tag=i18n_tag,
                    attr_addonly=bool(req.args.get('attr_addonly')),
                    change_uid_enabled=change_uid_enabled,
                    skip_delete=bool(req.args.get('skip_delete')),
                    uid_exists=bool(req.args.get('uid_exists')),
                    url=req.href.admin('accounts', 'users', username),
                    user=username)

        verify_enabled = False
        if env.is_enabled(EmailVerificationModule):
            verify_enabled = EmailVerificationModule(env).email_enabled and \
                             EmailVerificationModule(env).verify_email
        email_approved = req.args.get('email_approved')
        if verify_enabled:
            # Preserve selection during a series of requests.
            data['email_approved'] = email_approved
            data['verify_enabled'] = verify_enabled

        if req.method == 'POST':
            action = req.args.get('action', '')

            # Change attributes and or password of existing user account.
            if action == 'edit':
                labels = {
                    'email': _("Email Address"),
                    'name': _("Pre-/Surname (Nickname)"),
                    'password': _("Password")
                }
                attributes = get_user_attribute(self.env, username=username,
                                                authenticated=1)
                old_values = {}
                if username in attributes:
                    old_values['name'] = attributes[username][1].get('name')
                    old_values['email'] = attributes[username][1].get('email')
                success = []

                # Delete a single user account attribute value.
                if any(k.startswith('delete_email') for k in req.args):
                    del_user_attribute(env, username, attribute='email')
                    add_notice(req, tag_(
                        "Deleted %(attribute)s for %(username)s.",
                        attribute=tag.b(labels.get('email')),
                        username=tag.b(username)))
                elif any(k.startswith('delete_name') for k in req.args):
                    del_user_attribute(env, username, attribute='name')
                    add_notice(req, tag_(
                        "Deleted %(attribute)s for %(username)s.",
                        attribute=tag.b(labels.get('name')),
                        username=tag.b(username)))

                password = req.args.get('password')
                if password and (password.strip() != ''):
                    if password != req.args.get('password_confirm'):
                        add_warning(req, _("The passwords must match."))
                    else:
                        self._set_password(req, username, password)
                        success.append(labels.get('password'))
                for attribute in ('name', 'email'):
                    value = req.args.get(attribute, '').strip()
                    if (old_values.get(attribute) or '') != value:
                        # Save changes.
                        keys = dict(sent='email_verification_sent_to',
                                    token='email_verification_token')
                        if value:
                            set_user_attribute(env, username, attribute,
                                               value)
                            # Account email approval for authoritative action.
                            if attribute == 'email' and verify_enabled and \
                                    email_approved:
                                set_user_attribute(env, username,
                                                   keys['sent'],
                                                   value)
                                del_user_attribute(env, username,
                                                   attribute=keys['token'])
                        else:
                            del_user_attribute(env, username,
                                               attribute=attribute)
                            if attribute == 'email':
                                for key in keys:
                                    del_user_attribute(env, username,
                                                       attribute=keys[key])
                        success.append(labels.get(attribute))
                if success:
                    attributes = tag.b(', '.join(success))
                    add_notice(req, tag_(
                        "Updated %(attributes)s for %(username)s.",
                        attributes=attributes,
                        username=tag.b(username)))

            # Change user ID of existing user account.
            elif action == 'uid':
                new_uid = req.args.get('new_uid', '').strip()
                results = None
                if new_uid:
                    results = self._do_change_uid(req, username, new_uid)
                if not results:
                    pass
                elif 'error' in results:
                    for key, message in iteritems(results['error']):
                        add_warning(req, _(
                            "Update error in table %(table)s: %(message)s",
                            table=key[0], message=message))
                        break
                else:
                    add_notice(req, tag.ul(
                        [tag.li(ngettext(
                            "Table %(table)s column %(column)s%(constraint)s: "
                            "%(result)s change",
                            "Table %(table)s column %(column)s%(constraint)s: "
                            "%(result)s changes",
                            n_changes,
                            table=tag.b(key[0]),
                            column=tag.b(key[1]),
                            constraint='(' + key[2] + ')' if key[2] else '',
                            result=tag.b(n_changes)))
                            for key, n_changes in sorted(iteritems(results))]
                    ))
                    # Switch to display information for new user ID.
                    username = new_uid
                    data.update({
                        'url': req.href.admin('accounts', 'users', username),
                        'user': username,
                    })

        # Get account attributes and account status information.
        stores = ExtensionOrder(components=acctmgr.stores,
                                list=acctmgr.password_stores)
        user_store = acctmgr.find_user_store(username)
        if user_store:
            data['user_store'] = user_store.__class__.__name__
            data['store_order_num'] = stores[user_store]
            if hasattr(user_store, 'set_password'):
                data['password_change_enabled'] = True
        data['ignore_auth_case'] = \
            self.config.getbool('trac', 'ignore_auth_case')

        approval = email = name = None
        # Fetch data from 'session_attribute'.
        attributes = get_user_attribute(self.env, username=username,
                                        authenticated=1)
        if username in attributes:
            name = attributes[username][1].get('name')
            email = attributes[username][1].get('email')
            if self.config.getbool('account-manager', 'require_approval'):
                approval = attributes[username][1].get('approval')
        data['acctmgr'] = dict(email=email, name=name)

        if email and verify_enabled:
            data['verification'] = 'enabled'
            data['email_verified'] = email_verified(env, username, email)
            data['email_verification_token'] = \
                email_verification_token(env, username, email)
            self.log.debug('AcctMgr:admin:_do_acct_details for user "%s" '
                           'email "%s": %s', username, email,
                           data['email_verified'])

        if req.args.get('delete') or req.args.get('release'):
            if approval and req.args.get('release'):
                # Admit authenticated/registered session.
                del_user_attribute(env, username, attribute='approval')
                add_notice(req, tag_(
                    "Account lock (%(condition)s) for user %(user)s cleared",
                    condition=gettext(approval), user=tag.b(username)))
                approval = None
            # Delete failed login attempts, evaluating attempts count.
            if guard.failed_count(username, reset=True) > 0:
                add_notice(req, tag_(
                    "Failed login attempts for user %(user)s deleted",
                    user=tag.b(username)))
        data['approval'] = approval

        # Get access history.
        ts_seen = last_seen(env, username)
        if ts_seen and ts_seen[0][1]:
            data['last_visit'] = datetime.fromtimestamp(ts_seen[0][1], req.tz)

        if self.env.is_enabled(AccountGuard):
            attempts = []
            attempts_count = guard.failed_count(username, reset=None)
            if attempts_count > 0:
                for attempt in guard.get_failed_log(username):
                    attempt = attempt.copy()
                    attempt['time'] = datetime.fromtimestamp(attempt['time'],
                                                             req.tz)
                    attempts.append(attempt)
                data['attempts'] = attempts
                data['pretty_lock_time'] = guard.pretty_lock_time(username,
                                                                  next=True)
            data['attempts_count'] = attempts_count
            data['lock_count'] = guard.lock_count(username)
            if guard.user_locked(username) is True:
                data['user_locked'] = True
                data['release_time'] = guard.pretty_release_time(req,
                                                                 username)

        # TRANSLATOR: Optionally tabbed account editor's label
        forms = [('edit', _('Modify Account'))]
        if change_uid_enabled:
            forms.append(('uid', _('Change User ID')))

        data['forms'] = forms
        data['active_form'] = req.args.get('action') or forms[0][0]
        add_ctxtnav(req, _("Account Attributes"),
                    href=req.href.admin('accounts', 'users', cleanup='1',
                                        accounts=username))
        add_ctxtnav(req, _("Back to Accounts"),
                    href=req.href.admin('accounts', 'users'))
        add_stylesheet(req, 'acct_mgr/acctmgr.css')
        return 'account_admin.html', data

    def _do_users(self, req):
        env = self.env
        acctmgr = self.acctmgr
        acctmod = AccountModule(env)
        listing_enabled = acctmgr.supports('get_users')
        password_change_enabled = acctmgr.supports('set_password')
        password_reset_enabled = acctmod.reset_password_enabled
        delete_enabled = acctmgr.supports('delete_user')
        verify_enabled = (EmailVerificationModule(env).email_enabled and
                          EmailVerificationModule(env).verify_email)
        data = {
            'i18n_tag': i18n_tag,
            'acctmgr': dict(), 'email_approved': True, 'filters': [],
            'listing_enabled': listing_enabled,
            'create_enabled': acctmgr.supports('set_password'),
            'delete_enabled': delete_enabled,
            'verify_enabled': verify_enabled,
            'ignore_auth_case': self.config.getbool('trac',
                                                    'ignore_auth_case'),
            'password_change_enabled': password_change_enabled,
            'password_reset_enabled': password_reset_enabled
        }
        if req.method == 'GET':
            if req.args.get('cleanup'):
                return self._do_db_cleanup(req)

        if req.method == 'POST':
            email_approved = req.args.get('email_approved')
            # Preserve selection during a series of requests.
            data['email_approved'] = email_approved

            sel = req.args.getlist('sel')
            if 'add' in req.args:
                # Add new user account.
                data['acctmgr'] = self._do_add(req)

            elif 'approve' in req.args and sel:
                # Toggle approval status for selected accounts.
                ban = []
                unban = []
                for username in sel:
                    # Get account approval status.
                    status = get_user_attribute(env, username,
                                                attribute='approval')
                    status = username in status and \
                             status[username][1].get('approval') or None
                    if status:
                        # Admit authenticated/registered session.
                        del_user_attribute(env, username,
                                           attribute='approval')
                        unban.append(username)
                    else:
                        # Ban the account.
                        set_user_attribute(env, username, 'approval',
                                           'revoked')
                        ban.append(username)
                msg = None
                if unban:
                    accounts = tag.b(', '.join(unban))
                    msg = tagn_("Approved account: %(accounts)s",
                                "Approved accounts: %(accounts)s",
                                len(unban), accounts=accounts)
                if ban:
                    msg = tag(msg, tag.br()) if msg else tag()
                    accounts = tag.b(', '.join(ban))
                    msg(tagn_("Banned account: %(accounts)s",
                              "Banned accounts: %(accounts)s",
                              len(ban), accounts=accounts))
                if ban or unban:
                    add_notice(req, msg)
            elif 'reset' in req.args and sel:
                # Password reset for one or more accounts.
                if password_reset_enabled:
                    for username, name, email in env.get_known_users():
                        if username in sel:
                            acctmod._reset_password(req, username, email)
                    if sel:
                        add_notice(req, tag_(
                            "Password reset for %(accounts)s.",
                            accounts=tag.b(', '.join(sel))))
                else:
                    add_warning(req, _(
                        "The password reset procedure is not enabled."))
            elif 'remove' in req.args and sel:
                # Delete one or more accounts.
                if delete_enabled:
                    for account in sel:
                        self._delete_user(req, account)
                    if sel:
                        add_notice(req, tag_(
                            "Deleted account: %(accounts)s",
                            accounts=tag.b(', '.join(sel))))
                else:
                    add_warning(req, _("The password store does not support "
                                       "deleting users."))
            elif any(action for action in req.args
                            if action in ('cleanup', 'purge', 'unselect')):
                return self._do_db_cleanup(req)
            req.redirect(req.href.admin('accounts', 'users'))

        # (Re-)Build data for current user list.
        available_filters = [
            ('active', _("active")),
            ('revoked', _("revoked"), False),  # not shown by default
            ('pending', _("pending approval"))
        ]
        if verify_enabled:
            available_filters.append(('email', _("email unverified")))
        # Check request or session for enabled filters, or use default.
        filters = [f[0] for f in available_filters
                        if 'filter_%s' % f[0] in req.args]
        key = 'acctmgr_user.filter.%s'
        if not filters:
            filters = [f[0] for f in available_filters
                       if req.session.get(key % f[0]) == '1']
        if not filters:
            filters = [f[0] for f in available_filters
                       if len(f) == 2 or f[2]]
        for filter_ in available_filters:
            data['filters'].append({
                'name': filter_[0],
                'label': filter_[1],
                'enabled': filter_[0] in filters
            })
        if listing_enabled:
            data.update({
                'cls': 'listing',
                'cols': ['email', 'name'],
                'delete_msg_confirm': _(
                    "Are you sure you want to delete these accounts?")})

            # Preserve pager setting.
            if 'max_per_page' in req.args:
                max_per_page = req.args.get('max_per_page')
                req.session.set('acctmgr_user.max_items', max_per_page,
                                self.ACCTS_PER_PAGE)
                req.redirect(req.href.admin('accounts', 'users'))
            # Save results of submitted user list filter form to the session.
            elif 'update' in req.args:
                for filter_ in available_filters:
                    key = 'acctmgr_user.filter.%s' % filter_[0]
                    if 'filter_%s' % filter_[0] in req.args:
                        req.session[key] = '1'
                    elif key in req.session:
                        del req.session[key]
                req.redirect(req.href.admin('accounts', 'users'))

            # Read account information.
            data.update(self._paginate(req, fetch_user_data(env, req,
                                                            filters)))
        add_stylesheet(req, 'acct_mgr/acctmgr.css')
        add_stylesheet(req, 'common/css/report.css')
        return 'account_users.html', data

    def _do_change_uid(self, req, old_uid, new_uid):
        acctmgr = self.acctmgr
        acctmod = AccountModule(self.env)
        attr_overwrite = not bool(req.args.get('attr_addonly'))
        create_user = not bool(req.args.get('uid_exists'))
        delete_user = not bool(req.args.get('skip_delete'))
        email = None

        # Demand conditions required for a successful change.
        store_old = acctmgr.find_user_store(old_uid)
        if delete_user and store_old and \
                not hasattr(store_old, 'delete_user'):
            add_warning(req, tag_(
                "Removing the old user is not supported by %(store)s.",
                store=tag.b(store_old.__class__.__name__)))
            return
        stores = ExtensionOrder(components=acctmgr.stores,
                                list=acctmgr.password_stores)
        # Predict stores for old and new account.
        keep_passwd = False
        for store in stores.get_enabled_components():
            if not hasattr(store, 'set_password'):
                continue
            if store == store_old:
                # DEVEL: Preserve passwords for other stores too.
                keep_passwd = store.__class__.__name__ == 'SessionStore'
            break

        if create_user:
            if acctmgr.password_stores and \
                    not acctmgr.supports('set_password'):
                add_warning(req, _(
                    "None of the configured password stores is writable."))
                return
            if not (acctmod.reset_password_enabled or keep_passwd):
                add_warning(req, _(
                    "Password reset is a required action, but disabled yet."))
                return
            # Ensure, that the new ID must pass basic checks.
            checks = ExtensionOrder(components=acctmgr.checks,
                                    list=acctmgr.register_checks)
            required_check = 'BasicCheck'
            if required_check not in checks.get_enabled_component_names():
                add_warning(req, tag_(
                    "At least %(required_check)s must be configured and "
                    "enabled.", required_check=tag.b(required_check)))
                return

            req.args['username'] = new_uid
            # Prime request with data to prevent input validation failures.
            req.args['password'] = req.args['password_confirm'] = 'pass'
            attributes = get_user_attribute(self.env, old_uid)
            email = old_uid in attributes and \
                    attributes[old_uid][1].get('email') or None
            if email:
                req.args['email'] = email
                # Prevent account verification failure due to existing email
                # address.
                del_user_attribute(self.env, old_uid, attribute='email')

            name = old_uid in attributes and \
                   attributes[old_uid][1].get('name') or None
            if name:
                req.args['name'] = name

            try:
                acctmgr.validate_account(req)
            except RegistrationError as e:
                add_warning(req, e)
                if email:
                    set_user_attribute(self.env, old_uid, 'email', email)
                return
            if not keep_passwd and \
                            self._set_password(req, new_uid,
                                               acctmod._random_password,
                                               False) is None:
                add_warning(req, _(
                    "Failed to save new login data to a password store."))
                if email:
                    set_user_attribute(self.env, old_uid, 'email', email)
                return

        # Call all user ID changers.
        results = change_uid(self.env, old_uid, new_uid, self.uid_changers,
                             attr_overwrite)
        if 'error' in results:
            if create_user:
                # Rollback all changes including newly created account.
                self._delete_user(req, new_uid)
                if email:
                    set_user_attribute(self.env, old_uid, 'email', email)
            return results

        attributes = get_user_attribute(self.env, new_uid, attribute='email')
        email_new = new_uid in attributes and attributes[new_uid].get(1) and \
                    attributes[new_uid][1].get('email') or None
        if email and (create_user or attr_overwrite or not email_new):
            set_user_attribute(self.env, new_uid, 'email', email)
            if not keep_passwd:
                acctmod._reset_password(req, new_uid, email)
        elif email_new and not keep_passwd:
            acctmod._reset_password(req, new_uid, email_new)
        elif not keep_passwd:
            add_warning(req, tag_(
                "Cannot send the new password to the user, because no email "
                "address is associated with %(username)s.",
                username=tag.b(new_uid)))
        if delete_user:
            # Finally delete old user ID.
            self._delete_user(req, old_uid)
        # Notify listeners about successful ID change.
        try:
            acctmgr._notify('id_changed', old_uid, new_uid)
        except NotificationError as e:
            add_warning(req, _("Error raised while sending a change "
                               "notification.") +
                        _("You'll get details with TracLogging "
                          "enabled."))
            self.log.error('Unable to send user ID change notification: %s',
                           exception_to_unicode(e, traceback=True))
        return results

    def _set_password(self, req, username, password, overwrite=True):
        """Password saving with graceful handling of notification errors."""
        try:
            result = self.acctmgr.set_password(username, password,
                                               overwrite=overwrite)
        except NotificationError as e:
            add_warning(req, _("Error raised while sending a change "
                               "notification.") +
                        _("You'll get details with TracLogging enabled."))
            self.log.error('Unable to send password change notification: %s',
                           exception_to_unicode(e, traceback=True))
            result = self.acctmgr.has_user(username) or None
        return result

    def _delete_user(self, req, username):
        """Delete method, that handles notification errors gracefully."""
        try:
            self.acctmgr.delete_user(username)
        except NotificationError as e:
            add_warning(req, _("Error raised while sending a change "
                               "notification.") +
                        _("You'll get details with TracLogging "
                          "enabled."))
            self.log.error('Unable to send user delete notification: %s',
                           exception_to_unicode(e, traceback=True))

    def _paginate(self, req, accounts):
        max_per_page = as_int(req.session.get('acctmgr_user.max_items'),
                              self.ACCTS_PER_PAGE)
        page = int(req.args.get('page', '1'))
        total = len(accounts)
        pager = Paginator(accounts, page - 1, max_per_page)
        pagedata = []
        shown_pages = pager.get_shown_pages(21)
        for shown_page in shown_pages:
            page_href = req.href.admin('accounts', 'users', page=shown_page)
            pagedata.append([page_href, None, str(shown_page),
                             _("page %(num)s", num=str(shown_page))])
        # Prepare bottom and top pager navigation data.
        fields = ['href', 'class', 'string', 'title']
        pager.current_page = {'href': None, 'class': 'current',
                              'string': str(pager.page + 1), 'title': None}
        pager.shown_pages = [dict(zip(fields, p)) for p in pagedata]
        if pager.has_more_pages:
            # Show '# of #' instead of total count.
            total = pager.displayed_items()
        if pager.has_next_page:
            next_href = req.href.admin('accounts', 'users', page=page + 1)
            add_link(req, 'next', next_href, _('Next Page'))
        if pager.has_previous_page:
            prev_href = req.href.admin('accounts', 'users', page=page - 1)
            add_link(req, 'prev', prev_href, _('Previous Page'))
        page_href = req.href.admin('accounts', 'cleanup')
        return dict(accounts=pager, displayed_items=total,
                    page_href=page_href)


class ConfigurationAdminPanel(Component):
    implements(IAdminPanelProvider, IAuthenticator)

    auth_init = BoolOption('account-manager', 'auth_init', True,
                           doc="Launch an initial Trac authentication setup.")

    def __init__(self):
        self.acctmgr = AccountManager(self.env)
        self.authname = 'setup'
        self.cfg_action = 'ACCTMGR_CONFIG_ADMIN'
        self.guard = AccountGuard(self.env)
        self.perms = PermissionSystem(self.env)

    # IAdminPanelProvider methods

    def get_admin_panels(self, req):
        if 'ACCTMGR_CONFIG_ADMIN' in req.perm:
            yield 'accounts', _("Accounts"), 'config', _("Configuration")

    def render_admin_panel(self, req, cat, page, path_info):
        return self._do_config(req)

    def _do_config(self, req):
        cfg = self.config
        env = self.env

        def safe_wiki_to_html(context, text):
            """Convenience function from trac.admin.web_ui."""
            try:
                return format_to_html(env, context, text)
            except Exception as e:
                self.log.error('Unable to render component documentation: %s',
                               exception_to_unicode(e, traceback=True))
            return tag.pre(text)

        data = {
            'i18n_tag': i18n_tag,
            'format_timespan': format_timespan,
            'safe_wiki_to_html': safe_wiki_to_html,
        }

        # Prefer args from URL to make progress bar links work.
        step = req.args.get('step', 0)
        step = int(step and step or req.args.get('active', 0))
        stores = ExtensionOrder(components=self.acctmgr.stores,
                                list=self.acctmgr.password_stores)
        register_checks = self.config.getlist('account-manager',
                                              'register_checks')
        checks = ExtensionOrder(components=self.acctmgr.checks,
                                list=register_checks)

        def _redirect(req):
            # Use permission-sensitive redirection on exit.
            if 'ACCTMGR_USER_ADMIN' in req.perm:
                req.redirect(req.href.admin('accounts', 'users'))
            req.redirect(req.href())

        if req.method == 'POST':
            # Rollback unsaved configuration changes.
            if req.args.get('exit'):
                try:
                    cfg.parse_if_needed(force=True)  # Full reload
                except TypeError:
                    # Attribute was introduced in Trac 0.12, so a fallback
                    # for compatibility down to 0.11 is required.
                    cfg.touch()  # Fake write access for reload
                _redirect(req)
            # Don't care as long as the feature is disabled.
            elif req.args.get('restart') and self.acctmgr.refresh_passwd:
                del_user_attribute(self.env, attribute='password_refreshed')
                add_notice(req,
                           _("Password hash refresh procedure restarted."))

        account = dict()
        if req.method == 'POST' and (req.args.get('back') or
                                         req.args.get('next') or
                                         req.args.get('save')):
            # Handling only values for the current page is important.
            if step == 0:
                cfg.set('trac', 'auth_cookie_lifetime',
                        int(req.args.get('auth_cookie_lifetime')))
                cfg.set('trac', 'secure_cookies',
                        bool(req.args.get('secure_cookies', False)))
                cfg.set('trac', 'check_auth_ip',
                        bool(req.args.get('check_auth_ip', False)))
                cfg.set('trac', 'ignore_auth_case',
                        bool(req.args.get('ignore_auth_case', False)))
                acctmgr_login = bool(int(req.args.get('acctmgr_login')))
                # These two can't work in parallel.
                cfg.set('components', 'acct_mgr.web_ui.LoginModule',
                        acctmgr_login and 'enabled' or 'disabled')
                cfg.set('components', 'trac.web.auth.LoginModule',
                        acctmgr_login and 'disabled' or 'enabled')
                if acctmgr_login:
                    cfg.set('account-manager', 'login_opt_list',
                            bool(req.args.get('login_opt_list', False)))
                    cfg.set('account-manager', 'persistent_sessions',
                            bool(req.args.get('persistent_sessions', False)))
                    cfg.set('account-manager', 'cookie_refresh_pct',
                            int(req.args.get('cookie_refresh_pct', False)))
                    cfg.set('trac', 'auth_cookie_path',
                            req.args.get('auth_cookie_path'))

            elif step == 1:
                # This section is as critical as it is complicated by the
                # amount of available options and combinations of options.
                # We restrict initial setup to a single store, allowing to
                # configure additional ones later on in the self-adapting
                # multi-store setup view.
                init_store = req.args.get('init_store')
                init_store_file = req.args.get('init_store_file')
                if init_store:
                    # Define shortcuts for common strings.
                    a = 'account-manager'
                    c = 'components'
                    e = 'enabled'
                    p = 'password_store'
                    # Set minimal required options, leaving most options out
                    # to keep them at - maybe changing - default values.
                    if init_store == 'db':
                        cfg.set(a, p, 'SessionStore')
                        cfg.set(c, 'acct_mgr.db.SessionStore', e)
                        cfg.set(c, 'acct_mgr.pwhash.HtDigestHashMethod', e)
                        from .db import SessionStore
                        from .pwhash import HtDigestHashMethod
                        assert env.is_enabled(HtDigestHashMethod)
                        assert env.is_enabled(SessionStore)
                    elif init_store == 'file':
                        if init_store_file == 'htdigest':
                            cfg.set(a, 'htdigest_file', 'trac.htdigest')
                            cfg.set(a, p, 'HtDigestStore')
                            cfg.set(c, 'acct_mgr.htfile.HtDigestStore', e)
                            from .htfile import HtDigestStore
                            assert env.is_enabled(HtDigestStore)
                        elif init_store_file == 'htpasswd':
                            cfg.set(a, 'htpasswd_file', 'trac.htpasswd')
                            cfg.set(a, 'htpasswd_hash_type', 'md5')
                            cfg.set(a, p, 'HtPasswdStore')
                            cfg.set(c, 'acct_mgr.htfile.HtPasswdStore', e)
                            from .htfile import HtPasswdStore
                            assert env.is_enabled(HtPasswdStore)
                        elif init_store_file == 'svn_file':
                            cfg.set(a, p, 'SvnServePasswordStore')
                            cfg.set(c,
                                    'acct_mgr.svnserve.SvnServePasswordStore',
                                    e)
                            from .svnserve import SvnServePasswordStore
                            assert env.is_enabled(SvnServePasswordStore)
                    elif init_store == 'http':
                        cfg.set(a, p, 'HttpAuthStore')
                        cfg.set(c, 'acct_mgr.http.HttpAuthStore', e)
                        from .http import HttpAuthStore
                        assert env.is_enabled(HttpAuthStore)
                        # ToDo
                        # elif init_store == 'etc':
                        #    [account-manager]
                        #    password_store =
                        #    [components]
                else:
                    _setorder(req, stores)
                    cfg.set('account-manager', 'password_store',
                            ','.join(stores.get_enabled_component_names()))
                    for store in stores.get_all_components():
                        for attr, option in _getoptions(store):
                            cls_name = store.__class__.__name__
                            newval = req.args.get('%s.%s' % (cls_name, attr))
                            self.log.debug("%s.%s: %s", cls_name, attr,
                                           newval)
                            if newval is not None:
                                cfg.set(option.section, option.name, newval)
                    cfg.set('account-manager', 'refresh_passwd',
                            bool(req.args.get('refresh_passwd', False)))
                # Refresh object after changes.
                stores = ExtensionOrder(components=self.acctmgr.stores,
                                        list=self.acctmgr.password_stores)

            elif step == 2:
                reset_password = bool(req.args.get('reset_password', False))
                # Enable the required hash method for this SessionStore too.
                hash_method = cfg.get('account-manager', 'hash_method')
                cfg.set('components', 'acct_mgr.pwhash.%s'
                        % hash_method, 'enabled')
                cfg.set('components', 'acct_mgr.web_ui.ResetPwStore',
                        reset_password and 'enabled' or 'disabled')
                cfg.set('account-manager', 'reset_password', reset_password)
                cfg.set('account-manager', 'generated_password_length',
                        int(req.args.get('generated_password_length')))
                cfg.set('account-manager', 'force_passwd_change',
                        bool(req.args.get('force_passwd_change', False)))

            elif step == 3:
                change_uid_enabled = bool(req.args.get('change_uid_enabled'))
                cfg.set('components', 'acct_mgr.model.*',
                        change_uid_enabled and 'enabled' or 'disabled')
                # Force 'disabled' status for all related components.
                if not change_uid_enabled and cfg['components'].options():
                    for k, v in cfg['components'].options():
                        if k.startswith('acct_mgr.model.') and \
                                        k != 'acct_mgr.model.*':
                            cfg.remove('components', k)
                acctmgr_register = req.args.get('acctmgr_register', False)
                cfg.set('components', 'acct_mgr.register.RegistrationModule',
                        acctmgr_register and 'enabled' or 'disabled')
                cfg.set('account-manager', 'allow_delete_account',
                        bool(req.args.get('allow_delete_account', False)))
                _setorder(req, checks)
                cfg.set('account-manager', 'register_check',
                        ','.join(checks.get_enabled_component_names()))
                for check in checks.get_all_components():
                    for attr, option in _getoptions(check):
                        cls_name = check.__class__.__name__
                        newval = req.args.get('%s.%s' % (cls_name, attr))
                        self.log.debug("%s.%s: %s", cls_name, attr, newval)
                        if newval is not None:
                            cfg.set(option.section, option.name, newval)
                if acctmgr_register:
                    # Should require approval for user self-registrations,
                    # not for accounts created by admin users alone.
                    cfg.set('account-manager', 'require_approval',
                            bool(req.args.get('require_approval', False)))
                # Allow email verification regardless of account creator.
                verify_email = bool(req.args.get('verify_email', False))
                cfg.set('account-manager', 'verify_email', verify_email)
                cfg.set(
                    'components', 'acct_mgr.register.EmailVerificationModule',
                    verify_email and 'enabled' or 'disabled')
                # Refresh object after changes.
                register_checks = self.config.getlist('account-manager',
                                                      'register_check')
                checks = ExtensionOrder(components=self.acctmgr.checks,
                                        list=register_checks)

            elif step == 4:
                acctmgr_guard = req.args.get('acctmgr_guard', False)
                cfg.set('components', 'acct_mgr.guard.AccountGuard',
                        acctmgr_guard and 'enabled' or 'disabled')
                cfg.set('account-manager', 'login_attempt_max_count',
                        as_int(req.args.get('login_attempt_max_count'),
                               self.guard.login_attempt_max_count, min=0))
                user_lock_time = as_int(req.args.get('user_lock_time'),
                                        self.guard.user_lock_time, min=0)
                cfg.set('account-manager', 'user_lock_time', user_lock_time)
                # AccountGuard.lock_time_progression has the sanitized value.
                cfg.set('account-manager', 'user_lock_time_progression',
                        req.args.get('user_lock_time_progression') or
                        self.guard.lock_time_progression)
                cfg.set('account-manager', 'user_lock_max_time',
                        as_int(req.args.get('user_lock_max_time'),
                               self.guard.user_lock_max_time,
                               min=user_lock_time))

            if req.args.get('save') and step == 5:
                perms = self.perms.get_user_permissions(self.authname)
                if perms.get(self.cfg_action) and perms[self.cfg_action]:
                    # Revoke initial configuration permission.
                    self.perms.revoke_permission(self.authname,
                                                 self.cfg_action)
                    # Restore 'authenticated' users permissions.
                    perms = self.perms.get_user_permissions('auth_moved')
                    for action in perms:
                        # Filter actions inherited from 'anonymous'.
                        if perms[action] and \
                                        action not in PermissionCache(
                                    self.env):
                            self.perms.grant_permission('authenticated',
                                                        action)
                            self.perms.revoke_permission('auth_moved', action)
                # Prevent to run another initial setup later.
                cfg.set('account-manager', 'auth_init', False)
                # Write changes back to file to make them permanent, what
                # causes the environment to reload on following redirect.
                cfg.save()
                add_notice(req, _("Your changes have been saved."))
                _redirect(req)
            else:
                add_notice(req, _(
                    "Your changes are cached until you either drop or save "
                    "them all (see last step)."))

        if req.method == 'POST' and req.args.get('add'):
            # Initial admin account requested.
            account = _add_user_account(self.env, req)
            username = self.acctmgr.handle_username_casing(
                req.args.get('username', '').strip())
            if not account and username:
                self.perms.grant_permission(username, 'TRAC_ADMIN')

        # Prepare information for progress bar and page navigation.
        if req.method == 'POST':
            if 'next' in req.args:
                step += 1
            elif ('back' in req.args or 'prev' in req.args) and step > 0:
                step -= 1
        steps = [
            dict(label=_("Authentication Options"), past=step > 0),
            dict(image='users', label=_("Password Store"), past=step > 1),
            dict(image='refresh', label=_("Password Policy"), past=step > 2),
            dict(image='approval', label=_("Account Policy"), past=step > 3),
            dict(image='guard', label=_("Account Guard"), past=step > 4),
            dict(label=_("Initialization"))
        ]
        data.update({
            'active': step, 'steps': steps,

            'auth_cookie_lifetime': cfg.getint('trac',
                                               'auth_cookie_lifetime'),
            'secure_cookies': cfg.getbool('trac', 'secure_cookies'),
            'check_auth_ip': cfg.getbool('trac', 'check_auth_ip'),
            'ignore_auth_case': cfg.getbool('trac', 'ignore_auth_case'),
            'acctmgr_login': cfg.getbool('components',
                                         'acct_mgr.web_ui.LoginModule'),
            'login_opt_list': cfg.getbool('account-manager',
                                          'login_opt_list'),
            'persistent_sessions': self.acctmgr.persistent_sessions,
            'cookie_refresh_pct': cfg.getint('account-manager',
                                             'cookie_refresh_pct'),
            'auth_cookie_path': cfg.get('trac', 'auth_cookie_path'),
        })

        # Build password store configuration details.
        disabled_store = None
        password_store = cfg.getlist('account-manager', 'password_store')
        data.update({'password_store': password_store})
        if password_store:
            store_count = range(0, stores.component_count() + 1)
            store_list = []
            for store in self.acctmgr.stores:
                if store.__class__.__name__ == "ResetPwStore":
                    # Exclude special store, that is used strictly internally
                    # and inherits configuration from SessionStore anyway.
                    continue
                options = []
                for attr, option in _getoptions(store):
                    error = None
                    opt_val = None
                    value = None
                    try:
                        opt_val = option.__get__(store, store)
                    except AttributeError as e:
                        env.log.error(e)
                        regexp = r'^.* interface named \"(.*?)\".*$'
                        error = _("Error while reading configuration - Hint: "
                                  "Enable/install required component '%s'."
                                  % re.sub(regexp, r'\1', str(e)))
                        pass
                    if opt_val:
                        value = isinstance(opt_val, Component) and \
                                opt_val.__class__.__name__ or opt_val
                    opt_sel = None
                    try:
                        option.xtnpt.interface
                    except AttributeError:
                        # No ExtensionOption / Interface undefined.
                        pass
                    else:
                        opt_sel = {'options': [], 'selected': None}
                    if opt_sel:
                        for impl in option.xtnpt.extensions(env):
                            extension = impl.__class__.__name__
                            opt_sel['options'].append(extension)
                            if opt_val and extension == value:
                                opt_sel['selected'] = extension
                        if len(opt_sel['options']) == 0 and error:
                            opt_sel['error'] = error
                        value = opt_sel
                    options.append({
                        'label': attr,
                        'name': '%s.%s' % (store.__class__.__name__, attr),
                        'value': value,
                        'doc': gettext(option.__doc__)
                    })
                    continue
                store_list.append({
                    'name': store.__class__.__name__,
                    'classname': store.__class__.__name__,
                    'order': stores[store],
                    'options': options
                })
                continue
            store_list = sorted(store_list, key=lambda i: i['order'])
            disabled_store = frozenset(password_store).difference(frozenset(
                [store['classname'] for store in store_list]))
            data.update({
                'store_count': store_count,
                'disabled_store': disabled_store,
                'store_list': store_list,
                'refresh_passwd': self.acctmgr.refresh_passwd,
            })
        else:
            # Prepare initial setup information.
            data.update({
                'init_store': 'db',
                'init_store_hint': dict(
                    db=cleandoc("""
                        [account-manager]
                        db_htdigest_realm =
                        password_store = SessionStore

                        [components]
                        acct_mgr.db.SessionStore = enabled
                        acct_mgr.pwhash.HtDigestHashMethod = enabled
                        """),
                    htdigest=cleandoc("""
                        [account-manager]
                        htdigest_file = trac.htdigest
                        htdigest_realm =
                        password_store = HtDigestStore

                        [components]
                        acct_mgr.htfile.HtDigestStore = enabled
                        """),
                    htpasswd=cleandoc("""
                        [account-manager]
                        htpasswd_file = trac.htpasswd
                        htpasswd_hash_type = md5
                        password_store = HtPasswdStore

                        [components]
                        acct_mgr.htfile.HtPasswdStore = enabled
                        """),
                    svn_file=cleandoc("""
                        [account-manager]
                        password_file =
                        password_store = SvnServePasswordStore

                        [components]
                        acct_mgr.svnserve.SvnServePasswordStore = enabled
                        """),
                    http=cleandoc("""
                        [account-manager]
                        auth_url =
                        password_store = HttpAuthStore

                        [components]
                        acct_mgr.http.HttpAuthStore = enabled
                        """),
                    etc=cleandoc("""
                        [account-manager]
                        password_store =

                        [components]
                        """)
                ),
            })

        reset_password = cfg.getbool('account-manager', 'reset_password')
        data.update({
            'reset_password': reset_password,
            'generated_password_length':
                cfg.getint('account-manager', 'generated_password_length'),
            'force_passwd_change':
                cfg.getbool('account-manager', 'force_passwd_change'),
        })

        # Build registration check configuration details.
        acctmgr_register = cfg.getbool('components',
                                       'acct_mgr.register.RegistrationModule')
        check_list = []
        for check in self.acctmgr.checks:
            options = []
            for attr, option in _getoptions(check):
                error = None
                opt_val = None
                value = None
                try:
                    opt_val = option.__get__(check, check)
                except AttributeError as e:
                    env.log.error(e)
                    regexp = r'^.* interface named \"(.*?)\".*$'
                    error = _("Error while reading configuration - "
                              "Hint: Enable/install required component '%s'."
                              % re.sub(regexp, r'\1', str(e)))
                if opt_val:
                    value = isinstance(opt_val, Component) and \
                            opt_val.__class__.__name__ or opt_val
                opt_sel = None
                try:
                    option.xtnpt.interface
                except AttributeError:
                    # No ExtensionOption / Interface undefined.
                    pass
                else:
                    opt_sel = {'options': [], 'selected': None}
                if opt_sel:
                    for impl in option.xtnpt.extensions(env):
                        extension = impl.__class__.__name__
                        opt_sel['options'].append(extension)
                        if opt_val and extension == value:
                            opt_sel['selected'] = extension
                    if len(opt_sel['options']) == 0 and error:
                        opt_sel['error'] = error
                    value = opt_sel
                options.append({
                    'label': attr,
                    'name': '%s.%s' % (check.__class__.__name__, attr),
                    'value': value,
                    'doc': gettext(option.__doc__)
                })
                continue

            try:
                doc = dgettext(check._domain, check._description)
            except AttributeError:
                doc = check.__class__.__doc__
            check_list.append({
                'name': check.__class__.__name__,
                'classname': check.__class__.__name__,
                'doc': doc,
                'order': checks[check],
                'options': options
            })
            continue
        check_list = sorted(check_list, key=lambda i: i['order'])
        check_count = range(0, checks.component_count() + 1)
        register_check = cfg.getlist('account-manager', 'register_check')
        disabled_check = frozenset(register_check).difference(frozenset(
            [check['classname'] for check in check_list]))
        data.update({
            'change_uid_enabled': [k for k, v in cfg['components'].options()
                                   if k.startswith('acct_mgr.model.') and
                                   v == 'enabled'] and True or False,
            'acctmgr_register': acctmgr_register,
            'allow_delete_account': cfg.getbool('account-manager',
                                                'allow_delete_account'),
            'register_check': register_check,
            'disabled_check': disabled_check,
            'check_list': check_list,
            'check_count': check_count,
            'require_approval': cfg.getbool('account-manager',
                                            'require_approval'),
            'verify_email': EmailVerificationModule(env).verify_email,
        })

        # Prepare AccountGuard configuration details.
        acctmgr_guard = (
            cfg.getbool('components', 'acct_mgr.web_ui.LoginModule') and
            cfg.getbool('components', 'acct_mgr.guard.AccountGuard')
        )
        login_attempt_max_count = self.guard.login_attempt_max_count
        data.update({
            'acctmgr_guard': acctmgr_guard,
            'login_attempt_max_count': login_attempt_max_count,
            'user_lock_time': self.guard.user_lock_time,
            'user_lock_max_time': self.guard.user_lock_max_time,
            'user_lock_time_progression': self.guard.lock_time_progression,
        })

        # Prepare configuration check-up information.
        details = []
        status = (disabled_store and 'error' or not password_store and
                  'disabled' or 'ok')
        details.append(dict(desc=_("Password Store"), status=status, step=1))
        # Require no pending password store configuration issues.
        ready = status != 'error'

        details.append(dict(
            desc=_("Password Reset"),
            status=not reset_password and 'disabled' or 'ok',
            step=2
        )
        )
        status = (disabled_check and 'error' or not register_check and
                  'unknown' or not acctmgr_register and 'disabled' or 'ok')
        details.append(
            dict(desc=_("Account Registration"), status=status, step=3)
        )
        # Require no pending registration check configuration issues.
        ready = ready and status != 'error'

        details.append(dict(
            desc=_("Account Guard"),
            status=((not acctmgr_guard or login_attempt_max_count < 1) and
                    'disabled' or 'ok'),
            step=4)
        )
        admin_available = self.perms.get_users_with_permission('TRAC_ADMIN')
        status = 'ok' if admin_available else 'error'
        details.append(dict(desc=_("Admin user account"), status=status))
        # Require at least one admin account.
        ready = ready and status != 'error'

        details.append(dict(desc=_("Configuration Review"), status='unknown'))
        data.update({
            'admin_available': admin_available,
            'acctmgr': account,
            'set_password': self.acctmgr.supports('set_password'),
            'completion': dict(details=details, ready=ready),
        })

        # Extract relevant configuration options for final review.
        opts = [(k, v) for k, v in cfg['account-manager'].options()]
        roundup = {'account-manager': sorted(opts)}
        components = ['trac.web.auth.LoginModule']
        core_opts = (
            'auth_cookie_path', 'auth_cookie_lifetime', 'ignore_auth_case',
            'check_auth_ip', 'secure_cookies'
        )
        opts = [(k, v) for k, v in cfg['trac'].options() if k in core_opts]
        roundup['trac'] = sorted(opts)
        # Read sections marked as related too.
        components.extend(cfg['account-manager'].getlist('sibling_cmp'))
        roundup['components'] = [(k, v) for k, v in
                                 cfg['components'].options()
                                 if k.startswith('acct_mgr') or
                                 k in [c.lower() for c in components]]
        if 'sibling_cfg' in cfg['account-manager']:
            siblings = cfg['account-manager'].getlist('sibling_cfg')
            for sibling in siblings:
                opts = [(k, v) for k, v in cfg[sibling].options()]
                roundup[sibling] = sorted(opts)
        # Clean-up by filtering options with default values.
        roundup_defaults = dict()
        for section in roundup:
            defaults = cfg.defaults().get(section)
            for option in roundup[section]:
                if defaults and option[0] in defaults and \
                                defaults[option[0]] == option[1]:
                    if section in roundup_defaults:
                        roundup_defaults[section].append(option[0])
                    else:
                        roundup_defaults[section] = list((option[0],))
        data.update(dict(roundup=roundup, roundup_defaults=roundup_defaults))

        add_script(req, 'acct_mgr/js/acctmgr_admin.js')
        add_stylesheet(req, 'acct_mgr/acctmgr.css')
        add_stylesheet(req, 'common/css/report.css')
        return 'account_config.html', data

    # IAuthenticator methods

    def authenticate(self, req):
        """Launch an initial Trac authentication setup.

        This method authorizes the first login request after Trac environment
        load as setup session, while no user has full permissions, but can
        be locked by configuration to never authenticate at all.
        """
        init = self.config.getbool('account-manager', 'auth_init')
        remote_user = None

        if init and req.path_info == '/login' and not req.remote_user and \
                not self.perms.get_users_with_permission('TRAC_ADMIN'):
            # Prevent to run another initial setup in parallel.
            self.config.set('account-manager', 'auth_init', False)
            # Initialize a setup session.
            req.environ['REMOTE_USER'] = remote_user = self.authname
            if self.authname not in \
                    self.perms.get_users_with_permission(self.cfg_action):
                self.perms.grant_permission(self.authname, self.cfg_action)
            # Do not grant anything but the required configuration permission.
            perms = self.perms.get_user_permissions('authenticated')
            for action in perms:
                # Filter actions inherited from 'anonymous'.
                if perms[action] and action not in PermissionCache(self.env):
                    self.perms.grant_permission('auth_moved', action)
                    self.perms.revoke_permission('authenticated', action)
            add_notice(req, _("Initial Trac authentication setup launched."))
            # Set referer without interfering with redirect to '/login'.
            req.args['referer'] = req.href.admin('accounts', 'config')
        return remote_user


def _add_user_account(env, req):
    acctmgr = AccountManager(env)
    account = dict(email=req.args.get('email', '').strip(),
                   name=req.args.get('name', '').strip(),
                   username=acctmgr.handle_username_casing(
                       req.args.get('username', '').strip()))
    verify_enabled = EmailVerificationModule(env).email_enabled and \
                     EmailVerificationModule(env).verify_email

    if acctmgr.supports('set_password'):
        if account['username']:
            # Check request and prime account on success.
            try:
                acctmgr.validate_account(req, True)
                # Account email approval for authoritative action.
                if verify_enabled and account['email'] and \
                        req.args.get('email_approved'):
                    set_user_attribute(env, account['username'],
                                       'email_verification_sent_to',
                                       account['email'])
            except NotificationError as e:
                add_warning(req, _("Error raised while sending a change "
                                   "notification.") +
                            _("You'll get details with TracLogging "
                              "enabled."))
                env.log.error('Unable to send change notification: %s',
                              exception_to_unicode(e, traceback=True))
            except RegistrationError as e:
                add_warning(req, e)
            else:
                add_notice(req, tag_(
                    "Account %(username)s created.",
                    username=tag.b(account['username'])))
                # User editor form clean-up.
                account = {}
    else:
        add_warning(req, _(
            "None of the configured password stores is writable."))
    return account