+ I said: {{ post.content }} +
++ Commented on {{ titleFunc(comment.post_id) }} + I said: {{ comment.content }} +
+{% endfor %} + +{% endblock %} \ No newline at end of file diff --git a/forum/templates/send_message.html b/forum/templates/send_message.html new file mode 100644 index 0000000..46d7402 --- /dev/null +++ b/forum/templates/send_message.html @@ -0,0 +1,11 @@ +{% extends 'layout.html' %} +{% block body %} ++ {{ message.content }} +
+Reply +{% endfor %} + +{% endblock %} \ No newline at end of file diff --git a/forum/templates/viewpost.html b/forum/templates/viewpost.html index 3f489ca..8193fcd 100644 --- a/forum/templates/viewpost.html +++ b/forum/templates/viewpost.html @@ -3,17 +3,28 @@ {{ path|safe}}
+ {{ post.Likes|length }} + + + + + +
Username: {{ user.username }}
+{% if current_user.is_authenticated %} +Send Message +{% endif %} ++
{{ post.title }}
++ {{ user.username }} said: {{ post.content }} +
++
+{% for comment in comments %} +
+ Commented on {{ titleFunc(comment.post_id) }} + {{ user.username }} said: {{ comment.content }} +
+{% endfor %} + +{% endblock %} \ No newline at end of file diff --git a/forum/user.py b/forum/user.py new file mode 100644 index 0000000..e59d225 --- /dev/null +++ b/forum/user.py @@ -0,0 +1,112 @@ +from flask import * +import re + +from flask_login import UserMixin, login_manager, login_user, login_required, logout_user +from werkzeug.security import generate_password_hash, check_password_hash + +from forum.app import db, login_manager, app +from forum.model import User +from forum.utl import username_taken, email_taken, valid_username + + +# from forum.app import db + + + +@login_manager.user_loader +def load_user(userid): + return User.query.get(userid) + +# +# password_regex = re.compile("^[a-zA-Z0-9!@#%&]{6,40}$") +# username_regex = re.compile("^[a-zA-Z0-9!@#%&]{4,40}$") +# #Account checks +# def username_taken(username): +# return User.query.filter(User.username == username).first() +# def email_taken(email): +# return User.query.filter(User.email == email).first() +# def valid_username(username): +# if not username_regex.match(username): +# #username does not meet password reqirements +# return False +# #username is not taken and does meet the password requirements +# return True +# def valid_password(password): +# return password_regex.match(password) +# #Post checks +# def valid_title(title): +# return len(title) > 4 and len(title) < 140 +# def valid_content(content): +# return len(content) > 10 and len(content) < 5000 + +# class User(UserMixin, db.Model): +# id = db.Column(db.Integer, primary_key=True) +# username = db.Column(db.Text, unique=True) +# password_hash = db.Column(db.Text) +# email = db.Column(db.Text, unique=True) +# admin = db.Column(db.Boolean, default=False) +# posts = db.relationship("Post", backref="user") +# comments = db.relationship("Comment", backref="user") +# +# def __init__(self, email, username, password): +# self.email = email +# self.username = username +# self.password_hash = generate_password_hash(password) +# def check_password(self, password): +# return check_password_hash(self.password_hash, password) + + +@app.route('/action_createaccount', methods=['POST']) +def action_createaccount(): + username = request.form['username'] + password = request.form['password'] + email = request.form['email'] + errors = [] + retry = False + if username_taken(username): + errors.append("Username is already taken!") + retry=True + if email_taken(email): + errors.append("An account already exists with this email!") + retry = True + if not valid_username(username): + errors.append("Username is not valid!") + retry = True + # if not valid_password(password): + # errors.append("Password is not valid!") + # retry = True + if retry: + return render_template("login.html", errors=errors) + user = User(email, username, password) + if user.username == "admin": + user.admin = True + db.session.add(user) + db.session.commit() + login_user(user) + return redirect("/") + +@app.route('/action_login', methods=['POST']) +def action_login(): + username = request.form['username'] + password = request.form['password'] + user = User.query.filter(User.username == username).first() + if user and user.check_password(password): + login_user(user) + else: + errors = [] + errors.append("Username or password is incorrect!") + return render_template("login.html", errors=errors) + return redirect("/") + + +@login_required +@app.route('/action_logout') +def action_logout(): + #todo + logout_user() + return redirect("/") + +@app.route('/loginform') +def loginform(): + return render_template("login.html") + diff --git a/forum/user_settings.py b/forum/user_settings.py new file mode 100644 index 0000000..c3ea1e9 --- /dev/null +++ b/forum/user_settings.py @@ -0,0 +1,103 @@ +from flask import * +import re +from flask_login import UserMixin, current_user, login_manager, login_user, login_required, logout_user +from werkzeug.security import generate_password_hash, check_password_hash +from forum.app import db, login_manager, app +from forum.model import User +from forum.utl import username_taken, email_taken, valid_username + + +""" Change Settings View +Base view that shows the user settings that can be changed and their action buttons +""" +@login_required +@app.route('/user_settings') +def user_settings(): + return render_template("user_settings.html") + + + +""" Change Username View +login will be required for the view (request) +Will be a POST method I think, +need to return to a user settings page - html (still going to /) +on error render user settings again with errors +""" + + +@login_required +@app.route('/user_settings/action_change_username', methods=['POST']) +def action_change_username(): + + # Get the current user name and desired updated user name from the user_settings form + update_username = request.form['new_username'] + + # Check if new user name entered is valid + errors = [] + retry = False + if username_taken(update_username): + errors.append("Username is already taken!") + retry=True + if not valid_username(update_username): + errors.append("Username is not valid!") + retry = True + if retry: + return render_template("user_settings.html", errors=errors) + + # Use sql alchemy session method to update username in db + # db.session.execute("UPDATE User SET username = ? WHERE username = ?;", (update_username, current_username), ) + + # Set the User object in session to new username + current_user.username = update_username + + # Save changes to session db + db.session.commit() + + # Send the user back to forum page + # return render_template("user_settings.html", user=current_user) + + return redirect("/user_settings") + + +""" Change Email View +login will be required for the view (request) +Will be a POST method I think, +need to return to a user settings page - html (still going to /) +on error redner user settings html with error this time +""" + + +@login_required +@app.route('/user_settings/action_change_email', methods=['POST']) +def action_change_email(): + + # Get the current user name and desired updated user name from the user_settings form + current_email = current_user.email + + # Get the current user name and desired updated user name from the user_settings form + update_email = request.form['new_email'] + + # Check if new user name entered is valid + errors = [] + retry = False + if email_taken(update_email): + errors.append("Email is already taken!") + retry=True + if retry: + return render_template("user_settings.html", errors=errors) + + # (Use sql alchemy session instead?) Update username + # user.email = update_email + + # Use sql alchemy session method to update username in db + # db.session.execute("UPDATE User SET email = ? WHERE email = ?;", (update_email, current_email), ) + current_user.email = update_email + + # Save changes to session db + db.session.commit() + + # Send the user back to forum page + # return render_template("user_settings.html", user=current_user) + return redirect("/user_settings") + + diff --git a/forum/utl.py b/forum/utl.py new file mode 100644 index 0000000..a1e8b46 --- /dev/null +++ b/forum/utl.py @@ -0,0 +1,41 @@ +import re + +from forum.model import User + + +def error(errormessage): + return "" + errormessage + "" + + +password_regex = re.compile("^[a-zA-Z0-9!@#%&]{6,40}$") +username_regex = re.compile("^[a-zA-Z0-9!@#%&]{4,40}$") + + +# Account checks +def username_taken(username): + return User.query.filter(User.username == username).first() + + +def email_taken(email): + return User.query.filter(User.email == email).first() + + +def valid_username(username): + if not username_regex.match(username): + # username does not meet password reqirements + return False + # username is not taken and does meet the password requirements + return True + + +def valid_password(password): + return password_regex.match(password) + + +# Post checks +def valid_title(title): + return len(title) > 4 and len(title) < 140 + + +def valid_content(content): + return len(content) > 10 and len(content) < 5000 diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..0e04844 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 0000000..ec9d45c --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic,flask_migrate + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..4c97092 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,113 @@ +import logging +from logging.config import fileConfig + +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except (TypeError, AttributeError): + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option('sqlalchemy.url', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def get_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=get_metadata(), literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + conf_args = current_app.extensions['migrate'].configure_args + if conf_args.get("process_revision_directives") is None: + conf_args["process_revision_directives"] = process_revision_directives + + connectable = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_metadata(), + **conf_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..2c01563 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/4347cedbdd88_adding_messages.py b/migrations/versions/4347cedbdd88_adding_messages.py new file mode 100644 index 0000000..fe491b7 --- /dev/null +++ b/migrations/versions/4347cedbdd88_adding_messages.py @@ -0,0 +1,43 @@ +"""adding messages + +Revision ID: 4347cedbdd88 +Revises: +Create Date: 2023-11-25 13:13:48.987710 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '4347cedbdd88' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('message', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('sender_id', sa.Integer(), nullable=True), + sa.Column('recipient_id', sa.Integer(), nullable=True), + sa.Column('content', sa.String(length=200), nullable=True), + sa.Column('postdate', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['recipient_id'], ['user.id'], ), + sa.ForeignKeyConstraint(['sender_id'], ['user.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('user', schema=None) as batch_op: + batch_op.add_column(sa.Column('last_message_read_time', sa.DateTime(), nullable=True)) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('user', schema=None) as batch_op: + batch_op.drop_column('last_message_read_time') + + op.drop_table('message') + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index ece97dc..a3fe593 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,12 +1,13 @@ -Flask==1.1.2 -Flask-Login==0.5.0 -Flask-SQLAlchemy==2.4.4 -gunicorn==20.0.4 -itsdangerous==1.1.0 -Jinja2==2.11.2 -MarkupSafe==1.1.1 -psycopg2==2.9.3 -SQLAlchemy==1.3.20 -Werkzeug==1.0.1 -wheel==0.36.0 -honcho==1.0.1 \ No newline at end of file +Flask +Flask-Login +Flask-SQLAlchemy +gunicorn +itsdangerous +Jinja2 +MarkupSafe +SQLAlchemy +Werkzeug +wheel +honcho +cryptography +pymysql \ No newline at end of file