refactor with blueprints

This commit is contained in:
Trent Palmer 2021-01-30 06:36:25 -08:00
parent c2ccb01aab
commit 29afdd025c
41 changed files with 696 additions and 607 deletions

View File

@ -7,19 +7,20 @@ from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager from flask_login import LoginManager
from flask_mail import Mail from flask_mail import Mail
db = SQLAlchemy()
login = LoginManager()
mail = Mail()
def init_app():
app = Flask(__name__) app = Flask(__name__)
app.config.from_object(Config) app.config.from_object(Config)
db = SQLAlchemy(app) db.init_app(app)
login = LoginManager(app) login.init_app(app)
mail = Mail(app) mail.init_app(app)
from app.sendxmpp_handler import SENDXMPPHandler from app.sendxmpp_handler import SENDXMPPHandler
from app import routes
if app.debug:
print("flask app 'photo_app' is in debug mode")
else:
print("flask app 'photo_app' is not in debug mode")
if app.config['LOGGING_XMPP_SERVER']: if app.config['LOGGING_XMPP_SERVER']:
sendxmpp_handler = SENDXMPPHandler( sendxmpp_handler = SENDXMPPHandler(
@ -32,3 +33,17 @@ if app.config['LOGGING_XMPP_SERVER']:
) )
sendxmpp_handler.setLevel(logging.ERROR) sendxmpp_handler.setLevel(logging.ERROR)
app.logger.addHandler(sendxmpp_handler) app.logger.addHandler(sendxmpp_handler)
from .auth import auth, totp, dis_totp, profile, register, reset_password
from .photo_routes import proutes, photox, delete_download, photo_upload
with app.app_context():
app.register_blueprint(auth.auths)
app.register_blueprint(totp.totps)
app.register_blueprint(dis_totp.disabletotp)
app.register_blueprint(profile.prof)
app.register_blueprint(register.reg)
app.register_blueprint(reset_password.pwd)
app.register_blueprint(proutes.proute)
app.register_blueprint(photox.p_route)
app.register_blueprint(delete_download.d_d)
app.register_blueprint(photo_upload.pupload)
return app

72
app/auth/auth.py Normal file
View File

@ -0,0 +1,72 @@
#!/usr/bin/env python3
from flask import Blueprint, redirect, url_for, session, flash, render_template
from flask_login import current_user, login_user, logout_user
from app.forms import LoginForm, GetTotp
from app.models import Contributor
from pyotp.totp import TOTP
auths = Blueprint(
"auths", __name__, template_folder="templates"
)
@auths.route("/two-factor-input", methods=["GET", "POST"])
def two_factor_input():
if current_user.is_authenticated or 'id' not in session:
return redirect(url_for('proute.index'))
contributor = Contributor.query.get(session['id'])
if contributor is None:
return redirect(url_for('proute.index'))
form = GetTotp()
if form.validate_on_submit():
if TOTP(contributor.totp_key).verify(int(form.totp_code.data), valid_window=5):
login_user(contributor, remember=session['remember_me'])
flash("Congratulations, you are now logged in!")
return redirect(url_for('proute.index'))
else:
flash("Oops, the pin was wrong")
form.totp_code.data = None
return render_template('two_factor_input.html', form=form, inst="Code was wrong, try again?")
return render_template('two_factor_input.html', form=form, inst="Enter Auth Code")
@auths.route("/login", methods=["GET", "POST"])
def login():
if current_user.is_authenticated:
return redirect(url_for('proute.index'))
form = LoginForm()
if form.validate_on_submit():
contributor_by_name = Contributor.query.filter_by(name=form.username.data).first()
contributor_by_email = Contributor.query.filter_by(email=form.email.data).first()
if contributor_by_name is not None and contributor_by_name.check_password(form.password.data):
if contributor_by_name.use_totp:
session['id'] = contributor_by_name.id
session['remember_me'] = form.remember_me.data
return redirect(url_for('auths.two_factor_input'))
else:
login_user(contributor_by_name, remember=form.remember_me.data)
flash("Congratulations, you are now logged in!")
return redirect(url_for('proute.index'))
elif contributor_by_email is not None and contributor_by_email.check_password(form.password.data):
if contributor_by_email.use_totp:
session['id'] = contributor_by_email.id
session['remember_me'] = form.remember_me.data
return redirect(url_for('auths.two_factor_input'))
else:
login_user(contributor_by_email, remember=form.remember_me.data)
flash("Congratulations, you are now logged in!")
return redirect(url_for('proute.index'))
else:
flash("Error Invalid Contributor (Username or Email) or Password")
return(redirect(url_for('auths.login')))
return render_template('login.html', title='Sign In', form=form)
@auths.route("/logout")
def logout():
is_authenticated = current_user.is_authenticated
logout_user()
if is_authenticated:
flash("Congratulations, you are now logged out!")
return redirect(url_for('proute.index'))

39
app/auth/dis_totp.py Normal file
View File

@ -0,0 +1,39 @@
#!/usr/bin/env python3
from flask import Blueprint, redirect, url_for, flash, render_template
from flask_login import current_user
from app.models import Contributor
from flask_wtf import FlaskForm
from wtforms import SubmitField
from .. import db
disabletotp = Blueprint(
"disabletotp", __name__, template_folder="templates"
)
@disabletotp.route('/disable-totp', methods=['GET', 'POST'])
def disable_totp():
if current_user.is_anonymous or not current_user.use_totp:
return(redirect(url_for('proute.index')))
contributor = Contributor.query.get(current_user.id)
form = DisableTotp()
if form.validate_on_submit():
if disable_2fa(contributor):
flash('2FA Now Disabled')
return(redirect(url_for('prof.edit_profile')))
else:
flash('2FA Not Disabled')
return(redirect(url_for('prof.edit_profile')))
return render_template('disable_2fa.html', form=form, title="Disable 2FA")
def disable_2fa(contributor):
contributor.use_totp = False
contributor.totp_key = None
db.session.commit()
return True
class DisableTotp(FlaskForm):
submit = SubmitField('Disable 2FA')

View File

@ -1,15 +1,15 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from flask import render_template from flask import render_template, current_app
from flask_mail import Message from flask_mail import Message
from app import mail, app from .. import mail
from threading import Thread from threading import Thread
def send_password_reset_email(contributor, external_url): def send_password_reset_email(contributor, external_url):
token = contributor.get_reset_password_token() token = contributor.get_reset_password_token()
send_email('Photo App Reset Your Password', send_email('Photo App Reset Your Password',
sender=app.config['MAIL_ADMINS'][0], sender=current_app.config['MAIL_ADMINS'][0],
recipients=[contributor.email], recipients=[contributor.email],
text_body=render_template('email/reset_password_email_text.txt', text_body=render_template('email/reset_password_email_text.txt',
contributor=contributor, token=token, external_url=external_url), contributor=contributor, token=token, external_url=external_url),
@ -26,4 +26,4 @@ def send_email(subject, sender, recipients, text_body, html_body):
msg = Message(subject, sender=sender, recipients=recipients) msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body msg.body = text_body
msg.html = html_body msg.html = html_body
Thread(target=send_async_email, args=(app, msg)).start() Thread(target=send_async_email, args=(current_app._get_current_object(), msg)).start()

55
app/auth/profile.py Normal file
View File

@ -0,0 +1,55 @@
#!/usr/bin/env python3
from flask import Blueprint, redirect, url_for, request, flash, render_template
from flask_login import current_user
from .. import db
from app.models import Contributor
from app.forms import EditProfile, ChangePassword
prof = Blueprint(
"prof", __name__, template_folder="templates"
)
@prof.route("/change-password", methods=["GET", "POST"])
def change_password():
if not current_user.is_authenticated:
return(redirect(url_for('proute.index')))
contributor = Contributor.query.get(current_user.id)
form = ChangePassword()
if form.validate_on_submit():
if contributor.check_password(form.password.data):
contributor.set_password(form.new_password.data)
db.session.commit()
flash("Thanks for the update!")
return(redirect(url_for('proute.index')))
else:
flash("Error Invalid Password")
return(redirect(url_for('prof.change_password')))
return render_template('change_password.html', title='Change Password', form=form)
@prof.route("/edit-profile", methods=["GET", "POST"])
def edit_profile():
if current_user.is_anonymous:
return(redirect(url_for('proute.index')))
contributor = Contributor.query.get(current_user.id)
form = EditProfile()
if request.method == 'GET':
form.username.data = contributor.name
form.email.data = contributor.email
if form.validate_on_submit():
if contributor.check_password(form.password.data):
contributor.name = form.username.data
contributor.email = form.email.data
db.session.commit()
flash("Thanks for the update!")
return(redirect(url_for('proute.index')))
else:
flash("Error Invalid Password")
return(redirect(url_for('prof.edit_profile')))
return render_template(
'edit_profile.html',
title='Edit Profile', form=form,
contributor_use_totp=contributor.use_totp
)

28
app/auth/register.py Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env python3
from flask import Blueprint, redirect, url_for, render_template, flash
from flask_login import current_user
from app.forms import RegistrationForm
from app.models import Contributor
from .. import db
reg = Blueprint(
"reg", __name__, template_folder="templates"
)
@reg.route("/register", methods=["GET", "POST"])
def register():
if current_user.is_authenticated:
return redirect(url_for('proute.index'))
form = RegistrationForm()
if form.validate_on_submit():
db.engine.execute("SELECT setval('contributor_id_seq', (SELECT MAX(id) FROM contributor))")
db.session.commit()
contributor = Contributor(name=form.username.data, num_photos=0, email=form.email.data)
contributor.set_password(form.password.data)
db.session.add(contributor)
db.session.commit()
flash("Congratulations, you are now a registered user!")
return redirect(url_for('auths.login'))
return render_template('register.html', title='Register', form=form)

View File

@ -0,0 +1,46 @@
#!/usr/bin/env python3
from flask import Blueprint, redirect, url_for, flash, render_template, current_app
from flask_login import current_user
from app.models import Contributor
from app.forms import ResetPasswordForm, ResetPasswordRequestForm
from .email import send_password_reset_email
from .. import db
pwd = Blueprint(
"pwd", __name__, template_folder="templates"
)
@pwd.route('/reset-password/<token>', methods=['GET', 'POST'])
def reset_password(token):
if current_user.is_authenticated:
return redirect(url_for('proute.index'))
contributor = Contributor.verify_reset_password_token(token)
if not contributor:
return redirect(url_for('proute.index'))
form = ResetPasswordForm()
if form.validate_on_submit():
contributor.set_password(form.password.data)
db.session.commit()
flash('Your password has been reset.')
return redirect(url_for('auths.login'))
return render_template('reset_password.html', title="New Password?", form=form)
@pwd.route('/reset-password-request', methods=['GET', 'POST'])
def reset_password_request():
if current_user.is_authenticated:
return(redirect(url_for('proute.index')))
else:
form = ResetPasswordRequestForm()
if form.validate_on_submit():
contributor = Contributor.query.filter_by(email=form.email.data).first()
if contributor:
send_password_reset_email(contributor, current_app.config['EXTERNAL_URL'])
flash('Check your email for the instructions to reset your password')
return redirect(url_for('auths.login'))
else:
flash('Sorry, invalid email')
return redirect(url_for('auths.login'))
return render_template('reset_password_request.html', title='Reset Password', form=form)

View File

@ -33,15 +33,15 @@
</form> </form>
{% if current_user.is_authenticated %} {% if current_user.is_authenticated %}
<div> <div>
<button class="formButton" onclick="location.href='{{ url_for('change_password') }}';">Change Password</button> <button class="formButton" onclick="location.href='{{ url_for('prof.change_password') }}';">Change Password</button>
</div> </div>
{% if contributor_use_totp %} {% if contributor_use_totp %}
<div> <div>
<button class="formButton" onclick="location.href='{{ url_for('disable_totp') }}';">Disable 2 Factor</button> <button class="formButton" onclick="location.href='{{ url_for('disabletotp.disable_totp') }}';">Disable 2 Factor</button>
</div> </div>
{% else %} {% else %}
<div> <div>
<button class="formButton" onclick="location.href='{{ url_for('enable_totp') }}';">Enable 2 Factor</button> <button class="formButton" onclick="location.href='{{ url_for('totps.enable_totp') }}';">Enable 2 Factor</button>
</div> </div>
{% endif %} {% endif %}
{% endif %} {% endif %}

View File

@ -30,10 +30,9 @@
<p>{{ form.remember_me() }} {{ form.remember_me.label }}</p> <p>{{ form.remember_me() }} {{ form.remember_me.label }}</p>
<p>{{ form.submit() }}</p> <p>{{ form.submit() }}</p>
</form> </form>
<p>New User? <a href="{{ url_for('register') }}">Click to Register!</a></p> <p>New User? <a href="{{ url_for('reg.register') }}">Click to Register!</a></p>
<p> <p>
Forgot Your Password? <a href="{{ url_for('reset_password_request') }}">Click to Reset It</a> Forgot Your Password? <a href="{{ url_for('pwd.reset_password_request') }}">Click to Reset It</a>
</p> </p>
</div> </div>
{% endblock %} {% endblock %}

View File

@ -30,7 +30,7 @@ h3 {
<h3>{{ inst }}</h3> <h3>{{ inst }}</h3>
<div class='formContainer'> <div class='formContainer'>
<form action={{ url_for('two_factor_input') }} method="post" novalidate> <form action={{ url_for('auths.two_factor_input') }} method="post" novalidate>
{{ form.hidden_tag() }} {{ form.hidden_tag() }}
<p id="totpp"> <p id="totpp">
{{ form.totp_code.label }}<br> {{ form.totp_code.label }}<br>

56
app/auth/totp.py Normal file
View File

@ -0,0 +1,56 @@
#!/usr/bin/env python3
import pyotp
import qrcode
import qrcode.image.svg
from io import BytesIO
from flask import Blueprint, redirect, url_for, flash, render_template
from flask_login import current_user
from app.models import Contributor
from app.forms import ConfirmTotp
from .. import db
totps = Blueprint(
"totps", __name__, template_folder="templates"
)
@totps.route('/enable-totp', methods=['GET', 'POST'])
def enable_totp():
if current_user.is_anonymous or current_user.use_totp:
return(redirect(url_for('proute.index')))
contributor = Contributor.query.get(current_user.id)
form = ConfirmTotp()
qr = get_totp_qr(contributor)
if form.validate_on_submit():
if contributor.use_totp:
flash('2FA Already Enabled')
return(redirect(url_for('prof.edit_profile')))
if validate_totp(contributor, form.totp_code.data):
flash('2FA Now Enabled')
return(redirect(url_for('prof.edit_profile')))
else:
flash("TOTP Code didn't validate, rescan and try again")
return(redirect(url_for('prof.edit_profile')))
return render_template('qr.html', qr=qr, form=form, title="Aunthentication Code")
def get_totp_qr(contributor):
if contributor.totp_key is None:
contributor.totp_key = pyotp.random_base32()
db.session.commit()
totp_uri = pyotp.totp.TOTP(contributor.totp_key).provisioning_uri(name=contributor.email, issuer_name='Photo App')
img = qrcode.make(totp_uri, image_factory=qrcode.image.svg.SvgPathImage)
f = BytesIO()
img.save(f)
return(f.getvalue().decode('utf-8'))
def validate_totp(contributor, totp_code):
if pyotp.TOTP(contributor.totp_key).verify(int(totp_code), valid_window=5):
contributor.use_totp = True
db.session.commit()
return True
else:
return False

View File

@ -12,10 +12,6 @@ class ConfirmPhotoDelete(FlaskForm):
submit = SubmitField('Delete') submit = SubmitField('Delete')
class DisableTotp(FlaskForm):
submit = SubmitField('Disable 2FA')
class GetTotp(FlaskForm): class GetTotp(FlaskForm):
totp_code = StringField('6-Digit Code?', validators=[DataRequired(), Length(min=6, max=6, message="6 Digits")], render_kw={'autofocus': True}) totp_code = StringField('6-Digit Code?', validators=[DataRequired(), Length(min=6, max=6, message="6 Digits")], render_kw={'autofocus': True})
submit = SubmitField('OK') submit = SubmitField('OK')

View File

@ -1,7 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from flask_login import UserMixin from flask_login import UserMixin
from app import db, login, app from flask import current_app
from . import db, login
from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.security import generate_password_hash, check_password_hash
from time import time from time import time
import jwt import jwt
@ -63,12 +64,12 @@ class Contributor(UserMixin, db.Model):
return '<Contributor {}>'.format(self.name) return '<Contributor {}>'.format(self.name)
def get_reset_password_token(self, expires_in=1800): def get_reset_password_token(self, expires_in=1800):
return jwt.encode({'reset_password': self.id, 'exp': time() + expires_in}, app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8') return jwt.encode({'reset_password': self.id, 'exp': time() + expires_in}, current_app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8')
@staticmethod @staticmethod
def verify_reset_password_token(token): def verify_reset_password_token(token):
try: try:
id = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password'] id = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])['reset_password']
except BaseException as error: except BaseException as error:
print('An exception occurred: {}'.format(error)) print('An exception occurred: {}'.format(error))
return Contributor.query.get(id) return Contributor.query.get(id)

View File

@ -0,0 +1,68 @@
#!/usr/bin/env python3
from flask import Blueprint, request, redirect, url_for, render_template, current_app, send_file
from flask_login import current_user
from app.models import Photo
from app.forms import ConfirmPhotoDelete
import psycopg2
import os
d_d = Blueprint(
"d_d", __name__, template_folder="templates"
)
@d_d.route('/download')
def download():
if current_user.is_authenticated:
f = request.args['file']
try:
return send_file('/var/lib/photo_app/photos/{}'.format(f), attachment_filename=f)
except Exception as e:
return str(e)
@d_d.route('/delete', methods=['GET', 'POST'])
def delete():
photo = Photo.query.get(request.args['photo_id'])
if photo is None:
return(redirect(url_for('proute.index')))
if not current_user.is_authenticated or photo.contributor_id != current_user.id:
return(redirect(url_for('proute.index')))
form = ConfirmPhotoDelete()
if request.method == 'POST' and form.validate_on_submit():
return(redirect(url_for('p_route.photo', photo_id=delete_photo(photo))))
return(render_template(
'delete_photo.html',
title="Delete Photo?",
photo=photo,
photo_url=current_app.config['PHOTO_URL'],
form=form
))
def delete_photo(photo):
conn = psycopg2.connect(
dbname=current_app.config['DATABASE_NAME'],
user=current_app.config['DATABASE_USER'],
host=current_app.config['DATABASE_HOST'],
password=current_app.config['DATABASE_PASSWORD']
)
cur = conn.cursor()
cur.execute("SELECT count(id) FROM photo WHERE contributor_id=%s AND id>%s", (photo.contributor_id, photo.id))
if cur.fetchone()[0] == 0:
cur.execute("SELECT id FROM photo WHERE contributor_id=%s ORDER BY id", (photo.contributor_id, ))
else:
cur.execute("SELECT id FROM photo WHERE contributor_id=%s AND id>%s ORDER BY id", (photo.contributor_id, photo.id))
next_photo_id = cur.fetchone()[0]
os.chdir(current_app.config['PHOTO_SAVE_PATH'])
if os.path.exists('raw_' + photo.photo_name):
os.remove('raw_' + photo.photo_name)
if os.path.exists('1280_' + photo.photo_name):
os.remove('1280_' + photo.photo_name)
if os.path.exists('480_' + photo.photo_name):
os.remove('480_' + photo.photo_name)
cur.execute("DELETE FROM photo WHERE id=%s", (photo.id, ))
conn.commit()
conn.close()
return next_photo_id

View File

@ -0,0 +1,44 @@
#!/usr/bin/env python3
from flask import current_app
from flask_login import current_user
from flask import Blueprint, render_template, redirect, url_for, flash, request, abort
from app.forms import UploadPhotoForm
from .scripts.process_uploaded_photo import process_uploaded_photo
from werkzeug.utils import secure_filename
pupload = Blueprint(
"pupload", __name__, template_folder="templates"
)
@pupload.route('/photo-upload', methods=['GET', 'POST'])
def photo_upload():
if not current_user.is_authenticated:
return(redirect(url_for('proute.index')))
form = UploadPhotoForm()
if request.method == 'POST' and form.validate_on_submit():
f = request.files['image']
filename = secure_filename(f.filename)
if filename != '':
import os
file_ext = os.path.splitext(filename)[1]
if file_ext not in ['.jpg', '.png'] or file_ext != validate_image(f.stream):
abort(400)
f.save(os.path.join(current_app.config['PHOTO_SAVE_PATH'], 'raw_' + filename))
photo_id = process_uploaded_photo(filename, current_user, current_app.config)
print(photo_id)
flash("Thanks for the new photo!")
return(redirect(url_for('p_route.photo', photo_id=photo_id)))
return(redirect(url_for('proute.index')))
return render_template('upload.html', title="Photo Upload", form=form)
def validate_image(stream):
import imghdr
header = stream.read(512)
stream.seek(0)
format = imghdr.what(None, header)
if not format:
return None
return '.' + (format if format != 'jpeg' else 'jpg')

View File

@ -1,16 +1,37 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from flask import Blueprint, redirect, url_for, current_app, render_template
from flask_login import current_user
from app.models import Photo
import psycopg2 import psycopg2
import psycopg2.extras import psycopg2.extras
from shutil import disk_usage
p_route = Blueprint(
"p_route", __name__, template_folder="templates"
)
def find_next_previous(photo, app_config): @p_route.route('/photo/<int:photo_id>')
def photo(photo_id):
photo = Photo.query.get(photo_id)
if not current_user.is_authenticated or photo is None:
return(redirect(url_for('proute.index')))
find_next_previous(photo)
calc_additional_data(photo)
return render_template(
'photo.html',
title="Photo",
photo=photo,
photo_url=current_app.config['PHOTO_URL']
)
def find_next_previous(photo):
conn = psycopg2.connect( conn = psycopg2.connect(
dbname=app_config['DATABASE_NAME'], dbname=current_app.config['DATABASE_NAME'],
user=app_config['DATABASE_USER'], user=current_app.config['DATABASE_USER'],
host=app_config['DATABASE_HOST'], host=current_app.config['DATABASE_HOST'],
password=app_config['DATABASE_PASSWORD'] password=current_app.config['DATABASE_PASSWORD']
) )
cur = conn.cursor() cur = conn.cursor()
cur.execute("SELECT count(id) FROM photo WHERE contributor_id=%s AND id > %s", (photo.contributor_id, photo.id)) cur.execute("SELECT count(id) FROM photo WHERE contributor_id=%s AND id > %s", (photo.contributor_id, photo.id))
@ -53,26 +74,3 @@ def calc_additional_data(photo):
photo.MapUrl = "https://www.google.com/maps/search/?api=1&query={}".format(photo.LatLong) photo.MapUrl = "https://www.google.com/maps/search/?api=1&query={}".format(photo.LatLong)
else: else:
photo.LatLong, photo.MapUrl = None, None photo.LatLong, photo.MapUrl = None, None
def get_photo_list(contributor_id, app_config):
conn = psycopg2.connect(
dbname=app_config['DATABASE_NAME'],
user=app_config['DATABASE_USER'],
host=app_config['DATABASE_HOST'],
password=app_config['DATABASE_PASSWORD']
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("SELECT photo_name,id FROM photo WHERE contributor_id=%s ORDER BY timestamp,\"DateTimeOriginal\" DESC", (contributor_id, ))
photos = cur.fetchall()
conn.close()
return photos
def get_disk_stats():
disk_stats = disk_usage('/')
return("Used {}GB of {}GB, {}GB free".format(
round(disk_stats.used / 1073741824, 1),
round(disk_stats.total / 1073741824, 1),
round(disk_stats.free / 1073741824, 1)
))

View File

@ -0,0 +1,48 @@
#!/usr/bin/env python3
from flask import Blueprint, flash, render_template, current_app
from flask_login import current_user
from shutil import disk_usage
import psycopg2
proute = Blueprint(
"proute", __name__, template_folder="templates"
)
@proute.route("/")
@proute.route("/index")
def index():
if current_user.is_authenticated:
photos = get_photo_list(current_user.id)
flash(get_disk_stats())
return(render_template(
'index.html',
title="Photos",
photos=photos,
photo_url=current_app.config['PHOTO_URL']
))
return render_template('index.html', title="Photos")
def get_photo_list(contributor_id):
conn = psycopg2.connect(
dbname=current_app.config['DATABASE_NAME'],
user=current_app.config['DATABASE_USER'],
host=current_app.config['DATABASE_HOST'],
password=current_app.config['DATABASE_PASSWORD']
)
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cur.execute("SELECT photo_name,id FROM photo WHERE contributor_id=%s ORDER BY timestamp,\"DateTimeOriginal\" DESC", (contributor_id, ))
photos = cur.fetchall()
conn.close()
return photos
def get_disk_stats():
disk_stats = disk_usage('/')
return("Used {}GB of {}GB, {}GB free".format(
round(disk_stats.used / 1073741824, 1),
round(disk_stats.total / 1073741824, 1),
round(disk_stats.free / 1073741824, 1)
))

View File

@ -0,0 +1,95 @@
#!/usr/bin/env python3
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
import os
from datetime import datetime
def get_exif_data(photo):
exif_data = {}
get_file_sizes(photo, exif_data)
return(exif_data)
def get_exif(img_raw, exif_data):
if hasattr(img_raw, '_getexif'):
exifdata = img_raw._getexif()
if exifdata is not None:
date_format = "%Y:%m:%d %H:%M:%S"
for k, v in TAGS.items():
if k in exifdata:
if v == "Make":
exif_data['Make'] = exifdata[k]
if v == "Model":
exif_data['Model'] = exifdata[k]
if v == "Software":
exif_data['Software'] = exifdata[k]
if v == "DateTime":
exif_data['DateTime'] = datetime.strptime(exifdata[k], date_format)
if v == "DateTimeOriginal":
exif_data['DateTimeOriginal'] = datetime.strptime(exifdata[k], date_format)
if v == "DateTimeDigitized":
exif_data['DateTimeDigitized'] = datetime.strptime(exifdata[k], date_format)
if v == "FNumber":
exif_data['fnumber'] = round(exifdata[k][0] / exifdata[k][1], 1)
if v == "DigitalZoomRatio":
exif_data['DigitalZoomRatio'] = round(exifdata[k][0] / exifdata[k][1], 2)
if v == "TimeZoneOffset":
exif_data['TimeZoneOffset'] = exifdata[k]
if v == "GPSInfo":
gpsinfo = {}
for h, i in GPSTAGS.items():
if h in exifdata[k]:
if i == 'GPSAltitudeRef':
gpsinfo['GPSAltitudeRef'] = int.from_bytes(exifdata[k][h], "big")
if i == 'GPSAltitude':
gpsinfo['GPSAltitude'] = round(exifdata[k][h][0] / exifdata[k][h][1], 3)
if i == 'GPSLatitudeRef':
gpsinfo['GPSLatitudeRef'] = exifdata[k][h]
if i == 'GPSLatitude':
gpsinfo['GPSLatitude'] = calc_coordinate(exifdata[k][h])
if i == 'GPSLongitudeRef':
gpsinfo['GPSLongitudeRef'] = exifdata[k][h]
if i == 'GPSLongitude':
gpsinfo['GPSLongitude'] = calc_coordinate(exifdata[k][h])
update_gpsinfo(gpsinfo, exif_data)
def update_gpsinfo(gpsinfo, exif_data):
if 'GPSAltitudeRef' in gpsinfo and 'GPSLatitude' in gpsinfo:
exif_data['GPSAltitude'] = gpsinfo['GPSAltitude']
exif_data['GPSAboveSeaLevel'] = False if gpsinfo['GPSAltitudeRef'] != 0 else True
if 'GPSLatitudeRef' in gpsinfo and 'GPSLatitude' in gpsinfo:
exif_data['GPSLatitude'] = gpsinfo['GPSLatitude'] if gpsinfo['GPSLatitudeRef'] != 'S' else 0 - gpsinfo['GPSLatitude']
if 'GPSLongitudeRef' in gpsinfo and 'GPSLongitude' in gpsinfo:
exif_data['GPSLongitude'] = gpsinfo['GPSLongitude'] if gpsinfo['GPSLongitudeRef'] != 'W' else 0 - gpsinfo['GPSLongitude']
def calc_coordinate(x):
degrees = x[0][0] / x[0][1]
minutes = x[1][0] / x[1][1]
seconds = x[2][0] / x[2][1]
return round(degrees + minutes / 60 + seconds / 3600, 5)
def get_dimensions_and_format(photo, exif_data):
img_raw = Image.open('raw_' + photo)
img_1280 = Image.open('1280_' + photo)
img_480 = Image.open('480_' + photo)
exif_data['AspectRatio'] = round(img_raw.width / img_raw.height, 5)
exif_data['photo_format'] = img_raw.format
exif_data['photo_width'] = img_raw.width
exif_data['photo_height'] = img_raw.height
exif_data['photo_1280_width'] = img_1280.width
exif_data['photo_1280_height'] = img_1280.height
exif_data['photo_480_width'] = img_480.width
exif_data['photo_480_height'] = img_480.height
get_exif(img_raw, exif_data)
def get_file_sizes(photo, exif_data):
exif_data['photo_raw_size'] = os.path.getsize('raw_' + photo)
exif_data['photo_1280_size'] = os.path.getsize('1280_' + photo)
exif_data['photo_480_size'] = os.path.getsize('480_' + photo)
get_dimensions_and_format(photo, exif_data)

View File

@ -14,7 +14,7 @@
{% block content %} {% block content %}
<div class='formContainer'> <div class='formContainer'>
<form action={{ url_for('delete', photo_id=photo.id) }} method="post" novalidate> <form action={{ url_for('d_d.delete', photo_id=photo.id) }} method="post" novalidate>
<h2>Delete Photo?</h2> <h2>Delete Photo?</h2>
<img style="width: 100%;" src={{ photo_url + '480_' + photo['photo_name'] }} alt={{ '480_' + photo['photo_name'] }}> <img style="width: 100%;" src={{ photo_url + '480_' + photo['photo_name'] }} alt={{ '480_' + photo['photo_name'] }}>
{{ form.hidden_tag() }} {{ form.hidden_tag() }}

View File

@ -11,9 +11,9 @@
{% block morenavs %} {% block morenavs %}
<button id="previousPhoto" class="navBracket" onclick="location.href='{{ url_for('photo', photo_id=photo.previous_photo_id) }}';">&#8249;</button> <button id="previousPhoto" class="navBracket" onclick="location.href='{{ url_for('p_route.photo', photo_id=photo.previous_photo_id) }}';">&#8249;</button>
<button class="navBracket delButton" onclick="location.href='{{ url_for('delete', photo_id=photo.id) }}';">DEL</button> <button class="navBracket delButton" onclick="location.href='{{ url_for('d_d.delete', photo_id=photo.id) }}';">DEL</button>
<button id="nextPhoto" class="navBracket" onclick="location.href='{{ url_for('photo', photo_id=photo.next_photo_id) }}';">&#8250;</button> <button id="nextPhoto" class="navBracket" onclick="location.href='{{ url_for('p_route.photo', photo_id=photo.next_photo_id) }}';">&#8250;</button>
<style> <style>
#main { #main {
max-width: unset; max-width: unset;
@ -36,7 +36,7 @@
<div class="dataContainer"> <div class="dataContainer">
<div class="headingRow"> <div class="headingRow">
<h2 class="photoPageH2">Original as Uploaded</h2> <h2 class="photoPageH2">Original as Uploaded</h2>
<a href="{{ url_for('download', file='raw_' + photo.photo_name)}}" download="{{ 'raw_' + photo.photo_name }}" target="_blank"> <a href="{{ url_for('d_d.download', file='raw_' + photo.photo_name)}}" download="{{ 'raw_' + photo.photo_name }}" target="_blank">
<button class="downloadButton">Download</button> <button class="downloadButton">Download</button>
</a> </a>
</div> </div>
@ -156,7 +156,7 @@
<div class="dataContainer"> <div class="dataContainer">
<div class="headingRow"> <div class="headingRow">
<h2 class="photoPageH2">1280 Max-Conversion</h2> <h2 class="photoPageH2">1280 Max-Conversion</h2>
<a href="{{ url_for('download', file='1280_' + photo.photo_name)}}" download="{{ '1280_' + photo.photo_name }}" target="_blank"> <a href="{{ url_for('d_d.download', file='1280_' + photo.photo_name)}}" download="{{ '1280_' + photo.photo_name }}" target="_blank">
<button class="downloadButton">Download</button> <button class="downloadButton">Download</button>
</a> </a>
</div> </div>
@ -180,7 +180,7 @@
<div class="dataContainer"> <div class="dataContainer">
<div class="headingRow"> <div class="headingRow">
<h2 class="photoPageH2">480 Max-Conversion</h2> <h2 class="photoPageH2">480 Max-Conversion</h2>
<a href="{{ url_for('download', file='480_' + photo.photo_name)}}" download="{{ '480_' + photo.photo_name }}" target="_blank"> <a href="{{ url_for('d_d.download', file='480_' + photo.photo_name)}}" download="{{ '480_' + photo.photo_name }}" target="_blank">
<button class="downloadButton">Download</button> <button class="downloadButton">Download</button>
</a> </a>
</div> </div>
@ -220,12 +220,12 @@ gestureZone.addEventListener('touchend', function(event) {
function handleGesture() { function handleGesture() {
if (touchendX <= touchstartX - 100) { if (touchendX <= touchstartX - 100) {
console.log('Swiped left'); console.log('Swiped left');
location.href='{{ url_for('photo', photo_id=photo.next_photo_id) }}'; location.href='{{ url_for('p_route.photo', photo_id=photo.next_photo_id) }}';
} }
if (touchendX >= touchstartX + 100) { if (touchendX >= touchstartX + 100) {
console.log('Swiped right'); console.log('Swiped right');
location.href='{{ url_for('photo', photo_id=photo.previous_photo_id) }}'; location.href='{{ url_for('p_route.photo', photo_id=photo.previous_photo_id) }}';
} }
} }
activateHotKeys(); activateHotKeys();

View File

@ -1,295 +0,0 @@
#!/usr/bin/env python3
from pyotp import TOTP
from app import app, db
from flask_login import current_user, login_user, logout_user
from flask import render_template, redirect, url_for, session, flash, request, abort, send_file
from app.forms import LoginForm, RegistrationForm, ResetPasswordRequestForm, ConfirmTotp
from app.forms import ResetPasswordForm, EditProfile, ChangePassword, DisableTotp
from app.forms import GetTotp, UploadPhotoForm, ConfirmPhotoDelete
from app.models import Contributor, Photo
from app.email import send_password_reset_email
from app.scripts.set_contributor_id_seq import set_contributor_id_seq
from app.scripts.totp_utils import get_totp_qr, validate_totp, disable_2fa
from app.scripts.process_uploaded_photo import process_uploaded_photo
from app.scripts.get_photo_list import get_photo_list, get_disk_stats, calc_additional_data, find_next_previous
from app.scripts.delete_photo import delete_photo
from werkzeug.utils import secure_filename
@app.route('/download')
def download():
if current_user.is_authenticated:
f = request.args['file']
try:
return send_file('/var/lib/photo_app/photos/{}'.format(f), attachment_filename=f)
except Exception as e:
return str(e)
@app.route('/delete', methods=['GET', 'POST'])
def delete():
photo = Photo.query.get(request.args['photo_id'])
if photo is None:
return(redirect(url_for('index')))
if not current_user.is_authenticated or photo.contributor_id != current_user.id:
return(redirect(url_for('index')))
form = ConfirmPhotoDelete()
if request.method == 'POST' and form.validate_on_submit():
return(redirect(url_for('photo', photo_id=delete_photo(photo, app.config))))
return(render_template(
'delete_photo.html',
title="Delete Photo?",
photo=photo,
photo_url=app.config['PHOTO_URL'],
form=form
))
@app.route('/photo-upload', methods=['GET', 'POST'])
def photo_upload():
if not current_user.is_authenticated:
return(redirect(url_for('index')))
form = UploadPhotoForm()
if request.method == 'POST' and form.validate_on_submit():
f = request.files['image']
filename = secure_filename(f.filename)
if filename != '':
import os
file_ext = os.path.splitext(filename)[1]
if file_ext not in ['.jpg', '.png'] or file_ext != validate_image(f.stream):
abort(400)
f.save(os.path.join(app.config['PHOTO_SAVE_PATH'], 'raw_' + filename))
photo_id = process_uploaded_photo(filename, current_user, app.config)
print(photo_id)
flash("Thanks for the new photo!")
return(redirect(url_for('photo', photo_id=photo_id)))
return(redirect(url_for('index')))
return render_template('upload.html', title="Photo Upload", form=form)
@app.route('/photo/<int:photo_id>')
def photo(photo_id):
photo = Photo.query.get(photo_id)
if not current_user.is_authenticated or photo is None:
return(redirect(url_for('index')))
find_next_previous(photo, app.config)
calc_additional_data(photo)
return render_template(
'photo.html',
title="Photo",
photo=photo,
photo_url=app.config['PHOTO_URL']
)
@app.route("/")
@app.route("/index")
def index():
if current_user.is_authenticated:
photos = get_photo_list(current_user.id, app.config)
flash(get_disk_stats())
return(render_template(
'index.html',
title="Photos",
photos=photos,
photo_url=app.config['PHOTO_URL']
))
return render_template('index.html', title="Photos")
def validate_image(stream):
import imghdr
header = stream.read(512)
stream.seek(0)
format = imghdr.what(None, header)
if not format:
return None
return '.' + (format if format != 'jpeg' else 'jpg')
@app.route("/two-factor-input", methods=["GET", "POST"])
def two_factor_input():
if current_user.is_authenticated or 'id' not in session:
return redirect(url_for('index'))
contributor = Contributor.query.get(session['id'])
if contributor is None:
return redirect(url_for('index'))
form = GetTotp()
if form.validate_on_submit():
if TOTP(contributor.totp_key).verify(int(form.totp_code.data), valid_window=5):
login_user(contributor, remember=session['remember_me'])
flash("Congratulations, you are now logged in!")
return redirect(url_for('index'))
else:
flash("Oops, the pin was wrong")
form.totp_code.data = None
return render_template('two_factor_input.html', form=form, inst="Code was wrong, try again?")
return render_template('two_factor_input.html', form=form, inst="Enter Auth Code")
@app.route("/login", methods=["GET", "POST"])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = LoginForm()
if form.validate_on_submit():
contributor_by_name = Contributor.query.filter_by(name=form.username.data).first()
contributor_by_email = Contributor.query.filter_by(email=form.email.data).first()
if contributor_by_name is not None and contributor_by_name.check_password(form.password.data):
if contributor_by_name.use_totp:
session['id'] = contributor_by_name.id
session['remember_me'] = form.remember_me.data
return redirect(url_for('two_factor_input'))
else:
login_user(contributor_by_name, remember=form.remember_me.data)
flash("Congratulations, you are now logged in!")
return redirect(url_for('index'))
elif contributor_by_email is not None and contributor_by_email.check_password(form.password.data):
if contributor_by_email.use_totp:
session['id'] = contributor_by_email.id
session['remember_me'] = form.remember_me.data
return redirect(url_for('two_factor_input'))
else:
login_user(contributor_by_email, remember=form.remember_me.data)
flash("Congratulations, you are now logged in!")
return redirect(url_for('index'))
else:
flash("Error Invalid Contributor (Username or Email) or Password")
return(redirect(url_for('login')))
return render_template('login.html', title='Sign In', form=form)
@app.route('/disable-totp', methods=['GET', 'POST'])
def disable_totp():
if current_user.is_anonymous or not current_user.use_totp:
return(redirect(url_for('index')))
contributor = Contributor.query.get(current_user.id)
form = DisableTotp()
if form.validate_on_submit():
if disable_2fa(contributor, app.config):
flash('2FA Now Disabled')
return(redirect(url_for('edit_profile')))
else:
flash('2FA Not Disabled')
return(redirect(url_for('edit_profile')))
return render_template('disable_2fa.html', form=form, title="Disable 2FA")
@app.route('/enable-totp', methods=['GET', 'POST'])
def enable_totp():
if current_user.is_anonymous or current_user.use_totp:
return(redirect(url_for('index')))
contributor = Contributor.query.get(current_user.id)
form = ConfirmTotp()
qr = get_totp_qr(contributor, app.config)
if form.validate_on_submit():
if contributor.use_totp:
flash('2FA Already Enabled')
return(redirect(url_for('edit_profile')))
if validate_totp(contributor, form.totp_code.data, app.config):
flash('2FA Now Enabled')
return(redirect(url_for('edit_profile')))
else:
flash("TOTP Code didn't validate, rescan and try again")
return(redirect(url_for('edit_profile')))
return render_template('qr.html', qr=qr, form=form, title="Aunthentication Code")
@app.route("/change-password", methods=["GET", "POST"])
def change_password():
if not current_user.is_authenticated:
return(redirect(url_for('index')))
contributor = Contributor.query.get(current_user.id)
form = ChangePassword()
if form.validate_on_submit():
if contributor.check_password(form.password.data):
contributor.set_password(form.new_password.data)
db.session.commit()
flash("Thanks for the update!")
return(redirect(url_for('index')))
else:
flash("Error Invalid Password")
return(redirect(url_for('change_password')))
return render_template('change_password.html', title='Change Password', form=form)
@app.route("/edit-profile", methods=["GET", "POST"])
def edit_profile():
if current_user.is_anonymous:
return(redirect(url_for('index')))
contributor = Contributor.query.get(current_user.id)
form = EditProfile()
if request.method == 'GET':
form.username.data = contributor.name
form.email.data = contributor.email
if form.validate_on_submit():
if contributor.check_password(form.password.data):
contributor.name = form.username.data
contributor.email = form.email.data
db.session.commit()
flash("Thanks for the update!")
return(redirect(url_for('index')))
else:
flash("Error Invalid Password")
return(redirect(url_for('edit_profile')))
return render_template('edit_profile.html', title='Edit Profile', form=form, contributor_use_totp=contributor.use_totp)
@app.route('/reset-password/<token>', methods=['GET', 'POST'])
def reset_password(token):
if current_user.is_authenticated:
return redirect(url_for('index'))
contributor = Contributor.verify_reset_password_token(token)
if not contributor:
return redirect(url_for('index'))
form = ResetPasswordForm()
if form.validate_on_submit():
contributor.set_password(form.password.data)
db.session.commit()
flash('Your password has been reset.')
return redirect(url_for('login'))
return render_template('reset_password.html', title="New Password?", form=form)
@app.route('/reset-password-request', methods=['GET', 'POST'])
def reset_password_request():
if current_user.is_authenticated:
return(redirect(url_for('index')))
else:
form = ResetPasswordRequestForm()
if form.validate_on_submit():
contributor = Contributor.query.filter_by(email=form.email.data).first()
if contributor:
send_password_reset_email(contributor, app.config['EXTERNAL_URL'])
flash('Check your email for the instructions to reset your password')
return redirect(url_for('login'))
else:
flash('Sorry, invalid email')
return redirect(url_for('login'))
return render_template('reset_password_request.html', title='Reset Password', form=form)
@app.route("/register", methods=["GET", "POST"])
def register():
if current_user.is_authenticated:
return redirect(url_for('index'))
form = RegistrationForm()
if form.validate_on_submit():
set_contributor_id_seq(app.config)
contributor = Contributor(name=form.username.data, num_photos=0, email=form.email.data)
contributor.set_password(form.password.data)
db.session.add(contributor)
db.session.commit()
flash("Congratulations, you are now a registered user!")
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)
@app.route("/logout")
def logout():
is_authenticated = current_user.is_authenticated
logout_user()
if is_authenticated:
flash("Congratulations, you are now logged out!")
return redirect(url_for('index'))

View File

@ -1,31 +0,0 @@
#!/usr/bin/env python3
import psycopg2
import os
def delete_photo(photo, app_config):
conn = psycopg2.connect(
dbname=app_config['DATABASE_NAME'],
user=app_config['DATABASE_USER'],
host=app_config['DATABASE_HOST'],
password=app_config['DATABASE_PASSWORD']
)
cur = conn.cursor()
cur.execute("SELECT count(id) FROM photo WHERE contributor_id=%s AND id>%s", (photo.contributor_id, photo.id))
if cur.fetchone()[0] == 0:
cur.execute("SELECT id FROM photo WHERE contributor_id=%s ORDER BY id", (photo.contributor_id, ))
else:
cur.execute("SELECT id FROM photo WHERE contributor_id=%s AND id>%s ORDER BY id", (photo.contributor_id, photo.id))
next_photo_id = cur.fetchone()[0]
os.chdir(app_config['PHOTO_SAVE_PATH'])
if os.path.exists('raw_' + photo.photo_name):
os.remove('raw_' + photo.photo_name)
if os.path.exists('1280_' + photo.photo_name):
os.remove('1280_' + photo.photo_name)
if os.path.exists('480_' + photo.photo_name):
os.remove('480_' + photo.photo_name)
cur.execute("DELETE FROM photo WHERE id=%s", (photo.id, ))
conn.commit()
conn.close()
return next_photo_id

View File

@ -1,94 +0,0 @@
#!/usr/bin/env python3
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
import os
from datetime import datetime
def get_exif_data(photo):
exif_data = {}
get_file_sizes(photo, exif_data)
return(exif_data)
def get_exif(img_raw, exif_data):
if hasattr(img_raw, '_getexif'):
exifdata = img_raw._getexif()
date_format = "%Y:%m:%d %H:%M:%S"
for k, v in TAGS.items():
if k in exifdata:
if v == "Make":
exif_data['Make'] = exifdata[k]
if v == "Model":
exif_data['Model'] = exifdata[k]
if v == "Software":
exif_data['Software'] = exifdata[k]
if v == "DateTime":
exif_data['DateTime'] = datetime.strptime(exifdata[k], date_format)
if v == "DateTimeOriginal":
exif_data['DateTimeOriginal'] = datetime.strptime(exifdata[k], date_format)
if v == "DateTimeDigitized":
exif_data['DateTimeDigitized'] = datetime.strptime(exifdata[k], date_format)
if v == "FNumber":
exif_data['fnumber'] = round(exifdata[k][0] / exifdata[k][1], 1)
if v == "DigitalZoomRatio":
exif_data['DigitalZoomRatio'] = round(exifdata[k][0] / exifdata[k][1], 2)
if v == "TimeZoneOffset":
exif_data['TimeZoneOffset'] = exifdata[k]
if v == "GPSInfo":
gpsinfo = {}
for h, i in GPSTAGS.items():
if h in exifdata[k]:
if i == 'GPSAltitudeRef':
gpsinfo['GPSAltitudeRef'] = int.from_bytes(exifdata[k][h], "big")
if i == 'GPSAltitude':
gpsinfo['GPSAltitude'] = round(exifdata[k][h][0] / exifdata[k][h][1], 3)
if i == 'GPSLatitudeRef':
gpsinfo['GPSLatitudeRef'] = exifdata[k][h]
if i == 'GPSLatitude':
gpsinfo['GPSLatitude'] = calc_coordinate(exifdata[k][h])
if i == 'GPSLongitudeRef':
gpsinfo['GPSLongitudeRef'] = exifdata[k][h]
if i == 'GPSLongitude':
gpsinfo['GPSLongitude'] = calc_coordinate(exifdata[k][h])
update_gpsinfo(gpsinfo, exif_data)
def update_gpsinfo(gpsinfo, exif_data):
if 'GPSAltitudeRef' in gpsinfo and 'GPSLatitude' in gpsinfo:
exif_data['GPSAltitude'] = gpsinfo['GPSAltitude']
exif_data['GPSAboveSeaLevel'] = False if gpsinfo['GPSAltitudeRef'] != 0 else True
if 'GPSLatitudeRef' in gpsinfo and 'GPSLatitude' in gpsinfo:
exif_data['GPSLatitude'] = gpsinfo['GPSLatitude'] if gpsinfo['GPSLatitudeRef'] != 'S' else 0 - gpsinfo['GPSLatitude']
if 'GPSLongitudeRef' in gpsinfo and 'GPSLongitude' in gpsinfo:
exif_data['GPSLongitude'] = gpsinfo['GPSLongitude'] if gpsinfo['GPSLongitudeRef'] != 'W' else 0 - gpsinfo['GPSLongitude']
def calc_coordinate(x):
degrees = x[0][0] / x[0][1]
minutes = x[1][0] / x[1][1]
seconds = x[2][0] / x[2][1]
return round(degrees + minutes / 60 + seconds / 3600, 5)
def get_dimensions_and_format(photo, exif_data):
img_raw = Image.open('raw_' + photo)
img_1280 = Image.open('1280_' + photo)
img_480 = Image.open('480_' + photo)
exif_data['AspectRatio'] = round(img_raw.width / img_raw.height, 5)
exif_data['photo_format'] = img_raw.format
exif_data['photo_width'] = img_raw.width
exif_data['photo_height'] = img_raw.height
exif_data['photo_1280_width'] = img_1280.width
exif_data['photo_1280_height'] = img_1280.height
exif_data['photo_480_width'] = img_480.width
exif_data['photo_480_height'] = img_480.height
get_exif(img_raw, exif_data)
def get_file_sizes(photo, exif_data):
exif_data['photo_raw_size'] = os.path.getsize('raw_' + photo)
exif_data['photo_1280_size'] = os.path.getsize('1280_' + photo)
exif_data['photo_480_size'] = os.path.getsize('480_' + photo)
get_dimensions_and_format(photo, exif_data)

View File

@ -1,17 +0,0 @@
#!/usr/bin/env python3
import psycopg2
def set_contributor_id_seq(app_config):
conn = psycopg2.connect(
dbname=app_config['DATABASE_NAME'],
user=app_config['DATABASE_USER'],
host=app_config['DATABASE_HOST'],
password=app_config['DATABASE_PASSWORD']
)
cur = conn.cursor()
cur.execute("SELECT setval('contributor_id_seq', (SELECT MAX(id) FROM contributor))")
conn.commit()
conn.close()

View File

@ -1,59 +0,0 @@
#!/usr/bin/env python3
import psycopg2
import pyotp
import qrcode
import qrcode.image.svg
from io import BytesIO
def get_totp_qr(contributor, app_config):
totp_key = pyotp.random_base32() if contributor.totp_key is None else contributor.totp_key
if contributor.totp_key is None:
conn = psycopg2.connect(
dbname=app_config['DATABASE_NAME'],
user=app_config['DATABASE_USER'],
host=app_config['DATABASE_HOST'],
password=app_config['DATABASE_PASSWORD']
)
cur = conn.cursor()
cur.execute("UPDATE contributor SET totp_key=%s WHERE id=%s", (totp_key, contributor.id))
conn.commit()
conn.close()
totp_uri = pyotp.totp.TOTP(totp_key).provisioning_uri(name=contributor.email, issuer_name='Photo App')
img = qrcode.make(totp_uri, image_factory=qrcode.image.svg.SvgPathImage)
f = BytesIO()
img.save(f)
return(f.getvalue().decode('utf-8'))
def validate_totp(contributor, totp_code, app_config):
if pyotp.TOTP(contributor.totp_key).verify(int(totp_code)):
conn = psycopg2.connect(
dbname=app_config['DATABASE_NAME'],
user=app_config['DATABASE_USER'],
host=app_config['DATABASE_HOST'],
password=app_config['DATABASE_PASSWORD']
)
cur = conn.cursor()
cur.execute("UPDATE contributor SET use_totp='1' WHERE id=%s", (contributor.id, ))
conn.commit()
conn.close()
return True
else:
return False
def disable_2fa(contributor, app_config):
conn = psycopg2.connect(
dbname=app_config['DATABASE_NAME'],
user=app_config['DATABASE_USER'],
host=app_config['DATABASE_HOST'],
password=app_config['DATABASE_PASSWORD']
)
cur = conn.cursor()
cur.execute("UPDATE contributor SET use_totp='0', totp_key=Null WHERE id=%s", (contributor.id, ))
conn.commit()
conn.close()
return True

View File

@ -32,17 +32,17 @@
<div id="navbarContainer"> <div id="navbarContainer">
<div id="navbarLeftContainer"> <div id="navbarLeftContainer">
<nav id="navbar"> <nav id="navbar">
<a href="{{ url_for('index') }}"><div class="navbarLink">home</div></a> <a href="{{ url_for('proute.index') }}"><div class="navbarLink">home</div></a>
{% if current_user.is_authenticated %} {% if current_user.is_authenticated %}
<div class="navbarSpacer"></div> <div class="navbarSpacer"></div>
<a href="{{ url_for('logout') }}"><div class="navbarLink">logout</div></a> <a href="{{ url_for('auths.logout') }}"><div class="navbarLink">logout</div></a>
<div class="navbarSpacer"></div> <div class="navbarSpacer"></div>
<a href="{{ url_for('edit_profile') }}"><div class="navbarLink">edit profile</div></a> <a href="{{ url_for('prof.edit_profile') }}"><div class="navbarLink">edit profile</div></a>
<div class="navbarSpacer"></div> <div class="navbarSpacer"></div>
<a href="{{ url_for('photo_upload') }}"><div class="navbarLink">photo upload</div></a> <a href="{{ url_for('pupload.photo_upload') }}"><div class="navbarLink">photo upload</div></a>
{% else %} {% else %}
<div class="navbarSpacer"></div> <div class="navbarSpacer"></div>
<a href="{{ url_for('login') }}"><div class="navbarLink">contributor login</div></a> <a href="{{ url_for('auths.login') }}"><div class="navbarLink">contributor login</div></a>
{% endif %} {% endif %}
</nav> </nav>
</div> </div>

View File

@ -36,7 +36,7 @@
<div class="indexPagePhotos"> <div class="indexPagePhotos">
{% for photo in photos %} {% for photo in photos %}
<div class="photoContainer"> <div class="photoContainer">
<a href={{ url_for('photo', photo_id=photo['id']) }}> <a href={{ url_for('p_route.photo', photo_id=photo['id']) }}>
<img src={{ photo_url + '480_' + photo['photo_name'] }} alt={{ '480_' + photo['photo_name'] }}> <img src={{ photo_url + '480_' + photo['photo_name'] }} alt={{ '480_' + photo['photo_name'] }}>
</a> </a>
</div> </div>

View File

@ -1,51 +1,72 @@
#!/bin/bash #!/bin/bash
# /usr/local/sbin/deploy_photo_app.bash # deploy_photo_app.bash
SOURCE="/home/<user>/flaskapps/photo_app" SOURCE="/home/trent/flaskapps/photo_app"
DESTINATION="/var/lib/<app_user>" DESTINATION="/var/lib/photo_app"
[ ! -d "/var/lib/photo_app" ] && mkdir /var/lib/photo_app
cp -v "$SOURCE"/config.py "$DESTINATION"/ cp -v "$SOURCE"/config.py "$DESTINATION"/
cp -v "$SOURCE"/photo_app.py "$DESTINATION"/ cp -v "$SOURCE"/photo_app.py "$DESTINATION"/
[ ! -d "/var/lib/photo_app/app" ] && mkdir /var/lib/photo_app/app
cp -v "$SOURCE"/app/__init__.py "$DESTINATION"/app/ cp -v "$SOURCE"/app/__init__.py "$DESTINATION"/app/
cp -v "$SOURCE"/app/routes.py "$DESTINATION"/app/
cp -v "$SOURCE"/app/sendxmpp_handler.py "$DESTINATION"/app/ cp -v "$SOURCE"/app/sendxmpp_handler.py "$DESTINATION"/app/
cp -v "$SOURCE"/app/models.py "$DESTINATION"/app/ cp -v "$SOURCE"/app/models.py "$DESTINATION"/app/
cp -v "$SOURCE"/app/forms.py "$DESTINATION"/app/ cp -v "$SOURCE"/app/forms.py "$DESTINATION"/app/
cp -v "$SOURCE"/app/email.py "$DESTINATION"/app/
[ ! -d "/var/lib/photo_app/app/templates" ] && mkdir /var/lib/photo_app/app/templates
cp -v "$SOURCE"/app/templates/base.html "$DESTINATION"/app/templates/ cp -v "$SOURCE"/app/templates/base.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/index.html "$DESTINATION"/app/templates/ cp -v "$SOURCE"/app/templates/index.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/login.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/register.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/reset_password.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/reset_password_request.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/edit_profile.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/change_password.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/qr.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/disable_2fa.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/two_factor_input.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/upload.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/photo.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/delete_photo.html "$DESTINATION"/app/templates/
cp -v "$SOURCE"/app/templates/email/reset_password_email_html.html "$DESTINATION"/app/templates/email/ [ ! -d "/var/lib/photo_app/app/auth" ] && mkdir /var/lib/photo_app/app/auth
cp -v "$SOURCE"/app/templates/email/reset_password_email_text.txt "$DESTINATION"/app/templates/email/ cp -v "$SOURCE"/app/auth/auth.py "$DESTINATION"/app/auth/
cp -v "$SOURCE"/app/auth/totp.py "$DESTINATION"/app/auth/
cp -v "$SOURCE"/app/auth/dis_totp.py "$DESTINATION"/app/auth/
cp -v "$SOURCE"/app/auth/profile.py "$DESTINATION"/app/auth/
cp -v "$SOURCE"/app/auth/register.py "$DESTINATION"/app/auth/
cp -v "$SOURCE"/app/auth/reset_password.py "$DESTINATION"/app/auth/
cp -v "$SOURCE"/app/auth/email.py "$DESTINATION"/app/auth/
cp -v "$SOURCE"/app/scripts/set_contributor_id_seq.py "$DESTINATION"/app/scripts/ [ ! -d "/var/lib/photo_app/app/auth/templates" ] && mkdir /var/lib/photo_app/app/auth/templates
cp -v "$SOURCE"/app/scripts/totp_utils.py "$DESTINATION"/app/scripts/ cp -v "$SOURCE"/app/auth/templates/two_factor_input.html "$DESTINATION"/app/auth/templates/
cp -v "$SOURCE"/app/scripts/process_uploaded_photo.py "$DESTINATION"/app/scripts/ cp -v "$SOURCE"/app/auth/templates/login.html "$DESTINATION"/app/auth/templates/
cp -v "$SOURCE"/app/scripts/crop_photo.py "$DESTINATION"/app/scripts/ cp -v "$SOURCE"/app/auth/templates/change_password.html "$DESTINATION"/app/auth/templates/
cp -v "$SOURCE"/app/scripts/get_exif_data.py "$DESTINATION"/app/scripts/ cp -v "$SOURCE"/app/auth/templates/disable_2fa.html "$DESTINATION"/app/auth/templates/
cp -v "$SOURCE"/app/scripts/get_photo_list.py "$DESTINATION"/app/scripts/ cp -v "$SOURCE"/app/auth/templates/edit_profile.html "$DESTINATION"/app/auth/templates/
cp -v "$SOURCE"/app/scripts/delete_photo.py "$DESTINATION"/app/scripts/ cp -v "$SOURCE"/app/auth/templates/qr.html "$DESTINATION"/app/auth/templates/
cp -v "$SOURCE"/app/auth/templates/register.html "$DESTINATION"/app/auth/templates/
cp -v "$SOURCE"/app/auth/templates/reset_password.html "$DESTINATION"/app/auth/templates/
cp -v "$SOURCE"/app/auth/templates/reset_password_request.html "$DESTINATION"/app/auth/templates/
[ ! -d "/var/lib/photo_app/app/auth/templates/email" ] && mkdir /var/lib/photo_app/app/auth/templates/email
cp -v "$SOURCE"/app/auth/templates/email/reset_password_email_html.html "$DESTINATION"/app/auth/templates/email/
cp -v "$SOURCE"/app/auth/templates/email/reset_password_email_text.txt "$DESTINATION"/app/auth/templates/email/
[ ! -d "/var/lib/photo_app/app/photo_routes" ] && mkdir /var/lib/photo_app/app/photo_routes
cp -v "$SOURCE"/app/photo_routes/proutes.py "$DESTINATION"/app/photo_routes/
cp -v "$SOURCE"/app/photo_routes/photox.py "$DESTINATION"/app/photo_routes/
cp -v "$SOURCE"/app/photo_routes/delete_download.py "$DESTINATION"/app/photo_routes/
cp -v "$SOURCE"/app/photo_routes/photo_upload.py "$DESTINATION"/app/photo_routes/
[ ! -d "/var/lib/photo_app/app/photo_routes/scripts" ] && mkdir /var/lib/photo_app/app/photo_routes/scripts
cp -v "$SOURCE"/app/photo_routes/scripts/process_uploaded_photo.py "$DESTINATION"/app/photo_routes/scripts/
cp -v "$SOURCE"/app/photo_routes/scripts/crop_photo.py "$DESTINATION"/app/photo_routes/scripts/
cp -v "$SOURCE"/app/photo_routes/scripts/get_exif_data.py "$DESTINATION"/app/photo_routes/scripts/
[ ! -d "/var/lib/photo_app/app/photo_routes/templates" ] && mkdir /var/lib/photo_app/app/photo_routes/templates
cp -v "$SOURCE"/app/photo_routes/templates/upload.html "$DESTINATION"/app/photo_routes/templates/
cp -v "$SOURCE"/app/photo_routes/templates/photo.html "$DESTINATION"/app/photo_routes/templates/
cp -v "$SOURCE"/app/photo_routes/templates/delete_photo.html "$DESTINATION"/app/photo_routes/templates/
[ ! -d "/var/lib/photo_app/css" ] && mkdir /var/lib/photo_app/css
cp -v "$SOURCE"/css/photo_app.css "$DESTINATION"/css/ cp -v "$SOURCE"/css/photo_app.css "$DESTINATION"/css/
[ ! -d "/var/lib/photo_app/js" ] && mkdir /var/lib/photo_app/js
cp -v "$SOURCE"/js/photo_app.js "$DESTINATION"/js/ cp -v "$SOURCE"/js/photo_app.js "$DESTINATION"/js/
chown -R photo_app:photo_app "$DESTINATION" chown -R photo_app:photo_app "$DESTINATION"
chown root:root /etc/systemd/system/photo_app.service
chmod 600 "$DESTINATION"/.env chmod 600 "$DESTINATION"/.env

2
examples/foo Normal file
View File

@ -0,0 +1,2 @@
chown root:root /usr/local/sbin/deploy_photo_app.bash

View File

@ -1,3 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from app import app from app import init_app
app = init_app()