How Authlib python return the google profile picture to nextjs frontend?

154 Views Asked by At

I am learning to use Authlib to create Google oauth2 login.

By this example, I can make the oauth login successfully. However, I want to return the profile picture to frontend

My Flask backend is localhost:5001, and my Nextjs is localhost:3000

I have Three questions:

  1. How do Flask and Authlib send the session and send the picture URL as well?
  2. How does NextJS get and use the session and get the image?
  3. For NextAuth, they have useSession(), but I am not using NextAuth, how can handle this, or have any library to handle this?

My Flask code

@app.route('/login')
def login():
    # Redirect the user to Google's authentication page
    redirect_uri = url_for('auth', _external=True)
    return oauth.google.authorize_redirect(redirect_uri)

@app.route('/auth')
def auth():
    token = oauth.google.authorize_access_token()
    session['user'] = token['userinfo']
    print(token['userinfo']['picture']) // That's what I want, I want to return the picture URL as well
    return redirect('http://localhost:3000')

Nextjs code

"use client";
import React, { useState } from "react";
import Navbar from "@/app/components/Navbar";

export default function Loginpage() {
  const [authenticated, setAuthenticated] = useState(false);

  const handleLogin = () => {
    // Redirect to the Flask backend's /login route
    window.location.href = "http://localhost:5001/login";

    setAuthenticated(true); 
    // Can't set true since I don't know how to get the session
    // I see the cookies, the session is stored
  };

  return (
      
      <div className="flex items-center justify-center h-screen">
        <div className="max-w-md w-full mx-auto">
          <div className="bg-white py-12 px-8 rounded-lg shadow-lg">        
            <p className="text-gray-500 text-center mb-6">or</p>
            {authenticated ? (
              <p>You are authenticated!</p>
            ) : (
              <button
                onClick={handleLogin}
                className="bg-red-500 hover:bg-red-600 text-white font-medium py-2 px-4 rounded-lg w-full"
              >
                Sign In with Google
              </button>
            )}
          </div>
        </div>
      </div>
  );
}
0

There are 0 best solutions below