Skip to content

Commit

Permalink
frontend update backend token verification
Browse files Browse the repository at this point in the history
  • Loading branch information
AkhilS2 committed May 11, 2024
1 parent 056b0a3 commit 189f9fb
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 11 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ yarn-debug.log*
yarn-error.log*

# local env files
.env
.env*.local

# vercel
Expand Down
64 changes: 53 additions & 11 deletions app/loginPage/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { GoogleOAuthProvider, useGoogleLogin, googleLogout, TokenResponse} from
import { jwtDecode } from "jwt-decode";
import axios from "axios";

const GOOGLE_CLIENT_ID = process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID;

interface User {
name: string;
Expand All @@ -12,7 +13,7 @@ interface User {
}
const LoginPage = () => {
return(
<GoogleOAuthProvider clientId={'1040494859138-vji3ddfil5jancg23ifaginvmn71hktf.apps.googleusercontent.com'}>
<GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
<LoginComponent/>
</GoogleOAuthProvider>
)
Expand All @@ -21,14 +22,15 @@ const LoginPage = () => {
const LoginComponent = () => {
const [user, setUser] = useState<User | null>(null);




useEffect(() => {
console.log("LoginPage component mounted");
}, []);

const handleLoginSuccess = (tokenResponse: any) => {
if ('code' in tokenResponse) {
/*const handleLoginSuccess = async (tokenResponse: any) => {
if ('code' in tokenResponse) {
// Handle authorization code flow
console.log('Authorization Code:', tokenResponse.code);
// Exchange code for tokens here
Expand All @@ -41,19 +43,56 @@ const LoginComponent = () => {
email: decoded.email,
picture: decoded.picture
});
// Send token to backend if necessary
console.log(tokenResponse);
axios.post('http://localhost:8000/myapi/users/google-oauth2/', { token: tokenResponse.access_token })
.then(res => console.log('Backend login successful', res))
.catch(err => console.error('Backend login failed', err));
}
}*/
/*console.log(tokenResponse);
const decoded: User = jwtDecode(tokenResponse.id_token);
};
setUser({
name: decoded.name,
email: decoded.email,
picture: decoded.picture
})*/
// fetching userinfo can be done on the client or the server




const login = useGoogleLogin({
flow: "auth-code",
flow: "implicit",

onSuccess: async tokenResponse => {
console.log(tokenResponse);
//handleLoginSuccess
//client side authentication retrieve user info from access token
const userInfo = await axios
.get('https://www.googleapis.com/oauth2/v3/userinfo', {
headers: { Authorization: `Bearer ${tokenResponse.}` },
})

.then(res => res.data);
//frontend user info
setUser({
name: userInfo.name,
email: userInfo.email,
picture: userInfo.picture
})
//send the token to backend
axios.post('http://localhost:8000/myapi/users/', {tokenResponse: tokenResponse})
.then(res => console.log('Backend login successful', res))
.catch(err => console.error('Backend login failed', err))



onSuccess: (tokenResponse) => handleLoginSuccess,

},
onError: (errorResponse) => console.error('Login Failed', errorResponse),
});

const handleLogout = () => {
googleLogout();
setUser(null); // Clears the user state, effectively logging out the user
Expand All @@ -66,16 +105,19 @@ const LoginComponent = () => {
</button>
{user && (
<div>
<img src={user.picture} alt="User profile" />
<h2>Welcome, {user.name} - {user.email}</h2>

<div className="center">
<img src={user.picture} alt="User profile" />
</div>
<h2 className="m-5 p-2 text-[#003C6C] font-medium text-xl">Welcome, {user.name}</h2>
<h3 className="m-5 p-2 text-[#003C6C] font-medium text-xl">Email: {user.email}</h3>
</div>
)}
<button onClick={handleLogout} className="hover:underline decoration-yellow-400 underline-offset-8 top-0 right-0 m-5 p-2 text-[#003C6C] font-medium text-xl">
Logout
</button>
</div>


);
};

Expand Down
1 change: 1 addition & 0 deletions backend/myapi/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@
urlpatterns = [
path("hello-world/", views.hello_world, name="hello_world"),
path("locations/", views.get_locations, name="locations"),
path("users/", views.validate_user, name="users")
]
54 changes: 54 additions & 0 deletions backend/myapi/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
from django.conf.locale import fr
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.conf import settings
from django.http import JsonResponse
from rest_framework.decorators import api_view
from rest_framework.exceptions import ValidationError
import requests



GOOGLE_ID_TOKEN_INFO_URL = 'https://www.googleapis.com/oauth2/v3/tokeninfo'
GOOGLE_USER_INFO_URL = 'https://www.googleapis.com/oauth2/v3/userinfo'

from .db_functions.locations import (
get_all_locations_from_db,
Expand Down Expand Up @@ -59,3 +69,47 @@ def get_locations(request):
json_data = {"locations": locations}

return Response(json_data)

@api_view(["POST"])
def validate_user(request):
token_response = request.data.get('tokenResponse')
access_token = token_response.get('access_token')
id_token = token_response.get('code')
print(id_token)
try:
response = requests.get(
GOOGLE_ID_TOKEN_INFO_URL,
params={'id_token': id_token}
)
except:
return JsonResponse({'error': 'Failed to validate id token token'}, status=500)



#using access token we can get the user information

try:
response = requests.get(
GOOGLE_USER_INFO_URL,
headers={'Authorization': f'Bearer {access_token}'}
)
response.raise_for_status()
user_info = response.json()
print(user_info["email"])
#add user_info to database using get or create possibly
#print(user_info)


except requests.RequestException as e:
return JsonResponse({'error': 'Failed to validate access token'}, status=500)

return JsonResponse({'message': 'User is validated', 'user_info': user_info})









0 comments on commit 189f9fb

Please sign in to comment.