Skip to content

Commit

Permalink
Merge pull request #45 from Build-Squad/twitter-bug-fix
Browse files Browse the repository at this point in the history
Fix: Twitter authentication bug.
  • Loading branch information
varsha1305nav authored Dec 19, 2023
2 parents 15af05e + e26c314 commit d8f8f53
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 107 deletions.
185 changes: 80 additions & 105 deletions src/api/marketplace/marketplace/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,6 @@
client_secret=config("CLIENT_SECRET"),
)


# Apply these authentication class wherever JWT authentication is necessary.


def logoutUser(request):
response = HttpResponse("Token Deleted")
response = JWTOperations.deleteJwtToken(res=response, cookie_name="jwt")
Expand All @@ -45,27 +41,7 @@ def logoutUser(request):

def authTwitterUser(request):
auth_url = oauth2_user_handler.get_authorization_url()
html_content = f"""
<html>
<body>
<h1>Hello, Django!</h1>
<button onclick="sendRequest('{auth_url}')">Send Request</button>
<script>
function sendRequest(url) {{
// You can use the Fetch API or other methods to send a request
// For simplicity, I'm using window.location.href to simulate a redirect
window.location.href = url;
}}
</script>
</body>
</html>
"""

# Return the HTML content using HttpResponse
return HttpResponse(html_content, content_type="text/html")

return JsonResponse({"auth_url": auth_url})

return HttpResponseRedirect(auth_url)

def twitterLoginCallback(request):
authorization_response_url = request.build_absolute_uri()
Expand All @@ -88,88 +64,87 @@ def twitterLoginCallback(request):
"url",
],
).data
return HttpResponse(userData.name)
# existing_user = TwitterAccount.objects.filter(twitter_id=userData.id).first()

# if existing_user is None:
# newUser = TwitterAccount.objects.create(
# twitter_id=userData.id,
# name=userData.name,
# user_name=userData.username,
# access_token=access_token,
# description=userData.description,
# profile_image_url=userData.profile_image_url,
# followers_count=userData.public_metrics["followers_count"],
# following_count=userData.public_metrics["following_count"],
# tweet_count=userData.public_metrics["tweet_count"],
# listed_count=userData.public_metrics["listed_count"],
# verified=userData.verified,
# joined_at=userData.created_at,
# location=userData.location,
# url=userData.url,
# )

# newUser.save()
# else:
# existing_user.access_token = access_token
# # Update the user data
# existing_user.name = userData.name
# existing_user.user_name = userData.username
# existing_user.description = userData.description
# existing_user.profile_image_url = userData.profile_image_url
# existing_user.followers_count = userData.public_metrics["followers_count"]
# existing_user.following_count = userData.public_metrics["following_count"]
# existing_user.tweet_count = userData.public_metrics["tweet_count"]
# existing_user.listed_count = userData.public_metrics["listed_count"]
# existing_user.verified = userData.verified
# existing_user.joined_at = userData.created_at
# existing_user.location = userData.location
# existing_user.url = userData.url
# existing_user.save()

# current_twitter_user = TwitterAccount.objects.filter(
# twitter_id=userData.id
# ).first()
# existing_user_account = User.objects.filter(
# twitter_account=current_twitter_user
# ).first()

# if existing_user_account is None:
# new_user_account = User.objects.create(
# username=userData.username,
# first_name=userData.name,
# twitter_account_id=current_twitter_user.id,
# role=Role.objects.filter(name="influencer").first(),
# )
# new_user_account.save()
# else:
# existing_user_account.last_login = datetime.datetime.now()
# existing_user_account.save()

# current_user = User.objects.filter(twitter_account=current_twitter_user).first()

# # Creating a response object with JWT cookie
# response = HttpResponseRedirect(
# config("FRONT_END_URL") + "business/?authenticationStatus=success"
# )

# # Convert the UUID to string
# user_id = str(current_user.id)
# # Payload for JWT token
# payload = {
# "id": user_id,
# "exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=86400),
# "iat": datetime.datetime.utcnow(),
# }
# # Set the JWT token in the response object
# response = JWTOperations.setJwtToken(
# res=response, cookie_name="jwt", payload=payload
# )

# return response
existing_user = TwitterAccount.objects.filter(twitter_id=userData.id).first()

if existing_user is None:
newUser = TwitterAccount.objects.create(
twitter_id=userData.id,
name=userData.name,
user_name=userData.username,
access_token=access_token,
description=userData.description,
profile_image_url=userData.profile_image_url,
followers_count=userData.public_metrics["followers_count"],
following_count=userData.public_metrics["following_count"],
tweet_count=userData.public_metrics["tweet_count"],
listed_count=userData.public_metrics["listed_count"],
verified=userData.verified,
joined_at=userData.created_at,
location=userData.location,
url=userData.url,
)

newUser.save()
else:
existing_user.access_token = access_token
# Update the user data
existing_user.name = userData.name
existing_user.user_name = userData.username
existing_user.description = userData.description
existing_user.profile_image_url = userData.profile_image_url
existing_user.followers_count = userData.public_metrics["followers_count"]
existing_user.following_count = userData.public_metrics["following_count"]
existing_user.tweet_count = userData.public_metrics["tweet_count"]
existing_user.listed_count = userData.public_metrics["listed_count"]
existing_user.verified = userData.verified
existing_user.joined_at = userData.created_at
existing_user.location = userData.location
existing_user.url = userData.url
existing_user.save()

current_twitter_user = TwitterAccount.objects.filter(
twitter_id=userData.id
).first()
existing_user_account = User.objects.filter(
twitter_account=current_twitter_user
).first()

if existing_user_account is None:
new_user_account = User.objects.create(
username=userData.username,
first_name=userData.name,
twitter_account_id=current_twitter_user.id,
role=Role.objects.filter(name="influencer").first(),
)
new_user_account.save()
else:
existing_user_account.last_login = datetime.datetime.now()
existing_user_account.save()

current_user = User.objects.filter(twitter_account=current_twitter_user).first()

# Creating a response object with JWT cookie
response = HttpResponseRedirect(
config("FRONT_END_URL") + "business/?authenticationStatus=success"
)

# Convert the UUID to string
user_id = str(current_user.id)
# Payload for JWT token
payload = {
"id": user_id,
"exp": datetime.datetime.utcnow() + datetime.timedelta(seconds=86400),
"iat": datetime.datetime.utcnow(),
}
# Set the JWT token in the response object
response = JWTOperations.setJwtToken(
res=response, cookie_name="jwt", payload=payload
)

return response

except Exception as e:
return HttpResponse(e)
print("Error while logging in - ", e)
return HttpResponseRedirect(
config("FRONT_END_URL") + "business/?authenticationStatus=error"
)
3 changes: 1 addition & 2 deletions src/ui/src/hooks/useTwitterAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ export default function useTwitterAuth() {
// Function to initiate Twitter user authentication
const startTwitterAuthentication = async () => {
try {
const res = await axios.get(`${BACKEND_URL}auth-twitter-user/`);
window.location.href = res.data.auth_url;
window.location.href = `${BACKEND_URL}auth-twitter-user/`;
} catch (error) {
console.error("Error initiating Twitter authentication:", error);
}
Expand Down

0 comments on commit d8f8f53

Please sign in to comment.