HabitTracker/app.py

259 lines
6.0 KiB
Python
Raw Normal View History

2024-01-12 10:57:58 +01:00
import datetime
2024-01-12 16:53:03 +01:00
import hashlib
2024-01-12 10:57:58 +01:00
from flask import Flask, render_template, redirect, url_for, request
2024-01-12 16:53:03 +01:00
from flask_login import login_required, LoginManager, login_user, logout_user, current_user
2024-01-12 10:57:58 +01:00
from models.Habit import Habit
2024-01-26 09:06:31 +01:00
from models.HabitTrackings import HabitTrackings
2024-01-12 10:57:58 +01:00
from models.User import User
2024-01-12 16:53:03 +01:00
from utils import anonymous_required
2024-01-12 10:57:58 +01:00
# Create a new Flask instance
app = Flask(__name__)
2024-01-12 16:53:03 +01:00
app.secret_key = 'PSSSSSHHHT!'
# Initialize the Flask-Login extension
login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id)
@app.context_processor
def inject_user():
return dict(user=current_user)
2024-01-12 10:57:58 +01:00
@app.route('/login')
2024-01-12 16:53:03 +01:00
@anonymous_required
2024-01-12 10:57:58 +01:00
def login():
2024-01-12 16:53:03 +01:00
return render_template('auth/login.html', errors={})
2024-01-12 10:57:58 +01:00
@app.route('/signup')
2024-01-12 16:53:03 +01:00
@anonymous_required
2024-01-12 10:57:58 +01:00
def signup():
return render_template('auth/signup.html', errors={})
2024-01-12 16:53:03 +01:00
@app.route('/login', methods=['POST'])
def login_post():
2024-01-12 10:57:58 +01:00
email = request.form.get('email')
password = request.form.get('password')
# Check for errors
errors = {}
if not email:
errors['email'] = 'Die E-Mail Adresse ist erforderlich.'
2024-01-12 10:57:58 +01:00
if not password:
errors['password'] = 'Das Passwort ist erforderlich.'
2024-01-12 10:57:58 +01:00
# Check if user exists
user = User.get_by_email(email)
if not user:
errors['email'] = 'E-Mail Adresse nicht gefunden.'
elif user.password is None or hashlib.sha256(password.encode()).hexdigest() != user.password:
errors['password'] = 'Das Passwort ist falsch.'
2024-01-12 16:53:03 +01:00
if errors:
return render_template(
'auth/login.html',
2024-01-12 16:53:03 +01:00
email=email,
password=password,
errors=errors
)
2024-01-12 10:57:58 +01:00
2024-01-12 16:53:03 +01:00
login_user(user)
# Redirect to login page
return redirect(url_for('index'))
2024-01-12 16:53:03 +01:00
@app.route('/signup', methods=['POST'])
def signup_post():
2024-01-12 16:53:03 +01:00
email = request.form.get('email')
name = request.form.get('name')
2024-01-12 16:53:03 +01:00
password = request.form.get('password')
# Check for errors
errors = {}
if not email:
errors['email'] = 'Die E-Mail Adresse ist erforderlich.'
if not name:
errors['name'] = 'Der Name ist erforderlich.'
2024-01-12 16:53:03 +01:00
if not password:
errors['password'] = 'Das Passwort ist erforderlich.'
2024-01-12 16:53:03 +01:00
if errors:
return render_template(
'auth/signup.html',
2024-01-12 16:53:03 +01:00
email=email,
name=name,
2024-01-12 16:53:03 +01:00
password=password,
errors=errors
)
# Save user to database. Maybe log the user in directly.
user = User.create(name, email, password)
2024-01-12 16:53:03 +01:00
login_user(user)
2024-01-12 10:57:58 +01:00
# Redirect to login page
return redirect(url_for('index'))
2024-01-12 10:57:58 +01:00
@app.route('/logout')
@login_required
def logout():
# Log out functionality
2024-01-12 16:53:03 +01:00
logout_user()
2024-01-12 10:57:58 +01:00
return redirect(url_for('index'))
# Create a new route
@app.route('/')
def index():
if current_user.is_authenticated:
habits = current_user.get_habits()
2024-01-23 11:00:37 +01:00
name = "Hallo " + current_user.name
else:
habits = []
2024-01-23 11:00:37 +01:00
name = "Bitte melde dich an, du Vollhorst."
# habits = [("lesen", "eine Seite vor dem Schlafen gehen"), ("sport", "3x Gym")]
return render_template(
'index.html',
title=name,
utc_dt=datetime.datetime.now().strftime("%d.%m.%Y %H:%M %A"),
habits=habits,
errors={},
)
@app.route('/habit')
@login_required
def habit_creation():
return render_template(
'habit.html',
title='Erstelle ein Habit',
unit=1,
errors={},
)
@app.route('/habit', methods=['POST'])
@login_required
def habit_create():
name = request.form.get('name')
note = request.form.get('note')
times = request.form.get('times')
unit = request.form.get('unit')
# Check for errors
errors = {}
if not name:
errors['name'] = 'Der Name ist erforderlich.'
if not times:
errors['times'] = 'Die Anzahl ist erforderlich.'
if not note:
note = ''
if not unit:
errors['unit'] = 'Die Einheit ist erforderlich.'
# Check if times is an integer
try:
times = int(times)
2024-01-23 10:46:52 +01:00
# Check that times is greater than 0
if times <= 0:
errors['times'] = 'Die Anzahl muss größer als 0 sein.'
except ValueError:
errors['times'] = 'Die Anzahl muss eine Zahl sein.'
2024-01-19 11:05:27 +01:00
# Check that unit is valid
if unit not in ['Tag', 'Woche', 'Monat', 'Jahr']:
errors['unit'] = 'Die Einheit ist ungültig.'
if errors:
return render_template(
'habit.html',
title='Erstelle ein Habit',
name=name,
note=note,
times=times,
unit=unit,
errors=errors
)
# Map unit to integer
if unit == 'Tag':
unit = 0
elif unit == 'Woche':
unit = 1
elif unit == 'Monat':
unit = 2
elif unit == 'Jahr':
unit = 3
else:
unit = 1
# Save habit to database
habit = Habit.create(current_user.id, name, times, note, unit)
# Back to index
return redirect(url_for('index'))
"""return render_template(
'habit.html',
title='Erstelle ein Habit',
name=name,
note=note,
times=times,
unit=unit,
errors=errors,
)"""
2024-01-26 08:30:06 +01:00
@app.route('/check', methods=['POST'])
@login_required
def check_habit():
2024-01-26 09:06:31 +01:00
habit_id = request.get_json()["habitId"]
habit = Habit.get(habit_id)
if habit is None:
return {"error": "Habit not found"}
# Check if habit belongs to user
if habit.user_id != current_user.id:
return {"error": "Habit does not belong to user"}
trackings = habit.get_habitTrackings()
# Check if habit has been tracked today
unchecked = False
for tracking in trackings:
if tracking.created_at.date() == datetime.date.today():
tracking.delete()
unchecked = True
if not unchecked:
HabitTrackings.create(habit_id, 1)
return {
"habitId": habit_id,
"unchecked": unchecked,
}
2024-01-26 08:30:06 +01:00
2024-01-12 10:57:58 +01:00
# Run the application
if __name__ == '__main__':
app.run(port=5000, debug=True)