Skip to content

Commit

Permalink
Merge pull request #173 from codersforcauses/fix/backend-api-issues
Browse files Browse the repository at this point in the history
[PATCH] Fix backend API issues, refactor database, and improve structure
  • Loading branch information
yunho7687 authored Jul 28, 2024
2 parents 2d4b742 + 64e3a02 commit ccd6041
Show file tree
Hide file tree
Showing 25 changed files with 1,490 additions and 1,210 deletions.
6 changes: 3 additions & 3 deletions client/src/pages/sign-in.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default function SignIn() {
const router = useRouter();

const handleLogin = async (formData: FormData) => {
const username = formData.account;
const email = formData.account;
const password = formData.password;

setErrorMessage(null);
Expand All @@ -29,7 +29,7 @@ export default function SignIn() {
// }
try {
const response = await axios.post(LOGIN_URL, {
username,
email,
password,
});
const { token } = response.data;
Expand All @@ -45,7 +45,7 @@ export default function SignIn() {
console.error("Error response from server:", error.response.data);
console.error("Status code:", error.response.status);
// Handle specific error responses from the server
if (error.response.status === 401 || 400) {
if (error.response.status === 401 || error.response.status === 400) {
setErrorMessage("Invalid username or password. Please try again.");
// Show a message to the user or handle the error accordingly
} else if (error.response.status === 500) {
Expand Down
55 changes: 47 additions & 8 deletions server/api/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,17 @@
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from datetime import timedelta
import os
from pathlib import Path

from dotenv import load_dotenv
import django
from django.utils.translation import gettext

django.utils.translation.ugettext = gettext


load_dotenv()


Expand All @@ -26,16 +29,16 @@
FRONTEND_URL = os.environ.get("FRONTEND_URL")

# LOGGING
LOG_DIR = os.path.join(BASE_DIR, 'log')
LOG_FILE = '/api.log'
LOG_DIR = os.path.join(BASE_DIR, "log")
LOG_FILE = "/api.log"
LOG_PATH = LOG_DIR + LOG_FILE
if not os.path.exists(LOG_DIR):
os.mkdir(LOG_DIR)

if not os.path.exists(LOG_PATH):
f = open(LOG_PATH, 'a').close() # create empty log file
f = open(LOG_PATH, "a").close() # create empty log file
else:
f = open(LOG_PATH, 'w').close() # clear log file
f = open(LOG_PATH, "w").close() # clear log file


# Quick-start development settings - unsuitable for production
Expand All @@ -53,6 +56,8 @@
else []
)

AUTH_USER_MODEL = "app.Users"

CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True

Expand All @@ -68,11 +73,45 @@
"api.healthcheck",
"corsheaders",
"rest_framework",
"rest_framework_jwt",
"rest_framework_simplejwt",
"app",
'drf_yasg',
"drf_yasg",
]

REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework_simplejwt.authentication.JWTAuthentication",
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.BasicAuthentication",
),
"DEFAULT_PERMISSION_CLASSES": (
"rest_framework.permissions.IsAuthenticatedOrReadOnly",
),
}

SIMPLE_JWT = {
# Short-term access token lifetime
"ACCESS_TOKEN_LIFETIME": timedelta(hours=5),
# Long-term refresh token lifetime
"REFRESH_TOKEN_LIFETIME": timedelta(days=7),
# Rotate refresh tokens
"ROTATE_REFRESH_TOKENS": True,
# Blacklist old tokens after rotation
"BLACKLIST_AFTER_ROTATION": True,
# Signing algorithm
"ALGORITHM": "HS256",
# Secret key for signing tokens
"SIGNING_KEY": SECRET_KEY,
# Authentication header type
"AUTH_HEADER_TYPES": ("Bearer",),
# Authentication header name
"AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
# User ID field
"USER_ID_FIELD": "user_id",
# User ID claim in the token
"USER_ID_CLAIM": "user_id",
}

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
Expand Down Expand Up @@ -224,5 +263,5 @@


# This is where user uploaded file saved to
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
22 changes: 11 additions & 11 deletions server/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
schema_view = get_schema_view(
openapi.Info(
title="Snippets API",
default_version='v1',
default_version="v1",
description="Test description",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="contact@snippets.local"),
Expand All @@ -24,16 +24,16 @@
path("admin/", admin.site.urls),
path("api/healthcheck/", include(("api.healthcheck.urls"))),
path("api/app/", include("app.urls")),
path('swagger<format>/',
schema_view.without_ui(cache_timeout=0), name='schema-json'),
path('swagger/',
schema_view.with_ui('swagger',
cache_timeout=0), name='schema-swagger-ui'),
path('redoc/',
schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),

path(
"swagger<format>/", schema_view.without_ui(cache_timeout=0), name="schema-json"
),
path(
"swagger/",
schema_view.with_ui("swagger", cache_timeout=0),
name="schema-swagger-ui",
),
path("redoc/", schema_view.with_ui("redoc", cache_timeout=0), name="schema-redoc"),
]

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
2 changes: 1 addition & 1 deletion server/app/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
default_app_config = 'app.apps.AppConfig'
default_app_config = "app.apps.AppConfig"
110 changes: 90 additions & 20 deletions server/app/admin.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,84 @@
from django.contrib import admin
from .models import Users, Profiles, Tasks, Bids, Payments
from .models import Tasks, Bids, Payments
from django.contrib.auth.admin import UserAdmin

from .models import Users


# Users Table Interface
@admin.register(Users)
class UsersAdmin(admin.ModelAdmin):
list_display = ("user_id", "email", "mobile", "created_at",
"updated_at", "last_login", "status", "user_role")
list_filter = ("user_role", "status")
class UserAdminConfig(UserAdmin):
model = Users
list_display = (
"username",
"email",
"first_name",
"last_name",
)
list_filter = ("is_bidder", "is_poster")
search_fields = ("email", "mobile")
date_hierarchy = "created_at"
ordering = ("-created_at",)
fieldsets = (
(None, {"fields": ("username", "password")}),
("Personal info", {"fields": ("first_name", "last_name", "email", "mobile")}),
(
"Permissions",
{
"fields": (
"is_active",
"is_staff",
"is_superuser",
"groups",
"user_permissions",
)
},
),
("Important dates", {"fields": ("last_login", "date_joined")}),
)

add_fieldsets = (
(
None,
{
"classes": ("wide",),
"fields": (
"username",
"email",
"password1",
"password2",
"first_name",
"last_name",
"is_active",
"is_staff",
"is_bidder",
"is_superuser",
"groups",
"user_permissions",
),
},
),
)

# Profiles Table Interface
@admin.register(Profiles)
class ProfilesAdmin(admin.ModelAdmin):
list_display = ("profile_id", "user_id", "full_name", "avatar_url", "bio")
search_fields = ("full_name", )

# admin.site.register(Users, UserAdminConfig)

# Tasks Table Interface


@admin.register(Tasks)
class TasksAdmin(admin.ModelAdmin):
list_display = ("task_id", "owner_id", "title", "category",
"description", "location", "budget",
"estimated_time", "deadline", "status", "created_at",
"updated_at")
list_display = (
"task_id",
"poster_id",
"title",
"category",
"description",
"budget",
"estimated_time",
"deadline",
"created_at",
"updated_at",
)
list_filter = ("category", "status")
search_fields = ("title", "category", "description", "location")
date_hierarchy = "created_at"
Expand All @@ -36,17 +88,35 @@ class TasksAdmin(admin.ModelAdmin):
# Bids Table Interface
@admin.register(Bids)
class BidsAdmin(admin.ModelAdmin):
list_display = ("bid_id", "task_id", "bidder_id", "price", "message",
"status", "created_at", "updated_at")
list_display = (
"bid_id",
"task_id",
"bidder_id",
"price",
"message",
"status",
"created_at",
"updated_at",
)
list_filter = ("status", "task_id", "bidder_id")


# Payments Table Interface
@admin.register(Payments)
class PaymentsAdmin(admin.ModelAdmin):
list_display = ("payment_id", "task_id", "payer_id", "amount",
"payment_method", "status", "created_at")
list_filter = ("payment_method", "status", )
list_display = (
"payment_id",
"task_id",
"payer_id",
"amount",
"payment_method",
"status",
"created_at",
)
list_filter = (
"payment_method",
"status",
)
search_fields = ("payment_id", "task_id", "payer_id")
date_hierarchy = "created_at"
ordering = ("-created_at",)
1 change: 1 addition & 0 deletions server/app/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ class AppConfig(AppConfig):

def ready(self):
from .fixtures import create_mock_data

post_migrate.connect(create_mock_data, sender=self)
Loading

0 comments on commit ccd6041

Please sign in to comment.