mirror of
https://github.com/Derpy-Leggies/OnlyLegs.git
synced 2025-06-29 11:36:16 +00:00
Switch to SQLAlchemy for database management
Add Favicon
This commit is contained in:
parent
9e87c74c96
commit
2e86bfa072
11 changed files with 341 additions and 192 deletions
|
@ -8,14 +8,12 @@ print("""
|
|||
Created by Fluffy Bean - Version 23.03.02
|
||||
""")
|
||||
|
||||
|
||||
from flask import Flask, render_template
|
||||
from flask_compress import Compress
|
||||
|
||||
from dotenv import load_dotenv
|
||||
import platformdirs
|
||||
|
||||
# Load logger
|
||||
from gallery.logger import logger
|
||||
logger.innit_logger()
|
||||
|
||||
|
@ -25,7 +23,7 @@ import os
|
|||
|
||||
# Check if any of the required files are missing
|
||||
if not os.path.exists(platformdirs.user_config_dir('onlylegs')):
|
||||
from setup import setup
|
||||
from .setup import setup
|
||||
setup()
|
||||
|
||||
|
||||
|
@ -78,14 +76,12 @@ def create_app(test_config=None):
|
|||
except OSError:
|
||||
pass
|
||||
|
||||
# Load database
|
||||
from . import db
|
||||
db.init_app(app)
|
||||
|
||||
# Load theme
|
||||
from . import sassy
|
||||
sassy.compile('default', app.root_path)
|
||||
|
||||
|
||||
@app.errorhandler(405)
|
||||
def method_not_allowed(e):
|
||||
error = '405'
|
||||
|
|
|
@ -2,7 +2,11 @@ from flask import Blueprint, current_app, send_from_directory, send_file, reques
|
|||
from werkzeug.utils import secure_filename
|
||||
|
||||
from gallery.auth import login_required
|
||||
from gallery.db import get_db
|
||||
|
||||
from . import db
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
db_session = sessionmaker(bind=db.engine)
|
||||
db_session = db_session()
|
||||
|
||||
from PIL import Image, ImageOps, ImageFilter
|
||||
from . import metadata as mt
|
||||
|
@ -104,11 +108,9 @@ def upload():
|
|||
|
||||
# Save to database
|
||||
try:
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'INSERT INTO posts (file_name, author_id, description, alt)'
|
||||
' VALUES (?, ?, ?, ?)',
|
||||
(img_name, g.user['id'], form['description'], form['alt']))
|
||||
tr = db.posts(img_name, form['description'], form['alt'], g.user.id)
|
||||
db_session.add(tr)
|
||||
db_session.commit()
|
||||
except Exception as e:
|
||||
logger.server(600, f"Error saving to database: {e}")
|
||||
abort(500)
|
||||
|
@ -117,7 +119,6 @@ def upload():
|
|||
try:
|
||||
form_file.save(
|
||||
os.path.join(current_app.config['UPLOAD_FOLDER'], img_name))
|
||||
db.commit()
|
||||
except Exception as e:
|
||||
logger.server(600, f"Error saving file: {e}")
|
||||
abort(500)
|
||||
|
@ -128,28 +129,25 @@ def upload():
|
|||
@blueprint.route('/remove/<int:id>', methods=['POST'])
|
||||
@login_required
|
||||
def remove(id):
|
||||
img = get_db().execute(
|
||||
'SELECT author_id, file_name FROM posts WHERE id = ?',
|
||||
(id, )).fetchone()
|
||||
img = db_session.query(db.posts).filter_by(id=id).first()
|
||||
|
||||
if img is None:
|
||||
abort(404)
|
||||
if img['author_id'] != g.user['id']:
|
||||
if img.author_id != g.user.id:
|
||||
abort(403)
|
||||
|
||||
try:
|
||||
os.remove(
|
||||
os.path.join(current_app.config['UPLOAD_FOLDER'],
|
||||
img['file_name']))
|
||||
img.file_name))
|
||||
except Exception as e:
|
||||
logger.server(600, f"Error removing file: {e}")
|
||||
abort(500)
|
||||
|
||||
try:
|
||||
db = get_db()
|
||||
db.execute('DELETE FROM posts WHERE id = ?', (id, ))
|
||||
db.commit()
|
||||
except:
|
||||
db_session.query(db.posts).filter_by(id=id).delete()
|
||||
db_session.commit()
|
||||
except Exception as e:
|
||||
logger.server(600, f"Error removing from database: {e}")
|
||||
abort(500)
|
||||
|
||||
|
@ -160,15 +158,13 @@ def remove(id):
|
|||
|
||||
@blueprint.route('/metadata/<int:id>', methods=['GET'])
|
||||
def metadata(id):
|
||||
img = get_db().execute(
|
||||
'SELECT file_name, description, alt FROM posts WHERE id = ?',
|
||||
(id, )).fetchone()
|
||||
img = db_session.query(db.posts).filter_by(id=id).first()
|
||||
|
||||
if img is None:
|
||||
abort(404)
|
||||
|
||||
exif = mt.metadata.yoink(
|
||||
os.path.join(current_app.config['UPLOAD_FOLDER'], img['file_name']))
|
||||
os.path.join(current_app.config['UPLOAD_FOLDER'], img.file_name))
|
||||
|
||||
return jsonify(exif)
|
||||
|
||||
|
|
|
@ -2,7 +2,10 @@ import functools
|
|||
from flask import Blueprint, flash, g, redirect, request, session, url_for, abort, jsonify, current_app
|
||||
from werkzeug.security import check_password_hash, generate_password_hash
|
||||
|
||||
from gallery.db import get_db
|
||||
from gallery import db
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
db_session = sessionmaker(bind=db.engine)
|
||||
db_session = db_session()
|
||||
|
||||
from .logger import logger
|
||||
|
||||
|
@ -12,45 +15,26 @@ import uuid
|
|||
blueprint = Blueprint('auth', __name__, url_prefix='/auth')
|
||||
|
||||
|
||||
# def add_log(code, note=None):
|
||||
# code = int(code)
|
||||
# note = str(note)
|
||||
|
||||
# user_id = session.get('user_id')
|
||||
# user_ip = request.remote_addr
|
||||
# db = get_db()
|
||||
|
||||
# db.execute(
|
||||
# 'INSERT INTO logs (ip, user_id, code, note)'
|
||||
# ' VALUES (?, ?, ?, ?)',
|
||||
# (user_ip, user_id, code, note)
|
||||
# )
|
||||
# db.commit()
|
||||
|
||||
|
||||
@blueprint.before_app_request
|
||||
def load_logged_in_user():
|
||||
user_id = session.get('user_id')
|
||||
user_uuid = session.get('uuid')
|
||||
|
||||
if user_id is None or user_uuid is None:
|
||||
# This is not needed as the user is not logged in anyway, also spams the logs
|
||||
# This is not needed as the user is not logged in anyway, also spams the server logs with useless data
|
||||
#add_log(103, 'Auth error before app request')
|
||||
g.user = None
|
||||
session.clear()
|
||||
else:
|
||||
db = get_db()
|
||||
is_alive = db.execute('SELECT * FROM devices WHERE session_uuid = ?',
|
||||
(session.get('uuid'), )).fetchone()
|
||||
is_alive = db_session.query(db.sessions).filter_by(session_uuid=user_uuid).first()
|
||||
|
||||
if is_alive is None:
|
||||
logger.add(103, 'Session expired')
|
||||
flash(['Session expired!', '3'])
|
||||
session.clear()
|
||||
else:
|
||||
g.user = db.execute('SELECT * FROM users WHERE id = ?',
|
||||
(user_id, )).fetchone()
|
||||
|
||||
g.user = db_session.query(db.users).filter_by(id=user_id).first()
|
||||
|
||||
|
||||
@blueprint.route('/register', methods=['POST'])
|
||||
def register():
|
||||
|
@ -58,7 +42,6 @@ def register():
|
|||
email = request.form['email']
|
||||
password = request.form['password']
|
||||
password_repeat = request.form['password-repeat']
|
||||
db = get_db()
|
||||
error = []
|
||||
|
||||
if not username:
|
||||
|
@ -82,12 +65,10 @@ def register():
|
|||
|
||||
if not error:
|
||||
try:
|
||||
db.execute(
|
||||
'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
|
||||
(username, email, generate_password_hash(password)),
|
||||
)
|
||||
db.commit()
|
||||
except db.IntegrityError:
|
||||
tr = db.users(username, email, generate_password_hash(password))
|
||||
db_session.add(tr)
|
||||
db_session.commit()
|
||||
except Exception as e:
|
||||
error.append(f"User {username} is already registered!")
|
||||
else:
|
||||
logger.add(103, f"User {username} registered")
|
||||
|
@ -100,27 +81,24 @@ def register():
|
|||
def login():
|
||||
username = request.form['username']
|
||||
password = request.form['password']
|
||||
db = get_db()
|
||||
error = None
|
||||
user = db.execute('SELECT * FROM users WHERE username = ?',
|
||||
(username, )).fetchone()
|
||||
user = db_session.query(db.users).filter_by(username=username).first()
|
||||
|
||||
if user is None:
|
||||
logger.add(101, f"User {username} does not exist from {request.remote_addr}")
|
||||
abort(403)
|
||||
elif not check_password_hash(user['password'], password):
|
||||
elif not check_password_hash(user.password, password):
|
||||
logger.add(102, f"User {username} password error from {request.remote_addr}")
|
||||
abort(403)
|
||||
|
||||
try:
|
||||
session.clear()
|
||||
session['user_id'] = user['id']
|
||||
session['user_id'] = user.id
|
||||
session['uuid'] = str(uuid.uuid4())
|
||||
|
||||
db.execute(
|
||||
'INSERT INTO devices (user_id, session_uuid, ip) VALUES (?, ?, ?)',
|
||||
(user['id'], session.get('uuid'), request.remote_addr))
|
||||
db.commit()
|
||||
|
||||
tr = db.sessions(user.id, session.get('uuid'), request.remote_addr, request.user_agent.string, 1)
|
||||
db_session.add(tr)
|
||||
db_session.commit()
|
||||
except error as err:
|
||||
logger.add(105, f"User {username} auth error: {err}")
|
||||
abort(500)
|
||||
|
@ -135,7 +113,7 @@ def login():
|
|||
|
||||
@blueprint.route('/logout')
|
||||
def logout():
|
||||
logger.add(103, f"User {g.user['username']} - id: {g.user['id']} logged out")
|
||||
logger.add(103, f"User {g.user.username} - id: {g.user.id} logged out")
|
||||
session.clear()
|
||||
return redirect(url_for('index'))
|
||||
|
||||
|
|
157
gallery/db.py
157
gallery/db.py
|
@ -1,38 +1,133 @@
|
|||
import sqlite3
|
||||
import click
|
||||
from flask import current_app, g
|
||||
import os
|
||||
import platformdirs
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import create_engine, Column, Integer, String, Boolean, DateTime, ForeignKey
|
||||
from sqlalchemy.orm import declarative_base, relationship
|
||||
|
||||
|
||||
@click.command('init-db')
|
||||
def init_db_command():
|
||||
"""Create tables if not already created"""
|
||||
init_db()
|
||||
click.echo('Initialized the database!')
|
||||
path_to_db = os.path.join(platformdirs.user_config_dir('onlylegs'), 'gallery.sqlite')
|
||||
engine = create_engine(f'sqlite:///{path_to_db}', echo=False)
|
||||
base = declarative_base()
|
||||
|
||||
|
||||
def get_db():
|
||||
if 'db' not in g:
|
||||
g.db = sqlite3.connect(current_app.config['DATABASE'],
|
||||
detect_types=sqlite3.PARSE_DECLTYPES)
|
||||
g.db.row_factory = sqlite3.Row
|
||||
class users (base):
|
||||
__tablename__ = 'users'
|
||||
|
||||
return g.db
|
||||
id = Column(Integer, primary_key=True)
|
||||
username = Column(String, unique=True, nullable=False)
|
||||
email = Column(String, unique=True, nullable=False)
|
||||
password = Column(String, nullable=False)
|
||||
created_at = Column(DateTime, nullable=False)
|
||||
|
||||
posts = relationship('posts')
|
||||
groups = relationship('groups')
|
||||
session = relationship('sessions')
|
||||
log = relationship('logs')
|
||||
|
||||
def __init__(self, username, email, password):
|
||||
self.username = username
|
||||
self.email = email
|
||||
self.password = password
|
||||
self.created_at = datetime.now()
|
||||
|
||||
class posts (base):
|
||||
__tablename__ = 'posts'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
file_name = Column(String, unique=True, nullable=False)
|
||||
description = Column(String, nullable=False)
|
||||
alt = Column(String, nullable=False)
|
||||
author_id = Column(Integer, ForeignKey('users.id'))
|
||||
created_at = Column(DateTime, nullable=False)
|
||||
|
||||
junction = relationship('group_junction')
|
||||
|
||||
def __init__(self, file_name, description, alt, author_id):
|
||||
self.file_name = file_name
|
||||
self.description = description
|
||||
self.alt = alt
|
||||
self.author_id = author_id
|
||||
self.created_at = datetime.now()
|
||||
|
||||
class groups (base):
|
||||
__tablename__ = 'groups'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String, nullable=False)
|
||||
description = Column(String, nullable=False)
|
||||
author_id = Column(Integer, ForeignKey('users.id'))
|
||||
created_at = Column(DateTime, nullable=False)
|
||||
|
||||
junction = relationship('group_junction')
|
||||
|
||||
def __init__(self, name, description, author_id):
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.author_id = author_id
|
||||
self.created_at = datetime.now()
|
||||
|
||||
class group_junction (base):
|
||||
__tablename__ = 'group_junction'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
group_id = Column(Integer, ForeignKey('groups.id'))
|
||||
post_id = Column(Integer, ForeignKey('posts.id'))
|
||||
|
||||
def __init__(self, group_id, post_id):
|
||||
self.group_id = group_id
|
||||
self.post_id = post_id
|
||||
|
||||
class sessions (base):
|
||||
__tablename__ = 'sessions'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'))
|
||||
session_uuid = Column(String, nullable=False)
|
||||
ip = Column(String, nullable=False)
|
||||
user_agent = Column(String, nullable=False)
|
||||
active = Column(Boolean, nullable=False)
|
||||
created_at = Column(DateTime, nullable=False)
|
||||
|
||||
def __init__(self, user_id, session_uuid, ip, user_agent, active):
|
||||
self.user_id = user_id
|
||||
self.session_uuid = session_uuid
|
||||
self.ip = ip
|
||||
self.user_agent = user_agent
|
||||
self.active = active
|
||||
self.created_at = datetime.now()
|
||||
|
||||
class logs (base):
|
||||
__tablename__ = 'logs'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'))
|
||||
ip = Column(String, nullable=False)
|
||||
code = Column(Integer, nullable=False)
|
||||
msg = Column(String, nullable=False)
|
||||
created_at = Column(DateTime, nullable=False)
|
||||
|
||||
def __init__(self, user_id, ip, code, msg):
|
||||
self.user_id = user_id
|
||||
self.ip = ip
|
||||
self.code = code
|
||||
self.msg = msg
|
||||
self.created_at = datetime.now()
|
||||
|
||||
class bans (base):
|
||||
__tablename__ = 'bans'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
ip = Column(String, nullable=False)
|
||||
code = Column(Integer, nullable=False)
|
||||
msg = Column(String, nullable=False)
|
||||
created_at = Column(DateTime, nullable=False)
|
||||
|
||||
def __init__(self, ip, code, msg):
|
||||
self.ip = ip
|
||||
self.code = code
|
||||
self.msg = msg
|
||||
self.created_at = datetime.now()
|
||||
|
||||
|
||||
def close_db(e=None):
|
||||
db = g.pop('db', None)
|
||||
|
||||
if db is not None:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
db = get_db()
|
||||
|
||||
with current_app.open_resource('schema.sql') as f:
|
||||
db.executescript(f.read().decode('utf8'))
|
||||
|
||||
|
||||
def init_app(app):
|
||||
app.teardown_appcontext(close_db)
|
||||
app.cli.add_command(init_db_command)
|
||||
base.metadata.create_all(engine)
|
|
@ -3,23 +3,22 @@ from werkzeug.exceptions import abort
|
|||
from werkzeug.utils import secure_filename
|
||||
|
||||
from gallery.auth import login_required
|
||||
from gallery.db import get_db
|
||||
|
||||
from . import db
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
db_session = sessionmaker(bind=db.engine)
|
||||
db_session = db_session()
|
||||
|
||||
from . import metadata as mt
|
||||
from PIL import Image
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
dt = datetime.now()
|
||||
blueprint = Blueprint('gallery', __name__)
|
||||
|
||||
|
||||
@blueprint.route('/')
|
||||
def index():
|
||||
db = get_db()
|
||||
images = db.execute('SELECT * FROM posts'
|
||||
' ORDER BY created_at DESC').fetchall()
|
||||
images = db_session.query(db.posts).order_by(db.posts.id.desc()).all()
|
||||
|
||||
return render_template('index.html',
|
||||
images=images,
|
||||
|
@ -30,17 +29,15 @@ def index():
|
|||
|
||||
@blueprint.route('/image/<int:id>')
|
||||
def image(id):
|
||||
# Get image from database
|
||||
db = get_db()
|
||||
image = db.execute('SELECT * FROM posts WHERE id = ?', (id, )).fetchone()
|
||||
img = db_session.query(db.posts).filter_by(id=id).first()
|
||||
|
||||
if image is None:
|
||||
if img is None:
|
||||
abort(404)
|
||||
|
||||
exif = mt.metadata.yoink(
|
||||
os.path.join(current_app.config['UPLOAD_FOLDER'], image['file_name']))
|
||||
os.path.join(current_app.config['UPLOAD_FOLDER'], img.file_name))
|
||||
|
||||
return render_template('image.html', image=image, exif=exif)
|
||||
return render_template('image.html', image=img, exif=exif)
|
||||
|
||||
|
||||
@blueprint.route('/group')
|
||||
|
|
|
@ -1,78 +0,0 @@
|
|||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
profile_picture TEXT NOT NULL DEFAULT 'default.png',
|
||||
email TEXT NOT NULL,
|
||||
password TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS posts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
file_name TEXT NOT NULL UNIQUE,
|
||||
author_id INTEGER NOT NULL,
|
||||
description TEXT NOT NULL,
|
||||
alt TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (author_id) REFERENCES users (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS groups (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
author_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (author_id) REFERENCES users (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS group_junction (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
group_id INTEGER NOT NULL,
|
||||
image_id INTEGER NOT NULL,
|
||||
FOREIGN KEY (group_id) REFERENCES groups (id),
|
||||
FOREIGN KEY (image_id) REFERENCES posts (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS permissions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
admin BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
create_posts BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS devices (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
session_uuid TEXT NOT NULL,
|
||||
ip TEXT NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
token TEXT NOT NULL UNIQUE,
|
||||
is_used BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
used_by INTEGER DEFAULT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (used_by) REFERENCES users (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ip TEXT NOT NULL,
|
||||
user_id INTEGER DEFAULT NULL,
|
||||
code INTEGER NOT NULL,
|
||||
note TEXT DEFAULT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bans (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ip TEXT NOT NULL,
|
||||
code INTEGER NOT NULL,
|
||||
note TEXT DEFAULT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
|
@ -2,7 +2,6 @@ from flask import Blueprint, render_template, url_for
|
|||
from werkzeug.exceptions import abort
|
||||
|
||||
from gallery.auth import login_required
|
||||
from gallery.db import get_db
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
|
|
BIN
gallery/static/images/icon.png
Normal file
BIN
gallery/static/images/icon.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 29 KiB |
|
@ -4,6 +4,7 @@
|
|||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Gallery</title>
|
||||
<link rel="icon" href="{{url_for('static', filename='images/icon.png')}}">
|
||||
<link rel="stylesheet" href="{{url_for('static', filename='theme/style.css')}}" defer>
|
||||
<script src="{{url_for('static', filename='js/jquery-3.6.3.min.js')}}"></script>
|
||||
</head>
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue