Build Your Own AI Assistant Part 1 - Creating the Assistant
116820 Views
Is the new Raspberry Pi AI Kit better than Google Coral?
114678 Views
Control Arduino with Python using Firmata / PyFirmata
87081 Views
How to Map with LiDAR - using a Raspberry Pi Zero 2W, RPLidar and Rviz
57314 Views
Creating a Supercomputer with a Raspberry Pi 5 Cluster and Docker Swarm!
53588 Views
Node-Red Automation, MQTT, NodeMCU & MicroPython
52067 Views
SMARS Lab upgrade with PyCharm
Chicken Nugget Piano
Pi Tray - Mini-rack - Part II
Weather Station Display
Pi 10 Inch Mini-rack
Installing and Using DeepSeek-R1:1.5 on a Raspberry Pi with Docker
Mini-Rack 3D Design Tutorial
0h 20m
Using the Raspberry Pi Pico's Built-in Temperature Sensor
0h 24m
Getting Started with SQL
0h 32m
Introduction to the Linux Command Line on Raspberry Pi OS
0h 42m
How to install MicroPython
0h 8m
Wall Drawing Robot Tutorial
0h 22m
Learn Linux from the basics to advanced topics.
Learn how to use a Raspberry Pi Pico
Learn MicroPython the best language for MicroControllers
Learn Docker, the leading containerization platform. Docker is used to build, ship, and run applications in a consistent and reliable manner, making it a popular choice for DevOps and cloud-native development.
Learn how to build SMARS robots, starting with the 3D Printing the model, Designing SMARS and Programming SMARS
Learn how to build robots, starting with the basics, then move on to learning Python and MicroPython for microcontrollers, finally learn how to make things with Fusion 360.
Learn Python, the most popular programming language in the world. Python is used in many different areas, including Web Development, Data Science, Machine Learning, Robotics and more.
Learn how to create robots in 3D, using Fusion 360 and FreeCAD. The models can be printed out using a 3d printer and then assembled into a physical robot.
Learn how to create Databases in Python, with SQLite3 and Redis.
KevsRobots Learning Platform
66% Percent Complete
By Kevin McAleer, 3 Minutes
With our user models in place, we can now implement the registration and login functionalities. This process involves securely handling passwords, verifying user credentials, and generating authentication tokens.
Before saving a user’s password to the database, we must hash it. Using a library like passlib, we can securely hash passwords.
passlib
from passlib.context import CryptContext pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") def get_password_hash(password): return pwd_context.hash(password)
Our registration endpoint will accept username, email, and password, validate the data, hash the password, and then save the new user to the database.
from fastapi import FastAPI, HTTPException, Depends from sqlalchemy.orm import Session from . import models, schemas from .database import SessionLocal, engine app = FastAPI() # Dependency def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.post("/register/") def register_user(user: schemas.UserCreate, db: Session = Depends(get_db)): db_user = db.query(models.User).filter(models.User.email == user.email).first() if db_user: raise HTTPException(status_code=400, detail="Email already registered") hashed_password = get_password_hash(user.password) db_user = models.User(username=user.username, email=user.email, hashed_password=hashed_password) db.add(db_user) db.commit() db.refresh(db_user) return {"username": db_user.username, "email": db_user.email}
To log in a user, we need to verify their email and password. This involves fetching the user from the database and checking the password hash.
def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password, hashed_password) def authenticate_user(email: str, password: str, db: Session = Depends(get_db)): user = db.query(models.User).filter(models.User.email == email).first() if not user or not verify_password(password, user.hashed_password): return False return user
After verifying the user, we generate a JWT token for session management. This token is sent back to the user and used in subsequent requests.
from datetime import datetime, timedelta import jwt SECRET_KEY = "your_secret_key" ALGORITHM = "HS256" def create_access_token(data: dict, expires_delta: timedelta = None): to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt
You’ve now implemented the registration and login functionalities, including secure password handling and JWT token generation. These are key components of our user authentication system. In the next lessons, we’ll explore how to use these tokens for authenticating API requests and managing user sessions.
Implement an endpoint for logging out users. Consider how you would invalidate the JWT token and what impact this has on the server and client side of your application.
< Previous Next >