Skip to content

Commit

Permalink
Synchronize all changes
Browse files Browse the repository at this point in the history
  • Loading branch information
killvont committed Nov 2, 2024
1 parent 6d3bef1 commit b97d682
Show file tree
Hide file tree
Showing 9 changed files with 262 additions and 34 deletions.
23 changes: 18 additions & 5 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_socketio import SocketIO
from app.config import Config

# Initialize the Flask app
# Initialize the Flask application
app = Flask(__name__)
app.config.from_object(Config)

# Initialize SocketIO
# Ensure essential configurations like SECRET_KEY are set
if not app.config.get('SECRET_KEY'):
raise RuntimeError("SECRET_KEY is not set in the configuration.")

# Initialize extensions
db = SQLAlchemy(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login' # Redirect to login view if not authenticated
socketio = SocketIO(app, cors_allowed_origins='*')

# Import routes and models
# Load application components
from app import routes, models

# SocketIO event example
# SocketIO events for real-time communication
@socketio.on('connect')
def handle_connect():
print('Client connected')
Expand All @@ -22,7 +31,11 @@ def handle_disconnect():
print('Client disconnected')

def run():
socketio.run(app, host='0.0.0.0', port=5000, debug=True)
if app.config.get('DEBUG'):
print("Running in debug mode")
else:
print("Running in production mode")
socketio.run(app, host=app.config.get('HOST', '0.0.0.0'), port=app.config.get('PORT', 5000))

if __name__ == '__main__':
run()
56 changes: 27 additions & 29 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
import requests
from flask import Flask, render_template, redirect, url_for, flash, request
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user
from flask_bcrypt import Bcrypt
from flask_socketio import SocketIO, emit

# Initialize the Flask application
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'your_default_secret_key') # Use environment variable
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///data/scam_detector.db') # Use environment variable
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'your_default_secret_key')
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(
'DATABASE_URL', 'sqlite:///data/scam_detector.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Initialize extensions
Expand All @@ -37,29 +38,25 @@ def register():
username = request.form['username']
email = request.form['email']
password = request.form['password']
captcha_response = request.form['g-recaptcha-response']
captcha_secret = os.environ.get('CAPTCHA_SECRET_KEY') # Store your secret key in environment variables
captcha_response = request.form.get('g-recaptcha-response', '')

# Validate CAPTCHA
if not validate_captcha(captcha_secret, captcha_response):
if not validate_captcha(captcha_response):
flash('CAPTCHA validation failed. Please try again.', 'danger')
return redirect(url_for('register'))

# Check for existing user
if User.query.filter_by(username=username).first():
flash('Username already exists. Please choose a different one.', 'danger')
return redirect(url_for('register'))

if User.query.filter_by(email=email).first():
flash('Email already registered. Please use a different one.', 'danger')
existing_user = User.query.filter((User.username == username) | (User.email == email)).first()
if existing_user:
flash('Username or email already taken. Please choose a different one.', 'danger')
return redirect(url_for('register'))

# Password strength check
if not validate_password_strength(password):
flash('Password must be at least 8 characters long and include at least one uppercase letter, one lowercase letter, and one digit.', 'danger')
flash('Password does not meet the required complexity.', 'danger')
return redirect(url_for('register'))

# Hash the password and create new user
# Hash the password and create a new user
hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
new_user = User(username=username, email=email, password_hash=hashed_password)
db.session.add(new_user)
Expand All @@ -69,24 +66,34 @@ def register():

return render_template('register.html')

def validate_captcha(secret, response):
def validate_captcha(response):
secret = os.environ.get('CAPTCHA_SECRET_KEY')
if not secret:
raise ValueError("CAPTCHA_SECRET_KEY not set in environment variables.")

verification = requests.post(
f'https://www.google.com/recaptcha/api/siteverify?secret={secret}&response={response}'
'https://www.google.com/recaptcha/api/siteverify',
data={'secret': secret, 'response': response}
)
return verification.json().get('success')
return verification.json().get('success', False)

def validate_password_strength(password):
return re.match(r'^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$', password)

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
user = User.query.filter_by(username=request.form['username']).first()
if user and bcrypt.check_password_hash(user.password_hash, request.form['password']):
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username).first()

if user and bcrypt.check_password_hash(user.password_hash, password):
login_user(user)
flash('Login successful!', 'success')
return redirect(url_for('index'))
flash('Login unsuccessful. Please check your username and password.', 'danger')

flash('Invalid username or password.', 'danger')

return render_template('login.html')

@app.route('/logout')
Expand All @@ -101,7 +108,6 @@ def logout():
def index():
return render_template('index.html')

# SocketIO events
@socketio.on('connect')
def handle_connect():
print('Client connected')
Expand All @@ -111,13 +117,5 @@ def handle_connect():
def handle_disconnect():
print('Client disconnected')

# Create the data directory if it doesn't exist
if not os.path.exists('data'):
os.makedirs('data')

# Create the database tables
with app.app_context():
db.create_all()

if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000, debug=True)
28 changes: 28 additions & 0 deletions data/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from flask import Flask
from flask_socketio import SocketIO
from app.config import Config

# Initialize the Flask app
app = Flask(__name__)
app.config.from_object(Config)

# Initialize SocketIO
socketio = SocketIO(app, cors_allowed_origins='*')

# Import routes and models
from app import routes, models

# SocketIO event example
@socketio.on('connect')
def handle_connect():
print('Client connected')

@socketio.on('disconnect')
def handle_disconnect():
print('Client disconnected')

def run():
socketio.run(app, host='0.0.0.0', port=5000, debug=True)

if __name__ == '__main__':
run()
Empty file added flask
Empty file.
1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Single-database configuration for Flask.
50 changes: 50 additions & 0 deletions migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -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
113 changes: 113 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -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()
24 changes: 24 additions & 0 deletions migrations/script.py.mako
Original file line number Diff line number Diff line change
@@ -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"}
1 change: 1 addition & 0 deletions scam-detector
Submodule scam-detector added at ee36bf

0 comments on commit b97d682

Please sign in to comment.