Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
{
"liveServer.settings.root": "front-end/",
"python.defaultInterpreterPath": "backend/.venv/bin/python"
"python.defaultInterpreterPath": "backend/.venv/bin/python",
"python-envs.defaultEnvManager": "ms-python.python:system",
"python-envs.pythonProjects": []
}
4 changes: 2 additions & 2 deletions backend/data/blooms.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Bloom:
def add_bloom(*, sender: User, content: str) -> Bloom:
hashtags = [word[1:] for word in content.split(" ") if word.startswith("#")]

now = datetime.datetime.now(tz=datetime.UTC)
now = datetime.datetime.now(tz=datetime.timezone.utc)
bloom_id = int(now.timestamp() * 1000000)
with db_cursor() as cur:
cur.execute(
Expand All @@ -27,7 +27,7 @@ def add_bloom(*, sender: User, content: str) -> Bloom:
bloom_id=bloom_id,
sender_id=sender.id,
content=content,
timestamp=datetime.datetime.now(datetime.UTC),
timestamp=datetime.datetime.now(datetime.timezone.utc),
),
)
for hashtag in hashtags:
Expand Down
15 changes: 13 additions & 2 deletions backend/data/users.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
from dataclasses import dataclass
from hashlib import scrypt
import hashlib
import random
import string
from typing import List, Optional

try:
from hashlib import scrypt as _scrypt_impl
USE_HASHLIB_SCRYPT = True
except ImportError:
import scrypt as _scrypt_module
USE_HASHLIB_SCRYPT = False

from data.connection import db_cursor
from psycopg2.errors import UniqueViolation

Expand Down Expand Up @@ -91,7 +97,12 @@ def register_user(username: str, password_plaintext: str) -> User:


def scrypt(password_plaintext: bytes, password_salt: bytes) -> bytes:
return hashlib.scrypt(password_plaintext, salt=password_salt, n=8, r=8, p=1)
if USE_HASHLIB_SCRYPT:
# Python 3.11+ hashlib.scrypt
return _scrypt_impl(password_plaintext, salt=password_salt, n=8, r=8, p=1)
else:
# Python 3.9 scrypt package
return _scrypt_module.hash(password_plaintext, password_salt, N=8, r=8, p=1)


SALT_CHARACTERS = string.ascii_uppercase + string.ascii_lowercase + string.digits
Expand Down
41 changes: 27 additions & 14 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
)

from dotenv import load_dotenv
from flask import Flask
from flask import Flask, jsonify
from flask_cors import CORS
from flask_jwt_extended import JWTManager

Expand All @@ -32,34 +32,47 @@ def main():
# Configure CORS to handle preflight requests
CORS(
app,
resources={r"/*": {"origins": "*"}},
supports_credentials=True,
resources={
r"/*": {
"origins": "*",
"allow_headers": ["Content-Type", "Authorization"],
"methods": ["GET", "POST", "OPTIONS"],
}
},
allow_headers=["Content-Type", "Authorization"],
methods=["GET", "POST", "OPTIONS"]
)

app.config["JWT_SECRET_KEY"] = os.environ["JWT_SECRET_KEY"]
jwt = JWTManager(app)
jwt.user_lookup_loader(lookup_user)

# JWT error handlers
@app.errorhandler(422)
def handle_unprocessable_entity(e):
return jsonify({"success": False, "message": "Invalid or missing authentication token"}), 401

@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
return jsonify({"success": False, "message": "Token has expired"}), 401

@jwt.invalid_token_loader
def invalid_token_callback(error):
return jsonify({"success": False, "message": "Invalid token"}), 401

@jwt.unauthorized_loader
def missing_authorization_callback(error):
return jsonify({"success": False, "message": "Missing authorization token"}), 401

app.add_url_rule("/register", methods=["POST"], view_func=register)
app.add_url_rule("/login", methods=["POST"], view_func=login)

app.add_url_rule("/home", view_func=home_timeline)
app.add_url_rule("/home", methods=["GET"], view_func=home_timeline)

app.add_url_rule("/profile", view_func=self_profile)
app.add_url_rule("/profile/<profile_username>", view_func=other_profile)
app.add_url_rule("/profile", methods=["GET"], view_func=self_profile)
app.add_url_rule("/profile/<profile_username>", methods=["GET"], view_func=other_profile)
app.add_url_rule("/follow", methods=["POST"], view_func=do_follow)
app.add_url_rule("/suggested-follows/<limit_str>", view_func=suggested_follows)
app.add_url_rule("/suggested-follows/<limit_str>", methods=["GET"], view_func=suggested_follows)

app.add_url_rule("/bloom", methods=["POST"], view_func=send_bloom)
app.add_url_rule("/bloom/<id_str>", methods=["GET"], view_func=get_bloom)
app.add_url_rule("/blooms/<profile_username>", view_func=user_blooms)
app.add_url_rule("/hashtag/<hashtag>", view_func=hashtag)
app.add_url_rule("/blooms/<profile_username>", methods=["GET"], view_func=user_blooms)
app.add_url_rule("/hashtag/<hashtag>", methods=["GET"], view_func=hashtag)

app.run(host="0.0.0.0", port="3000", debug=True)

Expand Down
6 changes: 6 additions & 0 deletions db/schema.sql
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@

DROP TABLE IF EXISTS hashtags;
DROP TABLE IF EXISTS follows;
DROP TABLE IF EXISTS blooms;
DROP TABLE IF EXISTS users;

CREATE TABLE users (
id SERIAL PRIMARY KEY,
username VARCHAR NOT NULL,
Expand Down
2 changes: 1 addition & 1 deletion front-end/components/bloom.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const createBloom = (template, bloom) => {
function _formatHashtags(text) {
if (!text) return text;
return text.replace(
/\B#[^#]+/g,
/#\w+/g,
(match) => `<a href="/hashtag/${match.slice(1)}">${match}</a>`
);
}
Expand Down
7 changes: 5 additions & 2 deletions front-end/lib/api.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,13 @@ async function _apiRequest(endpoint, options = {}) {
if (!endpoint.includes("/login") && !endpoint.includes("/register")) {
state.destroyState();
}
if (!endpoint.includes("/profile")) {
handleErrorDialog(error);
}
} else {
handleErrorDialog(error);
}

// Pass all errors forward to a dialog on the screen
handleErrorDialog(error);
throw error;
}

Expand Down