Skip to content

Commit

Permalink
Merge pull request #202 from TheSecretOrganization/167-use-logger-in-…
Browse files Browse the repository at this point in the history
…ft_auth

logging auth actions
  • Loading branch information
antoineverin authored Oct 7, 2024
2 parents 9731ab6 + d155df9 commit 3b336b6
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
4 changes: 4 additions & 0 deletions django/src/ft_auth/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@
class FtAuthConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'ft_auth'

def ready(self) -> None:
from . import oauth
return super().ready()
10 changes: 9 additions & 1 deletion django/src/ft_auth/oauth.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from .models import FtOauth, User
import logging
from logging import getLogger
import os
import requests

logger = getLogger(__name__)

class RequestError(Exception):
def __init__(self, json, *args: object) -> None:
super().__init__(*args)
Expand All @@ -14,18 +16,22 @@ def get_ft(token):
})
res = req.json()
if req.status_code != 200:
logger.warning(f"Failed to fetch profile {res}")
raise RequestError(res, 'failed to gather user informations')
logger.debug(f"fetched profile for {res['login']}")
return res

def ft_register(token, username) -> FtOauth:
res = get_ft(token)
user = User.objects.create_user(username)
oauth = FtOauth.objects.create(ft_id=res['id'], login=res['login'], user=user)
logger.info(f"User {username} created for {res['login']}")
return oauth

def ft_oauth(token) -> FtOauth:
oauth = get_ft(token)
oauth = FtOauth.objects.get(ft_id=oauth['id'])
logger.info(f"got oauth link for {oauth.user.username} alias {oauth.login}")
return oauth

def get_token(code):
Expand All @@ -37,5 +43,7 @@ def get_token(code):
'redirect_uri': os.getenv('OAUTH_FALLBACK'),
})
if req.status_code != 200:
logger.debug('failed to fetch token')
raise RequestError(req.json(), 'failed to fetch token')
logger.debug('fetched token')
return req.json()['access_token']
10 changes: 10 additions & 0 deletions django/src/ft_auth/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,32 @@
from django.contrib.auth.password_validation import validate_password
from django.db.utils import IntegrityError
from django.core.exceptions import ValidationError
from logging import getLogger
from .oauth import get_token, ft_oauth, ft_register, RequestError
from .models import FtOauth
import json

logger = getLogger(__name__)

@require_POST
def login(request: HttpRequest):
data = json.loads(request.body.decode())
if not data or not all(k in data for k in ['username', 'password']):
return JsonResponse({'error': 'Missing fields (required username and password)'}, status=400)
user = authenticate(username=data['username'], password=data['password'])
if user is None:
logger.info(f"Tried to login to user {data['username']}")
return JsonResponse({'error': 'Wrong credentials'}, status=401)
dlogin(request, user)
logger.info(f"{user.username} logged in.")
return HttpResponse(status=200)

@require_GET
def logout(request: HttpRequest):
if request.user.is_authenticated:
username = request.user.username
dlogout(request)
logger.info(f"{username} logged out.")
return HttpResponse(status=200)
else:
return JsonResponse({'error': 'You\'re not logged in'}, status=401)
Expand All @@ -35,6 +42,7 @@ def register(request: HttpRequest):
try:
validate_password(data['password'])
get_user_model().objects.create_user(data['username'], data['password'])
logger.info(f"user '{data['username']}' created.")
except IntegrityError:
return JsonResponse({'error': 'Username already exist'}, status=400)
except ValidationError as error:
Expand All @@ -49,13 +57,15 @@ def password_update(request: HttpRequest):
if not request.user.is_authenticated:
return JsonResponse({'error': 'You must be authenticated to update password'}, status=401)
if not request.user.check_password(data['current_password']):
logger.info(f"Tried to update password of user {request.user.username}.")
return JsonResponse({'error': 'Invalid current password'}, status=400)
try:
validate_password(data['new_password'])
except ValidationError as error:
return JsonResponse({'error': error.messages}, status=400)
request.user.set_password(data['new_password'])
request.user.save()
logger.info(f"Updated password of {request.user.username}.")
return HttpResponse(status=200)

@require_POST
Expand Down

0 comments on commit 3b336b6

Please sign in to comment.