<?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 Yassinejdidi on Medium]]></title>
        <description><![CDATA[Stories by Yassinejdidi on Medium]]></description>
        <link>https://medium.com/@yassinejedidi10?source=rss-ad8291fe88b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JoAoPd37x5lKQGaeB4GlIQ.jpeg</url>
            <title>Stories by Yassinejdidi on Medium</title>
            <link>https://medium.com/@yassinejedidi10?source=rss-ad8291fe88b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:59:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yassinejedidi10/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[How to Implement a Payment Module in NestJS]]></title>
            <link>https://medium.com/@yassinejedidi10/how-to-implement-a-payment-module-in-nestjs-ad402aa7f83d?source=rss-ad8291fe88b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad402aa7f83d</guid>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[stripe]]></category>
            <dc:creator><![CDATA[Yassinejdidi]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 17:44:05 GMT</pubDate>
            <atom:updated>2024-10-14T17:44:05.084Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*HkDUfXYUxbY8kNXvXqwdig.png" /><figcaption>How to Implement a Payment Module in NestJS</figcaption></figure><h3>introduction</h3><p>In this article, I will guide you through the process of building a payment module using Stripe with NestJS, providing step-by-step instructions to ensure a smooth implementation.</p><h4>Step 1: Set Up Your NestJS Application</h4><p>If you haven’t set up your NestJS application yet, you can do so with the following command:</p><pre>npm i -g @nestjs/cli<br>nest new my-app</pre><h4>Step 2: Install Stripe and Necessary Packages</h4><p>Navigate to your project directory and install the Stripe package along with the NestJS configuration package:</p><pre>cd my-app<br>npm install stripe @nestjs/config</pre><p>Generate a new module for handling payments:</p><pre>nest generate module payment</pre><p>Generate a service that will contain the logic for Stripe integration:</p><pre>nest generate service payment</pre><h4>Step 3: Create the Payment Service and Controller</h4><p>First, you need to create a free account on the Stripe dashboard at <a href="https://dashboard.stripe.com/">https://dashboard.stripe.com/</a>. Since we will be testing locally, make sure to activate<strong> test mode</strong> to simulate transactions after setting up the API.</p><p>Create the payment.service.ts file with the following code:</p><pre>import { Injectable, InternalServerErrorException } from &#39;@nestjs/common&#39;;<br>import { Stripe } from &#39;stripe&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br><br>@Injectable()<br>export class PaymentService {<br>  private stripe: Stripe;<br><br>  constructor(private configService: ConfigService) {<br>      this.stripe = new Stripe(process.env.STRIPE_SECRET);<br>  }<br><br>  async createCheckoutSession(<br>    amount: number,<br>    currency: string,<br>    productId: string, // Product ID can be used for better data management<br>    quantity: number<br>  ): Promise&lt;Stripe.Checkout.Session&gt; {<br>    try {<br>      const session = await this.stripe.checkout.sessions.create({<br>        line_items: [<br>          {<br>            price_data: {<br>              currency: currency,<br>              product_data: {<br>                name: `Test Product`, // You can customize the product name as needed<br>                // Additional product information can be added here<br>              },<br>              unit_amount: amount * 100, // Amount is in cents<br>            },<br>            quantity: quantity, // Specify the quantity of the product<br>          },<br>        ],<br>        mode: &#39;payment&#39;, // Set the mode to &#39;payment&#39;<br>        success_url: `http://localhost:4242/success.html`, // Redirect URL on success<br>        cancel_url: `http://localhost:4242/cancel.html`, // Redirect URL on cancellation<br>        metadata: {<br>          // Pass any additional data here, such as user ID <br>          // or product ID for handling in webhooks<br>          productId: productId,<br>        },<br>      });<br><br>      return session; // Return the created session<br>    } catch (error) {<br>      console.error(&#39;Error creating session:&#39;, error);<br>      throw new InternalServerErrorException(<br>        &#39;Failed to create checkout session&#39;, // Handle errors gracefully<br>      );<br>    }<br>  }<br>}</pre><p>Create the payment.controller.ts file with the following code:</p><pre>import { Body, Controller, Post } from &#39;@nestjs/common&#39;;<br>import { PaymentService } from &#39;./payment.service&#39;;<br>import { Stripe } from &#39;stripe&#39;;<br><br>@Controller(&#39;payment&#39;) // Define the base route for this controller<br>export class PaymentController {<br>  constructor(private readonly paymentService: PaymentService) {}<br><br>  @Post(&#39;create-checkout-session&#39;) // Define the route for creating a checkout session<br>  async createCheckoutSession(<br>    @Body() body: { amount: number; currency: string; productId: string; quantity: number }<br>  ): Promise&lt;Stripe.Checkout.Session&gt; {<br>    const { amount, currency, productId, quantity } = body; // Destructure the body to get the necessary parameters<br><br>    return this.paymentService.createCheckoutSession(amount, currency, productId, quantity); // Call the service method to create the session<br>  }<br>}</pre><p>You can use tools like <strong>Postman</strong> or <strong>cURL</strong> to test your API endpoints. Here’s how to do it with both:</p><h4>Using postman :</h4><p>When you click on “Send” for the POST method, you will receive a link for the payment session, as shown in the screenshot. Now, click on the link to proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqJIsFBAaR1syh_gfJxyTg.png" /></figure><p>When you click on the link, you will be prompted to enter payment information. To test the payment process, you can use the test card information provided by Stripe. You can find the test card numbers on the <a href="https://stripe.com/docs/testing#international-cards">Stripe Testing Documentation</a>. Alternatively, you can use the following test card number for a simple transaction:</p><ul><li><strong>Card Number:</strong> 4242 4242 4242 4242</li><li><strong>Expiration Date:</strong> Any future date (e.g., 12/34)</li><li><strong>CVC:</strong> Any 3-digit number (e.g., 123)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtV0Am1Xru_uMfytvaJMKQ.png" /></figure><p>Enter the information using a valid email address that ends with @gmail.com, and fill in the other required details with the test card information provided above. After submitting the form, you will be redirected to the success page.</p><h4>Using cURL</h4><pre>curl -X POST http://localhost:3002/payment/create-checkout-session \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{&quot;amount&quot;: 5000, &quot;currency&quot;: &quot;usd&quot;, &quot;productId&quot;: &quot;prod_12345&quot;, &quot;quantity&quot;: 1}&#39;</pre><h3>Step 4: Creating Webhooks</h3><p>Webhooks are essential for handling asynchronous events from Stripe. They allow your application to respond to events that occur in your Stripe account, such as successful payments, refunds, or subscription updates. By using webhooks, you can ensure that your application is always in sync with Stripe, enabling you to manage transactions effectively and maintain accurate records.</p><h4>Setup webhook:</h4><p>In the Stripe Dashboard, navigate to the <strong>Webhooks</strong> section and create a new endpoint. In this section, enter the endpoint URL for the webhook controller in your application. If you encounter any issues with localhost, you can use <strong>ngrok</strong> to expose your local server to the internet. For guidance on running your application locally with ngrok, refer to the ngrok documentation.After creating the webhook endpoint, you will receive a <strong>webhook secret</strong> for that webhook. Save this secret in your .env file for secure access in your application.</p><pre>STRIPE_WEBHOOK_SECRET=your_webhook_secret_here</pre><p>Now, update your PaymentService with the handleWebhook method:</p><pre>async handleWebhook(event: Stripe.Event) {<br>    switch (event.type) {<br>      case &#39;checkout.session.completed&#39;:<br>        this.logger.log(&#39;Checkout session completed:&#39;, event.data.object);<br>        // Implement your business logic for successful checkout here<br>        // For example:<br>        const session = event.data.object as Stripe.Checkout.Session;<br>        // You can retrieve relevant information from the session object<br>        const { payment_status, customer, metadata } = session;<br><br>        if (payment_status === &#39;paid&#39;) {<br>          // Handle successful payment, e.g., update order status in the database<br>          this.logger.log(`Payment was successful for customer: ${customer}`);<br>          // You might want to send an email or update your database here<br>        } else {<br>          this.logger.warn(&#39;Payment status is not successful:&#39;, payment_status);<br>        }<br>        break;<br><br>      case &#39;checkout.session.expired&#39;:<br>        this.logger.log(&#39;Checkout session expired:&#39;, event.data.object);<br>        // Handle session expiration (e.g., notify the user or update the database)<br>        break;<br><br>      default:<br>        this.logger.warn(`Unhandled event type ${event.type}`);<br>        break;<br>    }<br>  }</pre><p><strong>In the webhook, we will check whether the payment was successful. If it is successful, we will retrieve the data from the metadata that we passed in the checkout session, such as the product ID, user ID, etc. Then, we can implement the necessary business logic based on this information.</strong></p><p>Now create endpoint for contoller the same enddpoint that you put here in the webhook when you setuo it from the dashboard</p><pre>@Post(&#39;webhook&#39;)<br>  async handleStripeWebhook(<br>    @Req() req: Request,<br>    @Headers(&#39;stripe-signature&#39;) sig: string,<br>  ) {<br>    const endpointSecret = process.env.WEB_HOOK_SECRET;<br>    let event: Stripe.Event;<br><br>    try {<br>      event = this.stripeService[&#39;stripe&#39;].webhooks.constructEvent(<br>        req.rawBody,<br>        sig,<br>        endpointSecret,<br>      );<br>    } catch (err) {<br>      return { error: `Webhook Error: ${err.message}` };<br>    }<br><br>    await this.stripeService.handleWebhook(event);<br>  }</pre><p>If you encounter errors while processing the webhook, you may need to configure your application to read the raw body of the request. To do this, set the rawBody option to true in your main application file. This is essential for verifying the webhook signature correctly.</p><pre>//main.ts<br>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>import * as bodyParser from &#39;body-parser&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br><br>  // Enable raw body parsing for Stripe webhooks<br>  app.use(bodyParser.raw({ <br>    type: &#39;application/json&#39;, // Use this for JSON requests<br>  }));<br><br>  await app.listen(3000); // Start the application on the specified port<br>}<br>bootstrap();</pre><p>Now, test the webhook. If you call the first API to create a checkout session and pass the transaction as discussed below, your webhook will detect the status of the transaction. If the transaction is completed successfully, it will return logs containing the metadata you passed at the beginning. Otherwise, it will return the corresponding status, such as “failed” or “expired.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hohktN8-BbGhA6HMW9PV7A.png" /></figure><p>Now if you go to the stripe dashboard an dtransaction you find the transaction and the details of the transaction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ZADHvKygvh_f3NHb4CMlg.png" /></figure><p>Now, if you go to the Stripe dashboard and navigate to the Transactions section, you will find the transaction along with its details</p><p><strong>This summary encapsulates the entire process of setting up a payment module with Stripe in a NestJS application, highlighting key components and configurations needed for successful integration. If you need further details or clarifications on any specific part, feel free to ask!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad402aa7f83d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating AWS Lambda Functions Using the Serverless Framework with Integrated CI/CD Pipelines]]></title>
            <link>https://aws.plainenglish.io/creating-aws-lambda-functions-using-the-serverless-framework-with-integrated-ci-cd-pipelines-8b9cb71a90cc?source=rss-ad8291fe88b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b9cb71a90cc</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Yassinejdidi]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 00:45:44 GMT</pubDate>
            <atom:updated>2024-10-04T22:42:11.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WuOHLjVJWWZYiPSSddyCVg.png" /><figcaption>Build Your First AWS Lambda Function Using the Serverless Framework with CI/CD Pipeline Integration</figcaption></figure><p>In this article, I will provide a comprehensive guide on setting up your AWS Lambda function using the Serverless Framework with TypeScript. Additionally, we’ll walk through the process of creating your first CI/CD pipeline</p><h4>This article will cover the following topics:</h4><ol><li>Setting up your development environment: Configuring your Serverless application.</li><li>Setting up TypeScript and Husky for pre-commit hooks, along with ESLint and Prettier.</li><li>Creating your first Lambda function.</li><li>Establishing a CI/CD pipeline and deploying your first Lambda function.</li></ol><h3>Introduction</h3><p>AWS Lambda functions are crucial for modern applications as they enable event-driven execution of code without the need for server management. This serverless approach allows your code to run only when triggered by events, such as API calls, ensuring optimal resource usage and cost efficiency. By leveraging Lambda, developers can focus on writing code instead of managing infrastructure, leading to faster deployment cycles.</p><blockquote><strong>Cost-Effective:</strong> Pay only for the compute time used, reducing overhead costs.<br><strong>Scalable:</strong> Automatically scales with demand, handling varying traffic effortlessly.<br><strong>Efficient Development:</strong> Enables faster iteration and deployment, streamlining the development process.</blockquote><h3>I- Set Up Your Development Environment</h3><h4>Install the Serverless Framework globally using npm:</h4><pre>npm install -g serverless</pre><h4>Create a New Serverless Project</h4><p>Run the command serverless, and you will see a list of options. For our project, we will select aws/nodejs/http Api and then specify the project name. Next, you need to set up your AWS credentials to allow the Serverless Framework to interact with your AWS account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*EST7OUW6D6q1Yy5IsaP9KA.png" /></figure><p>Finally, you will receive a template like this (voir capture): in the next steps, we will implement TypeScript along with ESLint and Husky for pre-commit and pre-push hooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*OCLhjTvJC9A2h1DIpWqBvQ.png" /></figure><h4>Setting Up TypeScript with ESLint and Husky for Git Hooks</h4><p>In this case, I will provide the complete package.json file. You can use the same package.json as it includes all the necessary TypeScript dependencies, along with the Serverless Offline plugin to run and test your application locally</p><pre>{<br>  &quot;name&quot;: &quot;serverless-typescript-template&quot;,<br>  &quot;private&quot;: true,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;TypeScript + Serverless Framework + AWS&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;serverless offline -s dev&quot;,<br>    &quot;test&quot;: &quot;jest&quot;,<br>    &quot;lint&quot;: &quot;eslint --fix \&quot;src/**/*.{js,mjs,cjs,ts}\&quot;&quot;,<br>    &quot;format&quot;: &quot;prettier --write \&quot;src/**/*.{js,ts,json,md}\&quot;&quot;,<br>    &quot;prepare&quot;: &quot;husky install&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;@eslint/js&quot;: &quot;^9.8.0&quot;,<br>    &quot;@types/aws-lambda&quot;: &quot;^8.10.142&quot;,<br>    &quot;@types/jest&quot;: &quot;^29.5.12&quot;,<br>    &quot;@types/node&quot;: &quot;^22.0.0&quot;,<br>    &quot;@typescript-eslint/eslint-plugin&quot;: &quot;^7.18.0&quot;,<br>    &quot;@typescript-eslint/parser&quot;: &quot;^7.18.0&quot;,<br>    &quot;eslint&quot;: &quot;^8.56.0&quot;,<br>    &quot;eslint-config-prettier&quot;: &quot;^9.1.0&quot;,<br>    &quot;eslint-plugin-prettier&quot;: &quot;^5.2.1&quot;,<br>    &quot;globals&quot;: &quot;^15.8.0&quot;,<br>    &quot;husky&quot;: &quot;^8.0.0&quot;,<br>    &quot;jest&quot;: &quot;^29.7.0&quot;,<br>    &quot;prettier&quot;: &quot;^3.3.3&quot;,<br>    &quot;serverless&quot;: &quot;^3.34.0&quot;,<br>    &quot;serverless-esbuild&quot;: &quot;^1.46.0&quot;,<br>    &quot;serverless-offline&quot;: &quot;^13.6.0&quot;,<br>    &quot;ts-jest&quot;: &quot;^29.2.3&quot;,<br>    &quot;typescript&quot;: &quot;^5.5.4&quot;<br>  }<br>}</pre><p>In the root directory of your project, you should also create a tsconfig.json file to configure TypeScript. Below is a sample configuration:</p><pre>{<br>    &quot;compilerOptions&quot;: {<br>      &quot;lib&quot;: [&quot;ES2022&quot;],<br>      &quot;module&quot;: &quot;ES2022&quot;,<br>      &quot;moduleResolution&quot;: &quot;Bundler&quot;,<br>      &quot;allowSyntheticDefaultImports&quot;: true,<br>      &quot;sourceMap&quot;: true,<br>      &quot;target&quot;: &quot;ES2022&quot;,<br>      &quot;strict&quot;: true,<br>      &quot;types&quot;: [&quot;jest&quot;, &quot;node&quot;]<br>    },<br>    &quot;include&quot;: [&quot;src/**/*.ts&quot;]<br>  }</pre><blockquote>By creating a tsconfig.json file, you ensure that TypeScript compiles your code according to your specified preferences, which is essential for building a robust and maintainable serverless application. This configuration helps streamline development and can prevent common issues before deployment.</blockquote><h4>Add eslints</h4><p>In the package.json file I provided earlier, it contains all the dependencies for ESLint, Jest, and everything you need , you just need to create the .eslintrc.js file</p><pre>module.exports = {<br>  parser: &#39;@typescript-eslint/parser&#39;,<br>  parserOptions: {<br>    project: &#39;tsconfig.json&#39;,<br>    tsconfigRootDir: __dirname,<br>    sourceType: &#39;module&#39;,<br>  },<br>  plugins: [&#39;@typescript-eslint/eslint-plugin&#39;],<br>  extends: [<br>    &#39;plugin:@typescript-eslint/recommended&#39;,<br>    &#39;plugin:prettier/recommended&#39;,<br>  ],<br>  root: true,<br>  env: {<br>    node: true,<br>    jest: true,<br>  },<br>  ignorePatterns: [&#39;.eslintrc.js&#39;],<br>};</pre><h4>Add prettier</h4><p>Now, create a file named .prettierrc that will contain the following data. As mentioned earlier, the necessary dependencies are already included in the initial package.json file</p><pre>{<br>    &quot;semi&quot;: true,<br>    &quot;singleQuote&quot;: true,<br>    &quot;trailingComma&quot;: &quot;all&quot;,<br>    &quot;printWidth&quot;: 80,<br>    &quot;tabWidth&quot;: 2<br>  }</pre><h4>Add Jest</h4><p>Next, create a file named jest.config.ts in the root directory of your project. This file will contain the necessary configuration for Jest testing. As mentioned earlier, the required dependencies are already included in the initial package.json file</p><pre>/** @type {import(&#39;ts-jest&#39;).JestConfigWithTsJest} */<br>module.exports = {<br>    preset: &#39;ts-jest&#39;,<br>    testEnvironment: &#39;node&#39;,<br>    testMatch: [&#39;**/src/**/*.test.ts&#39;],<br>  };</pre><h3>Add husky</h3><p>Now that everything is correctly set up with ESLint, Prettier, and Jest for testing, I will create Husky hooks for pre-commit and pre-push. The pre-commit hook will invoke Prettier and ESLint to ensure code quality, while the pre-push hook will run the build process and execute all tests. If everything passes successfully, the code will be pushed. This approach helps us avoid errors or issues related to failed builds in the pipeline</p><pre>npx husky-init<br>npm install</pre><p>This will create a .husky directory containing the pre-commit and pre-push hooks. Now, inside the pre-commit file, we will add the following content:</p><pre>#!/usr/bin/env sh<br>. &quot;$(dirname -- &quot;$0&quot;)/_/husky.sh&quot;<br>npm run lint &amp;&amp; npm run format</pre><p>Add the command npm run lint to run ESLint for code linting, and npm run format to run Prettier for code formatting.</p><p>For the pre-push hook, I will include the code that runs the tests. If desired, you can also add the build command</p><pre>#!/usr/bin/env sh<br>. &quot;$(dirname -- &quot;$0&quot;)/_/husky.sh&quot;<br>npm test</pre><h4>Creating your first Lambda function</h4><p>Now, create a folder named src in the root directory that will contain two files: one for the API Lambda function and the other for the test. The src/handler.ts file will contain the following code</p><pre>export const hello = async () =&gt; {<br>  return {<br>    statusCode: 200,<br>    body: JSON.stringify({<br>      message: &#39;Go Serverless v4! Your function executed successfully!&#39;,<br>    }),<br>  };<br>};</pre><p>Finally, here is your serverless.yml configuration file, which will be generated automatically during the project setup. This file handles the routing and necessary settings for your service. I&#39;ve included comments to explain each part for better understanding. Note that I have only added the routes and plugins required for your specific setup</p><pre># &quot;org&quot; ensures this service is used with the correct Serverless Framework Access Key.<br>org: exampleName  # This will be generated automatically once you sign in to the Serverless Dashboard, which is free to use.<br># &quot;app&quot; enables Serverless Framework Dashboard features and allows sharing with other services.<br>app: appname<br><br># &quot;service&quot; defines the name of this project. This will also be used in the names of your AWS resources.<br>service: appname<br><br>plugins:<br>  - serverless-esbuild  # Plugin used for compiling and packaging the TypeScript code.<br>  - serverless-offline   # Plugin used for local execution of your service.<br><br>provider:<br>  name: aws              # Cloud provider to be used.<br>  runtime: nodejs20.x    # Runtime environment for the Lambda function.<br><br>functions:<br>  hello:<br>    handler: src/handler.hello  # Specifies the handler function for this endpoint.<br>    events:<br>      - httpApi:<br>          path: /api/hello  # Defines the API path for this function.<br>          method: get       # Specifies the HTTP method for this endpoint.</pre><p>Now that everything is correctly set up, you can run npm run start to trigger the Serverless offline server in development mode, as specified in the package.json file.</p><h4>Test the app locally to ensure everything is functioning as expected</h4><p>Now, when you run npm run start, you will see the output indicating the port on which your server is running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*JpclU8jPxBR-Jj0-Abj_Jw.png" /></figure><p><strong>Test the API in Postman</strong>, and everything is working<strong> well!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*P8DRewl0o6xREsuVHB0JZw.png" /></figure><h3>II- Setting Up a Pipeline for Seamless Deployment of Lambda Functions</h3><p>First, let’s create a directory named .github and a subdirectory called workflows, which will contain the deploy.yaml file. By adding this configuration to your app&#39;s GitHub repository, it will be automatically triggered during the deployment process. The code inside the deploy.yaml file will be as follows:</p><pre>name: Deploy Lambda<br><br>on:<br>  push:<br>    branches:<br>      - main # Trigger this workflow when there is a push to the &#39;main&#39; branch<br><br>jobs:<br>  deploy:<br>    name: Deploy Job<br>    runs-on: ubuntu-latest  # Use the latest version of Ubuntu for the job<br>    strategy:<br>      matrix:<br>        node-version: [18.x]  # Specify the Node.js version to use<br><br>    steps:<br>      - uses: actions/checkout@v3  # Check out the repository code<br>      <br>      - name: Use Node.js ${{ matrix.node-version }}  # Set up Node.js environment<br>        uses: actions/setup-node@v3<br>        with:<br>          node-version: ${{ matrix.node-version }}  # Use the specified Node.js version<br>      <br>      - run: npm ci  # Install dependencies using npm ci for clean installs<br>      <br>      - name: Serverless Deploy  # Deploy the application using Serverless<br>        uses: serverless/github-action@v3.2<br>        with:<br>          args: deploy  # Command to deploy the service<br>        env:<br>          # Environment variables for Serverless deployment<br>          SERVERLESS_ACCESS_KEY: ${{ secrets.SERVERLESS_ACCESS_KEY }}  # Serverless access key<br>          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}  # AWS access key ID<br>          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}  # AWS secret access key</pre><h4>Note:</h4><p>You need to set up your secrets in GitHub. You can obtain the <strong>Serverless Access Key</strong> from the Serverless Dashboard. Once you have the key, navigate to your GitHub repository settings and add the following secrets:</p><ul><li><strong>SERVERLESS_ACCESS_KEY</strong>: Your Serverless Access Key.</li><li><strong>AWS_ACCESS_KEY_ID</strong>: Your AWS Access Key ID.</li><li><strong>AWS_SECRET_ACCESS_KEY</strong>: Your AWS Secret Access Key</li></ul><p>This will ensure that your deployment pipeline has the necessary credentials to deploy your Lambda function successfully.</p><h4>Test Pipeline</h4><p>Now, push your code, and in your GitHub project, navigate to the “Actions” tab to find your pipeline working successfully!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FeaqPYVFOj8ei6TvvR-NzA.png" /></figure><h4>Now, if you navigate to your AWS account under Lambda functions, you will find that your Lambda function has been deployed successfully.</h4><p>I hope this was helpful! Feel free to reach out if you have any questions or need further assistance.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b9cb71a90cc" width="1" height="1" alt=""><hr><p><a href="https://aws.plainenglish.io/creating-aws-lambda-functions-using-the-serverless-framework-with-integrated-ci-cd-pipelines-8b9cb71a90cc">Creating AWS Lambda Functions Using the Serverless Framework with Integrated CI/CD Pipelines</a> was originally published in <a href="https://aws.plainenglish.io/">AWS in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Your App with Helm, Kubernetes, and GitHub Actions: A Complete CI/CD Pipeline]]></title>
            <link>https://medium.com/@yassinejedidi10/deploying-your-app-with-helm-kubernetes-and-github-actions-a-complete-ci-cd-pipeline-8b57f4f5b563?source=rss-ad8291fe88b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b57f4f5b563</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[fullstack-development]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Yassinejdidi]]></dc:creator>
            <pubDate>Sun, 29 Sep 2024 01:34:49 GMT</pubDate>
            <atom:updated>2024-09-29T01:37:35.833Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>In this article, I will guide you step-by-step on how to deploy your app and create a CI/CD pipeline using GitHub Actions. We’ll start by dockerizing a ReactJS application using a Dockerfile. After that, I’ll show you how to create a Helm chart for your app. Finally, we’ll set up a CI/CD pipeline with GitHub Actions to automate the deployment process.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oeAQBjyM8qv1eb6YNiPCLw.png" /><figcaption><strong>CI/CD Pipeline with Docker, GitHub Actions, and Kubernetes using Helm</strong></figcaption></figure><h3>What We Will Learn:</h3><ol><li><strong>Dockerizing Your App for Optimal Performance: A Step-by-Step Guide</strong></li><li><strong>Creating and Configuring Your Helm Chart for Kubernetes Deployment</strong></li><li><strong>Creating a Pipeline Using GitHub Actions</strong></li><li><strong>Test the deployment</strong></li></ol><h3>Why Use Helm and Kubernetes?</h3><p>Using <strong>Helm</strong> in conjunction with <strong>Kubernetes</strong> enables developers to effectively manage and deploy containerized applications, ensuring they are robust, scalable, and easy to maintain. <strong>Kubernetes</strong> is a powerful container orchestration platform that automates the deployment, scaling, and management of applications within containers. On the other hand, <strong>Helm</strong> serves as a package manager for Kubernetes, simplifying the installation and management of applications through reusable templates known as charts. This combination creates a solid foundation for building cloud-native applications that can easily adapt to the evolving demands of modern software development.</p><h3>1- How to Dockerize Your React App for Optimal Performance: Step-by-Step Guide</h3><p>In this section, I’ll walk you through how to dockerize a ReactJS application while maintaining optimal performance. Below is the Dockerfile I used, and I’ll explain each step of the process to ensure the best practices are followed.</p><p>Create a file named Dockerfile in the root directory</p><pre><br># Stage 1: Build the React App<br>FROM node:20.11.1-alpine3.19 AS build<br><br># Set working directory<br>WORKDIR /app<br><br># Copy package files and install dependencies<br>COPY package.json package-lock.json ./<br>RUN npm install<br><br># Set PATH to include node_modules binaries<br>ENV PATH /app/node_modules/.bin:$PATH<br><br># Copy all other project files and run the build process<br>COPY . .<br>RUN npm run build<br><br># Stage 2: Serve the built app with NGINX<br>FROM nginx:1.25.4-alpine3.18<br><br># Copy custom NGINX configuration<br>COPY ./nginx.conf /etc/nginx/conf.d/default.conf<br><br># Copy the built React app from the build stage<br>COPY --from=build /app/dist /var/www/html/<br><br># Expose port 3005<br>EXPOSE 3005<br><br># Start NGINX server<br>ENTRYPOINT [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><blockquote>Benefits of This Approach:</blockquote><blockquote><strong>Performance Optimization:</strong> By using NGINX, we leverage a high-performance web server optimized for static file delivery, which can serve your React app faster and handle more concurrent requests.</blockquote><blockquote><strong>Smaller Image Size</strong>: The multi-stage build ensures that only the necessary files (the built React app) are included in the final image. The development dependencies (Node.js, build tools) are discarded after the build process.</blockquote><h4>Then create an &quot;nginx.conf&quot; file that will contain the following code:</h4><pre>server {<br>    listen 3005;  <br>    server_name localhost;<br><br>    location / {<br>        root /var/www/html;<br>        index index.html index.htm;<br>        try_files $uri $uri/ /index.html$is_args$args;<br>    }<br>}</pre><blockquote><strong>Note:</strong><br>If you’re using a Single Page Application (SPA) like React, this configuration is essential. Without it, refreshing the page or directly accessing client-side routes could lead to a “404 Not Found” error. This setup allows the browser to request the index.html file, which React will then use to render the correct page for the given route.</blockquote><h3>2- Creating and Configuring Your Helm Chart for Kubernetes Deployment</h3><p>First of all, you need to install Helm. You can check the official Helm installation guide for instructions <a href="https://helm.sh/docs/i">Link</a>.</p><p>Once Helm is installed, let’s use it in our app. To create a Helm chart, you can run the following command:</p><pre>helm create my-app</pre><blockquote>This command initializes a new Helm chart named <strong>my-app</strong>. A Helm chart is a package of pre-configured Kubernetes resources that can be easily deployed and managed.</blockquote><p>You will get a structure like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*FMNGKBhPwy_z9tjeKC5RdA.png" /></figure><blockquote><strong>Templates</strong>: Define the Kubernetes resources (like deployments and services) using Go templating syntax, allowing dynamic configuration based on provided values.</blockquote><blockquote><strong>Values</strong>: Contain default configuration settings that can be overridden during installation to customize the behavior of the chart.</blockquote><blockquote><strong>Chart</strong>: A package that includes metadata, templates, and values, which together facilitate the deployment and management of applications on Kubernetes</blockquote><p><strong><em>Now that our setup is complete, let’s create our image repository on Docker Hub. You can choose other options such as GitHub Containers or GitLab, but in this case, I will be using Docker Hub</em></strong></p><blockquote>using an image repository is essential for efficient, secure, and scalable application development and deployment, making it a best practice in modern software workflows</blockquote><h3>Creating an Image Registry</h3><p>Go to Docker Hub and follow the instructions on how to create an image registry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6HbVCgU2BQghJCx-ESCkGQ.png" /></figure><p>Now that everything is set up, your values.yaml file should look like this:</p><pre>image:<br>  repository: username/exemple<br>  tag: &quot;latest&quot;<br>  pullPolicy: Always<br><br>service:<br>  type: LoadBalancer<br>  port: 3005<br><br>replicaCount: 3</pre><blockquote>This configuration specifies the Docker image repository, the tag for the image, the pull policy, the service type, the port, and the number of replicas for your application <br><strong><em>Note:</em></strong> The values.yaml file is similar to a .env file, as it stores configuration values for the application. Additionally, the port for the service needs to match the port used in your Dockerfile.</blockquote><p>Now, let’s create our deployment and service in the templates directory. We will create a file named deployment.yaml that will contain the deployment configuration:</p><pre>apiVersion: apps/v1  # Specifies the version of the Kubernetes API to use for the Deployment<br>kind: Deployment     # Defines the resource type; in this case, it is a Deployment<br>metadata:<br>  name: my-app   # The name of the Deployment, used to identify it within the Kubernetes cluster<br>spec:<br>  replicas: 1        # The desired number of pod replicas to run<br>  selector:<br>    matchLabels:     # Selector to identify the pods managed by this Deployment<br>      app: my-app # The label that must match the pods to be managed<br>  template:          # Template for the pod that will be created by the Deployment<br>    metadata:<br>      labels:       # Labels assigned to the pods created by this Deployment<br>        app: my-app # The same label used in the selector to link the pods to the Deployment<br>    spec:<br>      containers:    # Specifies the list of containers to run in the pod<br>        - name: my-app  # Name of the container<br>          image: &quot;{{ .Values.image.repository }}:{{ .Values.image.tag }}&quot; # Docker image used for the container<br>          ports:       # List of ports to expose from the container<br>            - containerPort: 3005 # The port that the container listens on, matching the port defined in the Dockerfile</pre><blockquote>This structure allows Kubernetes to manage the application effectively, ensuring that the specified number of pod replicas are running and accessible.</blockquote><p>Now, let’s create our service in the templates directory. We will create a file named service.yaml that will contain the service configuration:</p><pre>apiVersion: v1                # Specifies the version of the Kubernetes API to use for the Service<br>kind: Service                 # Defines the resource type; in this case, it is a Service<br>metadata:<br>  name: my-app           # The name of the Service, used to identify it within the Kubernetes cluster<br>spec:<br>  type: {{ .Values.service.type }}   # The type of service (e.g., ClusterIP, NodePort, LoadBalancer), pulled from values.yaml<br>  ports:<br>    - port: {{ .Values.service.port }}  # The port exposed by the Service, pulled from values.yaml<br>      targetPort: 3005          # The port on the container that the Service should forward traffic to<br>  selector:<br>    app: my-app             # Selector to identify the pods the Service should route traffic to</pre><blockquote>The service.yaml file defines a Service resource in Kubernetes that allows external access to your application. By using Helm&#39;s templating features, we can dynamically set the service type and port through the values.yaml file. This flexibility allows you to easily modify the service configuration without changing the template directly.</blockquote><p>Now that everything is set up for the Helm installation, we can proceed with deploying our application.</p><h3><strong>3-Creating a Pipeline Using GitHub Actions</strong></h3><p>First, we need to store the credentials for our Docker Hub and the kubeconfig in the Secrets section inside GitHub. You can find the kubeconfig in your virtual machine in the .kube directory. To add these secrets, follow these steps:</p><h4>Steps to Add Secrets in GitHub</h4><ol><li><strong>Go to gitbub repository &gt;Settings&gt;Secrets and variables&gt;Actions</strong></li><li><strong>Click on the “New repository secret”</strong></li><li><strong>Store Docker Hub Credentials:Name: </strong><br>Enter a name for your Docker Hub credentials, DOCKER_USERNAME ,<br>Repeat this step for your Docker Hub password (name it DOCKER_PASSWORD).</li><li><strong>Store Kubeconfig:<br>Name</strong>: Enter a name for your kubeconfig , KUBECONFIG</li></ol><blockquote><strong>Value</strong>: Copy the contents of your kubeconfig file. You can find it by running the command:</blockquote><pre>cat ~/.kube/config</pre><p><strong>Note :</strong> By following these steps, you can securely store your Docker Hub and kubeconfig credentials in GitHub Secrets, allowing you to use them in your GitHub Actions workflow without exposing sensitive information.</p><h4>Creating Our Deployment for GitHub Actions</h4><p>In our application, we first need to create a .github directory. By doing this, GitHub will automatically detect it. Inside this directory, we will create a workflows folder and a file named deploy.yaml</p><pre>name: Deploy to Kubernetes using Helm<br><br>on:<br>  push:<br>    branches:<br>      - main<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - name: Checkout code<br>      uses: actions/checkout@v2<br><br>    - name: Set up Docker Buildx<br>      uses: docker/setup-buildx-action@v2<br><br>    - name: Log in to Docker Hub<br>      run: echo &quot;${{ secrets.DOCKER_PASSWORD }}&quot; | docker login -u &quot;${{ secrets.DOCKER_USERNAME }}&quot; --password-stdin<br><br>    - name: Build and push Docker image<br>      run: |<br>        docker build -t yourImageRepository:${{ github.sha }} .<br>        docker push yourImageRepository:${{ github.sha }}<br><br>    - name: Set up Kubectl<br>      uses: azure/setup-kubectl@v3<br>      with:<br>        version: &#39;v1.23.0&#39; <br><br>    - name: Install Helm<br>      uses: azure/setup-helm@v1<br><br>    - name: Create kubeconfig file<br>      run: echo &quot;${{ secrets.KUBECONFIG }}&quot; &gt; ${{ github.workspace }}/kubeconfig<br><br>    - name: Deploy to Kubernetes using Helm<br>      env:<br>        KUBECONFIG: ${{ github.workspace }}/kubeconfig<br>      run: |<br>       cd my-app       helm upgrade --install my-app . \<br>       --set image.repository=yourImageRepository \<br>       --set image.tag=${{ github.sha }} \<br>       --namespace default</pre><h4><strong>Each job consists of several steps that execute specific actions.</strong></h4><ol><li><strong>Checkout Code</strong>: This step checks out the repository code to the GitHub Actions runner, allowing subsequent steps to access it</li><li><strong>Set Up Docker Buildx</strong>:This step sets up Docker Buildx, which is an advanced tool for building multi-platform Docker images.</li><li><strong>Log in to Docker Hub</strong>:This step logs into Docker Hub using credentials stored in GitHub Secrets. The password is echoed into the docker login command to authenticate securely</li><li><strong>Build and Push Docker Image</strong>:This step builds a Docker image using the Dockerfile in the repository and tags it with the current commit SHA for uniqueness. After building, it pushes the image to Docker Hub.</li><li><strong>Set Up Kubectl</strong>:This step installs kubectl, the command-line tool for interacting with Kubernetes clusters, specifying the version to use.</li><li><strong>Install Helm</strong>:This step installs Helm, the package manager for Kubernetes, allowing you to manage your applications more easily.</li><li><strong>Create Kubeconfig File</strong>:This step creates a kubeconfig file from the secret stored in GitHub, which contains the configuration necessary for kubectl to communicate with the Kubernetes cluster.</li><li><strong>Deploy to Kubernetes Using Helm</strong>:In this final step, the workflow navigates to the my-app directory and deploys the application to Kubernetes using Helm. It uses the upgrade --install command, which either upgrades an existing release or installs a new one if it doesn&#39;t exist. The image repository and tag are set dynamically based on the built Docker image.</li></ol><p><strong>This workflow automates the build and deployment process, ensuring that every push to the main branch triggers a fresh deployment to the Kubernetes cluster, promoting a continuous integration/continuous deployment (CI/CD) strategy.</strong></p><h3>4- Test the Deployment</h3><p>Now, let’s push the code to the <strong>main</strong> branch and navigate to the <strong>Actions</strong> section in your GitHub repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILXgNxYqIaNi0yjSN5zouw.png" /></figure><p>Now that our build has passed successfully, let’s verify the deployment in our virtual machine. You can check the deployment by running the following commands:</p><pre>kubectl get services<br>kubectl get deployments</pre><p>You should see your app listed along with the port it is running on.</p><p>If you want to test your app and do not have a host set up (e.g., without an ingress file), you can run the following command to get the internal IP address:</p><pre>kubectl get nodes -o wide</pre><p>This will provide you with the internal IP that you can use as the host for your application.</p><h3>Summary:</h3><p>In this guide, we covered the essential steps to effectively dockerize a React application, ensuring optimal performance and streamlined deployment. We explored how to create and configure a Helm chart, which simplifies managing Kubernetes applications through reusable templates. Finally, we set up a CI/CD pipeline using GitHub Actions, automating the deployment process and enhancing the efficiency of our development workflow. This comprehensive approach empowers developers to build, deploy, and manage cloud-native applications seamlessly.</p><p><strong>I hope this article will be helpful to everyone. If you have any questions, feel free to ask!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b57f4f5b563" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Azure Infrastructure with Terraform]]></title>
            <link>https://awstip.com/deploying-azure-infrastructure-with-terraform-e34046c65d0f?source=rss-ad8291fe88b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e34046c65d0f</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[vm]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[hcl]]></category>
            <dc:creator><![CDATA[Yassinejdidi]]></dc:creator>
            <pubDate>Wed, 20 Mar 2024 03:10:57 GMT</pubDate>
            <atom:updated>2024-03-23T14:52:16.323Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story, I will demonstrate the process of deploying Azure infrastructure using Terraform as the provisioning tool. Before diving into the deployment steps, let’s first establish a foundational understanding of Terraform and relevant concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tlcW50v-Mvsd0CvexOLgTA.png" /></figure><p><strong>How to Provision an Azure VM<br></strong>To provision an Azure virtual machine, you need to specify the following parameters:<br>•Virtual Machine Name<br>•Operating System (Image)<br>•VM Size<br>•Geographical Location<br>•Username and Password (or SSH key for Linux VMs)”</p><p><strong>Method 1: Azure Portal (GUI)<br></strong>You can check out the following link for a guide on how to use the Azure portal to create a virtual network: <a href="https://docs.microsoft.com/en-us/azure/virtual-network/quick-create-portal">Azure Virtual Network — Quickstart</a></p><p><strong>Method 2: ARM Template<br></strong>An ARM template provides a consistent and reliable way to provision Azure resources using a JSON structure. This approach is favored for its ease of readability and editing. ARM, which stands for Azure Resource Manager, facilitates the deployment and management of Azure resources in a declarative manner. By defining the desired state of the Azure infrastructure through JSON templates, users can ensure consistency across deployments and automate resource provisioning processes</p><p><strong>Method 3: Provision with Terraform<br></strong>Using Terraform</p><p><strong>What is Terraform?</strong></p><p>•Executable Documentation<br>• Human and machine readable<br>• Easy to learn<br>• Test, share, re-use, automate<br>•Works on all major cloud providers</p><p><strong>Terraform </strong>is an infrastructure as code (IaC) tool that automates the provisioning, management, and deployment of cloud infrastructure resources. With Terraform, you define your infrastructure in code using a declarative configuration language<br><strong><em>Most terraform workspaces contain a minimum of three files</em></strong><em>:</em><br><strong>main.tf </strong>: Most of your functional code will go here.<br><strong>variables.tf</strong> : This file is for storing variables.<br><strong>outputs.tf :</strong> Define what is shown at the end of a terraform run.</p><p><strong>What is Infrastructure as Code?<br></strong>infrastructure as Code (IaC) is the process of managing and provisioning cloud infrastructure with machine-readable definition files. These files, typically written in languages like Terraform’s HashiCorp Configuration Language (HCL), YAML, or JSON, describe the desired state of the infrastructure, including resources such as virtual machines, networks, and storage accounts</p><p><strong>Infrastructure as Code Allows Us To =&gt;<br></strong>• Provide a codified workflow to create infrastructure<br>• Change and update existing infrastructure<br>•Integrate with application code workflows</p><p><strong>Terraform vs JSON<br></strong>Terraform code (HCL) is easy to learn and easy to read. It is also 50–70% more compact than an equivalent JSON configuration.</p><p><strong>Why Terraform on Azure?<br></strong>• Supports multi-cloud &amp; hybrid infrastructure<br>• Migrate from other cloud providers<br>• Increase provisioning speed<br>• Improve efficiency<br>• Reduce risk</p><p><strong><em>Most terraform commands:<br></em>init</strong> : Prepare your working directory for other commands<br><strong>validate : </strong>Check whether the configuration is valid<br><strong>plan : </strong>Show changes required by the current configuration<br><strong>apply: </strong>Create or update infrastructure<br><strong>destroy: </strong>Destroy previously-created infrastructure</p><p><strong>Terraform State<br></strong>Terraform is a stateful application, which means it maintains a record of the infrastructure it manages in a state file. You may notice files named terraform.tfstate and terraform.tfstate.backup within your working directory. These files serve as Terraform’s source of truth, containing information about the resources provisioned and their current state. Terraform relies on this state file to plan and execute changes to your infrastructure accurately</p><p><strong>Application for configuring infrastructure<br></strong>In this application, I will do the following:</p><ol><li>Provider Configuration: Declares the Azure provider and enables any necessary features.</li><li>Resource Group: Creates an Azure resource group with a name derived from the provided variable and located in the specified Azure region.</li><li>Virtual Network: Sets up an Azure virtual network named &quot;test&quot; with an address space of 10.0.0.0/16. It associates the virtual network with the previously created resource group.</li><li>Subnets: Creates three subnets within the virtual network. Each subnet is assigned an address prefix and associated with the resource group and virtual network.</li><li>Network Interfaces: Provisions Azure network interfaces for virtual machines. Each network interface is assigned to a specific subnet and configured with dynamic private IP address allocation.</li><li>Storage Account: Deploys an Azure storage account with the specified name, tier, and replication type. Tags are applied to identify the environment as &quot;staging&quot;.</li><li>Storage Container: Sets up a private storage container within the storage account named &quot;jdidi&quot; to organize and manage stored data securely.</li><li>Virtual Machines: Deploys three Azure virtual machines, each with its own configuration. They are placed within the resource group, connected to the virtual network via their respective network interfaces, and configured with operating system details. The OS disks for the virtual machines are created from the specified image references stored in the storage account.</li></ol><p>Now, after reviewing, let’s proceed to create the application and deploy it on the Azure provider. I will create two files, main.tf and variables.tf. I will add comments to help understand each block</p><pre># Declare the Azure provider and enable features<br>provider &quot;azurerm&quot; {<br>  features {}<br>}<br><br># Create a new Azure resource group<br>resource &quot;azurerm_resource_group&quot; &quot;test&quot; {<br>  name     = &quot;${var.name}-rg&quot;  # Name of the resource group<br>  location = &quot;${var.location}&quot;  # Location of the resource group<br>}<br><br># Create a new Azure virtual network<br>resource &quot;azurerm_virtual_network&quot; &quot;test&quot; {<br>  name                = &quot;test&quot;  # Name of the virtual network<br>  address_space       = [&quot;10.0.0.0/16&quot;]  # Address space for the virtual network<br>  location            = &quot;${var.location}&quot;  # Location of the virtual network<br>  resource_group_name = &quot;${azurerm_resource_group.test.name}&quot;  # Resource group for the virtual network<br>}<br><br># Create a new Azure subnet<br>resource &quot;azurerm_subnet&quot; &quot;test&quot; {<br>  name                 = &quot;test-subnet&quot;  # Name of the subnet<br>  resource_group_name  = &quot;${azurerm_resource_group.test.name}&quot;  # Resource group for the subnet<br>  virtual_network_name = &quot;${azurerm_virtual_network.test.name}&quot;  # Virtual network for the subnet<br>  address_prefixes     = [&quot;10.0.2.0/24&quot;]  # Address prefixes for the subnet<br>}<br><br># Create another new Azure subnet<br>resource &quot;azurerm_subnet&quot; &quot;test2&quot; {<br>  name                 = &quot;test-subnet2&quot;  # Name of the subnet<br>  resource_group_name  = &quot;${azurerm_resource_group.test.name}&quot;  # Resource group for the subnet<br>  virtual_network_name = &quot;${azurerm_virtual_network.test.name}&quot;  # Virtual network for the subnet<br>  address_prefixes     = [&quot;10.0.3.0/24&quot;]  # Address prefixes for the subnet<br>}<br><br># Create a third new Azure subnet<br>resource &quot;azurerm_subnet&quot; &quot;test3&quot;{<br>  name                 = &quot;test-subnet3&quot;  # Name of the subnet<br>  resource_group_name  = &quot;${azurerm_resource_group.test.name}&quot;  # Resource group for the subnet<br>  virtual_network_name = &quot;${azurerm_virtual_network.test.name}&quot;  # Virtual network for the subnet<br>  address_prefixes     = [&quot;10.0.4.0/24&quot;]  # Address prefixes for the subnet<br>}<br><br># Create a new Azure network interface for the first virtual machine<br>resource &quot;azurerm_network_interface&quot; &quot;test&quot; {<br>  name                = &quot;test&quot;  # Name of the network interface<br>  location            = &quot;${var.location}&quot;  # Location of the network interface<br>  resource_group_name = &quot;${azurerm_resource_group.test.name}&quot;  # Resource group for the network interface<br>  ip_configuration {<br>    name                          = &quot;config1&quot;  # Name of the IP configuration<br>    subnet_id                     = &quot;${azurerm_subnet.test.id}&quot;  # Subnet for the IP configuration<br>    private_ip_address_allocation = &quot;Dynamic&quot;  # Type of IP address allocation<br>  }<br>}<br><br># Create a new Azure network interface for the second virtual machine<br>resource &quot;azurerm_network_interface&quot; &quot;test2&quot; {<br>  name                = &quot;test2&quot;  # Name of the network interface<br>  location            = &quot;${var.location}&quot;  # Location of the network interface<br>  resource_group_name = &quot;${azurerm_resource_group.test.name}&quot;  # Resource group for the network interface<br>  ip_configuration {<br>    name                          = &quot;config2&quot;  # Name of the IP configuration<br>    subnet_id                     = &quot;${azurerm_subnet.test2.id}&quot;  # Subnet for the IP configuration<br>    private_ip_address_allocation = &quot;Dynamic&quot;  # Type of IP address allocation<br>  }<br>}<br><br># Create a new Azure network interface for the third virtual machine<br>resource &quot;azurerm_network_interface&quot; &quot;test3&quot; {<br>  name                = &quot;test3&quot;  # Name of the network interface<br>  location            = &quot;${var.location}&quot;  # Locationof the network interface<br>  resource_group_name = &quot;${azurerm_resource_group.test.name}&quot;  # Resource group for the network interface<br>  ip_configuration {<br>    name                          = &quot;config3&quot;  # Name of the IP configuration<br>    subnet_id                     = &quot;${azurerm_subnet.test3.id}&quot;  # Subnet for the IP configuration<br>    private_ip_address_allocation = &quot;Dynamic&quot;  # Type of IP address allocation<br>  }<br>}<br><br># Create a new Azure storage account<br>resource &quot;azurerm_storage_account&quot; &quot;test&quot; {<br>  name                     = &quot;yassinejdidi25662&quot;  # Name of the storage account<br>  resource_group_name      = &quot;${azurerm_resource_group.test.name}&quot;  # Resource group for the storage account<br>  location                 = &quot;${var.location}&quot;  # Location of the storage account<br>  account_tier             = &quot;Standard&quot;  # Tier of the storage account<br>  account_replication_type = &quot;GRS&quot;  # Replication type of the storage account<br><br>  tags = {<br>    environment = &quot;staging&quot;  # Tags for the storage account<br>  }<br>}<br><br># Create a new Azure storage container<br>resource &quot;azurerm_storage_container&quot; &quot;test&quot; {<br>  name                  = &quot;jdidi&quot;  # Name of the storage container<br>  storage_account_name  = &quot;${azurerm_storage_account.test.name}&quot;  # Storage account for the storage container<br>  container_access_type = &quot;private&quot;  # Access type for the storage container<br>}<br><br># Create the first Azure virtual machine<br>resource &quot;azurerm_virtual_machine&quot; &quot;test&quot; {<br>  name                  = &quot;jdidi&quot;  # Name of the virtual machine<br>  location              = &quot;${var.location}&quot;  # Location of the virtual machine<br>  resource_group_name   = &quot;${azurerm_resource_group.test.name}&quot;  # Resource group for the virtual machine<br>  network_interface_ids = [&quot;${azurerm_network_interface.test.id}&quot;]  # Network interface for the virtual machine<br>  vm_size               = &quot;Standard_B1s&quot;  # Size of the virtual machine<br><br>  os_profile {<br>    computer_name  = &quot;jdidi&quot;  # Name of the computer<br>    admin_username = &quot;${var.username}&quot;  # Admin username<br>    admin_password = &quot;${var.password}&quot;  # Admin password<br>  }<br><br>  os_profile_linux_config {<br>    disable_password_authentication = false  # Disable password authentication<br>  }<br><br>  storage_image_reference {<br>    publisher = &quot;Canonical&quot;  # Publisher of the image<br>    offer     = &quot;UbuntuServer&quot;  # Offer of the image<br>    sku       = &quot;16.04-LTS&quot;  # SKU of the image<br>    version   = &quot;latest&quot;  # Version of the image<br>  }<br><br>  storage_os_disk {<br>    name          = &quot;myosdisk1&quot;  # Name of the OS disk<br>    vhd_uri       = &quot;${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk1.vhd&quot;  # URI of the VHD<br>    caching       = &quot;ReadWrite&quot;  # Caching type for the OS disk<br>    create_option = &quot;FromImage&quot;  # Type of creation for the OS disk<br>  }<br>}<br><br># Create the second Azure virtual machine<br>resource &quot;azurerm_virtual_machine&quot; &quot;test2&quot; {<br>  name                  = &quot;jdidi2&quot;  # Name of the virtual machine<br>  location              = &quot;${var.location}&quot;  # Location of the virtual machine<br>  resource_group_name   = &quot;${azurerm_resource_group.test.name}&quot;  # Resource group for the virtual machine<br>  network_interface_ids = [&quot;${azurerm_network_interface.test2.id}&quot;]  # Network interface for the virtual machine<br>  vm_size               = &quot;Standard_B1s&quot;  # Size of the virtual machine<br><br>  os_profile {<br>    computer_name  = &quot;jdidi2&quot;  # Name of the computer<br>    admin_username = &quot;${var.username}&quot;  # Admin username<br>    admin_password = &quot;${var.password}&quot;  # Admin password<br>  }<br><br>  os_profile_linux_config {<br>    disable_password_authentication = false # Disable password authentication<br>  }<br><br>  storage_image_reference {<br>    publisher = &quot;Canonical&quot;  # Publisher of the image<br>    offer     = &quot;UbuntuServer&quot;  # Offer of the image<br>    sku       = &quot;16.04-LTS&quot;  # SKU of the image<br>    version   = &quot;latest&quot;  # Version of the image<br>  }<br><br>  storage_os_disk {<br>    name          = &quot;myosdisk2&quot;  # Name of the OS disk<br>    vhd_uri       = &quot;${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk2.vhd&quot;  # URI of the VHD<br>    caching       = &quot;ReadWrite&quot;  # Caching type for the OS disk<br>    create_option = &quot;FromImage&quot;  # Type of creation for the OS disk<br>  }<br>}<br><br># Create the third Azure virtual machine<br>resource &quot;azurerm_virtual_machine&quot; &quot;test3&quot; {<br>  name                  = &quot;jdidi3&quot;  # Name of the virtual machine<br>  location              = &quot;${var.location}&quot;  # Location of the virtual machine<br>  resource_group_name   = &quot;${azurerm_resource_group.test.name}&quot;  # Resource group for the virtual machine<br>  network_interface_ids = [&quot;${azurerm_network_interface.test3.id}&quot;]  # Network interface for the virtual machine<br>  vm_size               = &quot;Standard_B1s&quot;  # Size of the virtual machine<br><br>  os_profile {<br>    computer_name  = &quot;jdidi3&quot;  # Name of the computer<br>    admin_username = &quot;${var.username}&quot;  # Admin username<br>    admin_password = &quot;${var.password}&quot;  # Admin password<br>  }<br><br>  os_profile_linux_config {<br>    disable_password_authentication = false  # Disable password authentication<br>  }<br><br>  storage_image_reference {<br>    publisher = &quot;Canonical&quot;  # Publisher of the image<br>    offer     = &quot;UbuntuServer&quot;  # Offer of the image<br>    sku       = &quot;16.04-LTS&quot;  # SKU of the image<br>version   = &quot;latest&quot;  # Version of the image<br>  }<br><br>  storage_os_disk {<br>    name          = &quot;myosdisk3&quot;  # Name of the OS disk<br>    vhd_uri       = &quot;${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/myosdisk3.vhd&quot;  # URI of the VHD<br>    caching       = &quot;ReadWrite&quot;  # Caching type for the OS disk<br>    create_option = &quot;FromImage&quot;  # Type of creation for the OS disk<br>  }<br>}</pre><p>Now I’ll create a file named variables.tf where I&#39;ll define the variables. These variable definitions will allow us to easily adjust the values of name, location, username, and password when deploying our infrastructure, without directly modifying the Terraform configuration</p><pre><br>variable &quot;name&quot; {<br>  description = &quot;name of our ressource&quot;<br>  default     = &quot;test&quot;<br>}<br>variable &quot;location&quot;{ <br>    default = &quot;select a location for exemple : East US&quot; <br>    }<br>variable &quot;username&quot;{ <br>    default = &quot;adminuser&quot;<br>     }<br>variable &quot;password&quot; {<br>     default = &quot;select your password&quot;<br>      }</pre><p>Now that the setup is complete, let’s log in to the Azure account by running the command <strong>az login</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ig11TmsaswJQZyWlXGdtAg.png" /></figure><p>After successfully logging in, we need to run<strong> terraform init</strong> to initialize a Terraform working directory. This command sets up various backend settings, downloads providers, and performs other initialization tasks required for Terraform to manage your infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05BzY2vdIarfOlNrZg0Lqw.png" /></figure><p>After that , I’ll execute<strong> terraform apply</strong> to implement the changes specified in our Terraform configuration onto our infrastructure. This command evaluates the current state of the infrastructure, contrasts it with the desired state outlined in the configuration, and then executes any required alterations to align the infrastructure with the desired state. It may create, update, or delete resources as necessary, guided by the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*sUYoMAUO5ZneQBe-TgYo7Q.png" /></figure><p>After confirming with ‘yes’, the infrastructure has been provisioned in Azure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dMqqrv_8gGE50dTim3G4A.jpeg" /></figure><p>In summary, the provided code is used to create an Azure infrastructure comprising multiple resources. These resources include a resource group, virtual network, subnets, network interfaces, storage account, and a virtual machine. The resources are deployed within the designated resource group and location, and they are interconnected according to the specifications outlined in the code. For instance, the virtual machine is linked to the designated network interfaces, which in turn are associated with the specified subnets, all of which are contained within the designated virtual network residing in the specified resource group</p><p><strong>GitHub repository link:</strong> <a href="https://github.com/Yassinejedidi/vm_terraform_azure">https://github.com/Yassinejedidi/vm_terraform_azure</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e34046c65d0f" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/deploying-azure-infrastructure-with-terraform-e34046c65d0f">Deploying Azure Infrastructure with Terraform</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upload File Using Azure Blob Storage in NestJS Application and Integrate UseGuard Authentication]]></title>
            <link>https://blog.stackademic.com/upload-file-using-azure-blob-storage-in-nestjs-application-and-integrate-useguard-authentication-47873e9d315a?source=rss-ad8291fe88b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/47873e9d315a</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Yassinejdidi]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 06:08:26 GMT</pubDate>
            <atom:updated>2024-03-20T00:53:30.009Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story, I’ll share my latest project experience, which involves using NestJS with TypeORM, PostgreSQL, and Azure Blob Storage. I’ll walk you through the implementation steps and share insights into integrating these technologies to build a robust and scalable application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhLguCCyjpbH2I-FZ4-SBQ.png" /><figcaption>Upload File Using Azure Blob Storage in NestJS Application</figcaption></figure><p>Here’s an overview of what i’ll cover:</p><p>1-SetUp container for azure blob storage in azure <br>2-Creating Nestjs Application<br>3-Connect application with PostgreSQL using TypeORM<br>4- Implementing a signup method for user registration<br>5-Implementing a signin method to generate JWT tokens for authentication<br>6-Developing a service for Azure Blob Storage facilitates the process of uploading files into the Azure Blob Storage and storing them within the designated container provided by Azure<br>6-Integrating AuthGuard to protect routes<br>8-Utilizing the CRUD service for uploading, deleting, and retrieving files from Azure Blob Storage</p><p><strong>Set up storage account in Azure<br></strong>First, we need to log in to the Azure account. Upon accessing it, we will find an overview like this, and then we will click on “Storage account”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0WoVWESUlVU6YtlRW7N-w.png" /></figure><p>The next step is to click on ‘Create,’ then we will access this section for creating a storage account. In this part, we will fill in the fields such as the resource group and the storage account name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*AfC9AOmd65N4O5gg2xaRAQ.png" /></figure><p>Next, by clicking on ‘Verify,’ it will take some time to verify, typically under 1 minute or 30 seconds. After verification, we will click on ‘Create</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*rgZMDaQY37JLIOU1StuWaw.png" /></figure><p>After this, it will redirect us to an overview similar to this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQ-v2eyf3LrjTVAnYkRwDw.png" /></figure><p>Here, you’ll find a container in the search bar. We’ll access this container and create a new one to store the files. It’s necessary to create a container in Azure Blob Storage to organize and manage the files efficiently. Containers act as logical units for storing blobs (files) and help in maintaining a structured hierarchy for better organization and access control within the storage account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vamPB6V3Zt8yTx6W1t-iNA.png" /></figure><p>Now our container is being created successfully. Next, let’s verify the access keys for this container. Access keys are essential cryptographic keys that provide secure access to resources within Azure services. By checking the access keys for the container, we ensure that our application has the necessary credentials to interact securely with the Azure Blob Storage service and perform operations such as uploading, downloading, and managing files</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSRlB7SjvSuylWVMzLmZtg.png" /></figure><p>Now that the configuration is set up correctly, let’s create a Nest.js application by running the following command: $ nest new project-name</p><blockquote>Once the application is set up correctly, we’ll install the necessary dependencies such as @nestjs/typeorm, @azure/storage-blob, uuidv4, @types/multer, and pg using the command: npm install --save @nestjs/typeorm @azure/storage-blob uuidv4 @types/multer pg</blockquote><p><strong>Connect application with PostgreSQL using TypeORM</strong></p><p>We will create a file named typeorm.config.ts which will contain all the necessary configurations to ensure communication. Import the TypeOrmModuleOptions from @nestjs/typeorm, and retrieve the database configuration using config. Then, export typeOrmConfig with the specified database configuration, including the entities to be used and synchronization settings</p><pre>import { TypeOrmModuleOptions } from &quot;@nestjs/typeorm&quot;;<br>import * as config from &#39;config&#39;<br>import { User } from &quot;src/enteties/user.entity&quot;;<br><br>const dbConfig = config.get(&#39;db&#39;)<br><br>export const typeOrmConfig: TypeOrmModuleOptions={<br>    type: dbConfig.type,<br>    host:  dbConfig.host,<br>    port:dbConfig.port,<br>    username:dbConfig.username,<br>    password:dbConfig.password,<br>    database: dbConfig.database,<br>    entities:[User],<br>    synchronize: dbConfig.synchronize,<br><br>    <br>}</pre><p>Here is the entity for a user that we are going to use</p><pre>import { BaseEntity, Column, Entity, PrimaryGeneratedColumn, Unique } from &quot;typeorm&quot;;<br>import * as bcrypt from &#39;bcrypt&#39;<br><br><br>@Entity()<br>@Unique([&#39;email&#39;])<br>export class User extends BaseEntity{<br> @PrimaryGeneratedColumn()   <br>id: number;<br>@Column()<br>email: string;<br><br>@Column()<br>password: string;<br>@Column()<br>salt:string;<br><br>/**<br> * Validates a password against the stored hashed password and salt.<br> * @param password The plain text password to validate.<br> * @returns A Promise resolving to true if the password is valid, otherwise false.<br> */<br>async validatePassword(password: string): Promise &lt;boolean&gt;{<br>    const hash = await bcrypt.hash(password, this.salt);<br>    return hash === this.password;<br>}<br><br>}</pre><p>Next , importing the TypeORM module into the app module (AppModule) is necessary to configure and establish the database connection for the Nest.js application. By importing TypeOrmModule.forRoot(), the application gains access to database functionality globally</p><pre><br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forRoot(typeOrmConfig),<br>    AuthModule],<br>  controllers: [AppController],<br>  providers: [AppService<br>  ],<br>})<br>export class AppModule {}</pre><p>Now, if you close your server and restart it, you will find the ‘user’ table in the pgAdmin like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNys-KXrokngRfNr5FyvsA.png" /></figure><p><strong>Implementing a signIn &amp; singUp methods</strong></p><p>Now, let’s create a user module in Nestjs. We’ll start by creating separate files for the controller, service, and module. These files will help us organize and manage user-related functionality effectively within our application</p><p>This userModule in Nest.js is dedicated to user management within our application. It utilizes TypeOrmModule to interact with the database and specifically imports the ‘user’ entity for database operations. The module includes a userController to handle incoming requests related to users and a userService to manage user data and business logic</p><pre>//user.module.ts<br>@Module({<br>  imports: [<br>    TypeOrmModule.forFeature([user]),<br>  ],<br>  controllers: [userController],<br>  providers: [userService], <br><br>})<br>export class userModule {}</pre><p>Now, I’ll provide the <strong>complete user service</strong>, which includes methods for signing in and signing up. I’ll explain each method with comments, so the final <strong>user.service </strong>will look like this</p><pre>//user.service.ts<br>@Injectable()<br>export class userService {<br>    private logger = new Logger(&#39;AuthService&#39;);<br><br>    constructor(<br>        @InjectRepository(User)<br>        private userRepository: Repository&lt;User&gt;,<br>        private jwtService: JwtService,<br>    ){}<br><br>    // Method to register a new user<br>    async signUp(authCredentialsDto: AuthCredentialsDto): Promise&lt;User&gt; {<br>        const { email, password } = authCredentialsDto;<br><br>        const user = new User();<br>        user.email = email;<br>        user.salt = await bcrypt.genSalt(); // Generate a salt for password hashing<br>        user.password = await this.hashPassword(password, user.salt); // Hash the password<br><br>        try {<br>            await user.save(); // Save the user record in the database<br>            return user;<br>        } catch (error) {<br>            // Handle duplicate email error<br>            if (error.code === &#39;23505&#39;) {<br>                throw new ConflictException(&#39;Email already exists&#39;);<br>            } else {<br>                throw new InternalServerErrorException(&#39;Failed to register user&#39;);<br>            }<br>        }<br>    }<br><br>    // Method to sign in a user<br>    async signIn(authCredentialsDto: SingCredentialsDto): Promise&lt;{ accesToken: string  }&gt; {<br>        const email = await this.ValidateUserPassword(authCredentialsDto);<br><br>        // If no matching user or invalid credentials, throw UnauthorizedException<br>        if (!email) {<br>            throw new UnauthorizedException(&#39;Invalid credentials&#39;);<br>        }<br><br>        // Retrieve user object from database<br>        const user = await this.userRepository.findOne({ where: { email: authCredentialsDto.email } });<br><br>        // Generate JWT token payload<br>        const payload: JwtPayload = { email: user.email };<br><br>        // Sign the payload to generate JWT token<br>        const accesToken = await this.jwtService.sign(payload);<br>        return { accesToken };<br>    }<br><br>    // Method to validate user password during sign-in<br>    async ValidateUserPassword(authCredantialsDto: SingCredentialsDto): Promise&lt;string&gt; {<br>        const { email, password } = authCredantialsDto;<br>        const user = await this.userRepository.findOne({ where: { email } });<br><br>        // Validate password against stored hashed password<br>        if (user &amp;&amp; await user.validatePassword(password)) {<br>            return user.email;<br>        } else {<br>            return null;<br>        }<br>    }<br><br>    // Method to hash password<br>    private async hashPassword(password: string, salt: string): Promise&lt;string&gt; {<br>        return bcrypt.hash(password, salt);<br>    }<br>}</pre><p>In this section, I will create methods for uploading, retrieving, and deleting files from Azure Blob Storage. I will create a separate service for Azure Blob Storage that will contain the necessary CRUD operations. Then, I will inject this service into the user controller and utilize these methods<br>In the azureConnection variable, we will store the key obtained from the setup process after creating a storage account</p><pre>azure-blob.service.ts<br>@Injectable()<br>export class AzureBlobService {<br>  containerName: string;<br>// The containerName variable stores the name of the container in Azure Blob Storage where files will be uploaded, retrieved, and deleted.<br>// The azureConnection variable retrieves the Azure Storage Connection String from the configuration file, which contains the key required to connect to the Azure Storage Account.<br>azureConnection = config.get(&#39;azure.AZURE_STORAGE_CONNEXION_STRING&#39;);<br><br>  // Method to get blob client<br>  getBlobClient(imageName: string): BlockBlobClient {<br>    const blobClientService = BlobServiceClient.fromConnectionString(this.azureConnection);<br>    const containerClient = blobClientService.getContainerClient(this.containerName);<br>    const blobClient = containerClient.getBlockBlobClient(imageName);<br>    return blobClient;<br>  }<br><br>  // Method to upload file to Azure Blob Storage<br>  async upload(file: Express.Multer.File, containerName: string): Promise&lt;string&gt; {<br>    try {<br>      this.containerName = containerName;<br>      const pdfUrl = uuid() + file.originalname;<br>      const blobClient = this.getBlobClient(pdfUrl);<br>      await blobClient.uploadData(file.buffer); // Upload file data<br>      return pdfUrl; // Return URL of uploaded file<br>    } catch (error) {<br>      console.error(&#39;Error uploading file:&#39;, error);<br>      throw new Error(&#39;Failed to upload file&#39;);<br>    }<br>  }<br>  <br>  // Method to read file from Azure Blob Storage<br>  async getfile(fileName: string, containerName: string) {<br>    this.containerName = containerName;<br>    const blobClient = this.getBlobClient(fileName);<br>    const blobDownloaded = await blobClient.download(); // Download file from blob<br>    return blobDownloaded.readableStreamBody; // Return readable stream of file data<br>  }<br><br>  // Method to delete file from Azure Blob Storage<br>  async deletefile(filename: string, containerName: string) {<br>    this.containerName = containerName;<br>    const blobClient = this.getBlobClient(filename);<br>    await blobClient.deleteIfExists(); // Delete file if it exists<br>  }<br>}</pre><p><strong>Integrating </strong><strong>AuthGuard to protect routes<br></strong>Now, let’s set up a guard to protect the routes. First, we’ll create a folder called ‘guards’ that will contain the file ‘jwt-auth.guard.ts’.<br> The JwtAuthGuard intercepts incoming requests to protected routes, validates JWT tokens, and ensures that authenticated users have access to the requested resources</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*2dYnqQwGJ1T75q7lTVcrnQ.png" /></figure><pre>//jwt-auth.guard.ts<br>@Injectable()<br>export class JwtAuthGuard extends AuthGuard(&#39;jwt&#39;) {<br>  constructor(<br>    private readonly jwtStrategy: JwtStrategy,<br>    private readonly reflector: Reflector,<br>  ) {<br>    super();<br>  }<br><br>  async canActivate(context: ExecutionContext): Promise&lt;boolean&gt; {<br>    const isPublic = this.reflector.get&lt;boolean&gt;(<br>      IS_PUBLIC_KEY,<br>      context.getHandler(),<br>    );<br>    if (isPublic) {<br>      return true;<br>    }<br><br>    await super.canActivate(context);<br>    const request = context.switchToHttp().getRequest();<br>    const user = await this.jwtStrategy.validate(request.user);<br>    request.user = user;<br>    return true;<br>  }<br>}</pre><p>Now, we’ll globally apply the AuthGuard instead of using UseGuard in each method. By implementing UseGuard in the AppModule, all routes will be automatically protected<br>the appModule will be like this</p><pre>//app.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { userModule } from &#39;./user/user.module&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { typeOrmConfig } from &#39;./database/typeorm.config&#39;;<br>import { AzureBlobService } from &#39;./Azure_Services/azure-blob.service&#39;;<br>import { APP_GUARD } from &#39;@nestjs/core&#39;;<br>import { JwtAuthGuard } from &#39;./common/guards/jwt-auth.guard&#39;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.forRoot(typeOrmConfig),<br>    userModule],<br>  controllers: [AppController],<br>  providers: [AppService ,<br>    <br>    {<br>      provide: APP_GUARD,<br>      useClass: JwtAuthGuard,<br>      <br>    },<br>  <br>  ],<br>})<br>export class AppModule {}<br></pre><p>Now, our routes are protected. However, a challenge arises when attempting to sign in or sign up because there’s no token yet, resulting in an unauthorized response. To address this, we’ll create a decorator for public routes, ensuring they are not treated as private routes</p><pre>//public.decorator.ts<br>import { SetMetadata } from &#39;@nestjs/common&#39;;<br><br>export const IS_PUBLIC_KEY = &#39;isPublic&#39;;<br>export const Public = () =&gt; SetMetadata(IS_PUBLIC_KEY, true);</pre><p>Now that the Azure Blob Storage service and the user service are complete, the next step is to create a route in the user.controller to call the APIs. However, before that, we need to inject the JWT authentication and the Azure service into the user module to utilize them.<br>so the user.module will be like this</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { userController } from &#39;./user.controller&#39;;<br>import { userService } from &#39;./user.service&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import {JwtModule} from &#39;@nestjs/jwt&#39;<br>import {PassportModule} from &#39;@nestjs/passport&#39;<br>import { JwtStrategy } from &#39;./jwt.strategy&#39;;<br>import * as config from &#39;config&#39;<br>import { APP_GUARD } from &#39;@nestjs/core&#39;;<br>import { User } from &#39;src/enteties/user.entity&#39;;<br>import { AzureBlobService } from &#39;src/Azure_Services/azure-blob.service&#39;;<br><br><br>const jwtConfig= config.get(&#39;jwt&#39;);<br>@Module({<br>  imports: [<br>    PassportModule.register({<br>defaultStrategy:&#39;jwt&#39;<br>    }),<br>    JwtModule.register({<br>      secret:process.env.JWT_SECRET || jwtConfig.secret,<br>      signOptions:{<br>        expiresIn:jwtConfig.expiresIn,<br>      }<br>    }),<br>    TypeOrmModule.forFeature([User])<br><br>  ],<br>  controllers: [userController],<br>  providers: [userService,<br>  JwtStrategy,<br>  AzureBlobService<br>  <br>  ],<br>  exports: [<br>    JwtStrategy,<br>    PassportModule,<br>  ]<br>})<br>export class userModule {}</pre><p><strong>Utilizing the CRUD service for uploading, deleting, and retrieving files from Azure Blob Storage</strong></p><p>Now that the application is correctly set up, let’s proceed to create the API calls in the user.controller. I’ll provide the complete user.controller, which includes methods for signing in and signing up, as well as methods for uploading, retrieving, and deleting files</p><p>NOTE: Don’t forget to specify the container name from the Azure Blob Storage that you’ve created. In my case, I’ll use “nestapplicationtest” as the containerName.</p><pre><br>//user.controller.ts<br><br>@Controller(&#39;user&#39;)<br>export class userController {<br>    containerName = &quot;nestapplicationtest&quot;;<br>    constructor( <br>        @Inject(userService)<br>        private authService: userService,<br>        private readonly azureBlobService: AzureBlobService,<br>    ){}<br><br>    // Method for user sign-up<br>    @Public()<br>    @Post(&#39;/signup&#39;)<br>    async signUp(@Body(ValidationPipe) authCredantialsDto:AuthCredentialsDto){<br>        return await this.authService.signUp(authCredantialsDto)<br>    }<br><br>    // Method for user sign-in<br>    @Public()    <br>    @Post(&#39;/signin&#39;)<br>    async signIn(@Body(ValidationPipe) authCredantialsDto:SingCredentialsDto): Promise&lt;{accesToken:string}&gt;{<br>        return await this.authService.signIn(authCredantialsDto)<br>    }<br><br>    // Method to upload file to Azure Blob Storage<br>    @Post(&#39;upload&#39;)<br>    @UseInterceptors(FileInterceptor(&#39;myfile&#39;))<br>    async upload(@UploadedFile() file: Express.Multer.File): Promise&lt;string&gt; {<br>      console.log(&quot;hello world&quot;,file)<br>      const fileUploaded= this.azureBlobService.upload(file,this.containerName);<br>      return fileUploaded;<br>    }<br><br>    // Method to retrieve file from Azure Blob Storage<br>    @Get(&#39;read&#39;)<br>    async readFile(@Res() res,@Query(&#39;filename&#39;) filename){<br>      const file = await this.azureBlobService.getfile(filename,this.containerName);<br>      return file.pipe(res);<br>    }<br><br>    // Method to delete file from Azure Blob Storage<br>    @Delete(&#39;delete&#39;)<br>    async DeleteFile(@Query(&#39;filename&#39;) filename){<br>        await this.azureBlobService.deletefile(filename,this.containerName);<br>        return { message: &#39;File deleted successfully&#39; };<br>    }<br>}</pre><p>Let’s test the signup method via the route<br>http://localhost:3000/user/signup</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9jrp6X3PvOB-gbh6NePivw.png" /><figcaption>singIn</figcaption></figure><p>The user has been successfully created in the database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJeU5ZAwLdxPBO6r8XEgsg.png" /></figure><p>Let’s test the signIn method via the route <a href="http://localhost:3000/user/signin">http://localhost:3000/user/signin</a>. It correctly returns the access token ===&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcC6_qFz7fKyJpIBxV1-3w.png" /></figure><p><strong>Now let’s try to upload file in azure blob storage via the route </strong><a href="http://localhost:3000/user/upload">http://localhost:3000/user/upload</a></p><p>If I try to access the route directly and send the request, <strong>it will return 401 Unauthorized</strong> because the route is private</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93LLdBfCVOz4jApkQzwF2Q.png" /></figure><p>In this scenario, we need to utilize the token that was sent during the sign-in process and include it in the Authorization header as a Bearer token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dy5wPN9YwDD6mWDbZ1vv4g.png" /></figure><p>Now i will test again to see the result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*dw3edlgwWwf4k6-SKW5woQ.png" /></figure><p>When I navigate to the Azure interface and inspect the storage account, I can locate the uploaded files within the specified container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9a1Kebg9HSQWIwkr15byyg.png" /></figure><p><strong>Let’s now attempt to retrieve the file from Azure Blob Storage using its name.</strong></p><p><a href="http://localhost:3000/user/delete?filename=979147c8-8081-409a-813c-37699461cb39cv-YJ.pdf">http://localhost:3000/user/read?filename=</a>”Name of the file”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1SBOusPrLQqQaIeZkUAkPA.png" /></figure><p><strong>Let’s now attempt to delete the file from Azure Blob Storage using its name.</strong></p><p><a href="http://localhost:3000/user/delete?filename=979147c8-8081-409a-813c-37699461cb39cv-YJ.pdf">http://localhost:3000/user/delete?filename=</a>”Name of the file”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2eNx2TZZf4bngsHCeANlMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GXWtli06ZR26X4CJway4g.png" /></figure><p>I hope this information will be helpful for all of you. Best wishes! Feel free to contact me <a href="https://www.linkedin.com/in/yassine-jdidi-84576a214/"><strong>here</strong></a> if you have any further questions or need assistance , You can find the repository on GitHub by following this link : <a href="https://github.com/Yassinejedidi/AzureBlobStorage"><strong>https://github.com/Yassinejedidi/AzureBlobStorage</strong></a></p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47873e9d315a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/upload-file-using-azure-blob-storage-in-nestjs-application-and-integrate-useguard-authentication-47873e9d315a">Upload File Using Azure Blob Storage in NestJS Application and Integrate UseGuard Authentication</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Performant QR Code React App with Firebase in Minutes]]></title>
            <link>https://javascript.plainenglish.io/deploying-a-performant-qr-code-react-app-with-firebase-in-minutes-f73193191129?source=rss-ad8291fe88b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f73193191129</guid>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[swc]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Yassinejdidi]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 01:01:46 GMT</pubDate>
            <atom:updated>2024-03-21T00:37:29.702Z</atom:updated>
            <content:encoded><![CDATA[<p>In this story, I will explain the importance of using Vite and SWC. This is followed by a detailed guide on developing a QR code application, covering the processes of generating and downloading QR codes. Finally, I provide instructions for seamlessly deploying the application on Firebase</p><p><strong>Application link: </strong><a href="https://qrcode-8c9da.firebaseapp.com/"><strong>https://qrcode-8c9da.firebaseapp.com</strong></a><strong>&quot;</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHy5n8rYNY9QF18vSn0N7g.png" /></figure><p><strong>Why vite &amp; swc</strong></p><p>Utilizing Vite and SWC( Speedy Web Compiler<strong>)</strong> in your project offers a dynamic duo of speed and efficiency. Vite’s lightning-fast development server, coupled with SWC’s supercharged JavaScript/TypeScript compiler, streamlines your development workflow and optimizes production builds. Enjoy instant hot module replacement (HMR) and on-the-fly transpilation during development, while benefiting from reduced build times and smaller bundle sizes in production. Embrace modern JavaScript features with ease, customize your build process, and tap into vibrant community support. With Vite and SWC, enhance your project’s performance and developer experience effortlessly.</p><p><strong>Setting up a Lightning-Fast React Development Environment with Vite and SWC</strong></p><blockquote>run in the terminal :npm create vite@latest</blockquote><p>By running this command, it will prompt you to select a framework. There are various choices available, such as Vue, etc. In my case, I will select the React app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*yHpbw5DEUc_S5ZHSxF_A2w.png" /></figure><p>By running the command to set up Vite with React, you’re given the option to choose whether you want to use SWC as a compiler or not</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*08ws21kAM9Y-e0AtoK8w2g.png" /></figure><p>Now the application is set up, let’s create a QR code feature. We will use ‘react-qr-code’, and I will paste the code containing the QR code implementation, including the feature to download the QR code</p><p>Library link : <a href="https://www.npmjs.com/package/react-qr-code">https://www.npmjs.com/package/react-qr-code</a></p><p>In this library, you will find many options such as the ‘Level’ prop, which refers to the complexity of the QR code. Additionally, you can explore various other props and functionalities to customize the QR code according to your requirements</p><pre>function QrCode() {<br>    const [qrValue, setQrValue] = useState(&#39;&#39;);<br>    const canvasRef = useRef&lt;HTMLDivElement&gt;(null);<br><br>    const onChangeQrValue = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>        setQrValue(e.target.value);<br>    };<br>//download qr code <br>    const handleDownload = async () =&gt; {<br>        try {<br>            const canvas = await html2canvas(canvasRef.current as HTMLElement);<br>            const dataUrl = canvas.toDataURL(&#39;image/png&#39;);<br>            const a = document.createElement(&#39;a&#39;);<br>            a.download = &#39;QrCode.png&#39;;<br>            a.href = dataUrl;<br>            document.body.appendChild(a);<br>            a.click();<br>            document.body.removeChild(a);<br>        } catch (error) {<br>            console.error(&#39;Error generating QR code:&#39;, error);<br>        }<br>    };<br><br>    const TrythisOne = async () =&gt; {<br>      toast.success(&quot;❤️ Ramadhan mubarek ❤️&quot;);<br>    }<br>    return (<br>        &lt;div className=&#39;qr-container&#39;&gt;<br>          &lt;h2  style={{ display:&#39;flex&#39;  ,justifyContent:&quot;center&quot;}} &gt;QR Code Generator&lt;/h2&gt;<br>      <br>          &lt;div className=&#39;qr-code-container&#39; ref={canvasRef}&gt;<br>            &lt;QRCode<br>              size={300}<br>              level=&quot;H&quot;<br>              fgColor=&quot;#2ec5be&quot;<br>              style={{ height: &#39;auto&#39;, maxWidth: &#39;100%&#39;, width: &#39;100%&#39; }}<br>              value={qrValue}<br>            /&gt;<br>          &lt;/div&gt;<br>      <br>          &lt;div className=&quot;input-container&quot;&gt;<br>          &lt;input type=&#39;text&#39; onChange={onChangeQrValue} className=&quot;input-field&quot; placeholder=&quot;Enter text for QR code&quot; /&gt;<br>          &lt;/div&gt;<br>      <br>          &lt;div className=&quot;button-container&quot;&gt;<br>            &lt;button onClick={handleDownload}&gt;Download QR &lt;/button&gt;<br>            &lt;button <br>  onClick={TrythisOne} <br>  className=&quot;button-animation&quot;<br>&gt;<br>  Try this button<br>&lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      );<br>}</pre><p>The app will appear as follows: we can input any text or content, and it will generate into a QR code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*XF3L8FbxRx4p-OzjTFh4yA.png" /></figure><p><strong>The next step is deploying the app using Firebase</strong></p><p>First, we need to create an account on Firebase. Then, we’ll select ‘Create Project’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rdERc7f7lNq0StOZWu-pA.png" /></figure><p>Select a name for your project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAdK4pedbofogiyEef_2VQ.png" /></figure><p>Follow the steps to create the project. Once the loading is complete, we’ll be directed to this interface, where we’ll select ‘Hosting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rIdnvmdW1InyE4POfD2FRA.png" /></figure><p>Now all we need to do is follow these steps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jq2lb9S-LAc7w7Q3v9Rafg.png" /></figure><p>After installing the Firebase CLI tools, we will enter the following command: firebase login. This will prompt us to authenticate by visiting a provided link to connect to our Firebase account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3PSwfkVDrDLv07gZMcIlJA.png" /></figure><p>Now, all we need to do is initialize Firebase by navigating to the project directory and running firebase init</p><p>By entering this command, it will present you with several options. In our case, we will select the hosting configuration file for Firebase Hosting by pressing the spacebar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7w1WCip1F4NiRmuqYug4g.png" /></figure><p>Next, it will provide you with options such as using an existing project. We’ll select this option, and it will display all the projects in your Firebase account. You’ll choose the project that you want to deploy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*NLa2ak3n6GpOM5pTFtuFRg.png" /></figure><p>Now it will ask you for the public directory, which is the folder containing your project’s files. In my case, I will enter ‘dist’ . If your ‘index.html’ is in the ‘public’ folder, you should enter ‘build ’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*M4QAZhqNhyu7Mi6N4327iw.png" /></figure><p>Then it will present other options. You need to press ’N’ or ‘NO’ for these options until the Firebase initialization is completed correctly</p><p>Now that all the steps are completed, we need to perform the final steps. First, we’ll run npm run build, and then we&#39;ll execute firebase deploy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*v9oMFj7HusIE0VjDIfce7g.png" /></figure><p>It will provide you with the link to your application. Additionally, in the Firebase account, you’ll find the relevant information</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oA-q_FMpSlJzefmXhl8THw.png" /></figure><p>Once our application is deployed, we’ll access it like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ABBRSYkB4J50cKCGTXjM6w.png" /></figure><p>I hope this helps you. This is a simple way to deploy a React app in just a few minutes.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f73193191129" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/deploying-a-performant-qr-code-react-app-with-firebase-in-minutes-f73193191129">Deploying a Performant QR Code React App with Firebase in Minutes</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Secure NestJS Application with JWT, TypeORM, PostgreSQL, and LDAP Server]]></title>
            <link>https://blog.stackademic.com/building-a-secure-nestjs-application-with-jwt-typeorm-postgresql-and-ldap-server-1ac5249dae53?source=rss-ad8291fe88b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ac5249dae53</guid>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[ldap-server]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Yassinejdidi]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 03:11:55 GMT</pubDate>
            <atom:updated>2024-03-20T00:53:36.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6tjVh3uBDKFF-OmRBVP5g.png" /></figure><p>In this article, I’ll walk you through the process of building a dynamic authentication system using LDAP integration with a NestJS application. This system operates by first verifying a user’s credentials against an LDAP server. If the user exists in the LDAP directory, the system then checks if the user is present in the application’s database. If found, it generates a JWT token for the user. However, if the user exists in LDAP but not in the database, the system automatically creates a new database entry for the user and generates a token.</p><p>I’ll demonstrate how to set up and configure Apache Directory Studio in conjunction with NestJS to achieve this functionality. By the end of this tutorial, you’ll have a comprehensive understanding of how to seamlessly integrate LDAP authentication with NestJS, handling both existing and new user scenarios effectively.</p><p>This is a sequence diagram illustrating the authentication process and how it works (At the end, you can find the GitHub repository for this project)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilKXiG_YAzTBI3AlXD7g_A.png" /><figcaption>Authentication</figcaption></figure><p>First, setting up a NestJS application is straightforward. You can easily follow the documentation as it provides clear instructions. I’ll guide you directly through the code and the setup process for your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*dzWHb1OV6AJZDyanKst-bA.png" /></figure><p>I will directly provide the necessary code for better understanding. You can also check the GitHub repository</p><p>This code provides the configuration options for TypeORM, the Object-Relational Mapping (ORM) tool used in our NestJS application. It specifies parameters such as the database type, host, port, username, password, and database name. Additionally, it defines the entities to be managed by TypeORM, in this case, the User entity. The ‘synchronize’ option determines whether TypeORM should automatically synchronize the database schema with the application entities. These configuration settings can be customized through environment variables or by using default values from the application’s configuration file</p><pre>//typeOrm.config.ts<br><br><br>const dbConfig = config.get(&#39;db&#39;)<br><br>export const typeOrmConfig: TypeOrmModuleOptions={<br>    type: dbConfig.type,<br>    host: process.env.RDS_HOSTNAME || dbConfig.host,<br>    port: process.env.RDS_PORT || dbConfig.port,<br>    username: process.env.RDS_USERNAME || dbConfig.username,<br>    password:process.env.RDS_PASSWORD || dbConfig.password,<br>    database: process.env.RDS_DB_NAME || dbConfig.database,<br>    entities:[User],<br>    synchronize: process.env.TYPEORM_SYNC || dbConfig.synchronize,<br><br>    <br>}</pre><p>This module serves as the entry point for our NestJS application. It imports necessary modules such as TypeOrmModule for handling database connections and configurations, as well as AuthModule for managing authentication-related functionality. Additionally, it sets up global guards to protect routes and endpoints using JwtAuthGuard for JWT-based authentication. The AppModule orchestrates the configuration and integration of these components to establish the core functionality of our application</p><pre>//app.module.ts<br>@Module({<br>  imports: [<br>    TypeOrmModule.forRoot(typeOrmConfig),<br>    AuthModule,<br><br>  <br>  ],<br><br>  providers: [<br>    <br>    {<br>      provide: APP_GUARD,<br>      useClass: JwtAuthGuard,<br>      <br>    },<br>  ],<br> <br><br>})<br>export class AppModule {}</pre><p>To set up and configure your LDAP server, you can use tools like Apache Directory Studio. Apache Directory Studio offers a user-friendly interface for LDAP server configuration and management. You can download Apache Directory Studio from their official website. Once downloaded, you can use it to configure your LDAP server settings according to your application’s requirements</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iyr1vUNIIzT6sqrwDkRLAA.png" /><figcaption>Apache directory studio</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zp2nNvqQmkvMkFP_QGebeQ.png" /><figcaption>SetUp ldap server</figcaption></figure><p>In our project, we will create a file named ‘config.ts’ in the ‘ldaps’ directory. This code defines the configuration settings required to connect to an LDAP server using ldapsjs. The ‘config’ object specifies the LDAP server URL and the base Distinguished Name (DN) for the LDAP directory. Additionally, the ‘ldapAttributes’ array determines the LDAP attributes to be retrieved</p><pre>export const config = {<br>  ldapUrl: &#39;ldaps://localhost:10636&#39;,<br>  baseDn: &#39;ou=users,ou=system&#39;,<br>};<br><br>export const ldapAttributes = [&#39;cn&#39;, &#39;sn&#39;, &#39;mail&#39;, &#39;userPassword&#39;, &#39;telephoneNumber&#39;];<br></pre><p>This code implements JWT authentication in a NestJS application using Passport.js. It verifies incoming requests, extracts JWT tokens, validates them using a secret key, and retrieves user information from the token payload. This strategy ensures secure user authentication within the application</p><pre>//jwt.strategy.ts<br>@Injectable()<br>export class JwtStrategy extends PassportStrategy(Strategy) {<br>  constructor(<br>    @InjectRepository(User)<br>    private userRepository: Repository&lt;User&gt;,<br>  ) {<br>    super({<br>      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),<br>      secretOrKey:process.env.JWT_SECRET || config.get(&#39;jwt.secret&#39;), // use your own secret key<br>    });<br>  }<br><br> async validate(payload: JwtPayload): Promise&lt;User&gt; {<br>  const { username, role } = payload;<br>  const user = await this.userRepository.findOne({<br>    where: { username }<br>  });<br>  if (!user) {<br>    throw new UnauthorizedException();<br>  }<br><br> <br>  user.role = role;<br><br>  return user;<br>}<br><br>  <br>}</pre><p>now in the common folder we wil lcreate folder Guard that will contain <br>These guards are used to enforce authentication and authorization rules in NestJS applications. JwtAuthGuard verifies JWT tokens and sets authenticated users, while RolesGuard checks if users have the required roles to access specific routes</p><pre>//jwt-auth.guard.ts<br>@Injectable()<br>export class JwtAuthGuard extends AuthGuard(&#39;jwt&#39;) {<br>  constructor(<br>    private readonly jwtStrategy: JwtStrategy, // Injecting JwtStrategy to validate JWT tokens<br>    private readonly reflector: Reflector, // Injecting Reflector for metadata access<br>  ) {<br>    super();<br>  }<br><br>  async canActivate(context: ExecutionContext): Promise&lt;boolean&gt; {<br>    const isPublic = this.reflector.get&lt;boolean&gt;(<br>      IS_PUBLIC_KEY,<br>      context.getHandler(), // Checking if the route is marked as public<br>    );<br>    if (isPublic) {<br>      return true; // If marked as public, allow access without authentication<br>    }<br><br>    await super.canActivate(context); // Calling parent canActivate method for JWT validation<br>    const request = context.switchToHttp().getRequest();<br>    const user = await this.jwtStrategy.validate(request.user); // Validating JWT token and extracting user information<br>    request.user = user; // Setting authenticated user in the request object<br>    return true; // Allowing access<br>  }<br>}</pre><pre>//roles.guard.ts<br><br>@Injectable()<br>export class RolesGuard implements CanActivate {<br>  constructor(private reflector: Reflector) {}<br><br>  canActivate(context: ExecutionContext): boolean {<br>    const requiredRoles = this.reflector.getAllAndOverride&lt;Role[]&gt;(ROLES_KEY, [<br>      context.getHandler(),<br>      context.getClass(), // Getting required roles from metadata<br>    ]);<br>    if (!requiredRoles) {<br>      return true; // If no roles are specified, allow access<br>    }<br>    <br>    const { user } = context.switchToHttp().getRequest(); // Getting user information from the request<br>    return requiredRoles.some((role) =&gt; user.role?.includes(role)); // Checking if user has any of the required roles<br>  }<br>}</pre><p>Now, let’s delve into the AuthService and explain its methods:</p><ol><li>authenticate: This method validates user credentials by connecting to the LDAP server with the provided username and password. If the authentication is successful, it returns true; otherwise, it throws an UnauthorizedException.</li><li>CheckUserLdap: Here, we search the LDAP directory for a user based on their username. If the user is found, we retrieve attributes such as username and email; otherwise, an HttpException is thrown.</li><li>SignIn: This method orchestrates the authentication process. Firstly, it authenticates the user with LDAP using the authenticate method. Upon successful authentication, it retrieves user information from LDAP using CheckUserLdap. Then, it verifies if the user exists in the local database. If not, a new user entry with the default role &#39;Collaborateur&#39; and the retrieved email is created. Finally, it generates a JWT token containing the user&#39;s username and role using the JwtService provided by NestJS.</li></ol><pre>//auth.service.ts<br>@Injectable()<br>export class AuthService {<br>    private logger = new Logger(&#39;AuthService&#39;) <br>    private readonly client: ldap.Client;<br>    private readonly baseDn: string;<br>     <br>    constructor(<br>        @InjectRepository(User)<br>        private userRepository: Repository&lt;User&gt;,<br>        private jwtService:JwtService,<br>        <br>       <br>      ){this.client = ldap.createClient({<br>        url: config.ldapUrl,<br>      });<br>      this.baseDn = config.baseDn; }<br><br><br>      async getall(): Promise&lt;User[]&gt; {<br>        const result =await this.userRepository.find()<br>        return result <br>      } <br><br>      //auth using ldap <br><br>      async authenticate(username: string, password: string): Promise&lt;boolean&gt; {<br>        const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;<br>        const isEmail = regex.test(username);<br>        let cnValue: string;<br>      <br>        if (isEmail) {<br>          cnValue = username.split(&#39;@&#39;)[0];<br>        <br>        } else {<br>          cnValue = username;<br>        }<br>      <br>        const userDn = `cn=${cnValue},${this.baseDn}`;<br>        console.log(`Authenticating user with DN: ${userDn}`);<br>      <br>        return new Promise((resolve, reject) =&gt; {<br>          this.client.bind(userDn, password, (err) =&gt; {<br>            if (err) {<br>              console.error(`Authentication failed for user ${username}: ${err}`);<br>              reject(new UnauthorizedException(&#39;Unauthorized&#39;))<br><br>            } else {<br>              console.log(`Authentication successful for user ${username}`);<br>              resolve(true);<br>            }<br>          });<br>        });<br>      }<br>    <br>  //search for user with username<br>  async CheckUserLdap(cn: string): Promise&lt;any&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>      const searchOptions: ldap.SearchOptions = {<br>        scope: &#39;sub&#39;,<br>        filter: `(cn=${cn})`,<br>        attributes: ldapAttributes,<br>      };<br>      let user: any = {};<br>      this.client.search(this.baseDn, searchOptions, (err, res) =&gt; {<br>        if (err) {<br>          console.error(`LDAP search failed: ${err}`);<br>          reject(err);<br>        } else {<br>          res.on(&#39;searchEntry&#39;, (entry) =&gt; {<br>            const attributes = entry.pojo.attributes;<br>            const attributeMap = {<br>              <br>              cn: &#39;username&#39;,<br>              mail:&#39;email&#39;<br>              <br>             <br>            };<br>            attributes.forEach((attribute: any) =&gt; {<br>              const key = attribute.type.toLowerCase();<br>              if (attributeMap.hasOwnProperty(key)) {<br>                const propName = attributeMap[key];<br>                user[propName] = attribute.values[0];<br>              }<br>            });<br>          });<br>          res.on(&#39;end&#39;, () =&gt; {<br>            if (user.hasOwnProperty(&#39;username&#39;)) {<br>              resolve(user);<br>            } else {<br>              const errors = { User: &#39;the searched user does not exists in ldap !&#39; };<br>              reject(new HttpException({ errors }, 401));<br>            }<br>          });<br>        }<br>      });<br>    });<br>  }<br>  <br>// methode signin with ldap <br>  async SignIn(username: string, password: string): Promise&lt;{ accesToken: string , role:string, username:string}&gt; {<br>    <br>    // authenticate with LDAP<br>    const authenticated = await this.authenticate(username, password);<br>    if (!authenticated) {<br>      throw new UnauthorizedException(&#39;Invalid credentials&#39;);<br>    }<br>  <br>    // search for user in LDAP by username<br>    const userFromLdap = await this.CheckUserLdap(username);<br>    console.log(&#39;===&gt;checking username in ldap=&gt;:&#39;,userFromLdap )<br>    // search for a user in database<br>    let userFromDb = await this.userRepository.findOne({<br>      where: { username }<br><br>    })<br>    console.log(&#39;==&gt;checking username in database:=&gt;&#39;,{ username } )<br><br>    ;<br>  <br>    if (!userFromDb) {<br>      console.log(&#39;2===&gt;: not exist 9a3ed yetsna3 &#39;)<br>  <br>      // create new user in the database<br>      userFromDb = await this.userRepository.create({<br>        username: userFromLdap.username,<br>        role: Role.Collaborateur,<br>        email:userFromLdap.email<br>      });<br>      await this.userRepository.save(userFromDb);<br>      console.log(&quot;l user ili tisna3==&gt;:&quot;,userFromDb)<br>    } <br>  <br>    // generate access token<br>    const payload: JwtPayload = {<br>      username: userFromDb.username,<br>      role: userFromDb.role,<br>    };<br>    const accesToken = await this.jwtService.sign(payload);<br>  <br>    return { accesToken:accesToken, role: userFromDb.role, username:userFromDb.username };<br>  }<br><br><br><br>}</pre><p>Now, our AuthController will look like this</p><pre>//auth.controller.ts<br><br>@Controller(&#39;users&#39;)<br>export class AuthController {<br>    constructor( <br>        @Inject(AuthService)<br>        private authService: AuthService,<br>     ){}<br><br> <br><br>@Public()<br>  @Post(&#39;auth&#39;)<br>  async sign(@Body() authCredentialsDto: SingCredentialsDto): Promise&lt;{ accesToken: string, role: string, username:string}&gt; {<br>    const { username, password } = authCredentialsDto;<br>    console.log(authCredentialsDto)<br><br>    try {<br>      const { accesToken, role } = await this.authService.SignIn(username, password);<br>      return { accesToken,role, username };<br>    } catch (error) {<br>      throw new HttpException(error.message, error.status);<br>    }<br>  }<br><br><br>    <br>  }<br></pre><p>Let’s test our application now. Here, I’m creating a user named “authTest” on the LDAP server and setting a password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RL_nJfzPnyxssQivINzsIg.png" /></figure><p>The database is currently empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKZB10-3j9B1s55-6cNgiw.png" /><figcaption>user Table</figcaption></figure><p>Now, I will test with Postman. I will enter a username and an incorrect password. Here are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OONM93gFzGjChIAl8Re3jQ.png" /><figcaption>wrong password</figcaption></figure><p>Success case: When the username and password are correct</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oEZJ2aWUs1gTsLAxCv8DSA.png" /></figure><p>Now, our database should contain the user because they successfully signed in using LDAP</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-iJIH4zU7Vq4KCxNFtaZYA.png" /></figure><p>And now, our application is set up correctly. I hope this will help you all.</p><p><strong>Github repository:</strong><a href="https://github.com/Yassinejedidi/NestJs_Authentication"><strong>https://github.com/Yassinejedidi/NestJs_Authentication</strong></a></p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ac5249dae53" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/building-a-secure-nestjs-application-with-jwt-typeorm-postgresql-and-ldap-server-1ac5249dae53">Building a Secure NestJS Application with JWT, TypeORM, PostgreSQL, and LDAP Server</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>