<?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 Abdullah Alqahtani on Medium]]></title>
        <description><![CDATA[Stories by Abdullah Alqahtani on Medium]]></description>
        <link>https://medium.com/@anqorithm?source=rss-30833ccf4538------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LgZDqWifMTOBZQMnw_nJmg.jpeg</url>
            <title>Stories by Abdullah Alqahtani on Medium</title>
            <link>https://medium.com/@anqorithm?source=rss-30833ccf4538------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:18:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anqorithm/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[Convert Any Docker-Compose YAML to Kubernetes Manifests in Seconds with Kompose]]></title>
            <link>https://anqorithm.medium.com/convert-any-docker-compose-yaml-to-kubernetes-manifests-in-seconds-with-kompose-eeb97323d7f8?source=rss-30833ccf4538------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeb97323d7f8</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kompose]]></category>
            <dc:creator><![CDATA[Abdullah Alqahtani]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 12:27:18 GMT</pubDate>
            <atom:updated>2025-02-24T17:39:35.877Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Convert Docker-Compose to Kubernetes in Seconds</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZH8bZcsOeZ0PtylcDWJjA.png" /><figcaption>Convert Any Docker-Compose YAML to Kubernetes Manifests in Seconds with Kompose</figcaption></figure><h3>Introduction</h3><p>If you are using <strong>Docker Compose</strong> and want to switch to <strong>Kubernetes</strong>, you may find it difficult to manually write Kubernetes YAML files.</p><p><strong>Kompose</strong> is a tool that helps convert any docker-compose.yaml file into Kubernetes YAML files with a single command.</p><p>In this guide, I will show how to:</p><ul><li>Run a <strong>FastAPI</strong> application with <strong>Docker Compose</strong></li><li>Convert it to <strong>Kubernetes</strong> using <strong>Kompose</strong></li><li>Deploy it on <strong>Minikube</strong></li></ul><h3>1. Install Kompose and Minikube</h3><p>Before starting, install <strong>Kompose</strong> and <strong>Minikube</strong>.</p><h4>Install Kompose</h4><p>Follow the official installation guide: <a href="https://kompose.io/installation/">Kompose Installation</a></p><h4>For Linux/macOS:</h4><pre>$ curl -L https://github.com/kubernetes/kompose/releases/latest/download/kompose-linux-amd64 -o kompose<br>$ chmod +x kompose<br>$ sudo mv kompose /usr/local/bin/</pre><h4>For Windows:</h4><p>Download the latest release from <a href="https://github.com/kubernetes/kompose/releases">Kompose Releases</a> and add it to your system’s PATH.</p><p>Verify installation by running:</p><pre>$ kompose version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMlmPSfMe6z0bYnPTcw_-Q.png" /><figcaption><em>Kompose installed successfully and version confirmed</em></figcaption></figure><h3>Install Minikube</h3><p>Follow the instructions on the <a href="https://minikube.sigs.k8s.io/docs/start/">Minikube website</a> to install it.</p><p>Start Minikube:</p><pre>$ minikube start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VnFb6XJ8-Ay2qNeHP8WPfg.png" /><figcaption><em>Minikube started and running a local Kubernetes cluster</em></figcaption></figure><h3>2. Setup FastAPI Project</h3><p>The FastAPI application is structured as follows:</p><pre>kompose-fastapi/<br>│── Dockerfile<br>│── docker-compose.yml<br>│── pyproject.toml<br>│── src/<br>│   ├── app/<br>│   │   ├── __init__.py<br>│   │   ├── main.py<br>│   ├── config/<br>│   │   ├── __init__.py<br>│   │   ├── settings.py<br>│── k8s/ (Generated after Kompose conversion)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4PoUWu_BVeLko4AsbQfEQ.png" /><figcaption><em>Folder structure of the FastAPI application</em></figcaption></figure><h3>3. FastAPI Application Code</h3><p>Create a FastAPI application inside the src/app/main.py file:</p><pre>from fastapi import FastAPI<br>from src.config.settings import settings<br><br>app = FastAPI(<br>    title=settings.app_name,<br>    version=settings.app_version,<br>    description=settings.app_description,<br>)<br>@app.get(&quot;/&quot;)<br>async def root():<br>    return {<br>        &quot;app_name&quot;: settings.app_name,<br>        &quot;version&quot;: settings.app_version,<br>        &quot;environment&quot;: settings.app_env,<br>        &quot;debug&quot;: settings.debug,<br>    }</pre><p>Configuration is stored in src/config/settings.py:</p><pre>from pydantic_settings import BaseSettings<br><br>class Settings(BaseSettings):<br>    app_name: str = &quot;Kompose FastAPI&quot;<br>    app_version: str = &quot;1.0.0&quot;<br>    app_description: str = &quot;A FastAPI service for Kompose testing&quot;<br>    app_env: str = &quot;development&quot;<br>    debug: bool = False<br>    api_prefix: str = &quot;/api/v1&quot;<br><br>    class Config:<br>        env_file = &quot;.env&quot;<br>        case_sensitive = False<br><br>settings = Settings()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fc-OwrwvbEIbr-Tp8f-5zw.png" /><figcaption><em>FastAPI application setup and environment variables configured (image1)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O38uUAR1f7Zpgmm5coGf0g.png" /><figcaption><em>FastAPI application setup and environment variables configured (image2)</em></figcaption></figure><h3>4. Docker Setup</h3><p>Create a Dockerfile to containerize the application:</p><pre>FROM python:3.12-slim<br><br>WORKDIR /app<br><br>RUN pip install poetry<br><br>COPY pyproject.toml ./<br><br>RUN poetry config virtualenvs.create false &amp;&amp; poetry install --no-interaction --no-ansi<br><br>COPY src/ ./src/<br><br>EXPOSE 8000<br><br>CMD [&quot;poetry&quot;, &quot;run&quot;, &quot;uvicorn&quot;, &quot;src.app.main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6Ka4OaxujhitNv6guzDvA.png" /><figcaption><em>Dockerfile used to containerize the FastAPI application</em></figcaption></figure><h3>5. Build and Push Docker Image to Docker Hub</h3><h4>Step 1: Build the Docker Image</h4><p>Run the following command to build the FastAPI Docker image:</p><pre>$ docker build -t anqorithm/kompose-fastapi:latest .</pre><h4>Step 2: Log in to Docker Hub</h4><p>Authenticate with Docker Hub before pushing the image:</p><pre>$ docker login</pre><h4>Step 3: Push the Image to Docker Hub</h4><p>Upload the image to Docker Hub using:</p><pre>$ docker push anqorithm/kompose-fastapi:latest</pre><h4>Step 4: Verify the Image on Docker Hub</h4><p>Check that the image is available on Docker Hub by running:</p><pre>$ docker images | grep anqorithm/kompose-fastapi</pre><p>Alternatively, visit <a href="https://hub.docker.com/"><strong>Docker Hub</strong></a> and search for anqorithm/kompose-fastapi.</p><h3>Step 5: Use the Image in Kubernetes</h3><p>Now, the image is stored on Docker Hub and can be referenced in the <strong>Kubernetes deployment YAML</strong> as:</p><pre>containers:<br>  - name: api<br>    image: anqorithm/kompose-fastapi:latest<br>    ports:<br>      - containerPort: 8000</pre><h3>6. Docker Compose Setup</h3><p>Create a docker-compose.yml file:</p><pre>services:<br>  api:<br>    build: .<br>    ports:<br>      - &quot;8000:8000&quot;<br>    environment:<br>      - APP_NAME=Kompose FastAPI<br>      - APP_VERSION=1.0.0<br>      - APP_DESCRIPTION=FastAPI Application for Kompose Testing<br>      - APP_ENV=development<br>      - DEBUG=true<br>      - API_PREFIX=/api/v1<br>    volumes:<br>      - ./src:/app/src</pre><p>Run the application with Docker Compose:</p><pre>$ docker-compose up -d</pre><p>Test if it is running:</p><pre>$ curl http://localhost:8000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lVrRlW_8Yd0oW9RzI0riXg.png" /><figcaption><em>FastAPI application running using Docker Compose</em></figcaption></figure><h3>7. Convert to Kubernetes with Kompose</h3><p>Run the conversion command:</p><pre>$ kompose convert -f docker-compose.yml</pre><p>This generates Kubernetes YAML files in the k8s/ directory, including:</p><ul><li>api-deployment.yaml</li><li>api-service.yaml</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HS5hMGn9uhZMHJDsyR3Erg.png" /><figcaption><em>Kompose converting Docker Compose files to Kubernetes YAML</em></figcaption></figure><h4>Example: Kubernetes Deployment File</h4><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  annotations:<br>    kompose.cmd: kompose convert -f docker-compose.yml<br>    kompose.version: 1.35.0 (HEAD)<br>  labels:<br>    io.kompose.service: api<br>  name: api<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      io.kompose.service: api<br>  strategy:<br>    type: Recreate<br>  template:<br>    metadata:<br>      annotations:<br>        kompose.cmd: kompose convert -f docker-compose.yml<br>        kompose.version: 1.35.0 (HEAD)<br>      labels:<br>        io.kompose.service: api<br>    spec:<br>      containers:<br>        - env:<br>            - name: API_PREFIX<br>              value: /api/v1<br>            - name: APP_DESCRIPTION<br>              value: Kompose FastAPI<br>            - name: APP_ENV<br>              value: development<br>            - name: APP_NAME<br>              value: Kompose FastAPI<br>            - name: APP_VERSION<br>              value: 1.0.0<br>            - name: DEBUG<br>              value: &quot;true&quot;<br>          image: anqorithm/kompose-fastapi:latest<br>          name: api<br>          ports:<br>            - containerPort: 8000<br>              protocol: TCP<br>      restartPolicy: Always</pre><h4>Example: Kubernetes Service File</h4><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  annotations:<br>    kompose.cmd: kompose convert -f docker-compose.yml<br>    kompose.version: 1.35.0 (HEAD)<br>  labels:<br>    io.kompose.service: api<br>  name: api<br>spec:<br>  ports:<br>    - name: &quot;8000&quot;<br>      port: 8000<br>      targetPort: 8000<br>  selector:<br>    io.kompose.service: api</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UT0IABxRtCOQhPnOaCRtgA.png" /><figcaption><em>Generated Kubernetes deployment and service YAML files (Deployment)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMFilV4xybW7OMapB3281A.png" /><figcaption><em>Generated Kubernetes deployment and service YAML files (Service)</em></figcaption></figure><p>Note: I will move them to k8s directory to make it more organized.</p><h3>8. Deploy to Minikube</h3><p>Apply the Kubernetes files to Minikube:</p><pre>$ kubectl apply -f k8s/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3KiagZgmmT_20aLrZZchA.png" /><figcaption>kubectl apply -f k8s/</figcaption></figure><p>Check the running pods:</p><pre>$ kubectl get pods</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqRsY8oJjvHCirGN0fTyGA.png" /><figcaption>kubectl get pods</figcaption></figure><p>Check the logs of the pod:</p><pre>$ kubectl logs api-6854688558-2ntgv</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kMlm0gfjZeruvD6cusIJ8A.png" /><figcaption>kubectl logs api-6854688558–2ntgv</figcaption></figure><p>Check the services:</p><pre>$ kubectl get svc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_rkYOXiy-y0je7J7FR5gMg.png" /><figcaption>kubectl get svc</figcaption></figure><p>Expose the service in Minikube:</p><pre>$ minikube service api</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vN40vbZrR3mtEM-UlU0xxw.png" /><figcaption>minikube service api</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRAc33XYl3AAVKb2We5hnQ.png" /><figcaption><em>FastAPI application deployed to Minikube and service exposed</em></figcaption></figure><h3>9. Conclusion</h3><ul><li><strong>Kompose</strong> helps convert docker-compose.yml to <strong>Kubernetes YAML</strong> easily.</li><li>This method allows moving <strong>FastAPI applications (or any dockerized application) </strong>from <strong>Docker Compose to Kubernetes</strong> quickly.</li><li>Minikube provides a local Kubernetes environment for testing.</li></ul><p>This is a <strong>simple way</strong> to start using <strong>Kubernetes</strong> without writing YAML files manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xOYKtKu3rgvkxWDZtKdVbA.png" /><figcaption><em>Final FastAPI application running inside Minikube</em></figcaption></figure><h3>10. Source Code in GitHub</h3><p>The source code used in this article can be found here in Github:</p><p><a href="https://github.com/anqorithm/kompose-fastapi">GitHub - anqorithm/kompose-fastapi</a></p><h3>11. References</h3><ul><li><strong>Kompose Documentation</strong>: <a href="https://kompose.io/installation/">Installation Guide</a>, <a href="https://kompose.io/">Usage Guide</a></li><li><strong>Minikube Documentation</strong>: <a href="https://minikube.sigs.k8s.io/docs/start/">Getting Started with Minikube</a></li><li><strong>Docker Hub</strong>: <a href="https://hub.docker.com/u/anqorithm">Docker Hub — anqorithm/kompose-fastapi</a></li><li><strong>FastAPI Documentation</strong>: <a href="https://fastapi.tiangolo.com/">FastAPI Framework</a></li><li><strong>Kubernetes Documentation</strong>: <a href="https://kubernetes.io/docs/">Kubernetes Official Docs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeb97323d7f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Modular FastAPI App: Using Git Submodules as Packages]]></title>
            <link>https://anqorithm.medium.com/building-a-modular-fastapi-app-using-git-submodules-as-packages-7ae21d4a83b2?source=rss-30833ccf4538------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ae21d4a83b2</guid>
            <category><![CDATA[gitsubmodule]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[package]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Abdullah Alqahtani]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 14:25:08 GMT</pubDate>
            <atom:updated>2025-01-31T15:06:46.088Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOsV_TehBFnBwbP0de1wrw.png" /><figcaption>Building a Modular FastAPI App: Using Git Submodules as Packages</figcaption></figure><h3>Introduction</h3><p>As FastAPI projects grow, managing different functionalities within a single repository can become difficult. One way to keep the project modular and maintainable is by using <strong>Git submodules</strong>.</p><p>Git submodules allow you to <strong>include other repositories inside your main project</strong>. This is useful for adding reusable components like logging, authentication, or utilities while keeping them separate and independently managed.</p><p>In this guide, we will cover:</p><ul><li>What Git submodules are</li><li>Why they are useful in FastAPI projects</li><li>How to set up and manage them</li><li>A real-world example using fastapi-sub-modules and fastapi-sub-modules-logger-kit</li></ul><h3>What Are Git Submodules?</h3><p>Git submodules are repositories within a repository. They allow you to link an external Git repository to your main project while independently keeping its history and updates.</p><h3>Key Benefits of Git Submodules</h3><ol><li><strong>Modularity ~ </strong>Keep separate concerns in different repositories.</li><li><strong>Reusability ~ </strong>Use the same module across multiple projects without duplication.</li><li><strong>Independent Updates ~ </strong>Update submodules without affecting the main project.</li><li><strong>Better Team Collaboration ~ </strong>Teams can work on different modules independently.</li></ol><h3>Understanding Git Submodules in FastAPI</h3><p>Let’s say we have a <strong>main FastAPI project (</strong><strong>fastapi-sub-modules)</strong> that includes a <strong>logging package (</strong><strong>fastapi-sub-modules-logger-kit)</strong> as a Git submodule.</p><h3>Architecture Overview</h3><p>The diagram below illustrates the relationship between the main FastAPI repository and its submodule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*eKPPh4omDrL0s0erRJPkgg.png" /><figcaption><em>This diagram shows how the </em><em>fastapi-sub-modules repository is included </em><em>fastapi-sub-modules-logger-kit as a submodule. The logging package is managed separately but linked to the main project.</em></figcaption></figure><h3>Setting Up Git Submodules in FastAPI</h3><h3>1. Adding a Submodule to Your FastAPI Project</h3><p>To include a submodule inside your FastAPI project, use:</p><pre>git submodule add https://github.com/anqorithm/fastapi-sub-modules-logger-kit.git modules/logger-kit</pre><p>This will:</p><ul><li>Clone the submodule inside modules/logger-kit.</li><li>Track it as a separate Git repository inside your main project.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZvYsV9xxbuW3p9NC5iG1Vg.png" /><figcaption><em>After running the command, </em><em>fastapi-sub-modules-logger-kit appears as a submodule inside the main project.</em></figcaption></figure><h3>2. Cloning a Repository with Submodules</h3><p>When someone clones your FastAPI project, they <strong>won’t automatically get the submodules</strong>. To pull them in:</p><pre>git clone --recurse-submodules https://github.com/anqorithm/fastapi-sub-modules.git</pre><p>If the repository was cloned normally, initialize and update submodules with:</p><pre>git submodule update --init --recursive</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gfe8uYuzFoqVVyoomL9kGw.png" /><figcaption><em>The --recurse-submodules flag ensures that all submodules are fetched along with the main project.</em></figcaption></figure><h3>3. Updating a Submodule</h3><p>If fastapi-sub-modules-logger-kit is updated externally, pull the latest changes inside your main project:</p><pre>cd modules/logger-kit<br>git pull origin main</pre><p>Then commit the updated submodule reference in the main repository:</p><pre>git add modules/logger-kit<br>git commit -m &quot;chore: updated logger-kit submodule to latest version&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*_4uAVWgD2FJEgi2RybbaNw.png" /><figcaption><em>Submodules can be updated independently and pulled into the main project as needed.</em></figcaption></figure><h3>4. Removing a Submodule</h3><p>To remove a submodule, follow these steps:</p><pre>git submodule deinit -f modules/logger-kit<br>git rm -rf modules/logger-kit<br>rm -rf .git/modules/logger-kit<br>git commit -m &quot;Removed logger-kit submodule&quot;</pre><p>This ensures the submodule is completely removed from the main repository.</p><h3>Example FastAPI Project with Git Submodules</h3><p>This is a fully working FastAPI project that demonstrates <strong>how to use Git submodules</strong> to keep your project modular. The example integrates a <strong>logging package (</strong><strong>fastapi-sub-modules-logger-kit)</strong> as a submodule within the <strong>main FastAPI project (</strong><strong>fastapi-sub-modules)</strong>.</p><h3>Project Structure</h3><pre>fastapi-sub-modules/<br>│── modules/<br>│   ├── logger-kit/  # Git submodule for logging<br>│── app/<br>│   ├── routers/<br>│   │   ├── items.py  # API routes<br>│   ├── main.py       # FastAPI app entry point<br>│── .gitmodules       # Tracks submodule reference<br>│── pyproject.toml    # Poetry dependencies<br>│── README.md</pre><h3>1. Cloning the Project with Submodules</h3><p>Since fastapi-sub-modules-logger-kit is included as a Git submodule, clone the repository with:</p><pre>git clone --recurse-submodules https://github.com/anqorithm/fastapi-sub-modules.git</pre><p>If you forgot to include the submodules, initialize them manually:</p><pre>git submodule update --init --recursive</pre><h3>2. Installing Dependencies with Poetry</h3><p>This project uses <strong>Poetry</strong> for dependency management. Install dependencies using:</p><pre>cd fastapi-sub-modules<br>poetry install</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KEM-74nk2SgTRlN6UGf2XQ.png" /><figcaption>Setting up dependencies for the FastAPI sub-modules project using Poetry install while ensuring all required packages are properly updated and locked for a stable development environment</figcaption></figure><p>Ensure the logging package is included in pyproject.toml as a local dependency:</p><pre>[tool.poetry.dependencies]<br>python = &quot;^3.12&quot;<br>fastapi = &quot;^0.104.1&quot;<br>uvicorn = &quot;^0.24.0&quot;<br># Add logger-kit as a local dependency<br>fastapi-sub-modules-logger-kit = { path = &quot;./logger_kit&quot;, develop = true }<br></pre><h3>3. FastAPI Application</h3><p>The main.py file initializes the FastAPI app and integrates the logging submodule.</p><pre>from fastapi import FastAPI<br>from .routers import items<br>from logger_kit import app_logger, RequestLoggingMiddleware<br>app = FastAPI(title=&quot;FastAPI with Submodules&quot;)<br><br># Apply middleware to log requests, excluding health checks<br>app.add_middleware(RequestLoggingMiddleware, exclude_paths={&quot;/health&quot;})<br><br># Include API routes<br>app.include_router(items.router, prefix=&quot;/api/v1&quot;, tags=[&quot;items&quot;])<br>@app.get(&quot;/&quot;)<br>async def root():<br>    app_logger.info(&quot;Root endpoint accessed&quot;)<br>    return {&quot;message&quot;: &quot;Welcome to FastAPI with Git Submodules&quot;}<br>@app.get(&quot;/health&quot;)<br>async def health_check():<br>    return {&quot;status&quot;: &quot;healthy&quot;}</pre><h3>4. Implementing API Routes</h3><p>The API endpoints use the <strong>logging module</strong> from the submodule.</p><pre>from fastapi import APIRouter<br>from logger_kit import app_logger<br><br>router = APIRouter()<br>@router.get(&quot;/items&quot;)<br>async def read_items():<br>    # using the logger for info<br>    app_logger.info({<br>        &quot;action&quot;: &quot;fetch_items&quot;,<br>        &quot;message&quot;: &quot;Retrieving all items&quot;<br>    })<br>    items = [&quot;item1&quot;, &quot;item2&quot;]<br>    # using the logger for debug<br>    app_logger.debug(f&quot;Found {len(items)} items&quot;)<br>    return {&quot;items&quot;: items}<br>@router.get(&quot;/items/{item_id}&quot;)<br>async def read_item(item_id: int):<br>    # using the logger for info<br>    app_logger.info({<br>        &quot;action&quot;: &quot;fetch_item&quot;,<br>        &quot;item_id&quot;: item_id,<br>        &quot;message&quot;: f&quot;Retrieving item {item_id}&quot;<br>    })<br>    return {&quot;item_id&quot;: item_id}<br></pre><h3>5. Running the FastAPI Application</h3><p>Start the FastAPI application using Poetry:</p><pre>poetry run uvicorn app.main:app --reload</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVm1NJ6duNR41X3EAQ-ptQ.png" /><figcaption>Running FastAPI with Uvicorn in development mode while debugging API requests and responses, ensuring smooth execution and monitoring logs for any potential issues in the application</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHpNgvQl9jdsQoXaaDCDww.png" /><figcaption>Monitoring API activity in real-time with structured logging in VS Code, capturing detailed request and response logs for enhanced debugging and observability in the FastAPI project</figcaption></figure><h3>6. Expected Behavior</h3><p><strong>1. Fetch All Items </strong><strong>[GET /api/v1/items]</strong></p><pre>{<br>    &quot;items&quot;: [&quot;item1&quot;, &quot;item2&quot;]<br>}</pre><p><strong>Log Output:</strong></p><pre>INFO:logger: {&#39;action&#39;: &#39;fetch_items&#39;, &#39;message&#39;: &#39;Retrieving all items&#39;}<br>DEBUG:logger: Found 2 items</pre><p><strong>2. Fetch a Single Item </strong><strong>[GET /api/v1/items/42]</strong></p><pre>{<br>    &quot;item_id&quot;: 42<br>}</pre><p><strong>Log Output:</strong></p><pre>INFO:logger: {&#39;action&#39;: &#39;fetch_item&#39;, &#39;item_id&#39;: 42, &#39;message&#39;: &#39;Retrieving item 42&#39;}</pre><h3>7. Updating the Submodule</h3><p>If the fastapi-sub-modules-logger-kit submodule gets updated, pull the latest changes:</p><pre>cd modules/logger-kit<br>git pull origin main<br>cd ../..<br>poetry lock --no-update<br>poetry install</pre><h3>Conclusion</h3><p>Using Git submodules in FastAPI projects provides a structured way to <strong>keep your code modular, reusable, and easy to maintain</strong>. Instead of cluttering your repository with unrelated features, you can separate concerns into independent submodules and manage them efficiently.</p><p><strong>Summary:</strong></p><ul><li>Submodules help maintain a clean and modular FastAPI project structure.</li><li>They allow independent updates while remaining linked to the main project.</li><li>They are useful for sharing reusable components like logging, authentication, or database utilities across multiple projects.</li></ul><p>By following this approach, your FastAPI app remains <strong>organized, scalable, and easier to maintain</strong>.</p><h3>Repositories</h3><ul><li><strong>Main FastAPI Project:</strong> <a href="https://github.com/anqorithm/fastapi-sub-modules">fastapi-sub-modules</a> – A modular FastAPI application using Git submodules.</li></ul><p><a href="https://github.com/anqorithm/fastapi-sub-modules">GitHub - anqorithm/fastapi-sub-modules</a></p><ul><li><strong>Logging Submodule:</strong> <a href="https://github.com/anqorithm/fastapi-sub-modules-logger-kit/tree/bc5595af66aa47697c3b231227a9fc9313faf8c0">fastapi-sub-modules-logger-kit</a> – A separate logging module integrated into the main project.</li></ul><p><a href="https://github.com/anqorithm/fastapi-sub-modules-logger-kit/tree/bc5595af66aa47697c3b231227a9fc9313faf8c0">GitHub - anqorithm/fastapi-sub-modules-logger-kit at bc5595af66aa47697c3b231227a9fc9313faf8c0</a></p><h3>Resources</h3><ul><li><strong>Main FastAPI Project:</strong> <a href="https://github.com/anqorithm/fastapi-sub-modules">https://github.com/anqorithm/fastapi-sub-modules</a></li><li><strong>Logging Submodule:</strong> <a href="https://github.com/anqorithm/fastapi-sub-modules-logger-kit/tree/bc5595af66aa47697c3b231227a9fc9313faf8c0">https://github.com/anqorithm/fastapi-sub-modules-logger-kit/tree/bc5595af66aa47697c3b231227a9fc9313faf8c0</a></li><li><strong>Git Submodules Documentation:</strong> <a href="https://git-scm.com/book/en/v2/Git-Tools-Submodules">https://git-scm.com/book/en/v2/Git-Tools-Submodules</a></li><li><strong>FastAPI Official Documentation:</strong> <a href="https://fastapi.tiangolo.com/">https://fastapi.tiangolo.com/</a></li><li><strong>Poetry Official Documentation:</strong> <a href="https://python-poetry.org/docs/">https://python-poetry.org/docs/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ae21d4a83b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transforming Cursor into a VSCode-like Experience in WSL: Setting Up the AI Code Editor]]></title>
            <link>https://anqorithm.medium.com/transforming-cursor-into-a-vscode-like-experience-in-wsl-setting-up-the-ai-code-editor-fee5a531015d?source=rss-30833ccf4538------2</link>
            <guid isPermaLink="false">https://medium.com/p/fee5a531015d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cursor-ai]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Abdullah Alqahtani]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 10:00:15 GMT</pubDate>
            <atom:updated>2024-10-26T10:00:15.295Z</atom:updated>
            <content:encoded><![CDATA[<h4>Customize Cursor 🪝</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vtzg0YYHXj5hfKf773SuLg.png" /><figcaption>Transforming Cursor into a VSCode-like Experience in WSL: Setting Up the AI Code Editor</figcaption></figure><p><strong>Introduction</strong></p><p>In the world of development, a comfortable and efficient working environment is crucial for productivity. Cursor, <strong>The AI Code Editor</strong>, is built to make you extraordinarily productive, offering powerful AI tools to enhance your coding experience. Customizing Cursor in the Windows Subsystem for Linux (WSL) can optimize your workflow. This guide will walk you through the installation and setup process step-by-step.</p><h4>Understanding the Cursor Code Editor</h4><p><strong>Cursor</strong> is designed to enhance productivity by integrating AI capabilities directly into the coding process. It provides a clean interface and intelligent features that allow developers to focus on writing high-quality code. Customizing your environment, including the cursor and layout, can lead to improved productivity and reduced strain during long coding sessions.</p><figure><img alt="Transforming Cursor into a VSCode-like Experience in WSL: Setting Up the AI Code Editor" src="https://cdn-images-1.medium.com/max/1024/0*yCOU7QskMSX6YGXd.jpeg" /></figure><figure><img alt="Transforming Cursor into a VSCode-like Experience in WSL: Setting Up the AI Code Editor" src="https://cdn-images-1.medium.com/max/1024/0*dlYwu1wyIGIJibVL.png" /></figure><h4>Step 1: Install the Cursor Code Editor</h4><ol><li><strong>Open PowerShell</strong>:</li></ol><ul><li>Press Win + X and select <strong>Windows PowerShell</strong> or <strong>Windows Terminal</strong> if available.</li></ul><ol><li><em>Insert an image of PowerShell/Windows Terminal here.</em></li><li><strong>Install Cursor</strong>:</li></ol><ul><li>In the PowerShell window, run the following command:</li></ul><pre>winget install Anysphere.Cursor</pre><figure><img alt="Transforming Cursor into a VSCode-like Experience in WSL: Setting Up the AI Code Editor" src="https://cdn-images-1.medium.com/max/1024/0*5VNA7RMfY4Xv6x-T.png" /></figure><ol><li><strong>Open WSL</strong>:</li></ol><ul><li>After the installation is complete, open your WSL distribution (e.g., Ubuntu) by searching for it in the Start menu or running wsl in PowerShell.</li></ul><ol><li><em>Insert an image showing how to open WSL.</em></li><li><strong>Navigate to the Cursor Directory</strong>:</li></ol><ul><li>In your WSL terminal, run the following command to navigate to the cursor installation directory:</li></ul><pre>cd /mnt/c/Users/&lt;USER_NAME&gt;/AppData/Local/Programs/cursor/resources/app/bin</pre><ul><li>Replace &lt;USER_NAME&gt; with your actual Windows username.</li></ul><figure><img alt="Transforming Cursor into a VSCode-like Experience in WSL: Setting Up the AI Code Editor" src="https://cdn-images-1.medium.com/max/1024/0*HiGw2ER-6GqK3Gfi.png" /></figure><ol><li><strong>Add the Cursor to Your WSL</strong>:</li><li>To make this more permanent I can add the path to my .zshrc file:</li></ol><pre>echo -e &#39;\n# Cursor \nexport PATH=&quot;$PATH:/mnt/c/Users/&lt;USER_NAME&gt;/AppData/Local/Programs/cursor/resources/app/bin&quot;&#39; &gt;&gt; ~/.zshrc</pre><ol><li>Then source the .zshrc file with source ~/.zshrc.</li><li>Now I should be able to run the cursor . command by navigating to that file and running it from the terminal.</li></ol><figure><img alt="Transforming Cursor into a VSCode-like Experience in WSL: Setting Up the AI Code Editor" src="https://cdn-images-1.medium.com/max/1024/0*s9FMdHw52rA0Jdm0.png" /></figure><h4>Step 2: Making the Activity Bar Vertical in Cursor</h4><ol><li><strong>Open Settings</strong>:</li></ol><ul><li>In Cursor, access the settings by navigating to the settings icon or using a shortcut (typically Ctrl + ,).</li></ul><ol><li><em>Insert an image showing how to access settings in Cursor.</em></li><li><strong>Change Activity Bar Orientation</strong>:</li></ol><ul><li>Look for the option labeled <strong>Activity Bar Orientation</strong>.</li><li>Change the setting from <strong>horizontal</strong> to <strong>vertical</strong>.</li></ul><figure><img alt="Transforming Cursor into a VSCode-like Experience in WSL: Setting Up the AI Code Editor" src="https://cdn-images-1.medium.com/max/1024/0*1WR9GKpiCS6QKo4o.png" /></figure><ol><li><strong>Apply Changes</strong>:</li></ol><ul><li>Restart Cursor to apply the changes and see the activity bar in the new vertical orientation.</li></ul><figure><img alt="Transforming Cursor into a VSCode-like Experience in WSL: Setting Up the AI Code Editor" src="https://cdn-images-1.medium.com/max/1024/0*yH-JVDhj0JusyQgf.png" /></figure><h4>Conclusion</h4><p>Customizing the Cursor code editor in WSL will create a coding environment similar to Visual Studio Code. These simple adjustments can enhance your focus and productivity, making your development experience more enjoyable. Take a moment to implement these changes and enjoy a more tailored workspace!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fee5a531015d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating FastAPI with Keycloak for Authentication]]></title>
            <link>https://anqorithm.medium.com/integrating-fastapi-with-keycloak-for-authentication-151d0996afbc?source=rss-30833ccf4538------2</link>
            <guid isPermaLink="false">https://medium.com/p/151d0996afbc</guid>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Abdullah Alqahtani]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 08:16:25 GMT</pubDate>
            <atom:updated>2024-09-26T21:54:57.495Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simple Guide to Connecting FastAPI with Keycloak for Authentication using Python, Poetry, and Docker</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6hOvxH0uBk-Qjkx60wIAw.jpeg" /><figcaption>Integrating FastAPI with Keycloak for Authentication</figcaption></figure><p>In this article, we’ll explore how to secure a FastAPI application using Keycloak as the authentication provider. We’ll walk through setting up the FastAPI application, managing dependencies with Poetry, integrating it with a production-ready Keycloak server, and testing the authentication flow. This guide assumes that you already have a Keycloak server up and running.</p><h3>Introduction</h3><p>FastAPI is a modern, high-performance web framework for building APIs with Python. Keycloak is an open-source identity and access management solution that adds authentication to applications and secure services. By integrating Keycloak with FastAPI, you can implement robust authentication and authorization without building it from scratch.</p><h3>Prerequisites</h3><ul><li><strong>Python 3.12+</strong>: Ensure you have Python installed.</li><li><strong>Poetry</strong>: For dependency management.</li><li><strong>Docker and Docker Compose</strong>: This is used to containerize the application.</li><li><strong>Git</strong>: For cloning the repository.</li><li><strong>Existing Keycloak Server</strong>: A production-ready Keycloak server configured with the necessary realm, client, and users.</li><li><strong>Keycloak Server URL</strong>: <a href="https://sso.anqorithm.com/auth">https://sso.anqorithm.com/auth</a></li><li><strong>GitHub Repository</strong>: <a href="https://github.com/anqorithm/fastapi-keycloak.git">https://github.com/anqorithm/fastapi-keycloak.git</a></li></ul><h3>Key Highlights</h3><ul><li><strong>FastAPI</strong>: A modern web framework for building APIs with Python.</li><li><strong>Keycloak Integration</strong>: Offloads authentication and authorization to a dedicated identity provider.</li><li><strong>Poetry for Dependency Management</strong>: Simplifies dependency management and virtual environments.</li><li><strong>Dockerized Application</strong>: Simplifies deployment and ensures consistency across environments.</li><li><strong>Token-Based Authentication</strong>: Secures API endpoints using access tokens obtained from Keycloak.</li><li><strong>JWT Token-Based Authentication</strong>: Secures API endpoints using JSON Web Tokens (JWT) obtained from Keycloak, ensuring authenticated and authorized access to resources.</li></ul><h3>Project Structure</h3><p>Here’s the structure of the project we’ll be working with:</p><pre>fastapi-keycloak/<br>├── src/<br>│   ├── __init__.py<br>│   ├── main.py<br>│   ├── controller.py<br>│   ├── service.py<br>│   ├── models.py<br>│   ├── config.py<br>│   ├── .env.example<br>│   └── .env<br>├── assets/<br>│   ├── Integrating FastAPI with Keycloak for Authentication.jpg<br>│   └── other images...<br>├── Dockerfile<br>├── docker-compose.yaml<br>├── pyproject.toml<br>├── poetry.lock<br>├── README.md<br>├── LICENSE</pre><ul><li>src/: Contains the FastAPI application code.</li><li>assets/: Contains images used in this article.</li><li>Dockerfile and docker-compose.yaml: For containerizing the application.</li><li>pyproject.toml and poetry.lock: For dependency management with Poetry.</li></ul><h3>Setting Up Keycloak</h3><p>Before integrating Keycloak with FastAPI, we need to set up Keycloak by creating a new realm, client, and user.</p><h3>1. Access Keycloak Admin Console</h3><p>Open your web browser and navigate to the Keycloak Admin Console at:</p><pre>https://sso.anqorithm.com/auth/admin/</pre><p>Log in with your administrator account.</p><h3>2. Create a New Realm</h3><ul><li>Click on the <strong>Master</strong> realm dropdown on the left-hand side.</li><li>Click on <strong>Add Realm</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYrXn1jnoZpAxdYQm8czsg.png" /><figcaption>Creating a New Realm</figcaption></figure><ul><li><strong>Realm Name</strong>: Enter testing.</li><li>Click <strong>Create</strong>.</li></ul><h3>3. Create a New Client</h3><ul><li>In the left sidebar, select <strong>Clients</strong>.</li><li>Click on <strong>Create</strong>.</li><li><strong>Client ID</strong>: Enter fastapi-keycloak.</li><li><strong>Client Protocol</strong>: Ensure it’s set to openid-connect.</li><li>Click <strong>Save</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYA1XbfCMvfnQP3TuVFWlQ.png" /><figcaption>Creating a New Client 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btFx1GyHU0g9JvYQrzxB7A.png" /><figcaption>Creating a New Client 2</figcaption></figure><ul><li>Configure the client:</li><li><strong>Access Type</strong>: Set to confidential.</li><li><strong>Standard Flow Enabled</strong>: ON.</li><li><strong>Direct Access Grants Enabled</strong>: ON.</li><li><strong>Root URL</strong>: http://localhost:8000/ (or your FastAPI app URL).</li><li><strong>Valid Redirect URIs</strong>: <a href="http://localhost:8000/*.">http://localhost:8000/*.</a></li><li>Click <strong>Save</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLogZkuk1iyvfumm4AsBOw.png" /><figcaption>Creating a New Client 3</figcaption></figure><h3>4. Obtain Client Secret</h3><ul><li>After saving, navigate to the <strong>Credentials</strong> tab.</li><li>Your <strong>Client Secret</strong> will be displayed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEp3cKqMMNXOmQ78JXwzuw.png" /><figcaption>Obtaining Client Secret</figcaption></figure><ul><li>Copy the <strong>Client Secret</strong>. You’ll need it for configuring your FastAPI application.</li></ul><h3>5. Create a New User</h3><ul><li>In the left sidebar, select <strong>Users</strong>.</li><li>Click on <strong>Add User</strong>.</li><li><strong>Username</strong>: Enter your-username.</li><li><strong>Email: </strong>Enter your-email.</li><li><strong>First Name</strong>: your-first-name.</li><li><strong>Last Name</strong>: your-last-name</li><li>Set other optional fields as desired.</li><li>Click <strong>Save</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O_Ov-jvnooZUNv_pXidNfQ.png" /><figcaption>Adding a New User</figcaption></figure><h3>6. Set User Password</h3><ul><li>After saving the user, navigate to the <strong>Credentials</strong> tab.</li><li>Set a password for the user:</li><li><strong>New Password</strong>: Enter a password.</li><li><strong>Confirm Password</strong>: Re-enter the password.</li><li><strong>Temporary</strong>: Set to OFF.</li><li>Click <strong>Save</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUTmIqYC7XPfh2CeTKBnoQ.png" /><figcaption>Setting User Password</figcaption></figure><p>Your Keycloak setup is now complete.</p><h3>Setting Up the FastAPI Application</h3><h3>1. Clone the Repository</h3><p>First, clone the repository and navigate into the project directory:</p><pre>git clone https://github.com/anqorithm/fastapi-keycloak.git<br>cd fastapi-keycloak</pre><h3>2. Set Up Environment Variables</h3><p>Copy the example environment file and update it with your Keycloak configuration:</p><pre>cp src/.env.example src/.env</pre><p>Edit src/.env and set the following variables:</p><pre>KEYCLOAK_SERVER_URL=https://sso.anqorithm.com/auth<br>KEYCLOAK_REALM=testing<br>KEYCLOAK_CLIENT_ID=fastapi-keycloak<br>KEYCLOAK_CLIENT_SECRET=your-client-secret</pre><ul><li><strong>KEYCLOAK_SERVER_URL</strong>: The URL where your Keycloak server is accessible.</li><li><strong>KEYCLOAK_REALM</strong>: The realm you have configured in Keycloak (e.g., testing).</li><li><strong>KEYCLOAK_CLIENT_ID</strong>: The client ID for your application in Keycloak (e.g., fastapi-keycloak).</li><li><strong>KEYCLOAK_CLIENT_SECRET</strong>: The secret associated with your client.</li></ul><blockquote><strong><em>Note:</em></strong><em> Replace </em><em>your-client-secret with the actual client secret from your Keycloak client configuration. Ensure you keep your client secret secure and do not expose it in public repositories.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZY0xLEHz_mBXWNYLM0UaQ.png" /><figcaption>Editing the .env File</figcaption></figure><h3>3. Understanding the Application Code</h3><p>Let’s dive into the code files and understand how they work together.</p><h4>a. main.py</h4><p>This is the entry point of the FastAPI application.</p><pre>from fastapi import FastAPI, Depends, Form<br>from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials<br>from src.models import TokenResponse, UserInfo<br>from src.controller import AuthController<br><br># Initialize the FastAPI app<br>app = FastAPI()<br><br># Initialize the HTTPBearer scheme for authentication<br>bearer_scheme = HTTPBearer()<br><br><br># Define the root endpoint<br>@app.get(&quot;/&quot;)<br>async def read_root():<br>    &quot;&quot;&quot;<br>    Root endpoint that provides a welcome message and documentation link.<br>    &quot;&quot;&quot;<br>    return AuthController.read_root()<br><br><br># Define the login endpoint<br>@app.post(&quot;/login&quot;, response_model=TokenResponse)<br>async def login(username: str = Form(...), password: str = Form(...)):<br>    &quot;&quot;&quot;<br>    Login endpoint to authenticate the user and return an access token.<br><br>    Args:<br>        username (str): The username of the user attempting to log in.<br>        password (str): The password of the user.<br><br>    Returns:<br>        TokenResponse: Contains the access token upon successful authentication.<br>    &quot;&quot;&quot;<br>    return AuthController.login(username, password)<br><br><br># Define the protected endpoint<br>@app.get(&quot;/protected&quot;, response_model=UserInfo)<br>async def protected_endpoint(<br>    credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),<br>):<br>    &quot;&quot;&quot;<br>    Protected endpoint that requires a valid token for access.<br><br>    Args:<br>        credentials (HTTPAuthorizationCredentials): Bearer token provided via HTTP Authorization header.<br><br>    Returns:<br>        UserInfo: Information about the authenticated user.<br>    &quot;&quot;&quot;<br>    return AuthController.protected_endpoint(credentials)</pre><ul><li><strong>Endpoints</strong>:</li><li>GET /: Returns a welcome message.</li><li>POST /login: Authenticates the user and returns an access token.</li><li>GET /protected: A protected endpoint that requires a valid token.</li></ul><h4>b. models.py</h4><p>Defines the data models used in the application.</p><pre>from pydantic import BaseModel<br>from typing import Optional<br><br><br>class TokenRequest(BaseModel):<br>    username: str<br>    password: str<br><br><br>class TokenResponse(BaseModel):<br>    access_token: str<br>    token_type: str = &quot;bearer&quot;<br><br><br>class UserInfo(BaseModel):<br>    preferred_username: str<br>    email: Optional[str] = None<br>    full_name: Optional[str] = None</pre><h4>c. config.py</h4><p>Loads the environment variables and initializes the Keycloak client.</p><pre>from pydantic_settings import BaseSettings<br>from pydantic import Field<br>from keycloak import KeycloakOpenID<br><br>class Settings(BaseSettings):<br>    keycloak_server_url: str = Field(..., env=&quot;KEYCLOAK_SERVER_URL&quot;)<br>    keycloak_realm: str = Field(..., env=&quot;KEYCLOAK_REALM&quot;)<br>    keycloak_client_id: str = Field(..., env=&quot;KEYCLOAK_CLIENT_ID&quot;)<br>    keycloak_client_secret: str = Field(..., env=&quot;KEYCLOAK_CLIENT_SECRET&quot;)<br><br>    class Config:<br>        env_file = &quot;.env&quot;<br>        env_file_encoding = &quot;utf-8&quot;<br><br><br>settings = Settings()<br><br>keycloak_openid = KeycloakOpenID(<br>    server_url=settings.keycloak_server_url,<br>    realm_name=settings.keycloak_realm,<br>    client_id=settings.keycloak_client_id,<br>    client_secret_key=settings.keycloak_client_secret,<br>)<br><br>def get_openid_config():<br>    return keycloak_openid.well_known()</pre><h4>d. service.py</h4><p>Handles communication with Keycloak.</p><pre>from fastapi import HTTPException, status<br>from keycloak.exceptions import KeycloakAuthenticationError<br>from src.config import keycloak_openid<br>from src.models import UserInfo<br><br><br>class AuthService:<br>    @staticmethod<br>    def authenticate_user(username: str, password: str) -&gt; str:<br>        &quot;&quot;&quot;<br>        Authenticate the user using Keycloak and return an access token.<br>        &quot;&quot;&quot;<br>        try:<br>            token = keycloak_openid.token(username, password)<br>            return token[&quot;access_token&quot;]<br>        except KeycloakAuthenticationError:<br>            raise HTTPException(<br>                status_code=status.HTTP_401_UNAUTHORIZED,<br>                detail=&quot;Invalid username or password&quot;,<br>            )<br><br>    @staticmethod<br>    def verify_token(token: str) -&gt; UserInfo:<br>        &quot;&quot;&quot;<br>        Verify the given token and return user information.<br>        &quot;&quot;&quot;<br>        try:<br>            user_info = keycloak_openid.userinfo(token)<br>            print(user_info)<br>            if not user_info:<br>                raise HTTPException(<br>                    status_code=status.HTTP_401_UNAUTHORIZED, detail=&quot;Invalid token&quot;<br>                )<br>            return UserInfo(<br>                preferred_username=user_info[&quot;preferred_username&quot;],<br>                email=user_info.get(&quot;email&quot;),<br>                full_name=user_info.get(&quot;name&quot;),<br>            )<br>        except KeycloakAuthenticationError:<br>            raise HTTPException(<br>                status_code=status.HTTP_401_UNAUTHORIZED,<br>                detail=&quot;Could not validate credentials&quot;,<br>            )</pre><h4>e. controller.py</h4><p>It contains the logic for handling requests.</p><pre>from fastapi import Depends, HTTPException, status, Form<br>from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials<br>from src.models import TokenResponse, UserInfo<br>from src.service import AuthService<br><br># Initialize HTTPBearer security dependency<br>bearer_scheme = HTTPBearer()<br><br><br>class AuthController:<br>    &quot;&quot;&quot;<br>    Controller for handling authentication logic.<br>    &quot;&quot;&quot;<br><br>    @staticmethod<br>    def read_root():<br>        &quot;&quot;&quot;<br>        Root endpoint providing basic information and documentation link.<br><br>        Returns:<br>            dict: A welcome message and link to the documentation.<br>        &quot;&quot;&quot;<br>        return {<br>            &quot;message&quot;: (<br>                &quot;Welcome to the Keycloak authentication system. &quot;<br>                &quot;Use the /login endpoint to authenticate and /protected to access the protected resource.&quot;<br>            ),<br>            &quot;documentation&quot;: &quot;/docs&quot;,<br>        }<br><br>    @staticmethod<br>    def login(username: str = Form(...), password: str = Form(...)) -&gt; TokenResponse:<br>        &quot;&quot;&quot;<br>        Authenticate user and return access token.<br><br>        Args:<br>            username (str): The username of the user attempting to log in.<br>            password (str): The password of the user.<br><br>        Raises:<br>            HTTPException: If the authentication fails (wrong credentials).<br><br>        Returns:<br>            TokenResponse: Contains the access token upon successful authentication.<br>        &quot;&quot;&quot;<br>        # Authenticate the user using the AuthService<br>        access_token = AuthService.authenticate_user(username, password)<br><br>        if not access_token:<br>            raise HTTPException(<br>                status_code=status.HTTP_401_UNAUTHORIZED,<br>                detail=&quot;Invalid username or password&quot;,<br>            )<br><br>        return TokenResponse(access_token=access_token)<br><br>    @staticmethod<br>    def protected_endpoint(<br>        credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),<br>    ) -&gt; UserInfo:<br>        &quot;&quot;&quot;<br>        Access a protected resource that requires valid token authentication.<br><br>        Args:<br>            credentials (HTTPAuthorizationCredentials): Bearer token provided via HTTP Authorization header.<br><br>        Raises:<br>            HTTPException: If the token is invalid or not provided.<br><br>        Returns:<br>            UserInfo: Information about the authenticated user.<br>        &quot;&quot;&quot;<br>        # Extract the bearer token from the provided credentials<br>        token = credentials.credentials<br><br>        # Verify the token and get user information<br>        user_info = AuthService.verify_token(token)<br><br>        if not user_info:<br>            raise HTTPException(<br>                status_code=status.HTTP_401_UNAUTHORIZED,<br>                detail=&quot;Invalid token&quot;,<br>                headers={&quot;WWW-Authenticate&quot;: &quot;Bearer&quot;},<br>            )<br><br>        return user_info</pre><h3>Managing Dependencies with Poetry</h3><p><a href="https://python-poetry.org/">Poetry</a> is a tool for dependency management and packaging in Python. It allows you to declare the libraries your project depends on and manages them for you.</p><h3>1. Installing Poetry</h3><p>If you haven’t installed Poetry yet, you can do so using the following command:</p><pre>curl -sSL https://install.python-poetry.org | python3 -</pre><p>After installation, ensure that Poetry’s bin directory is in your PATH. You can verify the installation by running:</p><pre>poetry --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YH2NBwH93E-PgmjLH2X_3Q.png" /><figcaption>Installing Poetry</figcaption></figure><h3>2. Using pyproject.toml to Manage Dependencies</h3><p>The pyproject.toml file is where you specify your project&#39;s dependencies and other configurations.</p><p>Here’s the content of the pyproject.toml file:</p><pre>[tool.poetry]<br>name = &quot;fastapi-keycloak&quot;<br>version = &quot;0.0.1&quot;<br>description = &quot;&quot;<br>authors = [&quot;Abdullah Alqahtani &lt;abdullah@lameh.ai&gt;&quot;]<br>readme = &quot;README.md&quot;</pre><pre>[tool.poetry.dependencies]<br>python = &quot;^3.12&quot;<br>fastapi = {extras = [&quot;standard&quot;], version = &quot;^0.115.0&quot;}<br>python-keycloak = &quot;^4.4.0&quot;<br>httpx = &quot;^0.27.2&quot;<br>pydantic = &quot;^2.9.2&quot;<br>pydantic-settings = &quot;^2.5.2&quot;<br></pre><pre>[build-system]<br>requires = [&quot;poetry-core&quot;]<br>build-backend = &quot;poetry.core.masonry.api&quot;</pre><ul><li><strong>Dependencies</strong>:</li><li>fastapi: The web framework.</li><li>python-keycloak: Library to interact with Keycloak.</li><li>httpx: For making HTTP requests.</li><li>pydantic: For data validation.</li><li>pydantic-settings: For managing settings using Pydantic.</li></ul><h3>3. Installing Dependencies</h3><p>Run the following command to install all dependencies specified in pyproject.toml:</p><pre>poetry install</pre><p>This command will create a virtual environment and install all the required packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpAykLgGEdXjK2I5XjNgWw.png" /><figcaption>Installing Dependencies with Poetry</figcaption></figure><h3>4. Activating the Poetry Shell</h3><p>To activate the virtual environment created by Poetry, run:</p><pre>poetry shell</pre><p>This command spawns a new shell within the virtual environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x0ThQSAd3hEeDDybgZZB4w.png" /><figcaption>Activating Poetry Shell</figcaption></figure><h3>Running the Application</h3><h3>1. Running with Uvicorn</h3><p>You can run the FastAPI application using Uvicorn, an ASGI server:</p><pre>uvicorn src.main:app --reload</pre><ul><li>src.main:app points to the app instance in main.py.</li><li>--reload enables auto-reload on code changes.</li></ul><h3>2. Running with FastAPI CLI</h3><p>Alternatively, you can run the application using the FastAPI CLI if you have it installed:</p><pre>fastapi run src/main.py --reload</pre><h3>3. Running Inside Docker</h3><p>If you prefer to run the application inside Docker (as specified in the Dockerfile and docker-compose.yaml), use:</p><pre>docker-compose up --build</pre><p>This command builds the Docker image and starts the container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sfjKlkgvNKNF4rTIh-1Gw.png" /><figcaption>Running Docker Compose</figcaption></figure><h3>4. Accessing the Application</h3><p>Once the application is running, it will be accessible at <a href="http://localhost:8000/">http://localhost:8000/.</a></p><h3>Testing the Authentication Flow</h3><p>Let’s test the authentication flow using the endpoints we have defined.</p><h3>1. Accessing the Root Endpoint</h3><p>Open your browser and navigate to <a href="http://localhost:8000/">http://localhost:8000/.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzu3EsW9YDtr5x8H1Z8qfA.png" /><figcaption>Root endpoint</figcaption></figure><p>You should see a welcome message with a link to the documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfsJSsU4tMPeE02ocdEJXg.png" /><figcaption>Swagger docs</figcaption></figure><h3>2. Accessing the Protected Endpoint Without Authentication</h3><p>Try accessing the protected endpoint without a token:</p><pre>curl -X GET http://localhost:8000/protected</pre><p><strong>Response</strong>:</p><pre>{<br>  &quot;detail&quot;: &quot;Not authenticated&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dyXwQjYn69Wbz4MRL822WA.png" /><figcaption>Unauthorized Access</figcaption></figure><h3>3. Authenticating with the /login Endpoint</h3><p>Obtain an access token by providing your Keycloak credentials.</p><h4>a. Successful Authentication</h4><p>Use valid credentials to authenticate:</p><pre>curl -X POST http://localhost:8000/login \<br>  -H &quot;Content-Type: application/x-www-form-urlencoded&quot; \<br>  -d &quot;username=abdullah&amp;password=Test#123456&quot;</pre><p>Replace abdullah and Test#123456 with your Keycloak user credentials.</p><p><strong>Response</strong>:</p><pre>{<br>  &quot;access_token&quot;: &quot;eyJhbGciOiJSUzI1NiIsInR...&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y_qfQlKKXb93u4zgkfLCWw.png" /><figcaption><strong>Successful Login</strong></figcaption></figure><h4>b. Failed Authentication</h4><p>Use invalid credentials to simulate a failed login attempt:</p><pre>curl -X POST http://localhost:8000/login \<br>  -H &quot;Content-Type: application/x-www-form-urlencoded&quot; \<br>  -d &quot;username=abdullah&amp;password=abdullah&quot;</pre><p><strong>Response</strong>:</p><pre>{<br>  &quot;detail&quot;: &quot;Invalid username or password&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImEwTZbVtKdPz2V3c1eU0A.png" /><figcaption>Failed Login</figcaption></figure><h3>4. Accessing the Protected Endpoint with the Token</h3><p>Use the obtained access_token to access the protected endpoint:</p><pre>curl -X GET http://localhost:8000/protected \<br>  -H &quot;Authorization: Bearer your_access_token&quot;</pre><p>Replace your_access_token with the token you received.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QF7R5nrxfllkaoSht2JhKw.png" /><figcaption>Insert the JWT inside the authorize button</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JR_yEpF-l5rjGEd01vfkQ.png" /><figcaption>Successfully inserted</figcaption></figure><p><strong>Response</strong>:</p><pre>{<br>  &quot;preferred_username&quot;: &quot;your-username&quot;,<br>  &quot;email&quot;: &quot;your-email@example.com&quot;,<br>  &quot;full_name&quot;: &quot;Your Full Name&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMn2KLkSH4li5bx4Gui5Yw.png" /><figcaption>Authorized Access</figcaption></figure><p>5. Using Swagger UI</p><p>FastAPI provides interactive API documentation at <a href="http://localhost:8000/docs.">http://localhost:8000/docs.</a></p><p>You can test the endpoints directly from the Swagger UI.</p><h4>Testing /login Endpoint in Swagger</h4><ul><li>Click on the /login endpoint.</li><li>Click <strong>Try it out</strong>.</li><li>Enter your username and password.</li><li>Click <strong>Execute</strong>.</li></ul><p>Testing /protected Endpoint in Swagger</p><ul><li>Obtain the access token from the /login response.</li><li>Click on the <strong>Authorize</strong> button (lock icon).</li><li>Enter Bearer your_access_token in the <strong>value</strong> field.</li><li>Click <strong>Authorize</strong>.</li></ul><p>Now, test the /protected endpoint by clicking <strong>Try it out</strong> and then <strong>Execute</strong>.</p><h3>Conclusion</h3><p>FastAPI has been integrated with Keycloak, and dependencies are managed using Poetry. This setup includes on-premise security management, ensuring that authentication and authorization processes remain within the organization’s infrastructure. By utilizing OpenID Connect protocols, the system offers robust security features and better user management, all while providing greater control over data security, compliance, and internal policies.</p><h3>Repository</h3><p>You will find the source code for this article in the following GitHub repository</p><p><a href="https://github.com/anqorithm/fastapi-keycloak">GitHub - anqorithm/fastapi-keycloak: This project demonstrates how to integrate Keycloak with a FastAPI application using Docker and Docker Compose for authentication.</a></p><h3>Contact Me</h3><p>Feel free to connect with me on <a href="https://www.linkedin.com/in/anqahtani/">LinkedIn</a> for further discussions or inquiries 😁.</p><h3>References</h3><ul><li><a href="https://fastapi.tiangolo.com/">FastAPI Documentation</a></li><li><a href="https://www.keycloak.org/documentation">Keycloak Documentation</a></li><li><a href="https://pypi.org/project/python-keycloak/">Python Keycloak Library</a></li><li><a href="https://python-poetry.org/docs/">Poetry Dependency Management</a></li><li><a href="https://www.uvicorn.org/">Uvicorn ASGI Serve</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=151d0996afbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Production-Ready Keycloak Server on GCP with Cloudflare]]></title>
            <link>https://anqorithm.medium.com/deploying-a-production-ready-keycloak-server-on-gcp-with-cloudflare-81ee074eaf3a?source=rss-30833ccf4538------2</link>
            <guid isPermaLink="false">https://medium.com/p/81ee074eaf3a</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[keycloak]]></category>
            <dc:creator><![CDATA[Abdullah Alqahtani]]></dc:creator>
            <pubDate>Sat, 21 Sep 2024 14:57:29 GMT</pubDate>
            <atom:updated>2024-09-21T14:57:29.279Z</atom:updated>
            <content:encoded><![CDATA[<h4>Keycloak, PostgreSQL, Nginx, Certbot in a Docker Compose Stack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DV5gFgyvLZ0gN8arsKgoQ.jpeg" /><figcaption>Deploying a Production-Ready Keycloak Server on GCP with Cloudflare</figcaption></figure><h4><strong>Introduction</strong></h4><p>Keycloak is an open-source tool that makes it easy to add login and user access features to your applications. You don’t need to worry about storing or authenticating users yourself. Keycloak handles it for you. It also offers helpful features like connecting to other user databases, multi-factor authentication, and managing users and their permissions. In this guide, we’ll show you how to set up Keycloak on GCP and protect it using Cloudflare.</p><h4>How Keycloak Works?</h4><p>Keycloak acts as a secure intermediary between users and applications, managing authentication. When a user tries to access an application, they are redirected to Keycloak, where they log in. If the credentials are valid, Keycloak generates a token and redirects the user back to the application for access. If invalid, an error is shown. Keycloak simplifies authentication and supports modern protocols like OAuth2 and OpenID Connect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*4shnrkkk7Pxvc09Z" /></figure><h4>Why Use Keycloak?</h4><p>Keycloak provides a centralized solution for managing authentication and authorization, making it easier to secure applications. It offers features like Single Sign-On (SSO), user federation, social login integration, and multi-factor authentication. With Keycloak, applications can delegate authentication, reducing security risks and simplifying user management. It supports modern protocols like OAuth2 and OpenID Connect, making it compatible with various platforms and easy to integrate into both web and mobile applications.</p><h4>Use Cases:</h4><p><strong>1. Single Sign-On (SSO):</strong> Keycloak allows users to log in once and access multiple applications without needing to authenticate again, enhancing user experience.<br> <br><strong>2. User Federation:</strong> It integrates with existing user directories like LDAP or Active Directory, enabling centralized user management for organizations.</p><p><strong>3. Social Login: </strong>Keycloak supports social identity providers like Google, Facebook, and GitHub, allowing users to log in with their existing social accounts.</p><p><strong>4. API Security:</strong> By using OAuth2 and OpenID Connect, Keycloak secures APIs, handling authentication and access control across distributed services.</p><p><strong>5. Multi-Factor Authentication:</strong> It enables organizations to enforce an additional layer of security by requiring multi-factor authentication (e.g., OTP, email verification).</p><p><strong>6. Microservices Architecture:</strong> Keycloak can manage authentication for microservices, ensuring consistent and secure access control across services.</p><h4>Prerequisites</h4><ul><li>A Google Cloud Platform (GCP) account with billing enabled</li><li>Basic familiarity with GCP Console and cloud computing concepts</li><li>A domain name that you own and can manage</li><li>A Cloudflare account for managing your domain and providing additional security</li><li>Basic understanding of Docker and containerization concepts</li></ul><h4><strong>Setting Up Your Environment</strong></h4><p><strong>Step 1: Creating and Configuring the VM on GCP:</strong> A virtual machine on Google Cloud Platform (GCP) and configured with open ports (80 and 443).</p><p>Before starting, ensure you have a virtual machine (VM) set up on Google Cloud Platform (GCP). The key requirement for this setup is that your VM must have ports 80 and 443 open to allow HTTP and HTTPS traffic. These open ports are crucial for the proper functioning of Keycloak and its secure communication. We’re using an Ubuntu 22.04 LTS-based VM for this guide, but the specific machine type isn’t critical as long as it meets the basic requirements for running Keycloak and has the necessary ports configured.</p><p>The following are the current specifications for our VM setup:</p><pre>Machine type: e2-medium (2 vCPU, 4 GB memory)<br>Zone: me-central1-b<br>OS: Ubuntu 22.04 LTS (jammy)<br>Boot disk: 20 GB balanced persistent disk<br>Network: <br> - External IP: Ephemeral<br> - Network tags: http-server, https-server<br> - Firewalls: HTTP and HTTPS traffic allowed<br>VM provisioning model: Spot VM<br>Security:<br> - Shielded VM with vTPM and Integrity Monitoring enabled<br> - SSH access configured<br>Service account: Compute Engine default service account</pre><p>Note that this is a Spot VM instance, which may be terminated at any time by GCP, and it uses an ephemeral external IP that may change if the instance is stopped and started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wvgiY0WrnAgfpoPLHpFeoA.png" /><figcaption>The Public External IP Server for the VM</figcaption></figure><p>Note that this is a Spot VM instance, which may be terminated at any time by GCP. The external IP (<strong>34.18.8.227</strong>) is ephemeral and may change if the instance is stopped and started. Keep this in mind when configuring your Keycloak server and any services that need to connect to it.</p><p>Finally, check reachability by pining the domain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HgfBgrZQztwom6om1FTlmA.png" /><figcaption>Check Reachability by Pining the Domain</figcaption></figure><p><strong>Step 2: Configuring Your Domain with Cloudflare</strong>: A domain name properly configured to point to your server.</p><p>To set up your domain, you’ll need a valid domain name registered with a domain registrar. Once you have your domain, add it to Cloudflare as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqVkCikmtemjW6KDGlIDUQ.png" /><figcaption>Valid Domain on Cloudflare</figcaption></figure><p>After adding your domain to Cloudflare, create an A record that points to your VM’s public IP address. It’s crucial to set Cloudflare to “DNS only” mode for this record by ensuring the proxy is turned off (the cloud icon should be grey, not orange). This configuration allows direct communication with your server. The following image illustrates the correct Cloudflare DNS settings for your reference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*st7s7QeQssE4GVtPb8OEng.png" /><figcaption>Cloudflare DNS settings showing the A record configuration with the proxy turned off</figcaption></figure><p>Don’t forget to update your domain’s nameservers to use Cloudflare’s nameservers, completing the setup process.</p><p><strong>Step 3: Setting Up Docker on Your Server</strong></p><p>If you haven’t already installed Docker Engine and Docker Compose on your server, follow these steps:</p><ol><li>Update your package list:</li></ol><pre>sudo apt update</pre><p>2. Install prerequisites:</p><pre>sudo apt install -y apt-transport-https ca-certificates curl software-properties-common</pre><p>3. Add Docker’s official GPG key:</p><pre>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg - dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg</pre><p>4. Set up the Docker repository:</p><pre>echo &quot;deb [arch=$(dpkg - print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable&quot; | sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null</pre><p>5. Update the package list again:</p><pre>sudo apt update</pre><p>6. Install Docker Engine:</p><pre>sudo apt install -y docker-ce docker-ce-cli containerd.io</pre><p>7. Add your user to the docker group (to run Docker without sudo):</p><pre>sudo usermod -aG docker $USER</pre><p>8. Install Docker Compose:</p><pre>sudo curl -L &quot;https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)&quot; -o /usr/local/bin/docker-compose<br>sudo chmod +x /usr/local/bin/docker-compose</pre><p>9. Verify the installations:</p><pre>docker - version<br>docker-compose - version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0S9vtlyiA0JBkZOOCw_jkg.png" /><figcaption>Docker and Docker Compose version commands and their output</figcaption></figure><p>After completing these steps, log out and log back in for the group changes to take effect.</p><p>If you prefer to use a script for installation, you can use the following:</p><pre>#!/bin/bash<br><br># Update the apt package index<br>sudo apt-get update<br><br># Install packages to allow apt to use a repository over HTTPS<br>sudo apt-get install -y \<br>    apt-transport-https \<br>    ca-certificates \<br>    curl \<br>    gnupg \<br>    lsb-release<br><br># Add Docker&#39;s official GPG key<br>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg<br><br># Set up the stable repository<br>echo \<br>  &quot;deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \<br>  $(lsb_release -cs) stable&quot; | sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null<br><br># Update the apt package index (again)<br>sudo apt-get update<br><br># Install Docker Engine<br>sudo apt-get install -y docker-ce docker-ce-cli containerd.io<br><br># Add your user to the docker group to run Docker without sudo<br>sudo usermod -aG docker $USER<br><br># Install Docker Compose<br>sudo curl -L &quot;https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)&quot; -o /usr/local/bin/docker-compose<br>sudo chmod +x /usr/local/bin/docker-compose<br><br>echo &quot;Docker and Docker Compose have been installed. Please log out and log back in for the group changes to take effect.&quot;</pre><p>Always review scripts before running them, especially when they require sudo privileges.</p><p><strong>Step 4: Setting Up Keycloak on Production Mode:</strong></p><p>Once you’re logged into your GCP VM and Docker is installed, follow these steps to clone the Keycloak repository, configure it, and run the Docker containers.</p><p>1. Clone the Keycloak Production Repository</p><p>Run the following commands to clone the repository:</p><pre># Clone the Keycloak production repository<br>git clone https://github.com/anqorithm/keycloak-production.git<br>cd keycloak-production</pre><p>2. Configure Environment Variables Using `vim`</p><p>Next, configure the .env file to set up your domain and SSL email:</p><pre># Copy the example environment file<br>cp .env.example .env<br># Open the .env file with vim<br>vim .env</pre><p>Once the .env file is open in vim, make the following changes:</p><ul><li>Set your domain name:</li></ul><pre>KEYCLOAK_DOMAIN=sso.anqorithm.com</pre><ul><li>Set your email for SSL registration:</li></ul><pre>CERTBOT_LETSENCRYPT_EMAIL=abdullah@anqorithm.com</pre><p>To save and exit vim, type :wq and hit Enter.</p><p>3. Run the SSL Setup</p><p>Now, set up SSL certificates for your domain by running the following command:</p><pre>docker compose -f docker-compose-ssl.yml up -d </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4iDXzhwZmo0bHb-CNP4AA.png" /><figcaption>Generate SSL Certificate through Certbot</figcaption></figure><p>This command will launch Nginx and Certbot to request and install SSL certificates for your domain. Once the SSL certificates are successfully obtained, stop the containers:</p><pre>docker compose -f docker-compose-ssl.yml down</pre><p>4. Start the Docker Containers</p><p>After configuring SSL, start the full stack (Keycloak, PostgreSQL, Nginx, and Certbot) using Docker Compose:</p><pre>docker compose up -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKUCcIvgZpDUG8N1GLAH8g.png" /><figcaption>Pulling the Containers into the VM</figcaption></figure><p>This will launch all services in detached mode (-d).</p><p>5. Verify the Setup</p><p>To check if the containers are running, use:</p><pre>docker ps</pre><p>You should see the nginx, keycloak, postgres, and certbot containers running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhfk4nkXuYCDC9Wnaw-Kig.png" /><figcaption>Lisiting the Existing Containers</figcaption></figure><p>6. Access Keycloak</p><p>You can now access Keycloak by visiting your domain in a web browser:</p><pre>https://sso.anqorithm.com</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpdWY4wIZya1U7lLJraN7A.png" /><figcaption>Accessing the Keycloak Dashboard</figcaption></figure><p>Log in using the default admin credentials (admin/admin), or the ones you’ve set in the .env file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqjUg-2lCwXw6UHkWt0Phw.png" /><figcaption>Login to the Portal using the admin/admin Credentials</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T49sUkN0brS9SP9PawG3YA.png" /><figcaption>Logged in Successfully</figcaption></figure><p>This step guides you through cloning the project, configuring the environment, and running the containers for the Keycloak setup.</p><h4>GitHub Repository</h4><p>You will find the source code for this article in the following GitHub repository</p><p><a href="https://github.com/anqorithm/keycloak-production">https://github.com/anqorithm/keycloak-production</a></p><h4>Resources</h4><ul><li>Google Cloud Platform (GCP): <a href="https://cloud.google.com/">https://cloud.google.com/</a></li><li>Cloudflare: <a href="https://www.cloudflare.com/">https://www.cloudflare.com/</a></li><li>Keycloak: <a href="https://www.keycloak.org/documentation">https://www.keycloak.org/</a></li><li>Docker: <a href="https://www.docker.com/">https://www.docker.com/</a></li><li>Docker Compose: <a href="https://docs.docker.com/compose/">https://docs.docker.com/compose/</a></li><li>Ubuntu: <a href="https://ubuntu.com/">https://ubuntu.com/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81ee074eaf3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing LDAP Authentication in Laravel: A Guide to Using OpenLDAP, PHPLdapAdmin, and Docker…]]></title>
            <link>https://anqorithm.medium.com/implementing-ldap-authentication-integration-in-laravel-a-guide-to-using-openldap-phpldapadmin-f34a37e401bd?source=rss-30833ccf4538------2</link>
            <guid isPermaLink="false">https://medium.com/p/f34a37e401bd</guid>
            <category><![CDATA[ldap]]></category>
            <category><![CDATA[active-directory]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[openldap]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Abdullah Alqahtani]]></dc:creator>
            <pubDate>Fri, 29 Mar 2024 23:15:38 GMT</pubDate>
            <atom:updated>2024-04-04T21:25:33.250Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing LDAP Authentication in Laravel: A Guide to Using OpenLDAP, PHPLdapAdmin, and Docker with the LdapRecord Package</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Cx4Qy7fVjQcpLFdb5nKQA.png" /><figcaption>Article Poster</figcaption></figure><h3>Introduction</h3><p>Authentication through LDAP is a common way for organizations to manage user login information. LDAP (Lightweight Directory Access Protocol) is a protocol that helps keep track of usernames, passwords, and other important user details in a central directory server. This makes it easier for companies to control who can access what across different apps and services.</p><p><strong>OpenLDAP</strong> is one implementation of the LDAP protocol. It’s an open-source software that anyone can use and modify. Another popular implementation of LDAP is <strong>Microsoft Active Directory</strong>, which is used by many businesses to manage user accounts and permissions within their Windows environments.</p><p>By using LDAP implementations like <strong>OpenLDAP</strong> or Active Directory, organizations can simplify user management and provide a single sign-on experience for their users. This means that users can log in once and access multiple resources without having to remember separate usernames and passwords for each one.</p><p>In this article, we’ll use <strong>Laravel</strong> to implement LDAP authentication, but remember that LDAP is <strong>flexible</strong> and can work with many<strong> other frameworks</strong> and backends too.</p><h3><strong>LDAP’s authentication workflow</strong></h3><p>LDAP’s authentication workflow begins when a user tries to access a service. The service checks if the user is already <strong>authenticated</strong>. If not, the user is prompted to provide their credentials, usually a username and password.</p><p>The service then sends these credentials to the LDAP server for <strong>verification</strong>. The LDAP server compares the provided credentials against the user information stored in its directory. If the credentials match, the LDAP server confirms the user’s identity to the service, granting them access.</p><p>However, if the credentials are <strong>invalid</strong>, the LDAP server denies access, and the user is asked to try again. This centralized authentication process simplifies access management and ensures consistent security across multiple applications connected to the LDAP directory.</p><p>The following diagram illustrates the LDAP journey starting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*6b1dcMNfncToVzL8imQnew.png" /><figcaption>LDAP authentication journey workflow</figcaption></figure><h3><strong>Basic LDAP Terminologies</strong></h3><p><strong>Distinguished Name (DN):</strong> The DN is a unique identifier for each entry in an LDAP directory, serving as a complete path from the top-level root to the specific entity. For example, the DN for a user named Rishabh might be: cn=admin,dc=anq,dc=com.</p><p><strong>LDAP Domain:</strong> This is the top-most level of an organization’s directory structure in LDAP. An example of an LDAP domain could be: dc=anq,dc=com.</p><p><strong>Base DN:</strong> During an LDAP search for a particular entry, the Base DN represents the starting point from which the search begins. For instance, a Base DN for searching user entries might look like: ou=users,dc=anq,dc=com.</p><p><strong>Bind DN:</strong> Before carrying out any operations like lookup, insertion, or modification in LDAP, one needs to authenticate. The Bind DN is an entry that has the necessary permissions to authenticate and perform these tasks within LDAP. A Bind DN example would be: cn=admin,dc=anq,dc=com.</p><p><strong>LDIF (LDAP Data Interchange Format):</strong> An LDIF file is a standard plain text format used to represent directory entries. This format can be used to craft an LDIF file that defines a series of entries, which can then be imported to populate an LDAP server.</p><h3>Prerequisites</h3><ol><li><strong>Docker:</strong></li></ol><ul><li>Install Docker to create isolated environments (containers) for OpenLDAP and PHPLdapAdmin.</li><li>Docker documentation: <a href="https://docs.docker.com/get-started/">Get Started with Docker</a></li></ul><p><strong>2. Composer:</strong></p><ul><li>Install Composer, a dependency manager for PHP, to install Laravel and LdapRecord package.</li><li>Composer documentation: <a href="https://getcomposer.org/doc/00-intro.md">Composer Getting Started</a></li></ul><p><strong>3. PHP:</strong></p><ul><li>Ensure the latest PHP (8.3 ≥) is installed, as it is required to run Laravel and to execute Composer commands.</li><li>PHP documentation: <a href="https://www.php.net/manual/en/index.php">PHP Manual</a></li></ul><p><strong>4. Laravel:</strong></p><ul><li>Knowledge of setting up a Laravel project is essential.</li><li>Laravel installation guide: <a href="https://laravel.com/docs/installation">Installing Laravel</a></li></ul><p><strong>5. LdapRecord Package:</strong></p><ul><li>Understanding of how to install and configure third-party packages in Laravel.</li><li>LdapRecord documentation: <a href="https://ldaprecord.com/docs/core/v3/installation">LdapRecord Documentation</a></li></ul><p>After installing these prerequisites, you’ll have a working environment to implement LDAP authentication in your Laravel application using OpenLDAP and Docker through the LdapRecord package.</p><h3>Setting Up the Environment</h3><p>Begin by setting up your environment for LDAP authentication in Laravel. First, clone the GitHub repository containing the configuration files for OpenLDAP and PHPLdapAdmin.</p><p><a href="https://github.com/anqorithm/Laravel-OpenLDAP">https://github.com/anqorithm/Laravel-OpenLDAP</a></p><p>Open your terminal, and run the git <a href="https://github.com/anqorithm/Laravel-OpenLDAP">https://github.com/anqorithm/Laravel-OpenLDAP</a> command followed by the repository URL. Once the repository is successfully cloned, change your directory to openldap by typing cd openldap in the terminal.</p><p>You will find the folder structure is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-J4pVIKkPQBe4_iMkCnAAw.png" /><figcaption>Project folder directory</figcaption></figure><p>In this directory, you will find the .env file. Edit this file with your specific details to configure the environment variables for your LDAP services. This step is essential to tailor the setup to your particular needs and ensure that the services can communicate correctly.</p><pre># LDAP log level (256 is typically informational logging without debug)<br>LDAP_LOG_LEVEL=256<br><br># The name of your organization - this will often appear in management interfaces or LDAP utilities<br>LDAP_ORGANISATION=&quot;Abdullah Alqahtani&quot;<br><br># Your Internet domain - this should match with the domain you want to use for LDAP<br>LDAP_DOMAIN=anq.com<br><br># The Base Distinguished Name, should align with the domain - this is the starting point for directory tree structure<br>LDAP_BASE_DN=&quot;anq,dc=com&quot;<br><br># Password for the admin user - it&#39;s very important to change this to a secure password in production<br>LDAP_ADMIN_PASSWORD=anq<br><br># Password for the config user - used for initial configuration of LDAP, should also be a secure password<br>LDAP_CONFIG_PASSWORD=config<br><br># Whether to create a read-only user - set to &quot;true&quot; or &quot;false&quot;<br>LDAP_READONLY_USER=false<br><br># Whether to use the RFC2307BIS schema - it changes the object class of groups from posixGroup to groupOfMembers<br>LDAP_RFC2307BIS_SCHEMA=false<br><br># The database backend to use - mdb is a modern, high-performance storage engine<br>LDAP_BACKEND=mdb<br><br># Whether to enable TLS - set to &quot;true&quot; to enable encryption<br>LDAP_TLS=true<br><br># The filename for the TLS certificate - this should be in the same directory as the LDAP server&#39;s config files<br>LDAP_TLS_CRT_FILENAME=ldap.crt<br><br># The filename for the TLS key - must be kept secure and private<br>LDAP_TLS_KEY_FILENAME=ldap.key<br><br># The filename for the Diffie-Hellman parameter - used for setting up the secure TLS connection<br>LDAP_TLS_DH_PARAM_FILENAME=dhparam.pem<br><br># The filename for the TLS Certificate Authority certificate - used for validating client certificates<br>LDAP_TLS_CA_CRT_FILENAME=ca.crt<br><br># Whether to enforce client certificates - set to &quot;true&quot; to require clients to present a valid certificate<br>LDAP_TLS_ENFORCE=false<br><br># The cipher suite for TLS - here, selecting secure ciphers while excluding SSL 3.0<br>LDAP_TLS_CIPHER_SUITE=SECURE256:-VERS-SSL3.0<br><br># The level of verification for TLS client certificates - &quot;demand&quot; means client must present a valid certificate<br>LDAP_TLS_VERIFY_CLIENT=demand<br><br># Whether to enable replication - set to &quot;true&quot; to enable LDAP replication<br>LDAP_REPLICATION=false<br><br># Whether to keep existing config if found - if set to &quot;false&quot;, the LDAP server will generate new configs on startup<br>KEEP_EXISTING_CONFIG=false<br><br># Whether to remove the config after setup - helps with ensuring a clean state on startup<br>LDAP_REMOVE_CONFIG_AFTER_SETUP=true<br><br># Prefix for the SSL helper tool - relevant for certain LDAP utilities<br>LDAP_SSL_HELPER_PREFIX=ldap</pre><p>for more details and configurations please visit:</p><p><a href="https://github.com/osixia/docker-openldap">GitHub - osixia/docker-openldap: OpenLDAP container image 🐳🌴</a></p><p>After configuring your environment, it’s time to start the services using Docker. Run the command docker-compose up from within the openldap directory. This command will read the docker-compose.yml file and create the necessary containers for your LDAP setup. Wait for Docker to finish spinning up the containers, which may take a few minutes.</p><p>The provided <strong>docker-compose</strong> file orchestrates the deployment of <strong>two</strong> services: <strong>openldap</strong> and <strong>phpldapadmin</strong>. The openldap service uses the osixia/openldap:1.5.0 Docker image to create a container named openldap, which is configured via an environment file and has its data volumes and ports set up to persist data and interface with the host system on standard LDAP ports.</p><p>The <strong>phpldapadmin</strong> service employs the <strong>osixia/phpldapadmin</strong> image to set up a web UI for managing the LDAP server, linking it to the openldap service as its host. It exposes its web interface on the host’s port <strong>8080</strong>, allowing users to interact with it through a web browser. The <strong>depends_on</strong> directive ensures that phpldapadmin is started only after the openldap service is up and running.</p><p>This is the docker-compose.yaml</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  openldap:<br>    image: osixia/openldap:1.5.0<br>    container_name: openldap<br>    env_file:<br>      - .env<br>    tty: true<br>    stdin_open: true<br>    volumes:<br>      - /var/lib/ldap<br>      - /etc/ldap/slapd.d<br>      - /container/service/slapd/assets/certs/<br>    ports:<br>      - &quot;389:389&quot;<br>      - &quot;636:636&quot;<br>    domainname: &quot;example.org&quot;<br>    hostname: &quot;ldap-server&quot;<br>  phpldapadmin:<br>    image: osixia/phpldapadmin:latest<br>    container_name: phpldapadmin<br>    environment:<br>      PHPLDAPADMIN_LDAP_HOSTS: &quot;openldap&quot;<br>      PHPLDAPADMIN_HTTPS: &quot;false&quot;<br>    ports:<br>      - &quot;8080:80&quot;<br>    depends_on:<br>      - openldap</pre><p>Once the containers are running, perform a health check to confirm that the services are active and operational. Docker provides commands to inspect the status of your containers, ensuring they are in good health and ready to use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pv13KZAwAaA94gEb7eYP5w.png" /><figcaption>Running the docker-compose.yaml file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDKLr-Ac2N13ihTEVsNotg.png" /><figcaption>Docker desktop showing the two services are healthy and running</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXYJoGEpLY2zhaE7NIQIEg.png" /><figcaption>Openldap service logs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xb_xiPowksYUH8x0fqa53w.png" /><figcaption>Phpldapadmin logs</figcaption></figure><p>Next, verify that OpenLDAP is functioning correctly by testing its connectivity. Ensuring that OpenLDAP is responsive is crucial before proceeding further. Following this, ensure PHPLdapAdmin is accessible on your local machine. Open your web browser and navigate to localhost:8080 to reach the PHPLdapAdmin login page. Use the login credentials, the DN (Distinguished Name), and the password you specified in the .env file to log in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_ssHOgdkUDTxATrSRJEfQ.png" /><figcaption>Testing LDAP connectivity through ldapsearch query</figcaption></figure><pre>$ docker exec openldap ldapsearch -x -H ldap://localhost -b dc=anq,dc=com -D &quot;cn=admin,dc=anq,dc=com&quot; -w anq</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Un7LbYnR-hm_Pq2xLeWCog.png" /><figcaption>Phpldapadmin login page</figcaption></figure><p>In our .env file the BASE_DN anq,dc=com so the LOGIN_DN will be cn=admin,dn=anq,dn=com and the PASSWORD will be anq</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guqDG9ga2OnMl2ApfNiJXA.png" /><figcaption>Phpldapadmin with provided login DN and password</figcaption></figure><p>The last step in the environment setup is to populate the OpenLDAP database with users and groups. Import the LDIF schema, which contains predefined user and group entries, into OpenLDAP through PHPLdapAdmin. With the successful importation of this data, your LDAP service is now equipped with initial entries you can use for authentication.</p><p>anq.entries.ldif file</p><pre>dn: ou=Engineering,dc=anq,dc=com<br>objectClass: organizationalUnit<br>ou: Engineering<br><br>dn: ou=Product,dc=anq,dc=com<br>objectClass: organizationalUnit<br>ou: Product<br><br>dn: ou=Financial Analysis,dc=anq,dc=com<br>objectClass: organizationalUnit<br>ou: Financial Analysis<br><br>dn: uid=abdullah.alqahtani,ou=Engineering,dc=anq,dc=com<br>objectClass: inetOrgPerson<br>objectClass: posixAccount<br>objectClass: shadowAccount<br>uid: abdullah.alqahtani<br>sn: Alqahtani<br>givenName: Abdullah<br>cn: Abdullah Alqahtani<br>displayName: Abdullah Alqahtani<br>uidNumber: 10000<br>gidNumber: 5000<br>userPassword: {SSHA}5ravvW53pHzMCUBPjTyf3Tnph0GHrpn7<br>gecos: Abdullah Alqahtani<br>loginShell: /bin/bash<br>homeDirectory: /home/abdullah.alqahtani<br><br>dn: uid=mohammed.ahmed,ou=Product,dc=anq,dc=com<br>objectClass: inetOrgPerson<br>objectClass: posixAccount<br>objectClass: shadowAccount<br>uid: mohammed.ahmed<br>sn: Ahmed<br>givenName: Mohammed<br>cn: Mohammed Ahmed<br>displayName: Mohammed Ahmed<br>uidNumber: 10001<br>gidNumber: 5000<br>userPassword: {SSHA}5ravvW53pHzMCUBPjTyf3Tnph0GHrpn7<br>gecos: Mohammed Ahmed<br>loginShell: /bin/bash<br>homeDirectory: /home/mohammed.ahmed<br><br>dn: uid=fatima.ali,ou=Financial Analysis,dc=anq,dc=com<br>objectClass: inetOrgPerson<br>objectClass: posixAccount<br>objectClass: shadowAccount<br>uid: fatima.ali<br>sn: Ali<br>givenName: Fatima<br>cn: Fatima Ali<br>displayName: Fatima Ali<br>uidNumber: 10002<br>gidNumber: 5000<br>userPassword: {SSHA}5ravvW53pHzMCUBPjTyf3Tnph0GHrpn7<br>gecos: Fatima Ali<br>loginShell: /bin/bash<br>homeDirectory: /home/fatima.ali</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3hCvQTE1QK1c5l_FfnAcA.png" /><figcaption>Importing the LDIF file which contains our records</figcaption></figure><p>After clicking proceed &gt;&gt;</p><p>Now, I will execute the same query above to get all records again, and check that the users are added to the OpenLDAP</p><pre>$ docker exec openldap ldapsearch -x -H ldap://localhost -b dc=anq,dc=com -D &quot;cn=admin,dc=anq,dc=com&quot; -w anq</pre><p>After executing the command, this is the response I get from the terminal:</p><pre># extended LDIF<br>#<br># LDAPv3<br># base &lt;dc=anq,dc=com&gt; with scope subtree<br># filter: (objectclass=*)<br># requesting: ALL<br>#<br><br># anq.com<br>dn: dc=anq,dc=com<br>objectClass: top<br>objectClass: dcObject<br>objectClass: organization<br>o: Abdullah Alqahtani<br>dc: anq<br><br># Engineering, anq.com<br>dn: ou=Engineering,dc=anq,dc=com<br>objectClass: organizationalUnit<br>objectClass: top<br>ou: Engineering<br><br># Product, anq.com<br>dn: ou=Product,dc=anq,dc=com<br>objectClass: organizationalUnit<br>objectClass: top<br>ou: Product<br><br># Financial Analysis, anq.com<br>dn: ou=Financial Analysis,dc=anq,dc=com<br>objectClass: organizationalUnit<br>objectClass: top<br>ou: Financial Analysis<br><br># abdullah.alqahtani, Engineering, anq.com<br>dn: uid=abdullah.alqahtani,ou=Engineering,dc=anq,dc=com<br>objectClass: inetOrgPerson<br>objectClass: posixAccount<br>objectClass: shadowAccount<br>objectClass: top<br>uid: abdullah.alqahtani<br>sn: Alqahtani<br>givenName: Abdullah<br>cn: Abdullah Alqahtani<br>displayName: Abdullah Alqahtani<br>uidNumber: 10000<br>gidNumber: 5000<br>userPassword:: e1NTSEF9NXJhdnZXNTNwSHpNQ1VCUGpUeWYzVG5waDBHSHJwbjc=<br>gecos: Abdullah Alqahtani<br>loginShell: /bin/bash<br>homeDirectory: /home/abdullah.alqahtani<br><br># mohammed.ahmed, Product, anq.com<br>dn: uid=mohammed.ahmed,ou=Product,dc=anq,dc=com<br>objectClass: inetOrgPerson<br>objectClass: posixAccount<br>objectClass: shadowAccount<br>objectClass: top<br>uid: mohammed.ahmed<br>sn: Ahmed<br>givenName: Mohammed<br>cn: Mohammed Ahmed<br>displayName: Mohammed Ahmed<br>uidNumber: 10001<br>gidNumber: 5000<br>userPassword:: e1NTSEF9NXJhdnZXNTNwSHpNQ1VCUGpUeWYzVG5waDBHSHJwbjc=<br>gecos: Mohammed Ahmed<br>loginShell: /bin/bash<br>homeDirectory: /home/mohammed.ahmed<br><br># fatima.ali, Financial Analysis, anq.com<br>dn: uid=fatima.ali,ou=Financial Analysis,dc=anq,dc=com<br>objectClass: inetOrgPerson<br>objectClass: posixAccount<br>objectClass: shadowAccount<br>objectClass: top<br>uid: fatima.ali<br>sn: Ali<br>givenName: Fatima<br>cn: Fatima Ali<br>displayName: Fatima Ali<br>uidNumber: 10002<br>gidNumber: 5000<br>userPassword:: e1NTSEF9NXJhdnZXNTNwSHpNQ1VCUGpUeWYzVG5waDBHSHJwbjc=<br>gecos: Fatima Ali<br>loginShell: /bin/bash<br>homeDirectory: /home/fatima.ali<br><br># search result<br>search: 2<br>result: 0 Success<br><br># numResponses: 8<br># numEntries: 7</pre><p>Which indicates the creation of all records successfully.</p><p>With these steps completed, your environment is fully prepared, and you’re ready to start integrating LDAP authentication into your Laravel application.</p><h3>Integrating OpenLDAP with Laravel using LdapRecord</h3><p>LdapRecord is a powerful and efficient framework designed to simplify the process of integrating LDAP functionality into your PHP applications.</p><p>With LdapRecord, you can quickly establish a connection between your application and an LDAP server, enabling you to perform various LDAP operations with ease.</p><p>Whether you need to authenticate users, retrieve user attributes, or manage LDAP entries, LdapRecord provides a comprehensive set of tools and features to streamline the integration process.</p><p>By utilizing LdapRecord’s API and eloquent-like syntax, you can interact with LDAP directories easily, saving time and reducing the complexity of LDAP integration.</p><p>With minimal configuration and a developer-friendly approach, LdapRecord allows you to rapidly incorporate LDAP functionality into your PHP applications.</p><p>To install the package into your Laravel application (version 3 — latest)</p><pre>$ composer require directorytree/ldaprecord-laravel</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWd7WEmxM_XPYvdIbuMgcw.png" /><figcaption>Installing ldaprecord package</figcaption></figure><p>Please follow their documentation it’s well-written: <a href="https://ldaprecord.com/docs/laravel/v3/installation/">https://ldaprecord.com/docs/laravel/v3/installation/</a></p><p>Now, we need to publish the configuration file for ldap.php by running the following command:</p><pre>$ php artisan vendor:publish --provider=&quot;LdapRecord\Laravel\LdapServiceProvider&quot;</pre><p>and we need to add these environment variables to our .env file</p><pre>LDAP_CACHE=false<br>LDAP_LOGGING=true<br>LDAP_CONNECTION=default<br>LDAP_HOST=127.0.0.1<br>LDAP_USERNAME=&quot;cn=admin,dc=anq,dc=com&quot;<br>LDAP_PASSWORD=anq<br>LDAP_PORT=389<br>LDAP_BASE_DN=&quot;dc=anq,dc=com&quot;<br>LDAP_TIMEOUT=5<br>LDAP_SSL=false<br>LDAP_TLS=false<br>LDAP_SASL=false</pre><p>Now, we need to test the connectivity by simply running the command</p><pre>$ php artisan ldap:test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lM1CzexPrAhUqqdI1TyQaQ.png" /><figcaption>Susscufull connectivity between Laravel and LDAP</figcaption></figure><p>Now, we need to create a new model for the LDAP User</p><p>through running this command:</p><pre>$ php artisan ldap:make:model User</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEp24OFl-Ikn4-J2YZxgdA.png" /></figure><p>Once created, insert the following interface and trait onto the model:</p><p>Interface:</p><pre>Illuminate\Contracts\Auth\Authenticatable</pre><p>Trait:</p><pre>LdapRecord\Models\Concerns\CanAuthenticate</pre><p>So, it will be finally the following:</p><pre>&lt;?php<br><br>namespace App\Ldap;<br><br>use LdapRecord\Models\Model;<br>use LdapRecord\Models\Concerns\CanAuthenticate;<br>use Illuminate\Contracts\Auth\Authenticatable;<br><br>class User extends Model implements Authenticatable<br>{<br>  use CanAuthenticate;<br><br>  public static array $objectClasses = [&#39;...&#39;];<br><br>  protected string $guidKey = &#39;uuid&#39;;<br><br>  public function getAuthIdentifier()<br>  {<br>    // TODO: Implement getAuthIdentifier() method.<br>  }<br>}</pre><p>Now, we need to change the provider array inside auth.php file</p><p>to this update array, and make sure to use</p><p>LdapRecord\Models\OpenLDAP\User::class</p><p>as also LdapRecords provides API for the ActiveDirectoryusing this class:</p><p>LdapRecord\Models\ActiveDirectory\User::class</p><pre><br>&#39;providers&#39; =&gt; [<br>  &#39;users&#39; =&gt; [<br>    &#39;driver&#39; =&gt; &#39;ldap&#39;,<br>    &#39;model&#39; =&gt; LdapRecord\Models\OpenLDAP\User::class,<br>    &#39;rules&#39; =&gt; [],<br>    &#39;database&#39; =&gt; [<br>      &#39;model&#39; =&gt; App\Models\User::class,<br>      &#39;sync_passwords&#39; =&gt; false,<br>      &#39;sync_attributes&#39; =&gt; [<br>        &#39;name&#39; =&gt; &#39;cn&#39;,<br>        &#39;email&#39; =&gt; &#39;mail&#39;,<br>      ],<br>    ],<br>  ],<br>],</pre><p>Now, I will import all my users which already exists into the</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWRsaYHBmgkeJeLIsn8bgg.png" /></figure><p>Now, all users are imported to the database!</p><h3>Plain Authentication</h3><p>Implementing plain authentication using LDAP in a Laravel application involves several steps. First, you need to ensure that the LDAP PHP extension is installed and enabled on your server.</p><pre>$ sudo apt-get install php-ldap</pre><p>Then, install Laravel Breeze in your Laravel project using the command composer require laravel/breeze --dev. This will provide you with a basic authentication system out of the box. After installing Breeze, make sure to run the necessary migrations to set up the authentication tables in your database</p><p>Now, if you are using the database session driver, you <strong>must</strong> change the user_id column from its default type. This is due to LDAP Object GUID&#39;s being stored as the user&#39;s ID, which is not compatible with the unsigned big integer type:</p><p>From:</p><pre>Schema::create(&#39;sessions&#39;, function (Blueprint $table) {<br>    // ...<br>    $table-&gt;foreignId(&#39;user_id&#39;)-&gt;nullable()-&gt;index();<br>    // ...<br>});</pre><p>To:</p><pre>Schema::create(&#39;sessions&#39;, function (Blueprint $table) {<br>    // ...<br>    $table-&gt;string(&#39;user_id&#39;)-&gt;nullable()-&gt;index();<br>    // ...<br>});</pre><h3>Login Request</h3><p>For this example application, we will authenticate our LDAP users with their email address using the LDAP attribute mail.</p><p>For LdapRecord to properly locate the user in your directory during sign in, we will override the authenticate method in the LoginRequest, and pass in an array with the mail key (which is the attribute we are wanting to retrieve our LDAP users by) and the users password:</p><pre>// app/Http/Requests/Auth/LoginRequest.php</pre><pre>/**<br> * Attempt to authenticate the request&#39;s credentials.<br> *<br> * @return void<br> *<br> * @throws \Illuminate\Validation\ValidationException<br> */<br>public function authenticate()<br>{<br>    $this-&gt;ensureIsNotRateLimited();<br>    $credentials = [<br>        &#39;mail&#39; =&gt; $this-&gt;email,<br>        &#39;password&#39; =&gt; $this-&gt;password,<br>    ];<br>    if (! Auth::attempt($credentials, $this-&gt;filled(&#39;remember&#39;))) {<br>        RateLimiter::hit($this-&gt;throttleKey());<br>        throw ValidationException::withMessages([<br>            &#39;email&#39; =&gt; __(&#39;auth.failed&#39;),<br>        ]);<br>    }<br>    RateLimiter::clear($this-&gt;throttleKey());<br>}</pre><h3>Blade Views</h3><p>Once you have completed updating your LoginRequest.php class, you will then have to navigate to any Blade views that contain references to Auth::user(). Remember, when using plain authentication, LdapRecord models are returned, <strong>not Eloquent.</strong></p><p>In the standard scaffolding, this occurs namely in the navigation.blade.php view:</p><p>From:</p><pre>&lt;!-- resources/views/layouts/navigation.blade.php --&gt;{{ Auth::user()-&gt;name }} {{ Auth::user()-&gt;email }}</pre><pre>{{ Auth::user()-&gt;name }} {{ Auth::user()-&gt;email }}</pre><p>To:</p><pre>&lt;!-- resources/views/layouts/navigation.blade.php --&gt;</pre><pre>{{ Auth::user()-&gt;getName() }} {{ Auth::user()-&gt;getFirstAttribute(&#39;mail&#39;) }}</pre><p>Now we are up and running with the LDAP authentication integrated into our Laravel application!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*poT5Vh-ZjcW1o_unizJ6ug.png" /><figcaption>Laravel 11 Main Page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iIqpbMSf9RdJMpwdZ-fAw.png" /><figcaption>Login to Laravel application through Breeze UI Kit, providing the LDAP credentials</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tdFL7e_yfs1fIL1hm7CRQ.png" /><figcaption>Successfully logged in into the system through LDAP authentication</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxsfRnnAPCs1xs2AwQZRew.png" /><figcaption>My profile in the platform after successfully logged in through the LDAP</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FH1-BxPVNQxKGMVFt6fzdw.png" /><figcaption>LDAP logs after logged in successfully into the platform</figcaption></figure><h3>Security Concerns</h3><p>When it comes to security, make sure to use LDAPS (LDAP over SSL/TLS) instead of plain LDAP. Use port 636 instead of 389, and obtain an SSL/TLS certificate from a trusted authority. Configure your Laravel app to verify the certificate to prevent attacks.</p><p>To test LDAP authentication, create test cases that cover different scenarios like valid and invalid credentials, user existence, and edge cases. Use Laravel’s built-in testing tools and mock the LDAP server if needed. Test thoroughly to ensure your implementation is working as expected.</p><p>If you encounter issues, double-check your LDAP server settings, Laravel configuration, and firewall rules. Make sure your LDAP server is reachable and responding correctly.</p><p>By following these security practices and conducting proper testing, you can ensure a secure implementation of authentication using LDAP in your application.</p><h3>Conclusion</h3><p>In this article, we learned how to integrate LDAP authentication into a Laravel application using OpenLDAP, phpLDAPadmin, Docker, and the LdapRecord package.</p><p>We set up an OpenLDAP server, configured phpLDAPadmin, and integrated LDAP authentication into our Laravel app step by step.</p><p>Now you should have a good understanding of how to use LDAP with Laravel for user authentication and management.</p><p>Remember to prioritize security by using LDAPS and proper testing.</p><p>If you have any questions or want to share your experiences, feel free.</p><p>The GitHub repo for this article can be found here:</p><p><a href="https://github.com/anqorithm/Laravel-OpenLDAP">GitHub - anqorithm/Laravel-OpenLDAP</a></p><h3>Resources</h3><p><a href="https://github.com/osixia/docker-openldap">https://github.com/osixia/docker-openldap</a></p><p><a href="https://ldaprecord.com/docs">https://ldaprecord.com/docs</a></p><p><a href="https://ldap.com/">https://ldap.com/</a></p><p><a href="https://www.openldap.org/">https://www.openldap.org/</a></p><p><a href="https://www.okta.com/identity-101/what-is-ldap/">https://www.okta.com/identity-101/what-is-ldap/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f34a37e401bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Image Processing: Golang, Asynq, Redis, and Fiber for Asynchronous Queue Handling]]></title>
            <link>https://anqorithm.medium.com/efficient-image-processing-golang-asynq-redis-and-fiber-for-asynchronous-queue-handling-77d1cc5e75a1?source=rss-30833ccf4538------2</link>
            <guid isPermaLink="false">https://medium.com/p/77d1cc5e75a1</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Abdullah Alqahtani]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 14:56:44 GMT</pubDate>
            <atom:updated>2024-03-30T00:07:05.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwiazPxEDzDdVPJjk0rFVg.png" /><figcaption>Golang, Fiber, Async, and Redis as Stack to handle Queue System Tasks</figcaption></figure><h4>Introduction</h4><p>Hay there 👋,</p><p>In this brief article, I’ll explain a common method to speed up web applications. It involves moving tasks away from the main thread and placing them in a queue for asynchronous processing, using the queue to organize and handle these tasks separately.</p><p>In the world of server-side applications, the efficient handling of resource-intensive tasks like image processing is a significant challenge. These operations, often heavy on computation, can bog down the main thread, leading to decreased performance and poor scalability.</p><h4>The Challenge at Hand</h4><p>In server-side apps, managing image processing which uses a lot of computer power is a big challenge. If not done right, these tasks can overload the app’s main thread, making it slow and frustrating for users. I aimed to create a solution that improves performance in a simple way. The main goal was to keep the app’s core part running smoothly, even when it’s doing a lot of image processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*1j1wOlKBNzJ3skwIYEao9w.png" /><figcaption>Application without using a queue for handling tasks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*iz2mqT7-UfQjb_5lEOhAMg.png" /><figcaption>Application using a queue for enqueued tasks and the workers can consume the tasks asynchronously</figcaption></figure><h4>Used Tools and Prerequisites</h4><p>I picked <strong>Golang </strong>as the primary language for this image-processing platform because it excels at handling multiple tasks concurrently, allowing for swift image processing. Golang contributes to the speed and reliability of the service.</p><p><strong>Fiber</strong>, a lightweight web framework built on Golang, is what I use for handling web-related tasks. Its efficient design ensures seamless internet communication and reliable web operations. Fiber is effective in maintaining smooth web service performance.</p><p>For handling background tasks, I use <strong>Asynq</strong>. It arranges these tasks so they don’t overwhelm the main part of the service. This is important for keeping the service running well without any delays or issues.</p><p><strong>Redis </strong>is a fast key-value store that I’m using as a queue system, which is a popular way to use it. It’s vital for the Asynq package because Asynq depends on it to manage tasks. Redis helps keep everything organized and ensures tasks are completed efficiently and reliably.</p><p>Also, I have used <strong>Goland </strong>as the main IDE for coding and testing. It’s designed specifically for Go, making it incredibly handy for this project. With Goland, coding is streamlined and efficient, facilitating the development of Go applications.</p><p>I use <strong>Postman </strong>to manage and test API requests. It’s great for API work and makes the job easier and faster.</p><h4>Implementing the Solution: Asynq &amp; Redis</h4><p>To achieve this, I turned to Asynq and Redis. Async serves as a powerful task queue, allowing me to offload heavy image-processing tasks away from the main thread. This meant that these tasks could be handled asynchronously, ensuring that the core functionalities of the application remained unaffected. Redis, known for its high performance, acted as the backbone, supporting Asynq with fast, in-memory data storage capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*qaC0hgfP1S6SVadI00nKSA.png" /><figcaption>Workflow from adding new tasks to the Redis Queue, and then the workers can execute each task asynchronously</figcaption></figure><h4>Overview of the Image-Processing Service</h4><p>I built a service that makes working with images a lot easier. It’s written in a programming language called Go, which is great at doing many things at once without getting mixed up. This service can change image sizes, switch them to different formats, and make them look better, all very quickly. It’s made to handle lots of work without getting slow, which means the main part of an app using this service doesn’t have to do all the hard work by itself and can run smoothly.</p><h4><strong>Folder Structure</strong></h4><p>Now, let’s explore the folder structure:</p><p>Here’s the folder structure of the image-processing service:</p><ul><li><strong>docker-compose.yaml:</strong> This file contains the configuration for running the service using Docker Compose.</li><li><strong>go.mod and go.sum:</strong> These files are used for managing Go dependencies and version control.</li><li><strong>handlers:</strong> This directory holds the code for handling different aspects of the service, such as image processing.</li><li><strong>images:</strong> This directory is where the processed images are stored.</li><li><strong>routes:</strong> Here, you’ll find the routes defined for the service, specifying how different HTTP requests are handled.</li><li><strong>server:</strong> The server.go file in this directory contains the code for setting up and running the server.</li><li><strong>tasks: </strong>In this directory, you’ll find code related to managing tasks, including queuing and processing.</li><li><strong>worker:</strong> The worker.go file here handles background tasks and ensures efficient task execution.</li></ul><p>This organized folder structure keeps the service’s components separated, making it easier to manage and maintain the codebase.</p><pre>image-processing-service/<br>├── docker-compose.yaml<br>├── go.mod<br>├── go.sum<br>├── handlers<br>│   └── handlers.go<br>├── images<br>├── routes<br>│   └── routes.go<br>├── server<br>│   └── server.go<br>├── tasks<br>│   ├── queue.go<br>│   └── tasks.go<br>└── worker<br>    └── worker.go</pre><p>Now let’s look at the docker-compose.yaml file:</p><pre>version: &quot;3.9&quot;<br><br>services:<br>  redis:<br>    image: redis:latest<br>    ports:<br>      - &quot;6379:6379&quot;<br>    volumes:<br>      - redis-data:/data<br>    networks:<br>      - image-processing-network<br><br>  asynqmon:<br>    image: hibiken/asynqmon:latest<br>    environment:<br>      - REDIS_ADDR=redis:6379<br>    ports:<br>      - &quot;8080:8080&quot;<br>    depends_on:<br>      - redis<br>    networks:<br>      - image-processing-network<br><br>networks:<br>  image-processing-network:<br><br>volumes:<br>  redis-data:</pre><ol><li>Redis Service: This service uses the latest version of the Redis image. It’s like a container that runs the Redis database. It’s connected to the image-processing-networknetwork, allowing it to communicate with other services on the same network. Additionally, it uses a volume named redis-data to store data.</li><li>Asynqmon Service: This service uses the latest version of the hibiken/asynqmon image. It’s a monitoring tool for Asynq. It also connects to the image-processing-network network to communicate with other services. It depends on the Redis service, which means it waits for the Redis service to start before it does.</li></ol><p>So, in summary, this docker-compose.yaml file defines two services (Redis and Asynqmon) that are part of the &quot;image-processing-network&quot; network and use a volume called &quot;redis-data&quot; for data storage.</p><p>Now we run the underlying infrastructure through the command docker-compose up -d</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1EMoTxLi7cIOVPsA5KBGw.png" /><figcaption>Running the underlying services through Docker Compose</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_rHHn2eVvNRUATtesgb3Q.png" /><figcaption>The running services on Docker</figcaption></figure><p>Now let’s look at the main entry point of the application which is the server/server.go</p><p>This code sets up the image-processing service’s server using Fiber, configures routes, connects to Redis, and listens on port 3000 for requests.</p><pre>package main<br><br>import (<br> &quot;github.com/gofiber/fiber/v2&quot;<br> &quot;github.com/qahta0/image-processing-service/routes&quot;<br> &quot;github.com/qahta0/image-processing-service/tasks&quot;<br> &quot;log&quot;<br>)<br><br>const redisAddress = &quot;127.0.0.1:6379&quot;<br><br>func main() {<br> app := fiber.New()<br> routes.Setup(app)<br> tasks.Init(redisAddress)<br> defer tasks.Close()<br> log.Fatal(app.Listen(&quot;:3000&quot;))<br>}</pre><p>Now let’s look at the routes of the application which are the routes/routes.go</p><p>This code sets up a single POST route at “/image-process” using the Fiber framework, allowing image uploads to be processed by the handlers.UploadImage function.</p><pre>package routes<br><br>import (<br>    &quot;github.com/gofiber/fiber/v2&quot;<br>    &quot;github.com/qahta0/image-processing-service/handlers&quot;<br>)<br><br>func Setup(app *fiber.App) {<br>    app.Post(&quot;/image-process&quot;, handlers.UploadImage)<br>}</pre><p>In the tasks package, we create a centralized task queue using the hibiken/asynq library. This queue efficiently manages background tasks, connects to Redis for seamless processing, and streamlines task management in the image-processing service. It ensures consistent access to the same queue object.</p><pre>package tasks<br><br>import (<br> &quot;github.com/hibiken/asynq&quot;<br> &quot;sync&quot;<br>)<br><br>var (<br> client *asynq.Client<br> once   sync.Once<br>)<br><br>func Init(redisAddress string) {<br> once.Do(func() {<br>  client = asynq.NewClient(asynq.RedisClientOpt{Addr: redisAddress})<br> })<br>}<br><br>func Close() {<br> if client != nil {<br>  client.Close()<br> }<br>}<br><br>func GetClient() *asynq.Client {<br> return client<br>}</pre><p>Now let’s look at the routes of the application which are the handlers/handlers.go</p><p>This code defines the handler for uploading and processing images. Here’s a concise summary:</p><p>The UploadImage function handles image uploads via a POST request. It first checks if the upload was successful and handles errors accordingly. If the upload is successful, it reads the uploaded image data, creates image resize tasks, and enqueues them for processing. Finally, it responds with a success message.</p><pre>package handlers<br><br>import (<br> &quot;fmt&quot;<br> &quot;github.com/gofiber/fiber/v2&quot;<br> &quot;github.com/qahta0/image-processing-service/tasks&quot;<br> &quot;io&quot;<br>)<br><br>func UploadImage(c *fiber.Ctx) error {<br> file, err := c.FormFile(&quot;file&quot;)<br> if err != nil {<br>  return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{&quot;error&quot;: &quot;Upload failed&quot;})<br> }<br> fileData, err := file.Open()<br> if err != nil {<br>  return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{&quot;error&quot;: &quot;Failed to open the file&quot;})<br> }<br> defer fileData.Close()<br> data, err := io.ReadAll(fileData)<br> if err != nil {<br>  return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{&quot;error&quot;: &quot;Failed to read the file&quot;})<br> }<br> resizeTasks, err := tasks.NewImageResizeTasks(data)<br> if err != nil {<br>  return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{&quot;error&quot;: &quot;Could not create image resize tasks&quot;})<br> }<br> client := tasks.GetClient()<br> for _, task := range resizeTasks {<br>  if _, err := client.Enqueue(task); err != nil {<br>   fmt.Printf(&quot;Error enqueuing task: %v\n&quot;, err)<br>   return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{&quot;error&quot;: &quot;Could not enqueue image resize task&quot;})<br>  }<br> }<br> return c.JSON(fiber.Map{&quot;message&quot;: &quot;Image uploaded and resizing tasks started&quot;})<br>}</pre><p>In the next crucial step, the function creates image resize tasks and efficiently queues them for asynchronous execution. This approach ensures that image processing doesn’t delay the <strong>main thread</strong>, allowing it to continue processing the user’s request. This separation of tasks contributes to the overall responsiveness and efficiency of the image-processing service.</p><p>Now we run the main server through the following command go run ./server/server.go</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3X9jp61xQAjiIDujAmRnTw.png" /><figcaption>Running the main server</figcaption></figure><p>Now let’s check the Asynqmon portal by visiting the <a href="http://localhost:8080/">http://localhost:8080</a> and we notice here there is nothing really special because there are no jobs in execution right now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrhbyZ0FuoK0gzlXXhPcqw.png" /><figcaption>Asynqmon portal for monitoring queue Job execution</figcaption></figure><p>Now, please use Postman to request the endpoint we have for image processing at <a href="http://127.0.0.1:3000/process-image">http://127.0.0.1:3000/process-image</a>. You can upload the image to the image field</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMMolG-CdqehX_iI_GkUKQ.png" /><figcaption>Sending post Request to the endpoint /process-image</figcaption></figure><p>After sending the request, we observed that the processing time is very quick because enqueuing tasks in Redis happen almost instantly, with an O(1) complexity. Subsequently, we returned to Asyncmon and found that there are currently 10 tasks waiting in the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLwAlo3gnmXBwgKAOPkt4g.png" /><figcaption>10 Tasks are waiting in the queue to be executed asynchronously</figcaption></figure><p>Now, to consume tasks asynchronously, we will utilize the following code snippet. This task is designed to handle asynchronous image resizing tasks using the Asynq library. It defines a image:resizetask type and a payload structure for the image data, width, height, and filename.</p><p>The NewImageResizeTasksfunction generates multiple resizing tasks for various standard widths, while the HandleResizeImageTask function processes these tasks by resizing the image, saving it with a unique filename, and displaying an output UUID. This code facilitates efficient and concurrent image resizing within applications.</p><pre>package tasks<br><br>import (<br> &quot;bytes&quot;<br> &quot;context&quot;<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br> &quot;github.com/google/uuid&quot;<br> &quot;github.com/hibiken/asynq&quot;<br> &quot;github.com/nfnt/resize&quot;<br> &quot;image&quot;<br> &quot;image/jpeg&quot;<br> _ &quot;image/jpeg&quot;<br> _ &quot;image/png&quot;<br> &quot;os&quot;<br> &quot;path/filepath&quot;<br> &quot;time&quot;<br>)<br><br>const TypeResizeImage = &quot;image:resize&quot;<br><br>type ResizeImagePayload struct {<br> ImageData []byte<br> Width     uint<br> Height    uint<br> FileName  string<br>}<br><br>var StandardWidths = []uint{16, 32, 128, 240, 320, 480, 540, 640, 800, 1024}<br><br>func NewImageResizeTasks(imageData []byte, fileName string) ([]*asynq.Task, error) {<br> img, _, err := image.Decode(bytes.NewReader(imageData))<br> if err != nil {<br>  return nil, err<br> }<br> originalBounds := img.Bounds()<br> originalWidth := uint(originalBounds.Dx())<br> originalHeight := uint(originalBounds.Dy())<br> var tasks []*asynq.Task<br> for _, width := range StandardWidths {<br>  height := (width * originalHeight) / originalWidth<br>  payload := ResizeImagePayload{<br>   ImageData: imageData,<br>   Width:     width,<br>   Height:    height,<br>   FileName:  fileName,<br>  }<br>  payloadBytes, err := json.Marshal(payload)<br>  if err != nil {<br>   return nil, err<br>  }<br>  task := asynq.NewTask(TypeResizeImage, payloadBytes)<br>  tasks = append(tasks, task)<br> }<br> return tasks, nil<br>}<br><br>func HandleResizeImageTask(ctx context.Context, t *asynq.Task) error {<br> var payload ResizeImagePayload<br> if err := json.Unmarshal(t.Payload(), &amp;payload); err != nil {<br>  return fmt.Errorf(&quot;failed to parse resize image task payload: %v&quot;, err)<br> }<br> img, _, err := image.Decode(bytes.NewReader(payload.ImageData))<br> if err != nil {<br>  return fmt.Errorf(&quot;image decode failed: %v&quot;, err)<br> }<br> resizedImg := resize.Resize(payload.Width, payload.Height, img, resize.Lanczos3)<br> outputUUID := uuid.New()<br> outputFileName := fmt.Sprintf(&quot;images/%s/%s%s&quot;, time.Now().Format(&quot;2006-01-02&quot;), outputUUID.String(), filepath.Ext(payload.FileName))<br> outputDir := filepath.Dir(outputFileName)<br> if _, err := os.Stat(outputDir); os.IsNotExist(err) {<br>  if err := os.MkdirAll(outputDir, 0755); err != nil {<br>   return err<br>  }<br> }<br> outFile, err := os.Create(outputFileName)<br> if err != nil {<br>  return err<br> }<br> defer outFile.Close()<br> if err := jpeg.Encode(outFile, resizedImg, nil); err != nil {<br>  return err<br> }<br> fmt.Printf(&quot;Output UUID for the processed image: %s\n&quot;, outputUUID.String())<br> return nil<br>}</pre><p>Next, we should execute the workers by running the command go run worker/worker.go, and we observed that the 10 tasks were efficiently processed asynchronously, separate from the main thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vGXEI6D7QM_OfPYbqV2Yg.png" /><figcaption>Workers Executed the tasks and stored the processed images</figcaption></figure><p>Upon running the workers, we observed that the 10 tasks that were previously in the queue have now been processed and completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8atWmy_GPmdUJFArTIaLIw.png" /><figcaption>The queue is empty; no tasks are waiting to be executed asynchronously</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rzj6SxH17sfkHHo_qwag4g.png" /><figcaption>Visiting the \images path which has all processed images</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIUxTZzgifwef6QdH60t8g.png" /><figcaption>Processed image 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQavQmtx30faHfU1txJZuQ.png" /><figcaption>Processed image 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0us1bjz0kRqLWfFK7L4FA.png" /><figcaption>Processed image 3</figcaption></figure><p>As a final touch, the function responds with a message confirming the successful upload of the image. Additionally, it informs the user that the resizing tasks have been initiated in the background. This seamless process not only enhances user satisfaction but also showcases the power of asynchronous task handling in the image-processing service.</p><h4>Future Enhancement: Cloud Integration via GCP Bucket</h4><p>Moving forward, I plan to enhance the service’s functionality by integrating cloud storage capabilities, specifically targeting Google Cloud Platform (GCP) buckets. This will allow for uploading and storing of processed images, further streamlining the workflow and adding a layer of convenience and security.</p><h4><strong>Conclusion</strong></h4><p>In conclusion, this article addresses the critical challenge of optimizing image processing within web development. By leveraging Golang, Asynq, Redis, and Fiber, the image-processing service enhances performance through efficient asynchronous task handling. This article shows the power of well-considered software techniques in approaching crucial bottlenecks in web development, leading to a more responsive and efficient user experience.</p><h4>Source Code</h4><p>You can find the source code for this article down here 👇</p><p><a href="https://github.com/qahta0/image-processing-service-async">GitHub - qahta0/image-processing-service-async: This repository contains an asynchronous image processing service built using Golang, Asynq, Redis, Fiber and Docker Compose for easy deployment.</a></p><h4>References</h4><ol><li><a href="https://redis.io/docs/">https://redis.io/docs/</a></li><li><a href="https://github.com/hibiken/asynq">https://github.com/hibiken/asynq</a></li><li><a href="https://docs.gofiber.io/">https://docs.gofiber.io/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77d1cc5e75a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>