Open T-4004 opened 5 months ago
To implement Google sign-in on a website, we need to update both the front-end and back-end components. The front-end will include a Google sign-in button and the necessary JavaScript to handle the sign-in process. The back-end will handle the OAuth flow, create/update user records, and manage user sessions.
authlib
and flask-login
).flask-login
for session management.from flask import Flask, redirect, url_for
from flask_login import LoginManager, login_user, logout_user, login_required
from authlib.integrations.flask_client import OAuth
app = Flask(__name__)
app.secret_key = 'your_secret_key'
login_manager = LoginManager()
login_manager.init_app(app)
oauth = OAuth(app)
google = oauth.register(
name='google',
client_id='your_client_id',
client_secret='your_client_secret',
access_token_url='https://accounts.google.com/o/oauth2/token',
authorize_url='https://accounts.google.com/o/oauth2/auth',
api_base_url='https://www.googleapis.com/oauth2/v1/',
client_kwargs={'scope': 'openid profile email'},
)
@login_manager.user_loader
def load_user(user_id):
# Load the user from the database
return user
@app.route('/login')
def login():
redirect_uri = url_for('authorize', _external=True)
return google.authorize_redirect(redirect_uri)
@app.route('/authorize')
def authorize():
token = google.authorize_access_token()
resp = google.get('userinfo')
user_info = resp.json()
# Check if user exists in the database, if not create a new one
user = User.get_or_create(user_info)
login_user(user)
return redirect('/')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
import mysql.connector
connection = mysql.connector.connect(
host="your_host",
user="your_username",
password="your_password",
database="your_database"
)
def insert_google_user(google_id, email):
cursor = connection.cursor()
query = "INSERT INTO users (google_id, email) VALUES (%s, %s)"
values = (google_id, email)
cursor.execute(query, values)
connection.commit()
cursor.close()
def get_user_by_google_id(google_id):
cursor = connection.cursor(dictionary=True)
query = "SELECT * FROM users WHERE google_id = %s"
cursor.execute(query, (google_id,))
user = cursor.fetchone()
cursor.close()
return user
connection.close()
<!-- Include the Google API JavaScript library -->
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script>
function onSignIn(googleUser) {
// Handle sign-in
}
</script>
<!-- Add a div for the Google sign-in button -->
<div class="g-signin2" data-onsuccess="onSignIn"></div>
.google-signin-btn {
/* Styles for Google sign-in button */
}
.google-signin-btn:hover {
/* Hover state styles */
}
.google-signin-btn:active {
/* Active state styles */
}
function initGoogleSignIn() {
gapi.load('auth2', function() {
gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
});
});
}
function onSignIn(googleUser) {
// Handle the sign-in event
}
document.addEventListener('DOMContentLoaded', () => {
initGoogleSignIn();
});
Ensure that you replace placeholders like 'your_client_id'
, 'your_client_secret'
, and 'your_secret_key'
with actual values from your Google Developer Console and your application's configuration.
Click here to create a Pull Request with the proposed solution
Files used for this task:
What - description of what you me to do Example: Hey @autopilot implement a Google sign-in on my website. Make changes to the front end and the back end of the application
Why - explain why this is important Example: I want to allow users to signup and login using their Google account