App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
import React, { useState, useEffect } from "react"; import { Button, Card, Container, Row, Col } from "react-bootstrap"; import "bootstrap/dist/css/bootstrap.min.css"; function App() { const [user, setUser] = useState(null); useEffect(() => { // Load Google API script const script = document.createElement("script"); script.src = "https://accounts.google.com/gsi/client"; script.async = true; script.onload = () => { /* Initialize Google Sign-In */ window.google.accounts.id.initialize({ client_id: "YOUR_GOOGLE_CLIENT_ID", callback: handleCredentialResponse, }); /* Render Sign-In Button */ window.google.accounts.id.renderButton( document.getElementById("google-signin"), { theme: "outline", size: "large" } ); /* Auto sign-in */ window.google.accounts.id.prompt(); }; document.body.appendChild(script); }, []); const handleCredentialResponse = (response) => { const decoded = JSON.parse(atob(response.credential.split(".")[1])); // Decode JWT setUser(decoded); // Save user info }; const handleLogout = () => { setUser(null); window.google.accounts.id.disableAutoSelect(); // Clear session }; return ( <Container className="mt-5"> <Row> <Col md={6} className="offset-md-3 text-center"> <h1>React Google OAuth2 Login</h1> {!user ? ( <div> <div id="google-signin"></div> </div> ) : ( <Card className="mt-3"> <Card.Body> <Card.Title>Welcome, {user.name}</Card.Title> <Card.Text> <strong>Email:</strong> {user.email} </Card.Text> <Button variant="danger" onClick={handleLogout}> Logout </Button> </Card.Body> </Card> )} </Col> </Row> </Container> ); } export default App; |