/
web.py
865 lines (722 loc) · 27.5 KB
/
web.py
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
# -*- coding: utf-8 -*-
# Comet CMS v0.6.0
# Copyright © 2014-2015 Chris Warrick, Roberto Alsina, Henry Hirsch et al.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from __future__ import print_function, unicode_literals
import json
import os
import io
import pkg_resources
import nikola.__main__
import logbook
import kombu
import redis
from nikola.utils import unicode_str, get_logger, ColorfulStderrHandler
import nikola.plugins.command.new_post
from flask import Flask, request, redirect, send_from_directory, g, session
from flask.ext.login import (LoginManager, login_required, login_user,
logout_user, current_user, make_secure_token)
from flask.ext.bcrypt import Bcrypt
from comet.utils import USER_FIELDS, PERMISSIONS, parse_redis
site = None
app = None
db = None
def scan_site():
"""Rescan the site."""
app.logger.info(os.getcwd())
site.scan_posts(really=True, quiet=True)
app.logger.info("Posts scanned.")
def configure_url(url):
"""Configure site URL."""
app.config['COMET_URL'] = site.config['SITE_URL'] =\
site.config['BASE_URL'] = site.GLOBAL_CONTEXT['blog_url'] = url
def configure_site():
"""Configure the site for Comet."""
global site, db
nikola.__main__._RETURN_DOITNIKOLA = True
_dn = nikola.__main__.main([])
_dn.sub_cmds = _dn.get_commands()
site = _dn.nikola
app.config['BCRYPT_LOG_ROUNDS'] = 12
app.config['NIKOLA_ROOT'] = os.getcwd()
app.config['DEBUG'] = False
# Logging configuration
logf = (u'[{record.time:%Y-%m-%dT%H:%M:%SZ}] {record.level_name}: '
u'{record.channel}: {record.message}')
logh = (u'[{record.time:%Y-%m-%dT%H:%M:%SZ}] {record.channel} '
u'{record.message}')
loghandlers = [
ColorfulStderrHandler(level=logbook.DEBUG, format_string=logf,
bubble=True),
logbook.FileHandler('comet.log', 'a', 'utf-8', logbook.DEBUG, logf,
bubble=True)
]
hloghandlers = [
ColorfulStderrHandler(level=logbook.DEBUG, format_string=logh,
bubble=True),
logbook.FileHandler('comet.log', 'a', 'utf-8', logbook.DEBUG, logh,
bubble=True)
]
site.loghandlers = loghandlers
nikola.utils.LOGGER.handlers = loghandlers
nikola.plugins.command.new_post.POSTLOGGER.handlers = loghandlers
nikola.plugins.command.new_post.PAGELOGGER.handlers = loghandlers
app.config['LOGGER_NAME'] = 'Comet'
app._logger = get_logger('Comet', loghandlers)
app.http_logger = get_logger('CometHTTP', hloghandlers)
if not site.configured:
app.logger("Not a Nikola site.")
return
app.secret_key = site.config.get('COMET_SECRET_KEY')
app.config['COMET_URL'] = site.config.get('COMET_URL')
app.config['REDIS_URL'] = site.config.get('COMET_REDIS_URL', 'redis://')
# Redis configuration
redis_conn = parse_redis(app.config['REDIS_URL'])
db = redis.StrictRedis(**redis_conn)
site.template_hooks['menu_alt'].append(generate_menu_alt)
app.config['NIKOLA_URL'] = site.config['SITE_URL']
configure_url(app.config['COMET_URL'])
site.config['NAVIGATION_LINKS'] = {
'en': (
(app.config['NIKOLA_URL'],
'<i class="fa fa-globe"></i> Back to website'),
('/rebuild', '<i class="fa fa-cog rebuild"></i> Rebuild'),
)
}
site.GLOBAL_CONTEXT['navigation_links'] = site.config['NAVIGATION_LINKS']
TITLE = site.GLOBAL_CONTEXT['blog_title']('en') + ' Administration'
site.config['BLOG_TITLE'] = lambda _: TITLE
site.GLOBAL_CONTEXT['blog_title'] = lambda _: TITLE
site.GLOBAL_CONTEXT['lang'] = 'en'
site.GLOBAL_CONTEXT['extra_head_data'] = lambda _: (
"""<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/"""
"""font-awesome.min.css" rel="stylesheet">
<link href="/comet_assets/css/comet.css" rel="stylesheet">""")
# HACK: body_end appears after extra_js from templates, so we must use
# social_buttons_code instead
site.GLOBAL_CONTEXT['social_buttons_code'] = lambda _: """
<script src="/comet_assets/js/comet.js"></scripts>
"""
# Theme must inherit from bootstrap3, because we have hardcoded HTML for that.
bs3 = ('bootstrap3' in site.THEMES) or ('bootstrap3-jinja' in site.THEMES)
if not bs3:
app.logger.notice("THEME does not inherit from 'bootstrap3' or 'bootstrap3-jinja', using 'bootstrap3' instead.")
site.config['THEME'] = 'bootstrap3'
# Reloading some things
site._THEMES = None
site._get_themes()
site._template_system = None
site._get_template_system()
if 'has_custom_css' in site._GLOBAL_CONTEXT:
del site._GLOBAL_CONTEXT['has_custom_css']
site._get_global_context()
scan_site()
tmpl_dir = pkg_resources.resource_filename(
'comet', os.path.join('data', 'templates', site.template_system.name))
if os.path.isdir(tmpl_dir):
# Inject tmpl_dir low in the theme chain
site.template_system.inject_directory(tmpl_dir)
def password_hash(password):
"""Hash the password, using bcrypt.
:param str password: Password in plaintext
:return: password hash
:rtype: str
"""
return bcrypt.generate_password_hash(password)
def check_password(pwdhash, password):
"""Check the password hash from :func:`password_hash`.
:param str pwdhash: Hash from :func:`password_hash` to check
:param str password: Password in plaintext
:return: password match
:rtype: bool
"""
return bcrypt.check_password_hash(pwdhash, password)
def generate_menu_alt():
"""Generate ``menu_alt`` with log in/out links.
:return: HTML fragment
:rtype: str
"""
if not current_user.is_authenticated():
return """<li><a href="/login">Log in</a></li>"""
if current_user.is_admin:
edit_entry = """<li><a href="/users">Manage users</a></li>\
<li><a href="/users/permissions">Permissions</a></li>"""
else:
edit_entry = ''
return """
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"
role="button" aria-expanded="false">{0} [{1}]<span
class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="/account">Account</a></li>
{2}
<li><a href="/logout">Log out</a></li>
</ul>
</li>""".format(current_user.realname, current_user.username, edit_entry)
def _author_get(post):
"""Get the name of the post author.
:param Post post: The post object to determine authorship of
:return: Author real name
:rtype: str
"""
a = post.meta['en']['author']
return a if a else current_user.realname
def _author_uid_get(post):
"""Get the UID of the post author.
:param Post post: The post object to determine authorship of
:return: Author UID
:rtype: str
"""
u = post.meta['en']['author.uid']
return u if u else str(current_user.uid)
def render(template_name, context=None, code=200, headers=None):
"""Render a response using standard Nikola templates.
:param str template_name: Template name
:param dict context: Context (variables) to use in the template
:param int code: HTTP status code
:param headers: Headers to use for the response
:return: HTML fragment
:rtype: str
"""
if context is None:
context = {}
if headers is None:
headers = {}
context['g'] = g
context['request'] = request
context['session'] = session
context['current_user'] = current_user
context['_author_get'] = _author_get
context['_author_uid_get'] = _author_uid_get
headers['Pragma'] = 'no-cache'
headers['Cache-Control'] = 'private, max-age=0, no-cache'
return site.render_template(template_name, None, context), code, headers
def error(desc, code, permalink):
"""Render an error page.
:param str desc: Error description
:param int code: HTTP status code
:param str permalink: Path to page generating errors
:return: HTML fragment (from :func:`render`)
:rtype: str
"""
return render('comet_error.tmpl',
{'title': 'Error',
'code': code,
'desc': desc,
'permalink': permalink},
code)
def _unauthorized():
"""Redirect to the “unauthorized” page."""
return redirect('/login?status=unauthorized')
def find_post(path):
"""Find a post.
:param str path: Path to the post
:return: A post matching the path
:rtype: Post or None
"""
for p in site.timeline:
if p.source_path == path:
return p
return None
app = Flask('comet')
@app.after_request
def log_request(resp):
"""Log a request."""
l = "[{4}] {0} {1} {2} <{3}>".format(request.remote_addr, request.method,
request.url, request.endpoint,
resp.status_code)
c = str(resp.status_code)[0]
if c in ['1', '2'] or resp.status_code == 304:
app.http_logger.info(l)
elif c == '3':
app.http_logger.warn(l)
else:
app.http_logger.error(l)
return resp
bcrypt = Bcrypt(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.unauthorized_callback = _unauthorized
class User(object):
"""An user. Compatible with Flask-Login."""
def __init__(self, uid, username, realname, password, email, active,
is_admin, can_edit_all_posts, wants_all_posts,
can_upload_attachments, can_rebuild_site,
can_transfer_post_authorship):
"""Initialize an user with specified settings."""
self.uid = int(uid)
self.username = username
self.realname = realname
self.password = password
self.email = email
self.active = active
self.is_admin = is_admin
self.can_edit_all_posts = can_edit_all_posts
self.wants_all_posts = wants_all_posts
self.can_upload_attachments = can_upload_attachments
self.can_rebuild_site = can_rebuild_site
self.can_transfer_post_authorship = can_transfer_post_authorship
def get_id(self):
"""Get user ID."""
return unicode_str(self.uid)
def is_authenticated(self):
"""Check whether user is authorized to log in."""
return self.active
def is_active(self):
"""Check whether user is active."""
return self.active
def is_anonymous(self):
"""Check whether user is anonymous."""
return not self.active
def get_auth_token(self):
"""Generate an authentication token."""
return make_secure_token(self.uid, self.username, self.password)
def __repr__(self):
"""Return a programmer-friendly representation."""
return '<User {0}>'.format(self.username)
@login_manager.user_loader
def get_user(uid):
"""Get an user by the UID.
:param str uid: UID to find
:return: the user
:rtype: User object
:raises ValueError: uid is not an integer
:raises KeyError: if user does not exist
"""
d = db.hgetall('user:{0}'.format(uid))
if d:
for p in PERMISSIONS:
d[p] = d[p] == '1'
return User(uid=uid, **d)
else:
return None
def find_user_by_name(username):
"""Get an user by their username.
:param str username: Username to find
:return: the user
:rtype: User object or None
"""
uid = db.hget('users', username)
if uid:
return get_user(uid)
else:
return None
def write_user(user):
"""Write an user ot the database.
:param User user: User to write
"""
udata = {}
for f in USER_FIELDS:
udata[f] = getattr(user, f)
for p in PERMISSIONS:
udata[p] = '1' if getattr(user, p) else '0'
db.hmset('user:{0}'.format(user.uid), udata)
@app.route('/login', methods=['GET', 'POST'])
def login():
"""Handle user authentication.
If requested over GET, present login page.
If requested over POST, log user in.
:param str status: Status of previous request/login attempt
"""
alert = None
alert_status = 'danger'
code = 200
if request.method == 'POST':
user = find_user_by_name(request.form['username'])
if not user:
alert = 'Invalid credentials.'
code = 401
else:
if check_password(user.password,
request.form['password']) and user.is_active:
login_user(user, remember=('remember-me' in request.form))
return redirect('/')
else:
alert = "Invalid credentials."
code = 401
else:
if request.args.get('status') == 'unauthorized':
alert = 'Please log in to access this page.'
elif request.args.get('status') == 'logout':
alert = 'Logged out successfully.'
alert_status = 'success'
return render('comet_login.tmpl', {'title': 'Login', 'permalink': '/login',
'alert': alert,
'alert_status': alert_status}, code)
@app.route('/logout')
@login_required
def logout():
"""Log the user out and redirect them to the login page."""
logout_user()
return redirect('/login?status=logout')
@app.route('/')
@login_required
def index():
"""Show the index with all posts.
:param int all: Whether or not should show all posts
"""
if not os.path.exists(os.path.join(site.config["OUTPUT_FOLDER"],
'assets')):
return redirect('/setup')
context = {}
n = request.args.get('all')
if n is None:
wants_now = None
else:
wants_now = n == '1'
if wants_now is None and current_user.wants_all_posts:
wants = True
else:
wants = wants_now
if current_user.can_edit_all_posts and wants:
posts = site.posts
pages = site.pages
else:
wants = False
posts = []
pages = []
for p in site.timeline:
if (p.meta('author.uid')
and p.meta('author.uid') != str(current_user.uid)):
continue
if p.use_in_feeds:
posts.append(p)
else:
pages.append(p)
context['posts'] = posts
context['pages'] = pages
context['title'] = 'Posts & Pages'
context['permalink'] = '/'
context['wants'] = wants
return render('comet_index.tmpl', context)
# TODO: delete (with redirects) as soon as `comet init` and real docs exist
@app.route('/setup')
def setup():
"""TEMPORARY setup function."""
ns = not os.path.exists(os.path.join(site.config["OUTPUT_FOLDER"],
'assets'))
return render("comet_setup.tmpl", context={'needs_setup': ns})
@app.route('/edit/<path:path>', methods=['GET', 'POST'])
@login_required
def edit(path):
"""Edit a post.
If requested over GET, shows the edit UI.
If requested over POST, saves the post and shows the edit UI.
:param path: Path to post to edit.
"""
context = {'path': path, 'site': site}
post = find_post(path)
if post is None:
return error("No such post or page.", 404, '/edit/' + path)
if request.method == 'POST':
meta = {}
for k, v in request.form.items():
meta[k] = v
meta.pop('_wysihtml5_mode', '')
try:
meta['author'] = get_user(meta['author.uid']).realname
author_change_success = True
except:
author_change_success = False
if (not current_user.can_transfer_post_authorship
or not author_change_success):
meta['author'] = post.meta('author') or current_user.realname
meta['author.uid'] = post.meta('author.uid') or current_user.uid
post.compiler.create_post(post.source_path, onefile=True,
is_page=False, **meta)
scan_site()
post = find_post(path)
context['action'] = 'save'
context['post_content'] = meta['content']
else:
context['action'] = 'edit'
with io.open(path, 'r', encoding='utf-8') as fh:
context['post_content'] = fh.read().split('\n\n', 1)[1]
context['post'] = post
users = []
last_uid = int(db.get('last_uid'))
for u in range(1, last_uid + 1):
realname, active = db.hmget('user:{0}'.format(u), 'realname', 'active')
if active == '1':
users.append((u, realname))
context['users'] = sorted(users)
context['current_auid'] = int(post.meta('author.uid') or current_user.uid)
context['title'] = 'Editing {0}'.format(post.title())
context['permalink'] = '/edit/' + path
return render('comet_post_edit.tmpl', context)
@app.route('/delete', methods=['POST'])
@login_required
def delete():
"""Delete a post."""
path = request.form['path']
post = find_post(path)
if post is None:
return error("No such post or page.", 404, '/delete')
os.unlink(path)
scan_site()
return redirect('/')
@app.route('/rebuild')
@login_required
def rebuild():
"""Rebuild the site."""
return "<h1>Not implemented.</h1>", 500
@app.route('/bower_components/<path:path>')
def serve_bower_components(path):
"""Serve bower components.
This is meant to be used ONLY by the internal dev server.
Please configure your web server to handle requests to this URL::
/bower_components/ => comet/data/bower_components
"""
res = pkg_resources.resource_filename(
'comet', os.path.join('data', 'bower_components'))
return send_from_directory(res, path)
@app.route('/comet_assets/<path:path>')
def serve_comet_assets(path):
"""Serve Comet assets.
This is meant to be used ONLY by the internal dev server.
Please configure your web server to handle requests to this URL::
/comet_assets/ => comet/data/comet_assets
"""
res = pkg_resources.resource_filename(
'comet', os.path.join('data', 'comet_assets'))
return send_from_directory(res, path)
@app.route('/assets/<path:path>')
def serve_assets(path):
"""Serve Nikola assets.
This is meant to be used ONLY by the internal dev server.
Please configure your web server to handle requests to this URL::
/assets/ => output/assets
"""
res = os.path.join(app.config['NIKOLA_ROOT'],
site.config["OUTPUT_FOLDER"], 'assets')
return send_from_directory(res, path)
@app.route('/new/<obj>', methods=['POST'])
@login_required
def new(obj):
"""Create a new post or page.
:param str obj: Object to create (post or page)
"""
title = request.form['title']
site.config['ADDITIONAL_METADATA']['author.uid'] = current_user.uid
try:
if obj == 'post':
site.commands.new_post(title=title, author=current_user.realname,
content_format='html')
elif obj == 'page':
site.commands.new_page(title=title, author=current_user.realname,
content_format='html')
else:
return error("Cannot create {0} — unknown type.".format(obj),
400, '/new/' + obj)
except SystemExit:
return error("This {0} already exists!".format(obj),
500, '/new/' + obj)
finally:
del site.config['ADDITIONAL_METADATA']['author.uid']
# reload post list and go to index
scan_site()
return redirect('/')
@app.route('/account', methods=['POST', 'GET'])
@login_required
def acp_user_account():
"""Manage the user account of currently-logged-in users.
This does NOT accept admin-specific options.
"""
alert = ''
alert_status = ''
action = 'edit'
if request.method == 'POST':
action = 'save'
data = request.form
if data['newpwd1']:
if data['newpwd1'] == data['newpwd2'] and check_password(
current_user.password, data['oldpwd']):
current_user.password = password_hash(data['newpwd1'])
else:
alert = 'Passwords don’t match.'
alert_status = 'danger'
action = 'save_fail'
current_user.realname = data['realname']
current_user.email = data['email']
current_user.wants_all_posts = 'wants_all_posts' in data
write_user(current_user)
return render('comet_account.tmpl',
context={'title': 'My account',
'permalink': '/account',
'action': action,
'alert': alert,
'alert_status': alert_status})
@app.route('/users')
@login_required
def acp_users():
"""List all users."""
alert = ''
alert_status = ''
if request.args.get('status') == 'deleted':
alert = 'User deleted.'
alert_status = 'success'
if request.args.get('status') == 'undeleted':
alert = 'User undeleted.'
alert_status = 'success'
if not current_user.is_admin:
return error("Not authorized to edit users.", 401, "/users")
else:
last_uid = int(db.get('last_uid'))
USERS = {i: get_user(i) for i in range(1, last_uid + 1)}
return render('comet_users.tmpl',
context={'title': 'Users',
'permalink': '/users',
'USERS': USERS,
'alert': alert,
'alert_status': alert_status})
@app.route('/users/edit', methods=['POST'])
@login_required
def acp_users_edit():
"""Edit an user account."""
global current_user
if not current_user.is_admin:
return error("Not authorized to edit users.", 401, "/users/edit")
data = request.form
action = data['action']
if action == 'new':
if not data['username']:
return error("No username to create specified.", 400, "/users/edit")
uid = db.incr('last_uid')
pf = [False for p in PERMISSIONS]
pf[0] = True # active
user = User(uid, data['username'], '', '', *pf)
write_user(user)
db.hset('users', user.username, user.uid)
new = True
else:
user = get_user(data['uid'])
new = False
if not user:
return error("User does not exist.", 404, "/users/edit")
alert = ''
alert_status = ''
if action == 'save':
if data['newpwd1']:
if data['newpwd1'] == data['newpwd2']:
user.password = password_hash(data['newpwd1'])
else:
alert = 'Passwords don’t match.'
alert_status = 'danger'
action = 'save_fail'
elif new:
alert = 'Must set a password.'
alert_status = 'danger'
action = 'save_fail'
if data['username'] != user.username:
db.hdel('users', user.username)
user.username = data['username']
db.hset('users', user.username, user.uid)
user.realname = data['realname']
user.email = data['email']
for p in PERMISSIONS:
setattr(user, p, p in data)
user.active = True
if user.uid == current_user.uid:
user.is_admin = True
current_user = user
write_user(user)
return render('comet_users_edit.tmpl',
context={'title': 'Edit user',
'permalink': '/users/edit',
'user': user,
'new': new,
'action': action,
'alert': alert,
'alert_status': alert_status})
@app.route('/users/delete', methods=['POST'])
@login_required
def acp_users_delete():
"""Delete or undelete an user account."""
if not current_user.is_admin:
return error("Not authorized to edit users.", 401, "/users/delete")
user = get_user(int(request.form['uid']))
direction = request.form['direction']
if not user:
return error("User does not exist.", 404, "/users/edit/delete")
else:
for p in PERMISSIONS:
setattr(user, p, False)
user.active = direction == 'undel'
write_user(user)
return redirect('/users?status={_del}eted'.format(_del=direction))
@app.route('/users/permissions', methods=['GET', 'POST'])
@login_required
def acp_users_permissions():
"""Change user permissions."""
if not current_user.is_admin:
return error("Not authorized to edit users.",
401, "/users/permissions")
users = {}
last_uid = int(db.get('last_uid'))
if request.method == 'POST':
for uid in range(1, last_uid + 1):
user = get_user(uid)
for perm in PERMISSIONS:
if '{0}.{1}'.format(uid, perm) in request.form:
setattr(user, perm, True)
else:
setattr(user, perm, False)
if uid == current_user.uid:
user.is_admin = True # cannot deadmin oneself
user.active = True # cannot deactivate oneself
write_user(user)
users[uid] = user
action = 'save'
else:
action = 'edit'
def display_permission(user, permission):
checked = 'checked' if getattr(user, permission) else ''
if permission == 'wants_all_posts' and not user.can_edit_all_posts:
# If this happens, permissions are damaged.
checked = ''
if user.uid == current_user.uid and permission in ['active', 'is_admin']:
disabled = 'disabled'
else:
disabled = ''
permission_a = permission
if permission == 'active':
permission_a = 'is_active'
d = ('<input type="checkbox" name="{0}.{1}" data-uid="{0}" '
'data-perm="{4}" class="u{0}" {2} {3}>')
return d.format(user.uid, permission, checked, disabled, permission_a)
for uid in range(1, last_uid + 1):
users[uid] = get_user(uid)
return render('comet_users_permissions.tmpl',
context={'title': 'Permissions',
'permalink': '/users/permissions',
'USERS': users,
'PERMISSIONS': PERMISSIONS,
'action': action,
'json': json,
'display_permission': display_permission})
if not os.path.exists('._COMET_NO_CONFIG') and os.path.exists('conf.py'):
configure_site()
else:
# no Nikola site available
app = None