Spaces:
Sleeping
Sleeping
File size: 4,546 Bytes
8608e55 | 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 | """
auth.py
This module defines authentication routes for handling user login and logout sessions
using FastAPI. It manages session creation and termination by storing session details
(name, email, session ID, start time, and end time) in a local SQLite database (`sessions.db`).
Each session is uniquely identified by a UUID.
"""
from fastapi import APIRouter, Form
from pydantic import BaseModel
from datetime import datetime
import sqlite3
import uuid
import os
# Create a FastAPI router instance for handling authentication routes
router = APIRouter()
DB_PATH = os.environ.get("DB_PATH", "sessions.db")
def get_conn():
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
conn.execute("""
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
name TEXT,
email TEXT,
start_time TEXT,
end_time TEXT
);
""")
return conn
@router.post("/login")
def login(name: str = Form(...), email: str = Form(...)):
sid = str(uuid.uuid4())
with get_conn() as conn:
conn.execute(
"INSERT INTO sessions (id, name, email, start_time, end_time) VALUES (?, ?, ?, ?, ?)",
(sid, name, email, datetime.now().isoformat(), None)
)
return {"session_id": sid, "status": "ok"}
@router.post("/logout")
def logout(session_id: str = Form(...)):
with get_conn() as conn:
conn.execute(
"UPDATE sessions SET end_time = ? WHERE id = ? AND end_time is NULL",
(datetime.now().isoformat(), session_id)
)
return {"status": "ok"}
# def init_db():
# """
# Initializes the SQLite database and creates the `sessions` table if it does not already exist.
# The `sessions` table stores:
# - id (str): Unique identifier for the session (UUID)
# - name (str): Name of the user
# - email (str): Email of the user
# - start_time (str): ISO formatted string marking when the session started
# - end_time (str): ISO formatted string marking when the session ended (nullable)
# """
# conn = sqlite3.connect("sessions.db")
# cursor = conn.cursor()
# cursor.execute("""
# CREATE TABLE IF NOT EXISTS sessions (
# id TEXT PRIMARY KEY,
# name TEXT,
# email TEXT,
# start_time TEXT,
# end_time TEXT
# )
# """)
# conn.commit()
# conn.close()
#
#
# # Initialize the database on module load
# init_db()
#
#
# class LogoutRequest(BaseModel):
# """
# Request model for logging out a session.
# Expects:
# - session_id (str): The unique identifier of the session to be terminated.
# """
# session_id: str
#
#
# @router.post("/login")
# async def login(name: str = Form(...), email: str = Form(...)):
# """
# Handles user login.
#
# - Accepts user `name` and `email` as form data.
# - Generates a unique session ID using UUID.
# - Captures the session's start time in UTC (ISO format).
# - Stores the session details in the SQLite database (`sessions` table).
# - Returns the generated session ID and the session start time.
#
# This function essentially begins a new user session.
# """
# session_id = str(uuid.uuid4())
# start_time = datetime.utcnow().isoformat()
#
# conn = sqlite3.connect("sessions.db")
# cursor = conn.cursor()
# cursor.execute(
# "INSERT INTO sessions (id, name, email, start_time, end_time) VALUES (?, ?, ?, ?, ?)",
# (session_id, name, email, start_time, None),
# )
# conn.commit()
# conn.close()
#
# return {"session_id": session_id, "start_time": start_time}
#
#
# @router.post("/logout")
# async def logout(request: LogoutRequest):
# """
# Handles user logout.
#
# - Accepts a `LogoutRequest` object containing the session ID.
# - Records the current UTC time as the session's end time (ISO format).
# - Updates the corresponding session record in the database by setting its `end_time`.
# - Returns a confirmation message along with the recorded end time.
#
# This function effectively ends a user session.
# """
# end_time = datetime.utcnow().isoformat()
#
# conn = sqlite3.connect("sessions.db")
# cursor = conn.cursor()
# cursor.execute(
# "UPDATE sessions SET end_time = ? WHERE id = ?",
# (end_time, request.session_id),
# )
# conn.commit()
# conn.close()
#
# return {"message": "Session ended", "end_time": end_time}
|