Skip to content

Commit

Permalink
Merge pull request #118 from HE-Arc/mbu-50-edit-routes-to-make-use-of…
Browse files Browse the repository at this point in the history
…-the-users-account

Mbu 50 edit routes to make use of the users account
  • Loading branch information
maelys-buhler authored Apr 17, 2024
2 parents b9b10ca + 084e286 commit dbad49a
Show file tree
Hide file tree
Showing 19 changed files with 214 additions and 162 deletions.
16 changes: 14 additions & 2 deletions api/masteriq/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,19 @@
DEBUG = bool(strtobool(os.getenv('DEBUG')))

ALLOWED_HOSTS = [
os.getenv('BACKEND_HOST')
os.getenv('BACKEND_HOST'),
]

CORS_ALLOWED_ORIGINS = [
os.getenv('FRONTEND_URL'),
os.getenv('BACKEND_URL'),
]

CSRF_TRUSTED_ORIGINS = [
os.getenv('FRONTEND_URL'),
os.getenv('BACKEND_URL'),
]

CORS_ALLOW_CREDENTIALS = True

# Application definition
Expand All @@ -49,9 +54,10 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'masteriqapp',
'rest_framework',
"corsheaders",

]

MIDDLEWARE = [
Expand Down Expand Up @@ -155,5 +161,11 @@
IMAGES_FOLDER = os.path.join('data', 'images')
DEFAULT_IMAGE = "default.jpeg"

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}

AUTH_USER_MODEL='masteriqapp.CustomUser'
# end of file
3 changes: 3 additions & 0 deletions api/masteriqapp/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from masteriqapp.models import CustomUser

# Register your models here.
admin.site.register(CustomUser, UserAdmin)
49 changes: 42 additions & 7 deletions api/masteriqapp/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# Generated by Django 5.0.2 on 2024-03-01 12:31
# Generated by Django 5.0.2 on 2024-04-06 15:02

import django.contrib.auth.models
import django.contrib.auth.validators
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models

Expand All @@ -10,7 +13,7 @@ class Migration(migrations.Migration):
initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('auth', '0012_alter_user_first_name_max_length'),
]

operations = [
Expand All @@ -19,10 +22,37 @@ class Migration(migrations.Migration):
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('image_path', models.CharField(default='data\\images\\default.jpeg', max_length=255)),
],
),
migrations.CreateModel(
name='Iq',
name='CustomUser',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='IQ',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('iq', models.IntegerField()),
Expand All @@ -33,23 +63,28 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='category',
name='users',
field=models.ManyToManyField(through='masteriqapp.Iq', to=settings.AUTH_USER_MODEL),
field=models.ManyToManyField(through='masteriqapp.IQ', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='customuser',
name='iqs',
field=models.ManyToManyField(through='masteriqapp.IQ', to=settings.AUTH_USER_MODEL),
),
migrations.CreateModel(
name='Question',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.CharField(max_length=255)),
('text', models.CharField(max_length=1024)),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='masteriqapp.category')),
],
),
migrations.CreateModel(
name='Option',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.CharField(max_length=255)),
('text', models.CharField(max_length=1024)),
('is_correct', models.BooleanField()),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='masteriqapp.question')),
('question', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='options', to='masteriqapp.question')),
],
),
]
28 changes: 23 additions & 5 deletions api/masteriqapp/migrations/0002_auto_20240303_1147.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Generated by Django 5.0.2 on 2024-03-03 10:47
import glob

from django.db import migrations
from django.conf import settings
Expand All @@ -25,20 +26,37 @@ def load_initial_data(apps, schema_editor):
continue
question = question_model.objects.create(text=df['Questions'][row], category=category)
right_option_text = df['Correct'][row]
option_model.objects.create(text=right_option_text, is_correct=True, question=question)

for letter in ['A', 'B', 'C', 'D']:
if pd.isnull(df[letter][row]) or df[letter][row] == right_option_text:
if pd.isnull(df[letter][row]):
continue
option_model.objects.create(text=df[letter][row], is_correct=False, question=question)
if df[letter][row] == right_option_text:
option_model.objects.create(text=right_option_text, is_correct=True, question=question)
else:
option_model.objects.create(text=df[letter][row], is_correct=False, question=question)
print("Initial data loaded!")

def add_community_category(apps, schema_editor):
category_model = apps.get_model('masteriqapp', 'Category')
category_model.objects.create(name="Community", image_path='data\\images\\community.jpg')
def add_category_images(apps, schema_editor):
category_model = apps.get_model('masteriqapp', 'Category')

for category in category_model.objects.all():
directory = settings.IMAGES_FOLDER
img_name = category.name.lower().replace(' ', '_') + ".*"
f = os.path.join(directory, img_name)
files = glob.glob(f)
if len(files) > 0:
category.image_path = os.path.join(files[0])
category.save()
class Migration(migrations.Migration):
dependencies = [
('masteriqapp', '0003_alter_category_users'),
('masteriqapp', '0001_initial'),
]

operations = [
migrations.RunPython(load_initial_data)
migrations.RunPython(load_initial_data),
migrations.RunPython(add_community_category),
migrations.RunPython(add_category_images)
]
20 changes: 0 additions & 20 deletions api/masteriqapp/migrations/0003_alter_category_users.py

This file was deleted.

29 changes: 0 additions & 29 deletions api/masteriqapp/migrations/0004_auto_20240308_0923.py

This file was deleted.

17 changes: 0 additions & 17 deletions api/masteriqapp/migrations/0005_auto_20240314_1738.py

This file was deleted.

20 changes: 0 additions & 20 deletions api/masteriqapp/migrations/0005_category_image_path.py

This file was deleted.

This file was deleted.

7 changes: 7 additions & 0 deletions api/masteriqapp/models/CustomUser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.conf import settings


class CustomUser(AbstractUser):
iqs = models.ManyToManyField(settings.AUTH_USER_MODEL, through="IQ")
2 changes: 1 addition & 1 deletion api/masteriqapp/models/IQ.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

class IQManager(models.Manager):
def get_best_players_of_category(self, category, nb_players=10):
return self.filter(category=category).order_by('iq')[:nb_players]
return self.filter(category=category).order_by('-iq')[:nb_players]

def get_all_iq_of_user(self, user):
return self.filter(user=user).values("iq", "category")
Expand Down
1 change: 1 addition & 0 deletions api/masteriqapp/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
from .IQ import IQ
from .Question import Question
from .Option import Option
from .CustomUser import CustomUser
8 changes: 4 additions & 4 deletions api/masteriqapp/tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from django.contrib.auth import get_user_model
from django.test import TestCase
import django.apps

from masteriqapp.models import Category
from masteriqapp.models import IQ
from masteriqapp.models import Question
from masteriqapp.models import Option
from django.contrib.auth.models import User


class ModelTestCases(TestCase):
Expand All @@ -24,20 +24,20 @@ def test_use_model(self):
option_1 = Option.objects.create(text="Yes", is_correct=False, question=question_test)
option_2 = Option.objects.create(text="No", is_correct=True, question=question_test)

user_test = User.objects.create_user("test", "[email protected]", "password")
user_test = get_user_model().objects.create_user("test", "[email protected]", "password")

iq_test = IQ.objects.create(user=user_test, category=category_test, iq=100)

assert Category.objects.get(id=category_test.id).name == category_test.name
assert Question.objects.get(id=question_test.id).text == question_test.text
assert Option.objects.get(id=option_1.id).text == option_1.text
assert len(Option.objects.filter(question=question_test)) == 2
assert User.objects.get(id=user_test.id).username == user_test.username
assert get_user_model().objects.get(id=user_test.id).username == user_test.username
assert len(IQ.objects.filter(user=user_test, category=category_test)) == 1

def test_use_manager(self):
category_test = Category.objects.create(name="test_managers")
user_test = User.objects.create_user("test_managers", "[email protected]", "password")
user_test = get_user_model().objects.create_user("test_managers", "[email protected]", "password")
iq_test = IQ.objects.create(user=user_test, category=category_test, iq = 102)

leaderboard = IQ.objects.get_best_players_of_category(category=category_test)
Expand Down
4 changes: 4 additions & 0 deletions api/masteriqapp/tests/test_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
class RouteTestCases(TestCase):
def test_route(self):
c = Client()

response = c.post("/api/user/signup/", {"username":"test", "password":"test"})
assert response.status_code == 201

response = c.get("/api/category/1/image/")
assert response.status_code == 200

Expand Down
Loading

0 comments on commit dbad49a

Please sign in to comment.