Open erikg713 opened 3 weeks ago
To implement Google sign-in functionality on your website, you need to integrate both the frontend and backend components to handle Google OAuth authentication. This involves setting up the necessary libraries, creating endpoints for token verification, and managing user data. The solution involves updating the backend to verify Google tokens and manage user records, and updating the frontend to initiate the Google sign-in process and handle responses.
Update Dependencies:
google-auth
and google-auth-oauthlib
to backend/requirements.txt
to handle Google OAuth authentication.pip install -r backend/requirements.txt
.Create Google Sign-In Route:
backend/app/routes/auth.py
, create a new route /google-signin
to handle POST requests with the Google OAuth token.from flask import Blueprint, request, jsonify
from google.oauth2 import id_token
from google.auth.transport import requests as google_requests
from app.models import User, db
from app.utils.security import create_jwt
auth_bp = Blueprint('auth', __name__)
@auth_bp.route('/google-signin', methods=['POST'])
def google_signin():
token = request.json.get('token')
try:
idinfo = id_token.verify_oauth2_token(token, google_requests.Request(), 'YOUR_GOOGLE_CLIENT_ID')
email = idinfo.get('email')
name = idinfo.get('name')
user = User.query.filter_by(email=email).first()
if not user:
user = User(email=email, username=name)
db.session.add(user)
db.session.commit()
jwt_token = create_jwt({"user_id": user.id})
response = jsonify({"message": "Logged in successfully"})
response.set_cookie("access_token", jwt_token, httponly=True, secure=True)
return response, 200
except ValueError:
return jsonify({"error": "Invalid token"}), 401
Add Token Verification in Auth Service:
backend/services/auth_service.py
, add a function to verify Google OAuth tokens and manage user data.from google.oauth2 import id_token
from google.auth.transport import requests
class AuthService:
@staticmethod
def verify_google_token(token):
try:
CLIENT_ID = "YOUR_GOOGLE_CLIENT_ID"
idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID)
email = idinfo.get('email')
name = idinfo.get('name')
user = User.query.filter_by(email=email).first()
if not user:
user = User(email=email, username=name)
db.session.add(user)
db.session.commit()
access_token = create_access_token(identity=user.id)
return access_token
except ValueError:
return None
Install React Google Login Library:
react-google-login
using npm install react-google-login
.Update Login Form Component:
frontend/src/components/LoginForm.js
, import GoogleLogin
and add a Google sign-in button.import { GoogleLogin } from 'react-google-login';
function LoginForm() {
const handleGoogleSuccess = (response) => {
console.log("Google login success:", response);
};
const handleGoogleFailure = (response) => {
console.error("Google login failed:", response);
};
return (
<form>
<GoogleLogin
clientId="YOUR_GOOGLE_CLIENT_ID"
buttonText="Login with Google"
onSuccess={handleGoogleSuccess}
onFailure={handleGoogleFailure}
cookiePolicy={'single_host_origin'}
/>
</form>
);
}
Update Login Page:
frontend/src/pages/LoginPage.js
, handle the Google sign-in response and send the token to the backend.import { GoogleLogin } from 'react-google-login';
function LoginPage() {
const handleGoogleSuccess = async (response) => {
try {
const res = await axios.post(`${process.env.REACT_APP_API_URL}/auth/google-signin`, { token: response.tokenId });
localStorage.setItem('access_token', res.data.access_token);
window.location.href = '/quest';
} catch (err) {
console.error('Google sign-in failed', err);
}
};
const handleGoogleFailure = (error) => {
console.error('Google sign-in failed', error);
};
return (
<div>
<GoogleLogin
clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID}
buttonText="Login with Google"
onSuccess={handleGoogleSuccess}
onFailure={handleGoogleFailure}
cookiePolicy={'single_host_origin'}
/>
</div>
);
}
Environment Variables:
REACT_APP_GOOGLE_CLIENT_ID
).By following these steps, you will enable Google sign-in functionality on your website, allowing users to authenticate using their Google accounts.
Click here to create a Pull Request with the proposed solution
Files used for this task:
Hey @autopilot implement a Google sign-in on my website. Make changes to the front end and the back end of the application
I want to allow users to signup and login using their Google account