be-app / google_auth.py
riosiahaan's picture
Add Google Oauth
2e7afa7
Raw History Blame Contribute Delete
3.39 kB
from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token
import psycopg2.extras
from google.oauth2 import id_token
from google.auth.transport import requests as google_requests
from uuid import uuid4
import os
import traceback
google_auth_bp = Blueprint('google_auth', __name__)
GOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID')
@google_auth_bp.route('/api/auth/google', methods=['POST', 'OPTIONS'])
def google_login():
if request.method == 'OPTIONS':
return '', 200
try:
data = request.json
token = data.get('credential') # token from @react-oauth/google
if not token:
return jsonify({"error": "Token is required"}), 400
if not GOOGLE_CLIENT_ID:
return jsonify({"error": "Server is missing GOOGLE_CLIENT_ID configuration"}), 500
# Verify Google token
try:
idinfo = id_token.verify_oauth2_token(token, google_requests.Request(), GOOGLE_CLIENT_ID)
# Get user info from token
google_id = idinfo['sub']
email = idinfo['email']
name = idinfo.get('name', email.split('@')[0])
avatar_url = idinfo.get('picture', '')
except ValueError as e:
return jsonify({"error": f"Invalid Google token: {str(e)}"}), 401
from app import get_db_connection
conn = get_db_connection()
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# Check if user exists by email or google_id
cursor.execute("SELECT id, username, email, role, google_id FROM users WHERE email = %s OR google_id = %s", (email, google_id))
user = cursor.fetchone()
if not user:
# Register new user
user_id = str(uuid4())
cursor.execute(
"INSERT INTO users (id, username, email, google_id, avatar_url, role) VALUES (%s, %s, %s, %s, %s, %s)",
(user_id, name, email, google_id, avatar_url, 'user')
)
conn.commit()
is_admin = False
username = name
else:
user_id = user['id']
is_admin = user['role'] == 'admin'
username = user['username']
# Update google_id and avatar if missing
if not user.get('google_id'):
cursor.execute("UPDATE users SET google_id = %s, avatar_url = %s WHERE id = %s", (google_id, avatar_url, user_id))
conn.commit()
# Generate our own backend JWT
access_token = create_access_token(identity=str(user_id))
return jsonify({
"success": True,
"token": access_token,
"user": {
"id": user_id,
"username": username,
"email": email,
"is_admin": is_admin
}
}), 200
except Exception as e:
print(f"Google Auth error: {str(e)}")
print(traceback.format_exc())
return jsonify({"error": "Internal server error"}), 500
finally:
try:
if 'cursor' in locals() and cursor:
cursor.close()
if 'conn' in locals() and conn:
conn.close()
except:
pass