How to integrate Supabase for user authentication using email and password
Last updated
Was this helpful?
Key Steps
Create a Supabase Project
Set Up Authentication in Supabase
Implement Supabase Authentication in the Backend
Getting Started with Supabase Projects
Creating a Supabase Account
Sign Up: Go to the Supabase website and sign up using your email or a third-party provider like GitHub.
Create a New Project: Once logged in, click on "New Project," choose a name for your project, select a region closest to your location, and click "Create new project" to continue.
Enable Email and Password Authentication
Ensure that if you enable "Confirm Email," a default rate limit on the maximum number of emails is applied. However, you can also toggle off this feature for testing purposes.
Obtain Supabase API Credentials
Building the Backend / API in Databutton
Integrating the backend in Databutton is super easy. The agent is well aware of the supabase Python package. Here's an example prompt to set up with the backend.
Hey! I would like use the supabase Python package to create an authentication system.
- It must have a way to Sign Up ( create users )
- Log in
- Log out
Databutton starts by outlining the key actions to write the Python code
And, then installs the Supabase Python package to plan and execute effectively.
Databutton executes the storing of these secrets automatically. It provides a secure input dialog box to enter the Project API key and Secret Key.
Backend Code ( Sign Up, Log In and Log out APIs)
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, EmailStr
import databutton as db
from supabase import create_client, Client
# Router for endpoints
router = APIRouter()
# Initialize Supabase client
SUPABASE_URL = db.secrets.get("SUPABASE_API_URL")
SUPABASE_KEY = db.secrets.get("SUPABASE_API_KEY")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
# Define Pydantic models
class SignUpRequest(BaseModel):
email: EmailStr
password: str
class SignUpResponse(BaseModel):
message: str
class LoginRequest(BaseModel):
email: EmailStr
password: str
class LoginResponse(BaseModel):
message: str
session_token: str | None
user_data: dict | None
class LogoutRequest(BaseModel):
session_token: str
class LogoutResponse(BaseModel):
message: str
# Create Log In endpoint
@router.post("/log-in", response_model=LoginResponse)
def log_in(body: LoginRequest):
try:
response = supabase.auth.sign_in_with_password({"email": body.email, "password": body.password})
if response.user is None:
raise HTTPException(status_code=400, detail="Invalid login credentials.")
session_token = response.session.access_token if response.session else None
user_data = response.user.__dict__
return LoginResponse(
message="User logged in successfully.",
session_token=session_token,
user_data=user_data,
)
except Exception as e:
print(f"Error during login: {str(e)}") # Log the detailed error message
raise HTTPException(status_code=500, detail=str(e))
# Create Sign Up endpoint
@router.post("/sign-up", response_model=SignUpResponse)
def sign_up(body: SignUpRequest):
try:
response = supabase.auth.sign_up({"email": body.email, "password": body.password})
if response.user is None:
raise HTTPException(status_code=400, detail="User creation failed.")
return SignUpResponse(message="User created successfully.")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# Create Log Out endpoint
@router.post("/log-out", response_model=LogoutResponse)
def log_out(body: LogoutRequest):
try:
response = supabase.auth.sign_out()
print("Sign out response:", response)
if response and response.get("error"):
raise HTTPException(status_code=400, detail=response["error"]["message"])
return LogoutResponse(message="User logged out successfully.")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Databutton ensures a working endpoint by default through testing. This action can also be triggered via a prompt. Example: "Hey, can you please test the endpoint?"
Use Hashtag (#) to refer to any specific endpoint you would like to test.
Building an UI component
Buildin an UI component with a Login Portal is very easy in Databutton.
You can use Databutton with an existing screenshot of a Login Portal. Alternatively, start with a prompt for a UI that includes a Sign Up and Log In Portal.
Here's how this demo UI looks like -
Databutton designs the action.
Copy this Image and Paste as Databutton's prompt with few additonal content. Databutton can quickly spin out similar UI!