Skip to content
Open

Main #86

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
072817d
READ ME 업데이트
youngkwangjoo Aug 2, 2024
8be7a24
READ ME 업데이트
youngkwangjoo Aug 2, 2024
e200691
<REFACTOR> docker-compose.yml
dayeonkimm Aug 4, 2024
95db2c6
<REFACTOR> Dockerfile
dayeonkimm Aug 4, 2024
d207fdb
<REFACTOR> cors setting
dayeonkimm Aug 4, 2024
605a1e1
<REFACTOR> isort, black
dayeonkimm Aug 4, 2024
6776c32
<FEAT> 깃허브 커밋에 따른 감자 획득
dayeonkimm Aug 4, 2024
b571aac
<FEAT> 레벨업에 따른 감자 획득
dayeonkimm Aug 4, 2024
a704b24
<REFACTOR> 깃허브 api 수정
dayeonkimm Aug 4, 2024
25c8f49
<REFACTOR> permission_classes = [AllowAny] 추가
dayeonkimm Aug 4, 2024
7ff0a43
<REFACTOR> potato_id -> potato_type_id
dayeonkimm Aug 4, 2024
21b5058
<COMMENT> 주석 삭제
dayeonkimm Aug 4, 2024
71ec364
<REFACTOR> 변수이름 수정
dayeonkimm Aug 4, 2024
796d1aa
<REFACTOR> 감자레벨 디폴트 0 -> 1
dayeonkimm Aug 4, 2024
652b837
<REFACTOR> api 수정
dayeonkimm Aug 4, 2024
4b59ebc
<REFACTOR> 리디렉션 url 수정
dayeonkimm Aug 4, 2024
30e930f
Merge branch 'database' into feat/database_edit
dayeonkimm Aug 4, 2024
e6ea7b7
Merge pull request #85 from OZ-Coding-School/feat/database_edit
dayeonkimm Aug 4, 2024
24b6cd3
Update docker-compose.yml
dayeonkimm Aug 4, 2024
f01d057
<REFACTOR> csrf 설정 제거
dayeonkimm Aug 4, 2024
c42874b
Update readme.md
youngkwangjoo Aug 5, 2024
56cc71a
Merge branch 'develop' into main
youngkwangjoo Aug 5, 2024
ae196e1
<REFACTOR> 최종 main 수정
dayeonkimm Aug 12, 2024
a3a97df
Merge branch 'database' into feat/main_edit
dayeonkimm Aug 12, 2024
32bb6f8
Merge pull request #87 from OZ-Coding-School/feat/main_edit
dayeonkimm Aug 12, 2024
9498333
Merge branch 'main' into database
dayeonkimm Aug 12, 2024
f1e1244
Merge pull request #88 from OZ-Coding-School/database
dayeonkimm Aug 12, 2024
6faa749
Update readme.md
dayeonkimm Aug 12, 2024
a3a7ee1
Merge pull request #89 from OZ-Coding-School/dayeonkimm-patch-2
dayeonkimm Aug 12, 2024
5bf4e77
시그널 수정
dayeonkimm Sep 20, 2024
f409e28
isort, black
dayeonkimm Sep 20, 2024
dde905c
Merge pull request #90 from OZ-Coding-School/hotfix/edit_signals
dayeonkimm Sep 20, 2024
e6bc189
오류 수정
dayeonkimm Sep 20, 2024
d8e7a27
Merge pull request #91 from OZ-Coding-School/hotfix/edit_todos
dayeonkimm Sep 20, 2024
1576df9
오류 수정
dayeonkimm Sep 20, 2024
d92a743
Merge pull request #92 from OZ-Coding-School/hotfix/edit_errors
dayeonkimm Sep 20, 2024
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
40 changes: 20 additions & 20 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,35 +13,34 @@ ENV PYTHONUNBUFFERED 1
# 로컬 파일 시스템의 requirements.txt 파일을 컨테이너의 /tmp/requirements.txt로 복사합니다.
# 이 파일은 필요한 Python 패키지들을 명시합니다.
COPY ./requirements.txt /tmp/requirements.txt
COPY ./requirements.dev.txt /tmp/requirements.dev.txt
COPY ./potato_project /app
WORKDIR /app
EXPOSE 8000

ARG DEV=false

RUN python -m venv /py && \
/py/bin/pip install --upgrade pip && \
/py/bin/pip install -r /tmp/requirements.txt && \
apk add --update --no-cache postgresql-client jpeg-dev && \
apk add --update --no-cache --virtual .tmp-build-deps \
build-base postgresql-dev musl-dev zlib zlib-dev linux-headers && \
if [ $DEV = "true" ]; \
then /py/bin/pip install -r /tmp/requirements.dev.txt ; \
fi && \
rm -rf /tmp && \
apk del .tmp-build-deps && \
adduser \
--disabled-password \
--no-create-home \
django-user
# 가상 환경 설정 및 패키지 설치
RUN python -m venv /py
RUN /py/bin/pip install --upgrade pip
RUN /py/bin/pip install --no-cache-dir -r /tmp/requirements.txt

# 시스템 패키지 설치
RUN apk add --update --no-cache jpeg-dev
RUN apk add --update --no-cache --virtual .tmp-build-deps \
build-base musl-dev zlib zlib-dev linux-headers \
&& apk del .tmp-build-deps

# django-user 생성 및 권한 설정
RUN if ! getent passwd django-user; then adduser -D django-user; fi
USER root
RUN chown -R django-user:django-user /py/lib/python3.11/site-packages
USER django-user

# 추가 패키지 설치
ENV PATH="/py/bin:$PATH"
RUN /py/bin/pip install --no-cache-dir pytest pytest-django django-cors-headers

USER django-user

# 이 명령어를 추가하여 pytest를 설치합니다.
RUN /py/bin/pip install pytest pytest-django


# 개발용
Expand Down Expand Up @@ -88,4 +87,5 @@ RUN /py/bin/pip install pytest pytest-django
# USER django-user

# # 이 명령어를 추가하여 pytest를 설치합니다.
# RUN /py/bin/pip install pytest pytest-django
# RUN /py/bin/pip install pytest pytest-django

26 changes: 6 additions & 20 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,13 @@ services:
python manage.py migrate &&
python manage.py runserver --noreload 0.0.0.0:8000"
environment:
- DB_HOST=${DB_HOST}
- DB_NAME=${DB_NAME}
- DB_USER=${DB_USER}
- DB_PASSWORD=${DB_PASSWORD}
- DB_HOST=${RDS_HOSTNAME}
- DB_NAME=${RDS_DB_NAME}
- DB_USER=${RDS_USERNAME}
- DB_PASSWORD=${RDS_PASSWORD}
- PYDEVD_DISABLE_FILE_VALIDATION=1
env_file:
- .env

- .env

# 개발용

Expand Down Expand Up @@ -56,7 +55,7 @@ services:
# - .env
# depends_on:
# - db


# db: # PostgreSQL Database
# image: postgres:16-alpine
Expand All @@ -68,16 +67,3 @@ services:
# - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
# env_file:
# - .env



db: # PostgreSQL Database
image: postgres:16-alpine
volumes:
- ./data/db:/var/lib/postgresql/data
environment:
- POSTGRES_DB=${POSTGRES_DB}
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
env_file:
- .env
57 changes: 54 additions & 3 deletions potato_project/app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,10 @@
"allauth.account",
"allauth.socialaccount",
"allauth.socialaccount.providers.github",
"corsheaders",
]


INSTALLED_APPS = DJANGO_SYSTEM_APPS + CUSTOM_USER_APPS

# Custom user model
Expand All @@ -71,6 +73,7 @@

# 미들웨어 설정
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware",
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
Expand Down Expand Up @@ -115,6 +118,9 @@
"USER": os.environ.get("RDS_USERNAME"),
"PASSWORD": os.environ.get("RDS_PASSWORD"),
"PORT": os.environ.get("RDS_PORT", 5432),
"OPTIONS": {
"client_encoding": "UTF8", # UTF-8 문자셋 설정
},
}
}

Expand Down Expand Up @@ -205,6 +211,51 @@
}
}

SOCIALACCOUNT_LOGIN_ON_GET = True
LOGIN_REDIRECT_URL = "/oauth-callback/"
ACCOUNT_LOGOUT_REDIRECT_URL = "/landing/"
SOCIALACCOUNT_LOGIN_ON_GET = False
# LOGIN_REDIRECT_URL = "/oauth-callback/"
# ACCOUNT_LOGOUT_REDIRECT_URL = "/landing/"

DEFAULT_CHARSET = "utf-8"

LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {
"class": "logging.StreamHandler",
},
},
"root": {
"handlers": ["console"],
"level": "DEBUG",
},
}

# CORS_ORIGIN_WHITELIST = ['http://localhost:5173', 'http://127.0.0.1:5173', 'https://www.gitpotatoes.com',] # 특정 Origin만 허용
CORS_ALLOWED_ORIGINS = [
"https://www.gitpotatoes.com", # 실제 배포 프론트엔드 URL
# 'http://localhost:5173', # 프론트엔드 로컬 서버 URL
# 'http://127.0.0.1:5173', # 프론트엔드 로컬 서버 URL
]
CORS_ALLOW_CREDENTIALS = True # 쿠키 등 credential 정보 허용
CORS_ALLOW_METHODS = [
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
]
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

8 changes: 6 additions & 2 deletions potato_project/attendances/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ def increment(self, request):
# 출석날짜가 오늘이면 이미 출석함을 반환
attendance = self.get_user_attendance(user)
if attendance and attendance.date == today:
return Response({"오늘은 출석을 이미 하셨어요!"}, status=status.HTTP_400_BAD_REQUEST)
return Response(
{"오늘은 출석을 이미 하셨어요!"}, status=status.HTTP_400_BAD_REQUEST
)

# 새로운 출석 기록 생성
new_attendance = Attendance.objects.create(
Expand Down Expand Up @@ -71,4 +73,6 @@ def decrement(self, request):
user.save()

# 성공 응답 반환
return Response({"message": "물건을 구매했습니다.", "total_coins": user.total_coins})
return Response(
{"message": "물건을 구매했습니다.", "total_coins": user.total_coins}
)
3 changes: 3 additions & 0 deletions potato_project/githubs/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
class GithubsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "githubs"

def ready(self):
import githubs.signals
2 changes: 1 addition & 1 deletion potato_project/githubs/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
class Github(TimeStampedModel):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="User_id")
commit_num = models.BigIntegerField(verbose_name="Commit Number")
date = models.DateField(default=timezone.now)
date = models.DateField()

def __str__(self):
return f"{self.date}-{self.commit_num}"
150 changes: 150 additions & 0 deletions potato_project/githubs/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
from datetime import date, timedelta

from django.db.models.signals import post_save
from django.dispatch import receiver
from githubs.models import Github
from potatoes.models import Potato


@receiver(post_save, sender=Github)
def get_winter_potato(sender, instance, **kwargs):
# 새 Github 데이터가 생성 or 업데이트, 날짜가 크리스마스이며, commit_num이 >
if (
instance.commit_num >= 1
and instance.date.month == 12
and instance.date.day == 25
): # 월과 일만 비교
try:
# potato_type_id=6인 감자 조회
potato = Potato.objects.get(user=instance.user, potato_type_id=6)
if not potato.is_acquired: # 이미 획득한 경우에는 변경하지 않음
potato.is_acquired = True
potato.save()
except Potato.DoesNotExist:
# 해당 감자가 없는 경우 에러 처리 (필요에 따라 추가)
pass


@receiver(post_save, sender=Github)
def get_ghost_potato(sender, instance, **kwargs):
if (
instance.commit_num >= 1
and instance.date.month == 10
and instance.date.day == 31
):
try:
potato = Potato.objects.get(user=instance.user, potato_type_id=7)
if not potato.is_acquired:
potato.is_acquired = True
potato.save()
except Potato.DoesNotExist:
pass


@receiver(post_save, sender=Github)
def get_crystal_potato(sender, instance, **kwargs):
if instance.commit_num >= 1:
# 30일 전 날짜 계산
thirty_days_ago = instance.date - timedelta(days=30)

# 30일치 데이터가 있는지 확인
oldest_record = (
Github.objects.filter(user=instance.user).order_by("date").first()
)
if oldest_record and (instance.date - oldest_record.date).days >= 30:
# 30일 연속 커밋 여부 확인
commits_in_30_days = (
Github.objects.filter(
user=instance.user,
date__gte=thirty_days_ago,
date__lte=instance.date,
commit_num__gte=1,
)
.values("date")
.distinct()
.count()
)

if commits_in_30_days == 30:
try:
potato = Potato.objects.get(user=instance.user, potato_type_id=8)
if not potato.is_acquired:
potato.is_acquired = True
potato.save()
except Potato.DoesNotExist:
pass
else:
# 30일치 데이터가 없는 경우 로그 남기기 또는 다른 처리
print(
f"Not enough data for user {instance.user.id}. Oldest record date: {oldest_record.date if oldest_record else 'No records'}"
)


@receiver(post_save, sender=Github)
def get_dirty_potato(sender, instance, **kwargs):
if instance.commit_num == 0:
# 30일 전 날짜 계산
thirty_days_ago = instance.date - timedelta(days=30)

# 30일치 데이터가 있는지 확인
oldest_record = (
Github.objects.filter(user=instance.user).order_by("date").first()
)
if oldest_record and (instance.date - oldest_record.date).days >= 30:
# 30일 동안 커밋이 있었는지 확인
any_commits_in_30_days = Github.objects.filter(
user=instance.user,
date__gte=thirty_days_ago,
date__lte=instance.date,
commit_num__gte=1,
).exists()

if not any_commits_in_30_days:
# 30일 연속 커밋이 없는 경우 감자 아이디 9 획득 로직 실행
try:
potato = Potato.objects.get(user=instance.user, potato_type_id=9)
if not potato.is_acquired:
potato.is_acquired = True
potato.save()
except Potato.DoesNotExist:
pass # 필요에 따라 에러 처리 추가
else:
# 30일치 데이터가 없는 경우 로그 남기기 또는 다른 처리
print(
f"Not enough data for user {instance.user.id}. Oldest record date: {oldest_record.date if oldest_record else 'No records'}"
)


@receiver(post_save, sender=Github)
def get_green_potato(sender, instance, **kwargs):
if instance.commit_num == 0:
# 90일 전 날짜 계산
ninety_days_ago = instance.date - timedelta(days=90)

# 90일치 데이터가 있는지 확인
oldest_record = (
Github.objects.filter(user=instance.user).order_by("date").first()
)
if oldest_record and (instance.date - oldest_record.date).days >= 90:
# 90일 동안 커밋이 있었는지 확인
any_commits_in_90_days = Github.objects.filter(
user=instance.user,
date__gte=ninety_days_ago,
date__lte=instance.date,
commit_num__gte=1,
).exists()

if not any_commits_in_90_days:
# 90일 연속 커밋이 없는 경우 감자 아이디 10 획득 로직 실행
try:
potato = Potato.objects.get(user=instance.user, potato_type_id=10)
if not potato.is_acquired:
potato.is_acquired = True
potato.save()
except Potato.DoesNotExist:
pass # 필요에 따라 에러 처리 추가
else:
# 90일치 데이터가 없는 경우 로그 남기기 또는 다른 처리
print(
f"Not enough data for user {instance.user.id}. Oldest record date: {oldest_record.date if oldest_record else 'No records'}"
)
Loading