init
This commit is contained in:
@@ -0,0 +1,14 @@
|
|||||||
|
# venv
|
||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
|
||||||
|
# python
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
|
||||||
|
# env
|
||||||
|
.env
|
||||||
|
.flaskenv
|
||||||
|
|
||||||
|
#db
|
||||||
|
instance/
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
from flask import Flask
|
||||||
|
from settings import app, db
|
||||||
|
|
||||||
|
|
||||||
|
from routes.routes import *
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
"""Auth."""
|
||||||
|
|
||||||
|
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
|
||||||
|
from models.user import User
|
||||||
|
from errors import error_response
|
||||||
|
|
||||||
|
basic_auth = HTTPBasicAuth()
|
||||||
|
token_auth = HTTPTokenAuth()
|
||||||
|
|
||||||
|
|
||||||
|
@basic_auth.verify_password
|
||||||
|
def verify_password(email, password):
|
||||||
|
"""Verify password."""
|
||||||
|
user = User.query.filter_by(email=email).first()
|
||||||
|
if user and user.check_password(password):
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@basic_auth.error_handler
|
||||||
|
def basic_auth_error(status):
|
||||||
|
"""Basic auth error."""
|
||||||
|
return error_response(status)
|
||||||
|
|
||||||
|
|
||||||
|
@token_auth.verify_token
|
||||||
|
def verify_token(token):
|
||||||
|
"""Verify token."""
|
||||||
|
return User.check_token(token) if token else None
|
||||||
|
|
||||||
|
|
||||||
|
@token_auth.error_handler
|
||||||
|
def token_auth_error(status):
|
||||||
|
"""Token auth error."""
|
||||||
|
return error_response(status)
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
strategy_dicts = [
|
||||||
|
{
|
||||||
|
"name": "Brets Low Roller",
|
||||||
|
"initial_bets": [
|
||||||
|
{"name": "Dozen", "value": 1, "stake": 1},
|
||||||
|
{"name": "Dozen", "value": 2, "stake": 1},
|
||||||
|
],
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"requirements": [
|
||||||
|
{
|
||||||
|
"conditions": [
|
||||||
|
{"name": "milestone_passed", "invert": False},
|
||||||
|
{"name": "at_milestone", "invert": False},
|
||||||
|
],
|
||||||
|
"operator": "or",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updates": [{"name": "reset_bet"}, {"name": "inc_milestone"}],
|
||||||
|
"stage": "on_win",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"requirements": [
|
||||||
|
{
|
||||||
|
"conditions": [
|
||||||
|
{"name": "lost_since_reset", "invert": True},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updates": [{"name": "inc_bet"}],
|
||||||
|
"stage": "on_loss",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"requirements": [
|
||||||
|
{
|
||||||
|
"conditions": [
|
||||||
|
{"name": "lost_since_reset", "invert": False},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updates": [{"name": "inc_bet"}],
|
||||||
|
"stage": "on_spin",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"requirements": [
|
||||||
|
{
|
||||||
|
"conditions": [
|
||||||
|
{"name": "min_time_reached", "invert": False},
|
||||||
|
{"name": "at_milestone", "invert": False},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updates": [],
|
||||||
|
"stage": "end_requirements",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"stake_ratio": 200,
|
||||||
|
"milestone_perc": 5,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Second Dozen Second Column",
|
||||||
|
"initial_bets": [
|
||||||
|
{"name": "Column", "value": 2, "stake": 1},
|
||||||
|
{"name": "Dozen", "value": 2, "stake": 1},
|
||||||
|
],
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"requirements": [
|
||||||
|
{
|
||||||
|
"conditions": [
|
||||||
|
{"name": "session_profit", "invert": False}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updates": [{"name": "reset_bet"}],
|
||||||
|
"stage": "on_win",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"requirements": [],
|
||||||
|
"updates": [{"name": "inc_bet"}],
|
||||||
|
"stage": "on_loss",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"stake_ratio": 200,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Holy Grail",
|
||||||
|
"initial_bets": [
|
||||||
|
{"name": "Dozen", "value": 1, "stake": 1},
|
||||||
|
{"name": "Dozen", "value": 2, "stake": 1},
|
||||||
|
],
|
||||||
|
"actions": [
|
||||||
|
{
|
||||||
|
"requirements": [
|
||||||
|
{
|
||||||
|
"conditions": [
|
||||||
|
{"name": "session_profit", "invert": False}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"updates": [{"name": "reset_bet"}],
|
||||||
|
"stage": "on_win",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"requirements": [],
|
||||||
|
"updates": [{"name": "inc_bet"}],
|
||||||
|
"stage": "on_loss",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"stake_ratio": 200,
|
||||||
|
},
|
||||||
|
]
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
Flask
|
||||||
|
flask-Migrate
|
||||||
|
flask-sqlalchemy
|
||||||
|
sqlalchemy_serializer
|
||||||
|
python-dotenv
|
||||||
|
flask_httpauth
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"""Response errors."""
|
||||||
|
from flask import jsonify
|
||||||
|
from werkzeug.http import HTTP_STATUS_CODES
|
||||||
|
|
||||||
|
|
||||||
|
def error_response(status_code, message=None):
|
||||||
|
"""Error response."""
|
||||||
|
payload = {"error": HTTP_STATUS_CODES.get(status_code, "Unknown error")}
|
||||||
|
if message:
|
||||||
|
payload["message"] = message
|
||||||
|
response = jsonify(payload)
|
||||||
|
response.status_code = status_code
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
def bad_request(message):
|
||||||
|
"""Bad request."""
|
||||||
|
return error_response(400, message)
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
from settings import app, db
|
||||||
|
from models.user import User
|
||||||
|
|
||||||
|
|
||||||
|
def import_user():
|
||||||
|
user = User(
|
||||||
|
email="rob@test.com",
|
||||||
|
username="rob",
|
||||||
|
password_hash="pbkdf2:sha256:260000$ox0WH3KrvKXBNT1C$48624cc8b59a7ca1d510f12410b8c7e4c4a61f9e1b488f980f1ca352c86eee5b", # noqa E501
|
||||||
|
)
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
import_user()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Single-database configuration for Flask.
|
||||||
@@ -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
|
||||||
@@ -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()
|
||||||
@@ -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"}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""user table
|
||||||
|
|
||||||
|
Revision ID: 70b40a0d8417
|
||||||
|
Revises:
|
||||||
|
Create Date: 2024-08-28 13:35:01.725865
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = "70b40a0d8417"
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.create_table(
|
||||||
|
"user",
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("email", sa.String(length=80), nullable=True),
|
||||||
|
sa.Column("username", sa.String(length=100), nullable=True),
|
||||||
|
sa.Column("password_hash", sa.String(length=255), nullable=True),
|
||||||
|
sa.Column("token", sa.String(length=32), nullable=True),
|
||||||
|
sa.Column("token_expiration", sa.DateTime(), nullable=True),
|
||||||
|
sa.Column("refresh_token", sa.String(length=32), nullable=True),
|
||||||
|
sa.Column("reset_password_code", sa.String(length=8), nullable=True),
|
||||||
|
sa.Column("reset_password_expiration", sa.DateTime(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint("id", name=op.f("pk_user")),
|
||||||
|
sa.UniqueConstraint("email", name=op.f("uq_user_email")),
|
||||||
|
)
|
||||||
|
with op.batch_alter_table("user", schema=None) as batch_op:
|
||||||
|
batch_op.create_index(
|
||||||
|
batch_op.f("ix_user_refresh_token"), ["refresh_token"], unique=True
|
||||||
|
)
|
||||||
|
batch_op.create_index(
|
||||||
|
batch_op.f("ix_user_reset_password_code"),
|
||||||
|
["reset_password_code"],
|
||||||
|
unique=True,
|
||||||
|
)
|
||||||
|
batch_op.create_index(
|
||||||
|
batch_op.f("ix_user_token"), ["token"], unique=True
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
with op.batch_alter_table("user", schema=None) as batch_op:
|
||||||
|
batch_op.drop_index(batch_op.f("ix_user_token"))
|
||||||
|
batch_op.drop_index(batch_op.f("ix_user_reset_password_code"))
|
||||||
|
batch_op.drop_index(batch_op.f("ix_user_refresh_token"))
|
||||||
|
|
||||||
|
op.drop_table("user")
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
from sqlalchemy import MetaData
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
__abstract__ = True
|
||||||
|
naming_convention = {
|
||||||
|
"ix": "ix_%(column_0_label)s",
|
||||||
|
"uq": "uq_%(table_name)s_%(column_0_name)s",
|
||||||
|
"ck": "ck_%(table_name)s_%(constraint_name)s",
|
||||||
|
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
|
||||||
|
"pk": "pk_%(table_name)s",
|
||||||
|
}
|
||||||
|
metadata = MetaData(naming_convention=naming_convention)
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
from sqlalchemy_serializer import SerializerMixin
|
||||||
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
|
from settings import db
|
||||||
|
import base64
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
import os
|
||||||
|
|
||||||
|
|
||||||
|
class User(db.Model, SerializerMixin):
|
||||||
|
__tablename__ = "user"
|
||||||
|
serialize_only = ("id", "username")
|
||||||
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
|
email = db.Column(db.String(80), unique=True)
|
||||||
|
username = db.Column(db.String(100))
|
||||||
|
password_hash = db.Column(db.String(255))
|
||||||
|
token = db.Column(db.String(32), index=True, unique=True)
|
||||||
|
token_expiration = db.Column(db.DateTime)
|
||||||
|
refresh_token = db.Column(db.String(32), index=True, unique=True)
|
||||||
|
reset_password_code = db.Column(db.String(8), index=True, unique=True)
|
||||||
|
reset_password_expiration = db.Column(db.DateTime)
|
||||||
|
|
||||||
|
def set_password(self, password):
|
||||||
|
self.password_hash = generate_password_hash(password)
|
||||||
|
|
||||||
|
def check_password(self, password):
|
||||||
|
return check_password_hash(self.password_hash, password)
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return "<User {}, {}>".format(self.id, self.username)
|
||||||
|
|
||||||
|
def get_token(self, expires_in=3600):
|
||||||
|
now = datetime.utcnow()
|
||||||
|
if self.token and self.token_expiration > now + timedelta(seconds=60):
|
||||||
|
return self.token
|
||||||
|
self.token = base64.b64encode(os.urandom(24)).decode("utf-8")
|
||||||
|
self.token_expiration = now + timedelta(seconds=expires_in)
|
||||||
|
db.session.add(self)
|
||||||
|
return self.token
|
||||||
|
|
||||||
|
def get_refresh_token(self):
|
||||||
|
if self.refresh_token:
|
||||||
|
return self.refresh_token
|
||||||
|
self.refresh_token = base64.b64encode(os.urandom(24)).decode("utf-8")
|
||||||
|
db.session.add(self)
|
||||||
|
return self.refresh_token
|
||||||
|
|
||||||
|
def revoke_tokens(self):
|
||||||
|
self.token_expiration = datetime.utcnow() - timedelta(seconds=1)
|
||||||
|
self.refresh_token = None
|
||||||
|
|
||||||
|
def get_reset_code(self, expires_in=300):
|
||||||
|
now = datetime.utcnow()
|
||||||
|
if (
|
||||||
|
self.reset_password_code
|
||||||
|
and self.reset_password_expiration > now + timedelta(seconds=60)
|
||||||
|
):
|
||||||
|
return self.reset_password_code
|
||||||
|
self.reset_password_code = base64.b64encode(os.urandom(8)).decode(
|
||||||
|
"utf-8"
|
||||||
|
)[:8]
|
||||||
|
self.reset_password_expiration = now + timedelta(seconds=expires_in)
|
||||||
|
db.session.add(self)
|
||||||
|
return self.reset_password_code
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def check_token(token):
|
||||||
|
user = User.query.filter_by(token=token).first()
|
||||||
|
if user is None or user.token_expiration < datetime.utcnow():
|
||||||
|
return None
|
||||||
|
return user
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def check_reset_code(reset_code):
|
||||||
|
user = User.query.filter_by(reset_password_code=reset_code).first()
|
||||||
|
if user is None or user.reset_password_expiration < datetime.utcnow():
|
||||||
|
return None
|
||||||
|
return user
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
auth_routes.py
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
from settings import app
|
||||||
|
|
||||||
|
from routes.token_routes import *
|
||||||
|
from routes.user_routes import *
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""Token routes."""
|
||||||
|
|
||||||
|
from flask import jsonify, make_response, request
|
||||||
|
from settings import db, app
|
||||||
|
from auth import token_auth, basic_auth
|
||||||
|
from models.user import User
|
||||||
|
from errors import error_response
|
||||||
|
|
||||||
|
# todo - put in basic_auth
|
||||||
|
basic_auth.scheme = "Custom"
|
||||||
|
basic_auth.realm = "Incorrect Credentials"
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/auth/token", methods=["POST"])
|
||||||
|
@basic_auth.login_required
|
||||||
|
def get_token():
|
||||||
|
"""Get token."""
|
||||||
|
token = basic_auth.current_user().get_token()
|
||||||
|
refresh_token = basic_auth.current_user().get_refresh_token()
|
||||||
|
db.session.commit()
|
||||||
|
response = make_response(
|
||||||
|
jsonify(
|
||||||
|
{
|
||||||
|
"token": token,
|
||||||
|
"username": basic_auth.current_user().username,
|
||||||
|
"user_id": basic_auth.current_user().id,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
response.set_cookie("refresh_token", value=refresh_token, httponly=True)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/auth/tokens", methods=["DELETE"])
|
||||||
|
@token_auth.login_required
|
||||||
|
def revoke_token():
|
||||||
|
"""Revoke token."""
|
||||||
|
token_auth.current_user().revoke_tokens()
|
||||||
|
db.session.commit()
|
||||||
|
return {"success": True}
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/auth/refresh", methods=["GET"])
|
||||||
|
def refresh_token():
|
||||||
|
"""Refresh token."""
|
||||||
|
refresh_token = request.cookies.get("refresh_token")
|
||||||
|
if refresh_token is None:
|
||||||
|
return error_response(400, "Bad request, no refresh token")
|
||||||
|
user = User.query.filter_by(refresh_token=refresh_token).first()
|
||||||
|
if user is not None:
|
||||||
|
access_token = user.get_token()
|
||||||
|
db.session.commit()
|
||||||
|
return {
|
||||||
|
"token": access_token,
|
||||||
|
"user_id": user.id,
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"""User routes."""
|
||||||
|
|
||||||
|
from settings import app, db
|
||||||
|
from flask import request
|
||||||
|
from models.user import User
|
||||||
|
from errors import error_response
|
||||||
|
import os
|
||||||
|
|
||||||
|
# from flask_mail import Message
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/api/user/register", methods=["POST"])
|
||||||
|
def register_user():
|
||||||
|
"""Register user."""
|
||||||
|
req = request.get_json()
|
||||||
|
user = User.query.filter_by(email=req["email"]).first()
|
||||||
|
if user is None:
|
||||||
|
user = User(username=req["username"], email=req["email"])
|
||||||
|
user.set_password(req["password"])
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
return {"success": True}
|
||||||
|
else:
|
||||||
|
return error_response(409, "Email exists")
|
||||||
|
|
||||||
|
|
||||||
|
# @app.route("/api/user/reset-password", methods=["POST"])
|
||||||
|
# def reset_password():
|
||||||
|
# """Reset password."""
|
||||||
|
# email = request.get_json()["email"]
|
||||||
|
# user = User.query.filter_by(email=email).first()
|
||||||
|
# if user is None:
|
||||||
|
# return error_response(400, "Email not found")
|
||||||
|
# else:
|
||||||
|
# reset_code = user.get_reset_code()
|
||||||
|
# db.session.commit()
|
||||||
|
# sender = os.environ.get("MAIL_USERNAME")
|
||||||
|
# msg = Message(
|
||||||
|
# "PitchInvader password reset code",
|
||||||
|
# sender=sender,
|
||||||
|
# recipients=[email],
|
||||||
|
# )
|
||||||
|
# msg.body = (
|
||||||
|
# "Please enter the following reset code when prompted. {}".format(
|
||||||
|
# reset_code
|
||||||
|
# )
|
||||||
|
# )
|
||||||
|
# msg.html = "<p>{}</p>".filesat(msg.body)
|
||||||
|
# # mail.send(msg)
|
||||||
|
# return {"success": True}
|
||||||
|
|
||||||
|
|
||||||
|
# @app.route("/api/user/update-password", methods=["POST"])
|
||||||
|
# def update_password():
|
||||||
|
# """Update password."""
|
||||||
|
# req = request.get_json()
|
||||||
|
# if "reset_code" not in req.keys() or req["reset_code"] is None:
|
||||||
|
# return error_response(400, "Bad request")
|
||||||
|
# user = User.check_reset_code(req["reset_code"])
|
||||||
|
# if user is None:
|
||||||
|
# return error_response(400, "Bad request")
|
||||||
|
# else:
|
||||||
|
# user.set_password(req["password"])
|
||||||
|
# db.session.add(user)
|
||||||
|
# db.session.commit()
|
||||||
|
# return {"success": True}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
from flask import Flask
|
||||||
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
from flask_migrate import Migrate
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from models.base import Base
|
||||||
|
import os
|
||||||
|
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
app = Flask(__name__, static_folder="static")
|
||||||
|
app.config.update(
|
||||||
|
{
|
||||||
|
"DEBUG": bool(os.environ.get("DEBUG") == "True"),
|
||||||
|
"SQLALCHEMY_DATABASE_URI": "sqlite:///database.sqlite",
|
||||||
|
"SQLALCHEMY_ECHO": bool(os.environ.get("SQLALCHEMY_ECHO") == "True"),
|
||||||
|
"SQLALCHEMY_TRACK_MODIFICATIONS": bool(
|
||||||
|
os.environ.get("SQLALCHEMY_TRACK_MODIFICATIONS") == "True"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
db = SQLAlchemy(app, model_class=Base)
|
||||||
|
migrate = Migrate(app, db, render_as_batch=True)
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# React + Vite
|
||||||
|
|
||||||
|
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||||
|
|
||||||
|
Currently, two official plugins are available:
|
||||||
|
|
||||||
|
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
|
||||||
|
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import js from '@eslint/js'
|
||||||
|
import globals from 'globals'
|
||||||
|
import react from 'eslint-plugin-react'
|
||||||
|
import reactHooks from 'eslint-plugin-react-hooks'
|
||||||
|
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||||
|
|
||||||
|
export default [
|
||||||
|
{ ignores: ['dist'] },
|
||||||
|
{
|
||||||
|
files: ['**/*.{js,jsx}'],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 2020,
|
||||||
|
globals: globals.browser,
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
ecmaFeatures: { jsx: true },
|
||||||
|
sourceType: 'module',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
settings: { react: { version: '18.3' } },
|
||||||
|
plugins: {
|
||||||
|
react,
|
||||||
|
'react-hooks': reactHooks,
|
||||||
|
'react-refresh': reactRefresh,
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
...js.configs.recommended.rules,
|
||||||
|
...react.configs.recommended.rules,
|
||||||
|
...react.configs['jsx-runtime'].rules,
|
||||||
|
...reactHooks.configs.recommended.rules,
|
||||||
|
'react/jsx-no-target-blank': 'off',
|
||||||
|
'react-refresh/only-export-components': [
|
||||||
|
'warn',
|
||||||
|
{ allowConstantExport: true },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en" >
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>My App</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.jsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+4583
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
|||||||
|
{
|
||||||
|
"name": "react",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"base-64": "^1.0.0",
|
||||||
|
"bootstrap": "^5.3.3",
|
||||||
|
"react": "^18.3.1",
|
||||||
|
"react-bootstrap": "^2.10.4",
|
||||||
|
"react-dom": "^18.3.1",
|
||||||
|
"react-router": "^6.26.1",
|
||||||
|
"react-router-dom": "^6.26.1",
|
||||||
|
"sass": "^1.77.8"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.9.0",
|
||||||
|
"@types/react": "^18.3.3",
|
||||||
|
"@types/react-dom": "^18.3.0",
|
||||||
|
"@vitejs/plugin-react": "^4.3.1",
|
||||||
|
"eslint": "^9.9.0",
|
||||||
|
"eslint-plugin-react": "^7.35.0",
|
||||||
|
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||||
|
"eslint-plugin-react-refresh": "^0.4.9",
|
||||||
|
"globals": "^15.9.0",
|
||||||
|
"vite": "^5.4.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,37 @@
|
|||||||
|
import "./styles/custom.scss";
|
||||||
|
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||||
|
import { AuthProvider } from "./contexts/AuthContext";
|
||||||
|
import ProtectedRoute from "./routing/ProtectedRoute";
|
||||||
|
import PageNotFound from "./pages/PageNotFound/PageNotFound";
|
||||||
|
import Homepage from "./pages/Homepage/Homepage";
|
||||||
|
import Login from "./pages/Login/Login";
|
||||||
|
import Header from "./components/Header/Header";
|
||||||
|
import Footer from "./components/Footer/Footer";
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
return (
|
||||||
|
<div className="app" data-bs-theme="dark">
|
||||||
|
<BrowserRouter>
|
||||||
|
<AuthProvider>
|
||||||
|
<>
|
||||||
|
<Header />
|
||||||
|
<Routes>
|
||||||
|
<Route index element={<Homepage />} />
|
||||||
|
{/*<Route element={<ProtectedRoute />}>
|
||||||
|
<Route
|
||||||
|
path="some_protected_path"
|
||||||
|
element={<Some Page Element/>}
|
||||||
|
/>
|
||||||
|
</Route> */}
|
||||||
|
<Route path="login" element={<Login />} />
|
||||||
|
<Route path="*" element={<PageNotFound />} />
|
||||||
|
</Routes>
|
||||||
|
<Footer />
|
||||||
|
</>
|
||||||
|
</AuthProvider>
|
||||||
|
</BrowserRouter>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import styles from "./Footer.module.scss";
|
||||||
|
|
||||||
|
const Footer = () => {
|
||||||
|
return (
|
||||||
|
<footer className={styles.footer}>
|
||||||
|
<p className={styles.copyright}>
|
||||||
|
© Copyright {new Date().getFullYear()} by roborto.
|
||||||
|
</p>
|
||||||
|
</footer>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Footer;
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
@import "../../styles/colors.scss";
|
||||||
|
|
||||||
|
.footer {
|
||||||
|
padding: 10px;
|
||||||
|
height: 50px;
|
||||||
|
background-color: map-get($theme-colors, "footer-bg");
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
|
||||||
|
import styles from "./GuestNav.module.scss";
|
||||||
|
import { Nav } from "react-bootstrap";
|
||||||
|
import { NavLink } from "react-router-dom";
|
||||||
|
|
||||||
|
const GuestNav = () => {
|
||||||
|
return (
|
||||||
|
<Nav className={styles.nav}>
|
||||||
|
<Nav.Link as={NavLink} to="/login">Login</Nav.Link>
|
||||||
|
<Nav.Link as={NavLink} to="/register">Register</Nav.Link>
|
||||||
|
</Nav>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default GuestNav
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { Container, Navbar } from "react-bootstrap";
|
||||||
|
import styles from "./Header.module.scss";
|
||||||
|
import PageNav from "../PageNav/PageNav"
|
||||||
|
import Logo from "../Logo/Logo"
|
||||||
|
import { useAuth } from "../../contexts/AuthContext";
|
||||||
|
import GuestNav from "../GuestNav/GuestNav";
|
||||||
|
|
||||||
|
|
||||||
|
const Header = () => {
|
||||||
|
const { user } = useAuth()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Navbar expand="sm" className={styles.header} variant="dark">
|
||||||
|
<Container>
|
||||||
|
<Navbar.Brand><Logo /></Navbar.Brand>
|
||||||
|
<Navbar.Toggle aria-controls="navbar-nav" />
|
||||||
|
<Navbar.Collapse id="navbar-nav" className={styles.navbarCollapse}>
|
||||||
|
{
|
||||||
|
user ? <PageNav /> : <GuestNav />
|
||||||
|
}
|
||||||
|
|
||||||
|
</Navbar.Collapse>
|
||||||
|
</Container>
|
||||||
|
</Navbar>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Header
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
@import "../../styles/colors.scss";
|
||||||
|
|
||||||
|
.header {
|
||||||
|
height: 70px;
|
||||||
|
padding: 10px;
|
||||||
|
background-color: map-get($theme-colors, "header-bg")
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbarCollapse {
|
||||||
|
justify-content: flex-end !important;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import styles from "./Logo.module.scss";
|
||||||
|
import { Link } from "react-router-dom";
|
||||||
|
|
||||||
|
function Logo() {
|
||||||
|
return (
|
||||||
|
<Link to="/" className={styles.link}>
|
||||||
|
<img src="/logo.png" alt="App Logo" className={styles.logo} />
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Logo;
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
.link {
|
||||||
|
text-decoration: none;
|
||||||
|
color: unset;
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { Spinner } from "react-bootstrap"
|
||||||
|
import PropTypes from "prop-types";
|
||||||
|
|
||||||
|
const Main = ({isLoading=false, error='', children}) => {
|
||||||
|
return (
|
||||||
|
<main>
|
||||||
|
{ error !== '' && <div>{error}</div> }
|
||||||
|
{ error === '' && isLoading &&
|
||||||
|
<Spinner
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
left: '50%',
|
||||||
|
top: '50%'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
{ error === '' && !isLoading && children }
|
||||||
|
</main>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Main.propTypes = {
|
||||||
|
isLoading: PropTypes.bool,
|
||||||
|
error: PropTypes.string,
|
||||||
|
children: PropTypes.node
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Main
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { NavLink } from "react-router-dom";
|
||||||
|
import styles from "./PageNav.module.scss";
|
||||||
|
import { Nav } from "react-bootstrap"
|
||||||
|
import { useAuth } from "../../contexts/AuthContext";
|
||||||
|
|
||||||
|
|
||||||
|
const PageNav = () => {
|
||||||
|
const { logout } = useAuth()
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Nav className={styles.nav}>
|
||||||
|
<Nav.Link as={NavLink} onClick={logout} to="/">Logout</Nav.Link>
|
||||||
|
</Nav>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default PageNav;
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
/* eslint-disable react-refresh/only-export-components */
|
||||||
|
import { createContext, useContext, useReducer, useEffect } from "react";
|
||||||
|
import PropTypes from "prop-types";
|
||||||
|
import { encode as base64_encode } from "base-64";
|
||||||
|
import { useLocalStorage } from "../hooks/useLocalStorage";
|
||||||
|
import { useNavigate } from "react-router";
|
||||||
|
|
||||||
|
const AuthContext = createContext();
|
||||||
|
const BASE_URL = "/api";
|
||||||
|
|
||||||
|
const initialState = {
|
||||||
|
user: null,
|
||||||
|
isAuthenticated: false,
|
||||||
|
error: "",
|
||||||
|
isLoading: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
function reducer(state, action) {
|
||||||
|
const { type, payload } = action;
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case "auth/login":
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
user: payload,
|
||||||
|
isAuthenticated: true,
|
||||||
|
error: "",
|
||||||
|
};
|
||||||
|
case "auth/logout":
|
||||||
|
return { ...state, ...initialState };
|
||||||
|
case "auth/error":
|
||||||
|
return { ...state, error: payload };
|
||||||
|
case "auth/preRequest":
|
||||||
|
return { ...state, error: "", isLoading: true };
|
||||||
|
case "auth/postRequest":
|
||||||
|
return { ...state, isLoading: false };
|
||||||
|
case "auth/updateToken":
|
||||||
|
return { ...state, user: { ...state.user, token: payload } };
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown action type: ${action.type}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function AuthProvider({ children }) {
|
||||||
|
const [{ user, isAuthenticated, isLoading, error }, dispatch] = useReducer(
|
||||||
|
reducer,
|
||||||
|
initialState
|
||||||
|
);
|
||||||
|
const { setLSItems, removeLSItems, getLSItems } = useLocalStorage();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const user = getLSItems(["user_id", "token", "username"]);
|
||||||
|
if (!!user.user_id && !!user.token && !!user.username) {
|
||||||
|
dispatch({ type: "auth/login", payload: user });
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
function login(email, password) {
|
||||||
|
async function getToken(email, password) {
|
||||||
|
dispatch({ type: "auth/preRequest" });
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${BASE_URL}/auth/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization:
|
||||||
|
"Basic " + base64_encode(`${email}:${password}`),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (res.status === 401) {
|
||||||
|
throw new Error("Unauthorized");
|
||||||
|
}
|
||||||
|
const data = await res.json();
|
||||||
|
setLSItems(data);
|
||||||
|
dispatch({ type: "auth/login", payload: data });
|
||||||
|
} catch (err) {
|
||||||
|
dispatch({ type: "auth/error", payload: err.message });
|
||||||
|
} finally {
|
||||||
|
dispatch({ type: "auth/postRequest" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
getToken(email, password);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function logout() {
|
||||||
|
request("auth/tokens", { method: "DELETE" });
|
||||||
|
removeLSItems(["token", "username", "user_id"]);
|
||||||
|
dispatch({ type: "auth/logout" });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestWithToken(url, token, options = {}) {
|
||||||
|
const headers = new Headers();
|
||||||
|
if (!token || token === "") {
|
||||||
|
throw new Error("No bearer token");
|
||||||
|
}
|
||||||
|
headers.append("authorization", `Bearer ${token}`);
|
||||||
|
headers.append("X-Requested-With", "XMLHttpRequest");
|
||||||
|
const res = await fetch(
|
||||||
|
`${BASE_URL}/${url}`,
|
||||||
|
{
|
||||||
|
...options,
|
||||||
|
credentials: "include",
|
||||||
|
headers,
|
||||||
|
},
|
||||||
|
true
|
||||||
|
);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function request(url, options = {}, reauth = false) {
|
||||||
|
let token = user.token;
|
||||||
|
if (reauth) {
|
||||||
|
const res = await fetch(`${BASE_URL}/auth/refresh`);
|
||||||
|
const data = await res.json();
|
||||||
|
if (
|
||||||
|
res.status == 400 &&
|
||||||
|
data.message === "Bad request, no refresh token"
|
||||||
|
) {
|
||||||
|
dispatch({ type: "auth/logout" });
|
||||||
|
navigate("/login");
|
||||||
|
}
|
||||||
|
if (`${data.user_id}` !== `${user.user_id}`)
|
||||||
|
throw new Error(`Wrong user. ${data.user_id}, ${user.user_id}`);
|
||||||
|
else if (res.status === 200) {
|
||||||
|
token = data.token;
|
||||||
|
dispatch({ type: "auth/updateToken", payload: token });
|
||||||
|
} else {
|
||||||
|
throw new Error("Error refreshing token");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const res = await requestWithToken(url, token, options);
|
||||||
|
if (res.status == 401) {
|
||||||
|
if (reauth) {
|
||||||
|
throw new Error("Unauthorized");
|
||||||
|
}
|
||||||
|
return request(url, options, true);
|
||||||
|
}
|
||||||
|
if (!res.ok && !reauth) {
|
||||||
|
throw new Error("Error fetching data");
|
||||||
|
}
|
||||||
|
const data = await res.json();
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthContext.Provider
|
||||||
|
value={{
|
||||||
|
login,
|
||||||
|
logout,
|
||||||
|
user,
|
||||||
|
isAuthenticated,
|
||||||
|
error,
|
||||||
|
isLoading,
|
||||||
|
request,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</AuthContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const useAuth = () => {
|
||||||
|
const context = useContext(AuthContext);
|
||||||
|
if (context === undefined) {
|
||||||
|
throw new Error("AuthContext used outside AuthProvider");
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
};
|
||||||
|
|
||||||
|
AuthProvider.propTypes = {
|
||||||
|
children: PropTypes.object.isRequired,
|
||||||
|
};
|
||||||
|
|
||||||
|
export { AuthProvider, useAuth };
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
const useLocalStorage = () => {
|
||||||
|
const setLSItems = (items={}) => {
|
||||||
|
Object.keys(items).forEach(key => localStorage.setItem(key, items[key]))
|
||||||
|
}
|
||||||
|
const removeLSItems = (keys=[]) => {
|
||||||
|
keys.forEach(item => localStorage.removeItem(item))
|
||||||
|
}
|
||||||
|
const getLSItems = (keys=[]) => {
|
||||||
|
let items = {}
|
||||||
|
keys.forEach(key => items[key] = localStorage.getItem(key))
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
return {setLSItems, removeLSItems, getLSItems};
|
||||||
|
}
|
||||||
|
|
||||||
|
export { useLocalStorage}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { StrictMode } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import App from './App.jsx'
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')).render(
|
||||||
|
<StrictMode>
|
||||||
|
<App />
|
||||||
|
</StrictMode>,
|
||||||
|
)
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import styles from "./Homepage.module.scss";
|
||||||
|
|
||||||
|
const Homepage = () => {
|
||||||
|
return (
|
||||||
|
<main className={styles.homepage}>
|
||||||
|
<section>Homepage</section>
|
||||||
|
</main>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Homepage
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import styles from "./Login.module.scss";
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { useAuth } from "../../contexts/AuthContext";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { Form, Button } from "react-bootstrap";
|
||||||
|
|
||||||
|
const Login = () => {
|
||||||
|
const [email, setEmail] = useState("rob@test.com");
|
||||||
|
const [password, setPassword] = useState("password");
|
||||||
|
const { login, isAuthenticated, isLoading, error } = useAuth();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [validated, setValidated] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isAuthenticated) {
|
||||||
|
console.log({isAuthenticated})
|
||||||
|
navigate("/");
|
||||||
|
}
|
||||||
|
}, [isAuthenticated, navigate]);
|
||||||
|
|
||||||
|
function handleLogin(e) {
|
||||||
|
const form = e.currentTarget;
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
const valid = form.checkValidity();
|
||||||
|
setValidated(true);
|
||||||
|
if (valid) {
|
||||||
|
login(email, password);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateForm(key, value) {
|
||||||
|
setValidated(false);
|
||||||
|
if (key === "email") {
|
||||||
|
setEmail(value);
|
||||||
|
} else if (key === "password") {
|
||||||
|
setPassword(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className={styles.login}>
|
||||||
|
<Form className={styles.form} onSubmit={handleLogin}>
|
||||||
|
<Form.Group className={styles.formGroup}>
|
||||||
|
<Form.Label htmlFor="email">Email address</Form.Label>
|
||||||
|
<Form.Control
|
||||||
|
type="email"
|
||||||
|
id="email"
|
||||||
|
onChange={(e) => updateForm("email", e.target.value)}
|
||||||
|
value={email}
|
||||||
|
required
|
||||||
|
isInvalid={validated && error}
|
||||||
|
/>
|
||||||
|
<Form.Control.Feedback type="invalid" />
|
||||||
|
</Form.Group>
|
||||||
|
<Form.Group className={styles.formGroup}>
|
||||||
|
<Form.Label htmlFor="password">Password</Form.Label>
|
||||||
|
<Form.Control
|
||||||
|
type="password"
|
||||||
|
id="password"
|
||||||
|
onChange={(e) => updateForm("password", e.target.value)}
|
||||||
|
value={password}
|
||||||
|
required
|
||||||
|
isInvalid={validated && error}
|
||||||
|
/>
|
||||||
|
<Form.Control.Feedback type="invalid">
|
||||||
|
Invalid credentials
|
||||||
|
</Form.Control.Feedback>
|
||||||
|
</Form.Group>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
className={styles.btn}
|
||||||
|
disabled={isLoading}
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</Button>
|
||||||
|
</Form>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Login;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
.login {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
|
||||||
|
}
|
||||||
|
.form {
|
||||||
|
width: 240px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.formGroup {
|
||||||
|
margin: 20px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
float: right;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import styles from "./PageNotFound.module.scss";
|
||||||
|
|
||||||
|
export default function PageNotFound() {
|
||||||
|
return (
|
||||||
|
<main className={styles.pageNotFound}>
|
||||||
|
<h2>Page not found</h2>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
.pageNotFound {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { NavLink, Outlet } from 'react-router-dom'
|
||||||
|
import { useAuth } from '../contexts/AuthContext'
|
||||||
|
|
||||||
|
const ProtectedRoute = () => {
|
||||||
|
const { user } = useAuth()
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return (
|
||||||
|
<main style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
|
||||||
|
<div style={{textAlign: 'center'}}>
|
||||||
|
<h1>Unauthorized</h1>
|
||||||
|
<h5>
|
||||||
|
<span>
|
||||||
|
<NavLink to='/login' style={{color: 'white'}}>Login</NavLink> to gain access
|
||||||
|
</span>
|
||||||
|
</h5>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return <Outlet />
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ProtectedRoute
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
.app {
|
||||||
|
display: flex;
|
||||||
|
min-height: 100vh;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
padding: 20px;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
$primary: #09338e;
|
||||||
|
$body-bg: #222222;
|
||||||
|
$body-color: #dddddd;
|
||||||
|
$header-bg: #3b0c7e;
|
||||||
|
$light: #999999;
|
||||||
|
|
||||||
|
$theme-colors: (
|
||||||
|
"primary": $primary,
|
||||||
|
"light": $light,
|
||||||
|
"body-bg": $body-bg,
|
||||||
|
"body-color": $body-color,
|
||||||
|
"header-bg": $header-bg,
|
||||||
|
"footer-bg": $header-bg
|
||||||
|
);
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
@import 'node_modules/bootstrap/scss/functions';
|
||||||
|
@import 'node_modules/bootstrap/scss/variables';
|
||||||
|
@import 'node_modules/bootstrap/scss/mixins';
|
||||||
|
@import "./app.scss";
|
||||||
|
@import "./colors.scss";
|
||||||
|
@import "node_modules/bootstrap/scss/bootstrap";
|
||||||
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
server: {
|
||||||
|
proxy: { '/api': 'http://localhost:5000' }
|
||||||
|
},
|
||||||
|
plugins: [react()]
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user