Compare commits

..

8 commits

16 changed files with 79 additions and 150 deletions

41
LICENSE
View file

@ -1,28 +1,21 @@
Copyright 2010 Pallets MIT License
Redistribution and use in source and binary forms, with or without Copyright (c) 2023 PV Tejas
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright Permission is hereby granted, free of charge, to any person obtaining a copy
notice, this list of conditions and the following disclaimer. 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:
2. Redistributions in binary form must reproduce the above copyright The above copyright notice and this permission notice shall be included in all
notice, this list of conditions and the following disclaimer in the copies or substantial portions of the Software.
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
contributors may be used to endorse or promote products derived from IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
this software without specific prior written permission. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A SOFTWARE.
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View file

@ -10,7 +10,20 @@ Use `gunicorn -w 2 'flaskr:create_app()'` to run app. Increase the number of wor
## Initializing database ## Initializing database
The first time you install the app in each environment, you need to initialize database using `flask --app flaskr init-db`. This only needs to be run once per environment, and **will delete existing database if run again**. The first time you install the app in each environment, you need to initialize database using `flask --app flaskr init-db`. This only needs to be run once per environment, and **will delete existing database if run again**.
## Secret key ## Config file
The config file is located at `<python_environment>/var/flaskr-instance/config.py` in production, and in `instance/` in development. The instance folder is created when the database is initialized.
### Secret Key
Every website with login needs a secret key to hash passwords with. Every website with login needs a secret key to hash passwords with.
`<python_environment>/var/flaskr-instance/config.py` must contain a line `SECRET_KEY = '<secret_key>`, which must be randomly generated. The config file must contain a line `SECRET_KEY = '<secret_key>`, which must be randomly generated.
Suggested way of generating the key is `python -c 'import secrets; print(secrets.token_hex())'`, which returns a hexadecimal string with length 64. You may choose to randomly generate a key using a different method, but ensure that it is resistant to brute-force attacks. Suggested way of generating the key is `python -c 'import secrets; print(secrets.token_hex())'`, which returns a hexadecimal string with length 64. You may choose to randomly generate a key using a different method, but ensure that it is resistant to brute-force attacks.
### Registration
Since this blog is meant to be updated by a limited number of people, registration is forbidden (403) by default. In addition, registration (/auth/register) and login (/auth/login) URLs are not hyperlinked anywhere. Registration can be opened by including `REGISTER = True`, and is closed by default.
### Name
The default app name is "Flaskr", and it is visible on the header bar as well as the page title. Including a line `NAME = '<name>'` in the config file replaces "Flaskr" with your chosen name.
### Static folder
The default static folder is the one included in the repository. You can use a separate static folder to use your own assets by including a line `STATIC_FOLDER = '<absolute/path/to/folder>'` in the config file.

View file

@ -8,7 +8,8 @@ def create_app(test_config=None):
app.config.from_mapping( app.config.from_mapping(
SECRET_KEY='dev', SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
ALLOW_REGISTER=True, REGISTER=False,
NAME='Flaskr'
) )
app.wsgi_app = ProxyFix( app.wsgi_app = ProxyFix(
@ -22,6 +23,9 @@ def create_app(test_config=None):
# load the test config if passed in # load the test config if passed in
app.config.from_mapping(test_config) app.config.from_mapping(test_config)
if app.config.get('STATIC_FOLDER') is not None:
app.static_folder = app.config.get('STATIC_FOLDER')
# ensure the instance folder exists # ensure the instance folder exists
try: try:
os.makedirs(app.instance_path) os.makedirs(app.instance_path)

View file

@ -1,7 +1,7 @@
import functools import functools
from flask import ( from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for, current_app Blueprint, flash, g, redirect, render_template, request, session, url_for, current_app, abort
) )
from werkzeug.security import check_password_hash, generate_password_hash from werkzeug.security import check_password_hash, generate_password_hash
@ -11,8 +11,8 @@ bp = Blueprint('auth', __name__, url_prefix='/auth')
@bp.route('/register', methods=('GET', 'POST')) @bp.route('/register', methods=('GET', 'POST'))
def register(): def register():
if not current_app.config["ALLOW_REGISTER"]: if not current_app.config['REGISTER']:
return "Admin only", 403 abort(403)
if request.method == 'POST': if request.method == 'POST':
username = request.form['username'] username = request.form['username']
password = request.form['password'] password = request.form['password']

View file

@ -7,7 +7,6 @@ from flaskr.auth import login_required
from flaskr.db import get_db from flaskr.db import get_db
import markdown import markdown
import datetime
bp = Blueprint('blog', __name__) bp = Blueprint('blog', __name__)
@ -21,30 +20,11 @@ def index():
).fetchall() ).fetchall()
posts = [] posts = []
for post in db_posts: for post in db_posts:
if post['created'] > datetime.datetime.utcnow():
continue
post = dict(post) post = dict(post)
post['body'] = markdown.markdown(post['body']) post['body'] = markdown.markdown(post['body'])
posts.append(post) posts.append(post)
return render_template('blog/index.html', posts=posts) return render_template('blog/index.html', posts=posts)
@bp.route('/firehose')
def firehose():
db = get_db()
db_posts = db.execute(
'SELECT p.id, title, body, created, author_id, username'
' FROM post p JOIN user u ON p.author_id = u.id'
' ORDER BY created DESC'
).fetchall()
posts = []
for post in db_posts:
if post['created'] > datetime.datetime.utcnow():
continue
post = dict(post)
post['body'] = markdown.markdown(post['body'])
posts.append(post)
return render_template('blog/firehose.html', posts=posts)
@bp.route('/create',methods=('GET', 'POST')) @bp.route('/create',methods=('GET', 'POST'))
@login_required @login_required
def create(): def create():
@ -86,9 +66,10 @@ def get_post(id, check_author=True):
return post return post
@bp.route('/<int:id>/') @bp.route('/<int:id>')
def individual_post(id): def post(id):
post = dict(get_post(id, False)) post = get_post(id, check_author=False)
post = dict(post)
post['body'] = markdown.markdown(post['body']) post['body'] = markdown.markdown(post['body'])
return render_template('blog/post.html', post=post) return render_template('blog/post.html', post=post)
@ -100,23 +81,19 @@ def update(id):
if request.method == 'POST': if request.method == 'POST':
title = request.form['title'] title = request.form['title']
body = request.form['body'] body = request.form['body']
created = request.form['created']
error = None error = None
if not title: if not title:
error = 'Title is required.' error = 'Title is required.'
if not created:
error = "Created is required."
if error is not None: if error is not None:
flash(error) flash(error)
else: else:
db = get_db() db = get_db()
db.execute( db.execute(
'UPDATE post SET title = ?, body = ?, created = ?' 'UPDATE post SET title = ?, body = ?'
' WHERE id = ?', ' WHERE id = ?',
(title, body, created, id) (title, body, id)
) )
db.commit() db.commit()
return redirect(url_for('blog.index')) return redirect(url_for('blog.index'))
@ -131,3 +108,7 @@ def delete(id):
db.execute('DELETE FROM post WHERE id = ?',(id,)) db.execute('DELETE FROM post WHERE id = ?',(id,))
db.commit() db.commit()
return redirect(url_for('blog.index')) return redirect(url_for('blog.index'))
@bp.route('/temp')
def temp():
return render_template('temp.html')

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

After

Width:  |  Height:  |  Size: 73 B

Before After
Before After

View file

@ -1,30 +1,20 @@
html { font-family: sans-serif; background: #eee; padding: 1rem; } html { font-family: sans-serif; background: #eee; padding: 1rem; }
body { max-width: 960px; margin: 0 auto; background: white; } body { max-width: 960px; margin: 0 auto; background: white; }
h1 { font-family: serif; color: #377ba8; margin: 1rem 0; } h1 { font-family: serif; color: #377ba8; margin: 1rem 0; }
h2 { color: #377ba8; margin: 1rem 0; }
h3 { color: #377ba8; margin: 1rem 0; }
h4 { color: #377ba8; margin: 1rem 0; }
h5 { color: #377ba8; margin: 1rem 0; }
h6 { color: #377ba8; margin: 1rem 0; }
a { color: #377ba8; } a { color: #377ba8; }
hr { border: none; border-top: 1px solid lightgray; } hr { border: none; border-top: 1px solid lightgray; }
nav { background: lightgray; display: flex; align-items: center; padding: 0 0.5rem; } nav { background: lightgray; display: flex; align-items: center; padding: 0 0.5rem; }
nav h1 { flex: auto; margin: 0; } nav h1 { flex: auto; margin: 0; }
nav h1 a { text-decoration: none; padding: 0.25rem 0.5rem; } nav h1 a { text-decoration: none; padding: 0.25rem 0.5rem; }
nav ul { display: flex; list-style: none; margin: 0; padding: 0; } nav ul { display: flex; list-style: none; margin: 0; padding: 0; }
nav ul li a, nav ul li span, header .action { display: block;} nav ul li a, nav ul li span, header .action { display: block; padding: 0.5rem; }
.content { padding: 0 1rem 1rem; } .content { padding: 0 1rem 1rem; }
.content > header { border-bottom: 1px solid lightgray; display: flex; align-items: flex-end; } .content > header { border-bottom: 1px solid lightgray; display: flex; align-items: flex-end; }
.content > header h1 { flex: auto; margin: 1rem 0 0.25rem 0; } .content > header h1 { flex: auto; margin: 1rem 0 0.25rem 0; }
.flash { margin: 1em 0; padding: 1em; background: #cae6f6; border: 1px solid #377ba8; } .flash { margin: 1em 0; padding: 1em; background: #cae6f6; border: 1px solid #377ba8; }
.post > header { display: flex; align-items: flex-end; font-size: 0.85em; } .post > header { display: flex; align-items: flex-end; font-size: 0.85em; }
.post > header > div:first-of-type { flex: auto; } .post > header > div:first-of-type { flex: auto; }
.post > header h1 { margin-bottom: 0; } .post > header h1 { font-size: 1.5em; margin-bottom: 0; }
.post > h2 { margin-bottom: 0; }
.post > h3 { margin-bottom: 0; }
.post > h4 { margin-bottom: 0; }
.post > h5 { margin-bottom: 0; }
.post > h6 { margin-bottom: 0; }
.post .about { color: slategray; font-style: italic; } .post .about { color: slategray; font-style: italic; }
.post .body { white-space: pre-line; } .post .body { white-space: pre-line; }
.content:last-child { margin-bottom: 0; } .content:last-child { margin-bottom: 0; }

View file

@ -1,9 +1,9 @@
<!doctype html> <!doctype html>
<title>{% block title %}{% endblock %} - blogsparkinfinite</title> <title>{% block title %}{% endblock %} - {{ config['NAME'] }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.png') }}"> <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.png') }}">
<nav> <nav>
<h1>blogsparkinfinite</h1> <h1>{{ config['NAME'] }}</h1>
<ul> <ul>
{% if g.user %} {% if g.user %}
<li><span>{{ g.user['username'] }}</span> <li><span>{{ g.user['username'] }}</span>
@ -11,6 +11,9 @@
{% endif %} {% endif %}
</ul> </ul>
</nav> </nav>
</br>
</br>
</br>
<section class="content"> <section class="content">
<header> <header>
{% block header %}{% endblock %} {% block header %}{% endblock %}

View file

@ -1,28 +0,0 @@
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}Posts{% endblock %}</h1>
{% if g.user %}
<a class="action" href="{{ url_for('blog.create') }}">New</a>
{% endif %}
{% endblock %}
{% block content %}
{% for post in posts %}
<article class="post">
<header>
<div>
<h1>{{ post['title'] }}</h1>
<div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div>
</div>
{% if g.user['id'] == post['author_id'] %}
<a class="action" href="{{ url_for('blog.update', id=post['id']) }}">Edit</a>
{% endif %}
</header>
<p class="body">{{ post['body']|safe }}</p>
</article>
{% if not loop.last %}
<hr>
{% endif %}
{% endfor %}
{% endblock %}

View file

@ -12,12 +12,12 @@
<article class="post"> <article class="post">
<header> <header>
<div> <div>
<h1><a class="action" href="{{ url_for('blog.individual_post', id=post['id']) }}">{{ post['title'] }}</a></h1> <h1><a href="{{ url_for('blog.post', id=post['id']) }}">{{ post['title'] }}</a></h1>
<div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div> <div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div>
</div> </div>
{% if g.user['id'] == post['author_id'] %} {% if g.user['id'] == post['author_id'] %}
<a class="action" href="{{ url_for('blog.update', id=post['id']) }}">Edit</a> <a href="{{ url_for('blog.update', id=post['id']) }}">Edit</a>
{% endif %} {% endif %}
</header> </header>
</article> </article>
{% if not loop.last %} {% if not loop.last %}

View file

@ -1,19 +1,20 @@
{% extends 'base.html' %} {% extends 'base.html' %}
{% block header %} {% block header %}
<h1>{% block title %}{{ post['title'] }}{% endblock %}</h1> <h1>{% block title %}{{ post['title']}}{% endblock %}</h1>
{% endblock %} {% endblock %}
{% block content %} {% block content %}
<article class="post"> <article class="post">
<header> <header>
<div> <div>
<div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div> <h1>{{ post['title'] }}</h1>
</div> <div class="about">by {{ post['username'] }} on {{ post['created'].strftime('%Y-%m-%d') }}</div>
{% if g.user['id'] == post['author_id'] %} </div>
<a class="action" href="{{ url_for('blog.update', id=post['id']) }}">Edit</a> {% if g.user['id'] == post['author_id'] %}
{% endif %} <a class="action" href="{{ url_for('blog.update', id=post['id']) }}">Edit</a>
{% endif %}
</header> </header>
<p class="body">{{ post['body']|safe }}</p> <p class="body">{{ post['body']|safe }}</p>
</article> </article>
{% endblock %} {% endblock %}

View file

@ -11,9 +11,6 @@
value="{{ request.form['title'] or post['title'] }}" required> value="{{ request.form['title'] or post['title'] }}" required>
<label for="body">Body</label> <label for="body">Body</label>
<textarea name="body" id="body">{{ request.form['body'] or post['body'] }}</textarea> <textarea name="body" id="body">{{ request.form['body'] or post['body'] }}</textarea>
<label for="created">Created</label>
<input name="created" id="created"
value="{{ request.form['created'] or post['created'] }}" required>
<input type="submit" value="Save"> <input type="submit" value="Save">
</form> </form>
<hr> <hr>

View file

@ -8,11 +8,11 @@ dnspython==2.3.0
email-validator==2.0.0.post2 email-validator==2.0.0.post2
exceptiongroup==1.1.1 exceptiongroup==1.1.1
Flask==2.3.2 Flask==2.3.2
# -e git+https://gitlab.com/pvtejas/based4tech.git@4be89bd767a7c5a84ab62fbf4ad924ae1af077f1#egg=flaskr -e git+https://gitlab.com/pvtejas/based4tech.git@bda624e4dc1cf97ba2b5b3fcb66a5b28398307bc#egg=flaskr
gunicorn==20.1.0 gunicorn==20.1.0
h11==0.14.0 h11==0.14.0
httpcore==0.17.0 httpcore==0.17.0
httptools httptools==0.5.0
httpx==0.24.0 httpx==0.24.0
idna==3.4 idna==3.4
iniconfig==2.0.0 iniconfig==2.0.0
@ -20,20 +20,20 @@ itsdangerous==2.1.2
Jinja2==3.1.2 Jinja2==3.1.2
Markdown==3.4.3 Markdown==3.4.3
MarkupSafe==2.1.2 MarkupSafe==2.1.2
orjson orjson==3.8.11
packaging==23.1 packaging==23.1
pluggy==1.0.0 pluggy==1.0.0
pyproject_hooks==1.0.0 pyproject_hooks==1.0.0
pytest==7.3.2 pytest==7.3.2
python-dotenv==1.0.0 python-dotenv==1.0.0
python-multipart==0.0.6 python-multipart==0.0.6
# PyYAML==6.0 PyYAML==6.0
sniffio==1.3.0 sniffio==1.3.0
tomli==2.0.1 tomli==2.0.1
typing_extensions==4.5.0 typing_extensions==4.5.0
ujson ujson==5.7.0
uvicorn==0.22.0 uvicorn==0.22.0
uvloop uvloop==0.17.0
watchfiles==0.19.0 watchfiles==0.19.0
websockets==11.0.3 websockets==11.0.3
Werkzeug==2.3.3 Werkzeug==2.3.3

View file

@ -15,7 +15,6 @@ def app():
app = create_app({ app = create_app({
'TESTING': True, 'TESTING': True,
'DATABASE': db_path, 'DATABASE': db_path,
'ALLOW_REGISTER': True,
}) })
with app.app_context(): with app.app_context():

View file

@ -14,10 +14,6 @@ def test_register(client, app):
"SELECT * FROM user WHERE USERNAME = 'a'", "SELECT * FROM user WHERE USERNAME = 'a'",
).fetchone() is not None ).fetchone() is not None
app.config["ALLOW_REGISTER"] = False
response = client.get('/auth/register')
assert b"Admin only" in response.data
@pytest.mark.parametrize(('username', 'password', 'message'), ( @pytest.mark.parametrize(('username', 'password', 'message'), (
('', '', b'Username is required.'), ('', '', b'Username is required.'),
('a', '', b'Password is required.'), ('a', '', b'Password is required.'),

View file

@ -3,37 +3,17 @@ from flaskr.db import get_db
def test_index(client, auth): def test_index(client, auth):
response = client.get('/') response = client.get('/')
assert b"Log In" not in response.data assert b"Log In" in response.data
assert b"Register" not in response.data assert b"Register" in response.data
auth.login() auth.login()
response = client.get('/') response = client.get('/')
assert b'Log Out' in response.data assert b'Log Out' in response.data
assert b'test title' in response.data assert b'test title' in response.data
assert b'by test on 2018-01-01' in response.data assert b'by test on 2018-01-01' in response.data
assert b'test\nbody' not in response.data
assert b'href="/1/update"' in response.data
assert b'href="/1/"' in response.data
def test_firehose(client, auth):
response = client.get('/')
assert b"Log In" not in response.data
assert b"Register" not in response.data
auth.login()
response = client.get('/firehose')
assert b'Log Out' in response.data
assert b'test title' in response.data
assert b'by test on 2018-01-01' in response.data
assert b'test\nbody' in response.data assert b'test\nbody' in response.data
assert b'href="/1/update"' in response.data assert b'href="/1/update"' in response.data
def test_individual_page(client, auth):
response = client.get('/1/')
assert b'test title' in response.data
assert b'by test on 2018-01-01' in response.data
assert b'test\nbody' in response.data
@pytest.mark.parametrize('path', ( @pytest.mark.parametrize('path', (
'/create', '/create',
'/1/update', '/1/update',
@ -78,7 +58,7 @@ def test_create(client, auth, app):
def test_update(client, auth, app): def test_update(client, auth, app):
auth.login() auth.login()
assert client.get('/1/update').status_code == 200 assert client.get('/1/update').status_code == 200
client.post('/1/update', data={'title': 'updated', 'body': '', 'created': '1970-01-01 00:00:00'}) client.post('/1/update', data={'title': 'updated', 'body': ''})
with app.app_context(): with app.app_context():
db = get_db() db = get_db()
@ -91,7 +71,7 @@ def test_update(client, auth, app):
)) ))
def test_create_update_validate(client, auth, path): def test_create_update_validate(client, auth, path):
auth.login() auth.login()
response = client.post(path, data={'title': '', 'body': '', 'created': '1970-01-01 00:00:00'}) response = client.post(path, data={'title': '', 'body': ''})
assert b'Title is required.' in response.data assert b'Title is required.' in response.data
def test_delete(client, auth, app): def test_delete(client, auth, app):