<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by seymaozler on Medium]]></title>
        <description><![CDATA[Stories by seymaozler on Medium]]></description>
        <link>https://medium.com/@seymaaozlerr?source=rss-b380e5c9042a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H_pc8g-QOK4WC9eUozmLAQ.jpeg</url>
            <title>Stories by seymaozler on Medium</title>
            <link>https://medium.com/@seymaaozlerr?source=rss-b380e5c9042a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 09:40:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seymaaozlerr/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building an Authentication System with FastAPI, Redis and MySQL]]></title>
            <link>https://medium.com/@seymaaozlerr/building-an-authentication-system-with-fastapi-redis-and-mysql-cc8b005b9c30?source=rss-b380e5c9042a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc8b005b9c30</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[seymaozler]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 20:25:15 GMT</pubDate>
            <atom:updated>2023-11-19T14:29:50.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*qxaeZCFAutw9LhumVeBdCg.jpeg" /></figure><p><em>Hello, in this article, I will share how to create an effective authentication system using Redis and MySQL in the application I developed with FastAPI. The primary goal of my application is to use Redis in login processes after user registrations, eliminating the need to query the MySQL database for each login request. Redis is a tool of choice to enhance performance and speed up login processes. The user authentication request is efficiently handled through Redis, providing a quick and scalable solution without querying the MySQL database every time. This results in a faster application while reducing the load on the database, achieving a more efficient system. In this detailed article, we will explore the role of Redis in this project and delve into its performance advantages.</em></p><p><strong><em>Pulling Redis and MySQL Images with Docker<br></em></strong><em>To use Redis and MySQL on Docker, we first need to pull the relevant images:</em></p><pre><br>docker pull mysql/mysql-server:latest  <br>docker pull redis</pre><p><em>After pulling the images, we start our containers:<br>MySQL container:</em></p><pre>docker run --name=’your_container_name’ -e MYSQL_ROOT_PASSWORD=’your_password’ -e MYSQL_DATABASE=’your_db_name’ -p 3306:3306 -d mysql/mysql-server:latest</pre><p><em>Redis container:</em></p><pre>docker run --name ‘your_container_name’ -d redis</pre><p><em>You can confirm that your containers are running with the </em><em>docker ps -a command in the terminal.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*O_n4OdCSCTXY7iM-X-ORpg.png" /><figcaption><em>When we run ‘docker ps -a’ , we should see this result in our terminal</em></figcaption></figure><p><strong><em>Launching FastAPI Application and Installing Necessary Libraries</em></strong></p><p><em>To initialize a FastAPI application, you should create a new folder and set up a virtual environment inside it. As known, a virtual environment is a concept used to manage a project’s dependencies and required packages in an isolated environment. After activating the virtual environment, you can install the necessary libraries. Here are the commands you can use to perform these steps:</em></p><pre>python -m venv venv<br>venv\Scripts\activate<br>pip install &quot;fastapi[all]&quot;</pre><p><em>For other project dependencies, refer to the </em><em>requirements.txt file.<br>Now, create an </em><em>app folder within your project folder and use the following directory structure:</em></p><pre>app/<br>├── config/       <br>│   ├── config.py<br>|   ├── redis_db.py<br>│   └── database.py      <br>├── routers/         <br>│   ├── auth.py      <br>│   └── user.py     <br>├── service/         <br>│   ├── redis_service.py         <br>│   └── user_service.py <br>├── main.py     <br>├── models.py <br>│__ oauth2.py<br>│__ schemas.py      <br>└── utils.py   </pre><p><strong><em>User Model and Pydantic Models</em></strong></p><pre>#models.py<br>class User(Base):<br>    __tablename__ = &quot;users&quot;<br><br>    id = Column(Integer, primary_key=True, index=True)<br>    email = Column(String(100), nullable=False, unique=True)<br>    password = Column(String(100), nullable=False)<br>    date_created = Column(TIMESTAMP(timezone=True),<br>                          nullable=False, server_default=text(&#39;now()&#39;))<br>    date_modified = Column(TIMESTAMP(timezone=True), nullable=False,<br>                           server_default=text(&#39;now()&#39;), onupdate=text(&#39;now()&#39;))<br><br><br><br>#schemas.py<br><br>class UserCreate(BaseModel):<br>    email: str<br>    password: str<br><br>class User(BaseModel):<br>    id: int<br>    email: str<br>    date_created: datetime<br>    date_modified: datetime<br><br>    class Config:<br>        orm_mode = True<br><br>class Token(BaseModel):<br>    access_token: str<br>    token_type: str<br><br>class TokenData(BaseModel):<br>    id: Optional[str] = None</pre><p><strong><em>OAuth2 and Token Operations<br></em></strong><em>In the </em><em>oauth2.py file, you define the necessary functions for creating and validating access tokens. The </em><em>create_access_token function takes user credentials as a dictionary, encodes them into a JSON Web Token (JWT), and returns the JWT. On the other hand, </em><em>verify_token checks whether the user has a valid access token to make requests.</em></p><pre># oauth2.py <br><br>def create_access_token(data: dict):<br>    to_encode = data.copy()<br>    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)<br>    to_encode.update({&quot;exp&quot;: expire})<br>    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)<br><br>    return encoded_jwt<br><br>def verify_token(token: str, credentials_exception):<br>    try:<br>        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])<br>        id: str = payload.get(&quot;user_id&quot;)<br><br>        if id is None:<br>            raise credentials_exception<br><br>        token_data = schemas.TokenData(id=str(id))<br><br>    except JWTError:<br>        raise credentials_exception<br><br>    return token_data</pre><p><strong><em>User Creation and Database Storage<br></em></strong><em>In the ‘auth.py’ file within the ‘routers’ folder, create an endpoint for user creation ‘/user’</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*k6_pThO_bhOq1G1RC6TEjg.png" /></figure><pre># auth.py<br><br>@router.post(&quot;/&quot;, status_code=status.HTTP_201_CREATED, response_model=schemas.User)<br>def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):<br>    hashed_password = utils.hash(user.password)<br>    user.password = hashed_password<br>    new_user = user_create(user, db)<br>    data = {<br>        &quot;hashed_password&quot;: new_user.password,<br>        &quot;id&quot;: new_user.id<br>    }<br>    write_to_redis(new_user.email, data)<br><br>    return new_user</pre><p><em>This endpoint performs the following steps:</em></p><ol><li><em>Takes user data from the HTTP request.</em></li><li><em>Hashes the user password using the </em><em>hash function from </em><em>utils.py.</em></li><li><em>Calls the </em><em>user_create function from </em><em>user_service.py to create a user record in MySQL.</em></li></ol><pre>def user_create(user, db):<br>    email = db.query(User).filter(User.email == user.email).first()<br>    if email:<br>        raise HTTPException(<br>            status_code=409, detail=&quot;This email has already exists&quot;)<br>    new_user = User(**user.dict())<br>    db.add(new_user)<br>    db.commit()<br>    db.refresh(new_user)<br>    return new_user</pre><p><em>4. Creates a dictionary (</em><em>data) containing the user ID and hashed password.</em></p><p><em>5. Calls the </em><em>write_to_redis function from </em><em>redis_service.py to store user data in Redis.</em></p><pre>def write_to_redis(key, value):<br>    redis.set(key, json.dumps(value))</pre><p><strong><em>User Login and Redis Check</em></strong></p><p><em>In the ‘auth.py’ file, the ‘/login’ endpoint checks Redis when a user tries to log in.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*jjxOPOIDuAbsmSrwjFcUBg.png" /></figure><pre># user.py<br><br>@router.post(&quot;/login&quot;, response_model=schemas.Token)<br>def login(user_credentials: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):<br>    id = utils.verify(user_credentials.username, user_credentials.password, db)<br>    if id is None:<br>        raise HTTPException(<br>            status_code=status.HTTP_404_NOT_FOUND, detail=&quot;User could not found&quot;)<br>    if not id:<br>        raise HTTPException(<br>            status_code=status.HTTP_403_FORBIDDEN, detail=&quot;Invalid Credentials&quot;)<br><br>    access_token = oauth2.create_access_token(data={&quot;user_id&quot;: id})<br>    return {&quot;access_token&quot;: access_token, &quot;token_type&quot;: &quot;bearer&quot;}</pre><p><em>Firstly, it retrieves the username and password from </em><em>user_credentials, then calls the </em><em>verify function in </em><em>utils to perform the authentication process. The </em><em>verify function is defined as follows:</em></p><pre># utils.py<br><br>def verify(username, plain_password, db):<br>    if not check_user_in_redis(username):<br>        return None<br>    data = read_from_redis(username)<br>    if pwd_context.verify(plain_password, data[&quot;hashed_password&quot;]):<br>        write_to_redis(username, data)<br>        data = read_from_redis(username)<br>        return data[&quot;id&quot;]<br>    return False<br><br># service&gt;redis_service.py<br><br>def write_to_redis(key, value):<br>    redis.set(key, json.dumps(value))<br><br><br>def read_from_redis(key):<br>    return json.loads(redis.get(key))<br><br><br>def check_user_in_redis(username):<br>    return redis.exists(username)<br></pre><p><em>The </em><em>check_user_in_redis function is used to check if the user is present in Redis. If the user is in Redis, the function proceeds to retrieve user information from Redis using </em><em>read_from_redis.<br>The </em><em>pwd_context.verify function is used to verify the user&#39;s password. If the password verification is successful, it performs the necessary operations to update the information in Redis and return the user&#39;s identity. If the password verification fails, it returns False.</em></p><p><em>When these steps come together, we are creating an effective authentication system using Redis and MySQL in an application developed with FastAPI.</em></p><p><em>Full source code available at:<br></em><a href="https://github.com/seymaozler/card-application"><em>https://github.com/seymaozler/card-application</em></a></p><p><em>Thank you for reading :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc8b005b9c30" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>