Skip to content

Commit 9bbf9a3

Browse files
committed
Fixed error with api handling duplicate usernames
1 parent f5ea159 commit 9bbf9a3

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

api/src/api/views.py

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,22 @@
1414
load_dotenv('./.env')
1515

1616

17+
def get_unique_username(base_username):
18+
username = base_username
19+
counter = 1
20+
while User.objects.filter(username=username).exists():
21+
username = f"{base_username}_{counter}"
22+
counter += 1
23+
return username
24+
25+
1726
@api_view(['POST'])
1827
def github_login(request):
1928
code = request.data.get('code')
2029
if not code:
2130
return Response({"error": "Missing code"}, status=status.HTTP_400_BAD_REQUEST)
2231

23-
# Wymiana kodu na token - tylko raz
32+
# 1. Exchange code for access_token
2433
token_res = requests.post(
2534
"https://github.com/login/oauth/access_token",
2635
headers={"Accept": "application/json"},
@@ -45,6 +54,7 @@ def github_login(request):
4554
"Accept": "application/vnd.github+json"
4655
}
4756

57+
# 2. Get user data from Github
4858
user_res = requests.get("https://api.github.com/user", headers=headers)
4959
email_res = requests.get(
5060
"https://api.github.com/user/emails", headers=headers)
@@ -60,14 +70,25 @@ def github_login(request):
6070
if not primary_email:
6171
return Response({"error": "No primary email found"}, status=status.HTTP_400_BAD_REQUEST)
6272

73+
# 3. Check if user exists
6374
user = User.objects.filter(email=primary_email).first()
64-
if not user:
65-
user = User.objects.create(
66-
email=primary_email,
67-
username=github_user.get("login", primary_email)
68-
)
75+
if user:
76+
# If exists refresh JWT
77+
refresh = RefreshToken.for_user(user)
78+
return Response({
79+
"access": str(refresh.access_token),
80+
"refresh": str(refresh),
81+
"user": UserSerializer(user).data
82+
}, status=200)
83+
84+
# 4. Create new user with unique username
85+
username = get_unique_username(github_user.get("login", primary_email))
86+
user = User.objects.create(
87+
email=primary_email,
88+
username=username
89+
)
6990

70-
# ZAWSZE wydajemy JWT
91+
# 5. Generate JWT
7192
refresh = RefreshToken.for_user(user)
7293
return Response({
7394
"access": str(refresh.access_token),

0 commit comments

Comments
 (0)