Skip to content

Commit

Permalink
fix #20
Browse files Browse the repository at this point in the history
Signed-off-by: Chris Warrick <kwpolska@gmail.com>
  • Loading branch information
Kwpolska committed Jan 13, 2015
1 parent da79a12 commit 4422725
Show file tree
Hide file tree
Showing 9 changed files with 161 additions and 25 deletions.
3 changes: 2 additions & 1 deletion comet/data/templates/mako/comet_account.tmpl
Expand Up @@ -66,9 +66,10 @@

% if current_user.is_admin:
<p class="text-muted">You can edit your permissions in the <a
href="/users/permissions">permissions panel</a>.
href="/users/permissions">permissions panel</a>.</p>
% endif

${form.csrf_token}
<div style="text-align: center;">
<button type="submit" class="btn btn-primary btn-lg save-btn"><i class="fa fa-save fa-fw save-icon"></i> Save</button>
</div>
Expand Down
3 changes: 3 additions & 0 deletions comet/data/templates/mako/comet_index.tmpl
Expand Up @@ -36,6 +36,7 @@ Show posts of:
<h2>Posts</h2>
</div>
<form method="POST" action="/new/post" class="input-group">
${postform.csrf_token}
<input class="form-control" name="title" id="title" placeholder="Title">
<span class="input-group-btn"><button type="submit" class="btn btn-success"><i class="fa fa-file-o"></i> Create Post</button></span>
</form>
Expand All @@ -60,6 +61,7 @@ Show posts of:
</div>
<form method="POST" action="/new/page" class="input-group">
<input class="form-control" name="title" id="title" placeholder="Title">
${pageform.csrf_token}
<span class="input-group-btn"><button type="submit" class="btn btn-success"><i class="fa fa-file-o"></i> Create Page</button></span>
</form>
<div class="list-group pages">
Expand Down Expand Up @@ -92,6 +94,7 @@ Show posts of:
<div class="modal-footer">
<form method="POST" action="/delete" class="delete-button">
<input type="hidden" name="path" class="sourcepath">
${delform.csrf_token}
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger">Delete</button>
</div>
Expand Down
3 changes: 2 additions & 1 deletion comet/data/templates/mako/comet_login.tmpl
Expand Up @@ -13,9 +13,10 @@
<input name="password" type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" name="remember-me" value="remember-me"> Remember me
<input type="checkbox" name="remember" value="remember"> Remember me
</label>
</div>
${form.csrf_token}
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</%block>
1 change: 1 addition & 0 deletions comet/data/templates/mako/comet_post_edit.tmpl
Expand Up @@ -104,6 +104,7 @@
</div>

<textarea name="content" id="content-area" class="form-control" rows="24">${post_content}</textarea>
${form.csrf_token}
</form>
% if is_html:
<script src="/bower_components/wysihtml/dist/wysihtml5x-toolbar.min.js"></script>
Expand Down
5 changes: 3 additions & 2 deletions comet/data/templates/mako/comet_users.tmpl
Expand Up @@ -66,7 +66,7 @@ $('#deleteModal').on('show.bs.modal', function (event) {
% endif
</td>
<td class="actions">
<form action="/users/edit" method="POST">
<form action="/users/edit" method="POST">${editform.csrf_token}
<input type="hidden" name="uid" value="${uid}">
<input type="hidden" name="action" value="edit">
<div class="btn-group" role="group">
Expand All @@ -89,7 +89,7 @@ $('#deleteModal').on('show.bs.modal', function (event) {
<td></td>
<td><input name="username" placeholder="New user" class="form-control"></td>
<td><input name="action" value="new" type="hidden"></td>
<td></td>
<td>${editform.csrf_token}</td>
<td></td>
<td><button type="submit" class="btn btn-sm btn-primary"><i class="fa fa-plus-square fa-fw"></i> Create</button></td>
</form></tr>
Expand All @@ -110,6 +110,7 @@ $('#deleteModal').on('show.bs.modal', function (event) {
<input type="hidden" name="uid" class="del-uid">
<input type="hidden" name="direction" class="del-direction">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
${delform.csrf_token}
<button type="submit" class="btn del-verb-capital">Delete</button>
</div>
</div>
Expand Down
1 change: 1 addition & 0 deletions comet/data/templates/mako/comet_users_edit.tmpl
Expand Up @@ -123,6 +123,7 @@
</div>
</div>

${form.csrf_token}
<div style="text-align: center;">
<button type="submit" class="btn btn-primary btn-lg save-btn"><i class="fa fa-save fa-fw save-icon"></i> Save</button>
</div>
Expand Down
1 change: 1 addition & 0 deletions comet/data/templates/mako/comet_users_permissions.tmpl
Expand Up @@ -108,6 +108,7 @@ ${p}
% endfor
</table>

${form.csrf_token}
<div style="text-align: center;"><button type="submit" class="btn btn-primary btn-lg save-btn"><i class="fa fa-save fa-fw save-icon"></i> Save</button></div>

</form>
Expand Down
84 changes: 84 additions & 0 deletions comet/forms.py
@@ -0,0 +1,84 @@
# -*- 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

from flask.ext.wtf import Form
from wtforms.fields import TextField, PasswordField, BooleanField
from wtforms.validators import Required, ValidationError


class LoginForm(Form):
"""A login form."""
username = TextField('Username', validators=[Required()])
password = PasswordField('Password', validators=[Required()])
remember = BooleanField('Remember me')


class NewPostForm(Form):
"""A new post form."""
title = TextField('Title', validators=[Required()])


class NewPageForm(Form):
"""A new page form."""
title = TextField('Title', validators=[Required()])


class DeleteForm(Form):
"""A deletion form. Strong Bad sold separately."""
path = TextField('Path', validators=[Required()])


class UserDeleteForm(Form):
"""An user deletion form."""
direction = TextField('Direction', validators=[Required()])
uid = TextField('UID', validators=[Required()])

def validate_direction(form, field):
if field.data not in ['del', 'undel']:
raise ValidationError('invalid direction')


class AccountForm(Form):
"""An account form, used for CSRF protection only."""
pass


class UserEditForm(Form):
"""A user editor form, used for CSRF protection only."""
pass


class PermissionsForm(Form):
"""A permissions form, used for CSRF protection only."""
pass


class PostEditForm(Form):
"""A post editor form, used for CSRF protection only."""
pass
85 changes: 64 additions & 21 deletions comet/web.py
Expand Up @@ -43,7 +43,9 @@
logout_user, current_user, make_secure_token)
from flask.ext.bcrypt import Bcrypt
from comet.utils import USER_FIELDS, PERMISSIONS, SiteProxy

from comet.forms import (LoginForm, NewPostForm, NewPageForm, DeleteForm,
UserDeleteForm, UserEditForm, AccountForm,
PermissionsForm, PostEditForm)

_site = None
site = None
Expand Down Expand Up @@ -437,27 +439,32 @@ def login():
alert = None
alert_status = 'danger'
code = 200
form = LoginForm()
if request.method == 'POST':
user = find_user_by_name(request.form['username'])
if not user:
if form.validate():
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' in request.form))
return redirect('/')
else:
alert = "Invalid credentials."
code = 401
else:
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': alert, 'form': form,
'alert_status': alert_status}, code)


Expand All @@ -480,7 +487,9 @@ def index():
'assets')):
return redirect('/setup')

context = {}
context = {'postform': NewPostForm(),
'pageform': NewPageForm(),
'delform': DeleteForm()}

n = request.args.get('all')
if n is None:
Expand Down Expand Up @@ -541,7 +550,11 @@ def edit(path):
if post is None:
return error("No such post or page.", 404, '/edit/' + path)

form = PostEditForm()

if request.method == 'POST':
if not form.validate():
return error("Bad Request", 400, '/edit/' + path)
meta = {}
for k, v in request.form.items():
meta[k] = v
Expand Down Expand Up @@ -592,17 +605,21 @@ def edit(path):
context['title'] = 'Editing {0}'.format(post.title())
context['permalink'] = '/edit/' + path
context['is_html'] = post.compiler.name == 'html'
context['form'] = form
return render('comet_post_edit.tmpl', context)


@app.route('/delete', methods=['POST'])
@login_required
def delete():
"""Delete a post."""
form = DeleteForm()
path = request.form['path']
post = find_post(path)
if post is None:
return error("No such post or page.", 404, '/delete')
if not form.validate():
return error("Bad Request", 400, '/delete')
os.unlink(path)
scan_site()
return redirect('/')
Expand Down Expand Up @@ -708,11 +725,19 @@ def new(obj):
_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')
f = NewPostForm()
if f.validate():
_site.commands.new_post(title=title, author=current_user.realname,
content_format='html')
else:
return error("Bad Request", 400, '/new/' + obj)
elif obj == 'page':
_site.commands.new_page(title=title, author=current_user.realname,
content_format='html')
f = NewPageForm()
if f.validate():
_site.commands.new_page(title=title, author=current_user.realname,
content_format='html')
else:
return error("Bad Request", 400, '/new/' + obj)
else:
return error("Cannot create {0} — unknown type.".format(obj),
400, '/new/' + obj)
Expand All @@ -736,7 +761,10 @@ def acp_user_account():
alert = ''
alert_status = ''
action = 'edit'
form = AccountForm()
if request.method == 'POST':
if not form.validate():
return error("Bad Request", 400, "/account")
action = 'save'
data = request.form
if data['newpwd1']:
Expand All @@ -757,7 +785,8 @@ def acp_user_account():
'permalink': '/account',
'action': action,
'alert': alert,
'alert_status': alert_status})
'alert_status': alert_status,
'form': form})


@app.route('/users')
Expand All @@ -782,7 +811,9 @@ def acp_users():
'permalink': '/users',
'USERS': USERS,
'alert': alert,
'alert_status': alert_status})
'alert_status': alert_status,
'delform': UserDeleteForm(),
'editform': UserEditForm()})


@app.route('/users/edit', methods=['POST'])
Expand All @@ -794,6 +825,10 @@ def acp_users_edit():
if not current_user.is_admin:
return error("Not authorized to edit users.", 401, "/users/edit")
data = request.form

form = UserEditForm()
if not form.validate():
return error("Bad Request", 400, "/users/edit")
action = data['action']

if action == 'new':
Expand Down Expand Up @@ -851,7 +886,8 @@ def acp_users_edit():
'new': new,
'action': action,
'alert': alert,
'alert_status': alert_status})
'alert_status': alert_status,
'form': form})


@app.route('/users/delete', methods=['POST'])
Expand All @@ -860,10 +896,13 @@ 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")
form = UserDeleteForm()
if not form.validate():
return error("Bad Request", 400, '/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")
return error("User does not exist.", 404, "/users/delete")
else:
for p in PERMISSIONS:
setattr(user, p, False)
Expand All @@ -880,9 +919,12 @@ def acp_users_permissions():
return error("Not authorized to edit users.",
401, "/users/permissions")

form = PermissionsForm()
users = {}
last_uid = int(db.get('last_uid'))
if request.method == 'POST':
if not form.validate():
return error("Bad Request", 400, '/users/permissions')
for uid in range(1, last_uid + 1):
user = get_user(uid)
for perm in PERMISSIONS:
Expand Down Expand Up @@ -926,6 +968,7 @@ def display_permission(user, permission):
'PERMISSIONS': PERMISSIONS,
'action': action,
'json': json,
'form': form,
'display_permission': display_permission})

if not os.path.exists('._COMET_NO_CONFIG') and os.path.exists('conf.py'):
Expand Down

0 comments on commit 4422725

Please sign in to comment.