<?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 Yusuf Fachroni on Medium]]></title>
        <description><![CDATA[Stories by Yusuf Fachroni on Medium]]></description>
        <link>https://medium.com/@ahmedyusuf?source=rss-8ef59354fdda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y4QobhMtizSNtlr0Zz2plQ.jpeg</url>
            <title>Stories by Yusuf Fachroni on Medium</title>
            <link>https://medium.com/@ahmedyusuf?source=rss-8ef59354fdda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 16:54:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmedyusuf/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[Setting Up Multilanguage Support in Your Flutter iOS App]]></title>
            <link>https://ahmedyusuf.medium.com/setting-up-multilanguage-support-in-your-flutter-ios-app-a63d812b2eec?source=rss-8ef59354fdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/a63d812b2eec</guid>
            <dc:creator><![CDATA[Yusuf Fachroni]]></dc:creator>
            <pubDate>Wed, 22 Jan 2025 22:29:26 GMT</pubDate>
            <atom:updated>2025-01-22T22:29:26.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PFwG9l3yliNm3ql4" /></figure><p>Creating a multilingual iOS application can significantly enhance user experience by catering to a diverse audience. In this article, we’ll walk you through the process of setting up multilanguage support for your Flutter iOS app using Xcode. By the end of this guide, your app will be equipped to handle multiple languages seamlessly.</p><h3>Prerequisites</h3><ul><li><strong>Flutter Installed</strong>: Ensure you have Flutter installed on your machine.</li><li><strong>Xcode Installed</strong>: Necessary for iOS development.</li><li><strong>Basic Flutter Knowledge</strong>: Familiarity with Flutter project structure and basics.</li></ul><h3>Step 1: Open the iOS Folder in Xcode</h3><ol><li>Navigate to your Flutter project directory.</li><li>Open the ios folder using Xcode:</li></ol><ul><li>Right-click on the ios folder.</li><li>Select <strong>Open with Xcode</strong>.</li></ul><h3>Step 2: Add a New Strings File</h3><ol><li>In Xcode’s Project Navigator, right-click on the Runner directory.</li><li>Select <strong>New File</strong> from the context menu.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*o-4Jh5QOJ1IhWQfje_7hyw.png" /></figure><p>3. In the file template chooser, select <strong>Strings File</strong> under <strong>Resource</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*RDm2_mujCmxSGMrg66vFsA.png" /></figure><p>4. Name the file InfoPlist.strings and click <strong>Create</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*rdxCcYV82NDAaLvCVnvoDA.png" /></figure><h3>Step 3: Configure Localization</h3><ol><li>Click on the newly created InfoPlist.strings file.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*ydpUieXYjZM7al_hNoI8cw.png" /></figure><p>2. On the right side of Xcode, you will see the localization settings with the default English value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*jZOTI--V66YYN_k5sjv_hQ.png" /></figure><h3>Step 4: Enable Base Internationalization</h3><ol><li>In the Project Navigator, select the Runner project.</li><li>Go to the <strong>Info</strong> tab.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLdfMYZar-SuB507FzldNA.png" /></figure><p>3. Locate the <strong>Use Base Internationalization</strong> checkbox.</p><p>4. Click <strong>Add</strong> and choose the InfoPlist.strings file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*MHy0uF7YiCKQ_rzOYtgzAQ.png" /></figure><p>For example, to add Japanese:</p><ul><li>Select <strong>Japanese</strong> from the list.</li><li>Ensure only the InfoPlist.strings file is selected.</li><li>Click <strong>Finish</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1Fu64vnFf1KviYg3JLR5Yg.png" /></figure><h3>Step 5: Verify Language Addition</h3><ol><li>You should now see Japanese listed among the supported languages.</li></ol><p>2. Returning to your InfoPlist.strings file, you&#39;ll notice both English and Japanese entries are available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*tWcKJD23rH8UPR2GwgCBqQ.png" /></figure><h3>Step 6: Edit the Strings File</h3><ol><li>Open the InfoPlist.strings file.</li><li>Add key-value pairs for each language. For example:</li></ol><pre>&quot;CFBundleDisplayName&quot; = &quot;YourAppName&quot;;</pre><p>3. Translate the values accordingly for each language:</p><pre>/* English */<br>&quot;CFBundleDisplayName&quot; = &quot;YourAppName&quot;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*IhMT0KdYIvkgIWRszv0srA.png" /></figure><pre>/* Japanese */<br>&quot;CFBundleDisplayName&quot; = &quot;あなたのアプリ名&quot;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*b1Ku5HU5hXhC7wuLXeTdLQ.png" /></figure><h3>Step 7: Run Your App</h3><ol><li>After setting up the localization, run your Flutter app.</li><li>Change the device language to one of the supported languages (e.g., Japanese) to see the changes reflected in your app.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xf3Agysbt2OLRs-k8pjfaA.png" /></figure><h3>Conclusion</h3><p>By following these steps, you’ve successfully added multilanguage support to your Flutter iOS app. This enhancement not only broadens your app’s accessibility but also improves user satisfaction by providing a localized experience. Feel free to add more languages by repeating the localization steps, ensuring your app caters to a global audience.</p><p><strong>Tips:</strong></p><ul><li><strong>Testing</strong>: Always test your app in different languages to ensure all strings are properly translated and displayed.</li><li><strong>Dynamic Content</strong>: For dynamic content within your app, consider using Flutter’s <a href="https://flutter.dev/docs/development/accessibility-and-localization/internationalization">internationalization (i18n) support</a> to manage translations efficiently.</li><li><strong>Cultural Sensitivity</strong>: Beyond mere translation, ensure that your app’s content is culturally appropriate for each target language.</li></ul><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a63d812b2eec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Flutter Web Deployment with CI/CD on Google Cloud Storage and GitHub Actions]]></title>
            <link>https://ahmedyusuf.medium.com/automate-flutter-web-deployment-with-ci-cd-on-google-cloud-storage-and-github-actions-22349aa64582?source=rss-8ef59354fdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/22349aa64582</guid>
            <dc:creator><![CDATA[Yusuf Fachroni]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 04:07:29 GMT</pubDate>
            <atom:updated>2024-12-16T01:02:53.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQTtkVNxYkvlofX-WxLxNA.png" /></figure><p>Flutter Web has become a powerful tool for developing fast, responsive, and beautiful web applications with a single codebase. However, as your project scales, manually deploying your Flutter Web app can become tedious and error-prone. This is where Continuous Integration and Continuous Deployment (CI/CD) come to the rescue.</p><p>In this guide, we’ll streamline your Flutter Web deployment process using <strong>GitHub Workflow</strong> for automation and <strong>Google Cloud Storage</strong> as your hosting platform. By the end, you’ll have a fully automated pipeline that builds, tests, and deploys your Flutter Web app with ease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*iMJclwGU-rg_G5lLIGxQQg.gif" /></figure><p>Let’s dive into how you can reduce deployment complexity and focus on what matters most — building great apps! 🚀</p><h3>1. Create Cloud Storage Buckets</h3><p>To deploy your Flutter Web application to <strong>Google Cloud Storage</strong>, the first step is to create a bucket that will serve as your hosting environment. Here’s a step-by-step guide to creating a Cloud Storage bucket using the Google Cloud Console:</p><p>Open <a href="https://console.cloud.google.com/storage">https://console.cloud.google.com/storage</a></p><p>click create bucket, for example the bucket name is xxx-corporate-sales-demo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*EbpYXSLCiHtQZmJ2_w2Gdw.png" /></figure><p>for the region, select the geographic placement, for this I select singapore</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*GWiiWs8hMKwSzGpAEqA6Hg.png" /></figure><p>select storage class for our data, for this I select Autoclass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*9GwORnZ5_ElWsafxo653Qw.png" /></figure><p>For control access I uncheck the Enforce public access on this bucket select Uniform access control. <strong>Uniform Access Control</strong> means that permissions are set at the bucket level, not the object level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*_JAZaxXNIDZYAEJwJZeQwQ.png" /></figure><p>Check the soft-delete policy to protect object data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*Gdsgc20wxT2noruWcdSMkg.png" /></figure><p>Click Create, and wait until bucket created</p><p>After the bucket is created, open the Permissions tab and click Grant Access on the Permission menu (bottom)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*Sb2bQO_MLT74eUxjYvFsog.png" /></figure><p>type allUsers on New principals, and select Storage Object Viewer Role</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*93hg20a0HLfxPZkuqsCPmg.png" /></figure><p>this popup will appear, select Allow public access</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*Cqh0dSa7v4qk6CQbxz_BnA.png" /></figure><p>Now back to bucket list, then click option &gt; Edit website configuration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*vc4bPMK2pe29xIoRNmDIfQ.png" /></figure><p>Set index.html and 404.html</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*c0P1_Nd85J5ZTCf7zMtZqA.png" /></figure><h3>2. Create Load Balancer</h3><p>A <strong>Google Cloud Load Balancer</strong> helps distribute traffic efficiently across your Flutter Web app, improving availability and scalability. Here’s a step-by-step guide to setting up a Load Balancer to serve your Flutter Web app from Google Cloud Storage.</p><p>Open <a href="https://console.cloud.google.com/net-services/loadbalancing">https://console.cloud.google.com/net-services/loadbalancing</a> then click Create a load balancer</p><p>Select Application load balancer (Http/Https) for Type of load balancer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*pN4f441rvQB_PbgEwsFRVQ.png" /></figure><p>Select Public face (external)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*LpcBvbW-Jwa4bORxSO72Vg.png" /></figure><p>Select Best for global workloads for deployment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*LWv0OGXck7avFO8snZhSng.png" /></figure><p>Select Global external application load balancer for Load balancer generation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*kRCMnmbxOTlxWupo0RbnVg.png" /></figure><p>Click configure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*pUFgrUDoQOvX5COrgsKYmw.png" /></figure><p>Set the load balancer name and IP configuration. In this case, I’m using HTTPS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*c3i-1X6H0Pwz5rcPh7lMHg.png" /></figure><p>For the certificate, I’ll create a new certificate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*cu2tjKlrDQ7aKuD9EG2KMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*MR5if-i8LAMRi5ab9eFKrw.png" /></figure><p>Continue to Backend Configuration, then click Create a Backend Service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*afkkD-WtfaG_b8VYTjq8tw.png" /></figure><p>For the cloud storage bucket, select the bucket that we’ve created before</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*Rvi2q1-HznlBaYAsUaVzgw.png" /></figure><p>Continue to Routing rules, then select simple host and path rule mode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*7fNOg3YzVqM8JpkJ4lKQtQ.png" /></figure><h3>3. Create a service account</h3><p>A <strong>service account</strong> is necessary to authenticate your GitHub Workflow when deploying your Flutter Web app to Google Cloud Storage. Here’s a step-by-step guide to creating a service account and generating the credentials you’ll need.</p><p>Open <a href="https://console.cloud.google.com/iam-admin/serviceaccounts">https://console.cloud.google.com/iam-admin/serviceaccounts</a> then select your project</p><p>Click Create Service account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*Zk8z8QyaeftHQSThChMGdA.png" /></figure><p>then click Done.</p><p>Open Keys tab then click add key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*rJ9Zw-na5Z8T9Zb8JGBKtQ.png" /></figure><p>Select JSON for private key file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*5p_PhSOhmDOL6_c8doKywQ.png" /></figure><p>Open cloud storage again, select our bucket, and Grant access with new principle with email from service account that we created before</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*GqReYNkLkZ4FmJOFko3rEg.png" /></figure><p>Open our repository then open Settings &gt; Secret and variables &gt; actions</p><p>Click New repository Secret, and fill secret with content of Json file from Google Service account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*-ArcpBiLkQeQeocKLsc3TQ.png" /></figure><p>Create the env variable, for example for storing API Url</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*WKpKc3AJsk0CrmUwjsgsyg.png" /></figure><h3>4. Setup GitHub Workflow</h3><p>To automate the deployment of your Flutter Web app to Google Cloud Storage, you can create a GitHub Workflow using GitHub Actions. Here’s a step-by-step guide to setting up the workflow file.</p><p>Open your flutter project, create deploy-gcs-demo.yaml file on .github/workflows folder, and make sure it is on the root project directory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*t79LzQl0s3vyDxGFG7M9NQ.png" /></figure><p>Set the content of yaml file with this code, and make sure the flutter version, secret variable name, and Google Cloud Storage match with our configuration. In this configuration file, I set this workflow will autorun when I push on “demo” branch.</p><pre>name: Deploy to Google Cloud Storage - Staging<br>on:<br>  push:<br>    branches:<br>      - demo<br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - name: Setup Flutter<br>        uses: subosito/flutter-action@v2<br>        with:<br>          flutter-version: &quot;3.24.5&quot;<br>          channel: &quot;stable&quot;<br>          cache: true<br>      - name: Get dependencies<br>        run: flutter pub get<br>      - name: Set environment variables<br>        run: |<br>          echo &quot;API_URL=${{ secrets.DEMO_API_URL }}&quot; &gt;&gt; .env<br>      - name: Build web<br>        run: flutter build web --release --no-tree-shake-icons<br>      # Setup gcloud CLI<br>      - name: Auth to google cloud<br>        uses: &quot;google-github-actions/auth@v2&quot;<br>        with:<br>          credentials_json: ${{ secrets.GCP_SA_KEY_DEMO }}<br>          project_id: github-actions-gcs<br>      - name: Setup Gcloud<br>        uses: google-github-actions/setup-gcloud@v2<br>      - name: Deploy via GCS<br>        run: |<br>          gsutil -m rsync -r -d build/web gs://xxx-corporate-sales-demo</pre><p>Now let’s edit our code so we can get the env value from GitHub secret. For the first, we need to add flutter_dotenv dependency, then we can get the value using this code</p><pre>final apiUrl = dotenv.env[&#39;API_URL&#39;] ?? &#39;Default API URL&#39;;</pre><p>Everything is ready! let’s push the code and it will automatically run workflows on GitHub actions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4SUfIcVhMA1ukJPldvCcA.png" /></figure><p>Check the workflow, and make sure everything is fine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xS_rA1DF_eiEyb4hDZzYA.png" /></figure><p>If everything is good, let’s back to our bucket. We can see that all files have uploaded</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*2Q56YG3tyg5WossSkw0h-w.png" /></figure><p>The last thing we need to do is point the domain to the IP of the load balancer</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22349aa64582" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Telegram Mini App with Flutter]]></title>
            <link>https://ahmedyusuf.medium.com/building-a-telegram-mini-app-with-flutter-b8dee09e9e69?source=rss-8ef59354fdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8dee09e9e69</guid>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[telegram-mini-app]]></category>
            <category><![CDATA[telegram]]></category>
            <dc:creator><![CDATA[Yusuf Fachroni]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 08:53:00 GMT</pubDate>
            <atom:updated>2024-09-26T01:29:14.443Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*XAtZjWAMWKhmV-dPpQTaTQ.png" /></figure><p><strong>What is Telegram Mini App?</strong></p><p>Telegram Mini Apps provide a seamless way to integrate external apps directly into the Telegram environment. Users can interact with these apps within the chat interface, making for a more fluid user experience.</p><p>Before starting, make sure you’ve already set up a Flutter project using GetX state management. GetX is a popular and lightweight state management solution for Flutter that simplifies reactive programming, dependency injection, and routing. If you’re new to GetX, you can refer to the official documentation to get started.</p><p>Here’s a quick overview of the Telegram Web App setup process:</p><ol><li><strong>Telegram Web App Object</strong>: The window.Telegram.WebApp object gives access to various properties and methods to control the behavior of your mini-app.</li><li><strong>Initialization</strong>: When a mini-app is loaded, Telegram automatically initializes the Telegram.WebApp.init() function. This handles app setup, such as the title and back button behavior.</li><li><strong>Accessing User Information</strong>: You can access user details like user_id, first_name, and last_name through Telegram.WebApp.initDataUnsafe.</li><li><strong>Sending Data Back to Telegram</strong>: After interacting with the mini-app, you can send data back to Telegram using Telegram.WebApp.sendData(&quot;your_data_here&quot;). This method allows you to pass information back to the bot.</li><li><strong>Customizing Button Controls</strong>: Use Telegram.WebApp.MainButton to control the appearance of buttons within the app interface, allowing further customization.</li></ol><p>Now, let’s dive into how to integrate this with Flutter.</p><h3>Step 1: Add JavaScript Interop Support in Flutter</h3><p>To interact with JavaScript functions from your Dart code in Flutter, you’ll need to use the dart:js library.</p><ol><li>Open your pubspec.yaml file and add the following dependency:</li></ol><pre>dependencies:<br>  js: ^0.6.3</pre><h3>Step 2: Add JavaScript Code to Your HTML</h3><p>Next, you need to insert the Telegram WebApp initialization JavaScript code into the HTML file of your Flutter web project. This can be found in the web/index.html file, inside the &lt;head&gt; tag.</p><pre>&lt;script src=&quot;https://telegram.org/js/telegram-web-app.js&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>  function initTelegramWebApp() {<br>    if (window.Telegram) {<br>      Telegram.WebApp.ready();<br>      return Telegram.WebApp.initDataUnsafe;<br>    }<br>    return null;<br>  }<br>  function sendTelegramData(data) {<br>      if (window.Telegram) {<br>        Telegram.WebApp.sendData(data);<br>      }<br>    }<br>    function setMainButton(text, isVisible) {<br>      if (window.Telegram) {<br>        Telegram.WebApp.MainButton.setText(text);<br>        if (isVisible) {<br>          Telegram.WebApp.MainButton.show();<br>        } else {<br>          Telegram.WebApp.MainButton.hide();<br>        }<br>      }<br>    }<br>&lt;/script&gt;</pre><h3>Step 3: Create Dart Functions to Call JavaScript</h3><p>In your Flutter app, use Dart’s interop library to call JavaScript functions. To manage this, create a TelegramController class that will interact with the JavaScript functions.</p><pre>import &#39;dart:convert&#39;;<br>import &#39;package:flutter/widgets.dart&#39;;<br>import &#39;package:get/get.dart&#39;;<br>import &#39;dart:js&#39; as js;<br><br>class TelegramController extends GetxController {<br>  Map&lt;String, dynamic&gt;? telegramData;<br><br>  @override<br>  void onInit() {<br>    super.onInit();<br>    getTelegramData();<br>  }<br><br>  void getTelegramData() {<br>    telegramData = initTelegramWebApp();<br>    if (telegramData != null) {<br>      debugPrint(&#39;Telegram Data: $telegramData&#39;);<br>    } else {<br>      debugPrint(&#39;Telegram data is null. This app is opened outside telegram&#39;);<br>    }<br>    update();<br>  }<br><br>  // Function to initialize the Telegram WebApp<br>  static Map&lt;String, dynamic&gt;? initTelegramWebApp() {<br>    final result = js.context.callMethod(&#39;initTelegramWebApp&#39;);<br>    debugPrint(&quot;result: $result&quot;);<br>    if (result != null) {<br>      // Convert JsObject to JSON string and then parse it to a Map<br>      String jsonString = js.context[&#39;JSON&#39;].callMethod(&#39;stringify&#39;, [result]);<br>      return jsonDecode(jsonString);<br>    }<br><br>    return null;<br>  }<br><br>  // Function to send data back to Telegram<br>  static void sendTelegramData(String data) {<br>    js.context.callMethod(&#39;sendTelegramData&#39;, [data]);<br>  }<br><br>  // Function to control the MainButton in Telegram<br>  static void setMainButton(String text, bool isVisible) {<br>    js.context.callMethod(&#39;setMainButton&#39;, [text, isVisible]);<br>  }<br>}</pre><h3>Step 4: Use the Telegram API in Your Flutter Widget</h3><p>Now, you can use the TelegramController class to interact with the Telegram API within your Flutter widget. Here’s an example of how you can display user information in your app:</p><pre>GetBuilder&lt;TelegramController&gt;(builder: (telegramController) {<br>  return Row(<br>    mainAxisAlignment: MainAxisAlignment.spaceAround,<br>    children: &lt;Widget&gt;[<br>      Column(<br>        children: &lt;Widget&gt;[<br>          const CircleAvatar(<br>            backgroundImage: AssetImage(&#39;assets/captain.jpg&#39;),<br>            radius: 30.0,<br>          ),<br>          const SizedBox(height: 8.0),<br>          Text(<br>            &#39;Capt. &#39; + (telegramController.telegramData?[&#39;user&#39;]?[&#39;username&#39;] ?? &#39;Unknown&#39;),<br>            style: const TextStyle(fontSize: 16),<br>          ),<br>        ],<br>      ),<br>      (telegramController.telegramData != null &amp;&amp; telegramController.telegramData![&#39;user&#39;] != null)<br>          ? Column(<br>              children: [<br>                Text(<br>                  telegramController.telegramData?[&#39;user&#39;]?[&#39;first_name&#39;] ?? &#39;Unknown&#39;,<br>                  style: const TextStyle(fontSize: 16),<br>                ),<br>                Text(<br>                  telegramController.telegramData?[&#39;user&#39;]?[&#39;id&#39;].toString() ?? &#39;Unknown&#39;,<br>                  style: const TextStyle(fontSize: 16),<br>                ),<br>              ],<br>            )<br>          : Container(),<br>    ],<br>  );<br>})</pre><p>This code displays a user’s Telegram username, first name, and user ID within the app interface.</p><h3>Step 5: Deploying Flutter Web to Vercel</h3><p>After developing your Flutter Web app, it’s time to deploy it to Vercel. Follow these steps:</p><ol><li><strong>Push Your Code to Git</strong>: Make sure your code is committed and pushed to a Git repository.</li><li><strong>Deploy to Vercel</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*_JGHB0eVlKyECyMgqqrRfw.png" /></figure><p>Configure your Vercel project with the following settings:</p><ul><li>Build Command: flutter/bin/flutter build web --release</li><li>Output Directory: build/web</li><li>Install Command:</li></ul><pre>if cd flutter; then git pull &amp;&amp; cd .. ; else git clone --branch flutter-3.21-candidate.12 https://github.com/flutter/flutter.git; fi &amp;&amp; ls &amp;&amp; flutter/bin/flutter doctor &amp;&amp; flutter/bin/flutter clean &amp;&amp; flutter/bin/flutter config --enable-web</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*IvuCfRqZ3T_AhccG55l2sQ.png" /></figure><p>You can check for available Flutter versions <a href="https://github.com/flutter/flutter">here</a>.</p><p>Once the deployment is complete, your app will be accessible. Here’s an example of a deployed app:<br><a href="https://flutter-telegram-miniapp.vercel.app/">https://flutter-telegram-miniapp.vercel.app/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*HDXSZGwizIdZ71vC4jlb3A.png" /></figure><h3>Step 6: Create a Telegram Bot</h3><p>Now, you need to create a Telegram bot to link with your mini-app. You can create it from <a href="https://t.me/BotFather">https://t.me/BotFather</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*ttxXel8Ar5EuA5EZSR_qRg.png" /></figure><p>Save your bot token for future backend access. Let’s continue with creating new app on telegram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*NIddlSr3jT2Fz4jPWZi1Cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*zckOUFBaE0NdR7EaQoBwwg.png" /></figure><p>Once the bot is set up, you can easily test the app by clicking on the web app. You should be able to retrieve the Telegram username, first name, and user ID.</p><p><a href="https://t.me/CatInGalaxy_bot/Cat_in_Galaxy">https://t.me/CatInGalaxy_bot/Cat_in_Galaxy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*atMtwlejviQWjOH_5-u9lw.png" /></figure><p>With that, you’ve successfully built and deployed a Flutter-based Telegram Web App on Vercel. Integrating your service into Telegram opens up exciting opportunities to reach users more effectively without leaving their messaging environment.</p><p>You can check the full source code in here</p><p><a href="https://github.com/c0deslinger/flutter-telegram-miniapp">GitHub - c0deslinger/flutter-telegram-miniapp</a></p><p>Here are some examples of successful mini apps that have many users that you can use as a reference.</p><ol><li><a href="https://t.me/ForUAICryptoBot/app?startapp=D0784FF3">ForuAI</a></li><li><a href="https://t.me/blum/app?startapp=ref_y6U65pAHq3">Blum</a></li></ol><p><strong>References</strong>:<br><a href="https://core.telegram.org/bots/webapps#initializing-mini-apps">Telegram WebApps Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8dee09e9e69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy and Verify Privado iD / Polygon ID Issuer-Node]]></title>
            <link>https://ahmedyusuf.medium.com/deploy-polygonid-issuer-node-a901ac280875?source=rss-8ef59354fdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/a901ac280875</guid>
            <category><![CDATA[did]]></category>
            <category><![CDATA[matic-network]]></category>
            <category><![CDATA[decentralized-identity]]></category>
            <category><![CDATA[polygon]]></category>
            <category><![CDATA[polygon-id]]></category>
            <dc:creator><![CDATA[Yusuf Fachroni]]></dc:creator>
            <pubDate>Fri, 21 Jun 2024 02:04:50 GMT</pubDate>
            <atom:updated>2024-07-16T05:11:21.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bdelTqoANdqKgqH6Cl3Kg.png" /></figure><h3>What is Polygon ID / Privado ID?</h3><p>Privado ID, previously branded as Polygon ID, is a decentralized identity solution designed to provide secure and private identity verification for Web3 applications. It leverages zero-knowledge proofs (ZKPs) to ensure that users can prove their identity without revealing personal information. This system is built on a permissionless blockchain, ensuring both privacy and decentralization</p><p>Key features of Privado ID include:</p><p>1. <em>Self-Sovereign Identity</em>: Users have full control over their identity and personal data. They can manage their identity through an identity wallet, which holds their credentials and private keys.</p><p>2. <em>Zero-Knowledge Proofs</em>: This cryptographic technology allows users to prove the validity of their identity claims without disclosing any actual data. For instance, a user can prove they are over 18 without revealing their exact birthdate.</p><p>3. <em>Verifiable Credentials (VCs)</em>: These are issued by trusted entities (issuers) and can be stored in the user’s wallet. The credentials are cryptographically signed to ensure they are tamper-proof.</p><p>4. <em>Triangle of Trust</em>: This framework includes three roles — the Identity Holder, the Issuer, and the Verifier. The Identity Holder manages their credentials, the Issuer creates and signs the credentials, and the Verifier checks the credentials against specific criteria without accessing the actual data.</p><p>5. <em>On-Chain and Off-Chain Verification</em>: Privado ID supports both on-chain verification via smart contracts and off-chain verification, enhancing flexibility and privacy in various applications.</p><p>This system is particularly beneficial for creating privacy-preserving and decentralized identity solutions in the Web3 space, enabling more secure and user-centric digital interactions.</p><h3>How Privado ID Works?</h3><p>Polygon ID, now known as Privado ID, operates as a self-sovereign identity framework leveraging zero-knowledge proofs (ZKPs) to ensure privacy and security in identity verification processes. Here’s a detailed breakdown of how it works:</p><p><strong>Core Components<br></strong>1. <em>Identity Holder</em>: This is the user who holds identity-related information in the form of verifiable credentials (VCs). These VCs are stored in a digital wallet, which also manages the user’s private keys. The Identity Holder generates ZKPs to authenticate without revealing actual data.<br> <br>2. <em>Issuer</em>: An entity (such as a government, university, or organization) that issues VCs. These credentials are cryptographically signed to ensure their authenticity and tamper-proof nature.</p><p>3. <em>Verifier</em>: An entity that verifies the proofs presented by the Identity Holder. Verification can be conducted both off-chain and on-chain. The Verifier checks that the proof meets specific criteria without accessing the underlying data.</p><ul><li>The Issuer creates a verifiable credential based on the identity information provided by the Identity Holder.</li><li>This credential is cryptographically signed and issued to the Identity Holder, who stores it in their digital wallet.</li></ul><p>2. <em>Proof Generation</em></p><ul><li>When the Identity Holder needs to prove certain information (e.g., age, identity), they generate a zero-knowledge proof using the VCs stored in their wallet.</li><li>This proof does not reveal the underlying data but confirms that the data meets the required criteria.</li></ul><p>3. <em>Verification</em>:</p><ul><li>The Verifier requests proof of a specific claim from the Identity Holder.</li><li>The Identity Holder’s wallet generates the required proof and sends it to the Verifier.</li><li>The Verifier checks the proof against the criteria without accessing the actual data. This can be done via smart contracts on the blockchain (on-chain) or through off-chain mechanisms.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*22SrQUEi18LU1r-r.png" /><figcaption><a href="https://docs.privado.id/docs/introduction/">https://docs.privado.id/docs/introduction/</a></figcaption></figure><p><strong>Key Technologies</strong></p><ul><li>Zero-Knowledge Proofs (ZKPs): ZKPs allow the Identity Holder to prove the validity of their credentials without revealing any personal data. This ensures privacy and security.</li><li>Blockchain: The use of blockchain ensures that the credentials and proofs are tamper-proof and verifiable. It also facilitates decentralized verification processes.</li><li>Verifiable Credentials (VCs): VCs are compliant with W3C standards and are used to represent any type of identity-related information securely.</li></ul><p><strong>Practical Example<br></strong>Consider a scenario where a user wants to access age-restricted content:</p><ul><li>The user requests a VC from a trusted Issuer (e.g., a government authority) that verifies their age.</li><li>The Issuer issues the VC, which is stored in the user’s digital wallet.</li><li>When accessing the restricted content, the Verifier requests proof that the user is over a certain age.</li><li>The user’s wallet generates a ZKP that confirms their age without revealing the exact date of birth.</li><li>The Verifier checks the proof and grants access based on the validated criteria.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*Gvd7q6ucTT1qAo9W" /></figure><p><strong>Benefits</strong></p><ul><li><em>Privacy</em>: Users can prove their identity without exposing personal information.</li><li><em>Security</em>: Cryptographic techniques ensure data integrity and authenticity.</li><li>Decentralization: Users control their identity data, reducing reliance on central authorities.</li><li>Flexibility: Supports both on-chain and off-chain verification, adaptable to various applications.</li></ul><h3>Setup</h3><p>Run and Install docker</p><p>git clone the repository</p><pre>https://github.com/0xPolygonID/issuer-node.git</pre><h4>Tunneling All Port</h4><p>since we need to make some ports can be accessed on public, we need to tunnel the port. In this case I’m using Cloudflare (thanks to <a href="https://www.linkedin.com/in/brixzen">Ali Usman</a> for helping me)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6jpq0hIVUrWt6_A-PjPLA.png" /></figure><p>Copy the Public hostname</p><ol><li>ISSUER_API_UI_SERVER_URL</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*Dx5Dr1ycpfJQyi8BEqHJ2w.png" /></figure><p>2. ISSUER_SERVER_URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*p0VGH9XFTZesrOasp7mDNA.png" /></figure><p>3. ISSUER_CREDENTIAL_STATUS_RHS_URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*9b8fvc7j9wO5w1YymjB_IQ.png" /></figure><p>Based on .env-issuer config file, we can see</p><p>ISSUER_ETHEREUM_CONTRACT_ADDRESS=0x1a4cC30f2aA0377b0c3bc9848766D90cb4404124</p><p>This is the address that lives on Polygon Amoy to be able to update the claims or update the credentials from the issuer to say if something is still valid</p><h4>Configure RPC URL</h4><p>Create Polygon RPC in any provider (ex: <a href="https://alchemy.com/">Alchemy</a>)</p><p>activate Polygon Amoy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-M8RKF_i6yQNJwFzimI_cQ.png" /></figure><p>copy the HTTPS url to ISSUER_ETHEREUM_URL on .env-issuer file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w2s0qtR8_gsMcgbdW-BKrg.png" /></figure><h4>Setup Vault</h4><p>make sure that the vault stores all credentials that we have from our wallet to be able to sign requests essentially</p><p>make sure there’s no existing vault</p><pre>make clean-vault</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*mV0S55KjldY-9PQNA-Pagg.png" /></figure><h3>Start the infrastructure</h3><p>Let’s start our issuer-node</p><pre>make up</pre><p>it will download all docker images and run them locally</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5AHjwTdsLFE_9eZsZ4v3w.png" /></figure><p>wait 20 seconds for the vault to start, and check all services are running</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGolhYJkDjCWMW1Flt2AMA.png" /></figure><p>now we need to get the initial root token which is the sort of identifier for the vault where will be storing our private keys for our wallet to be able to sign transactions</p><p>you can find the initial root token by checking the logs on container issuer-vault-1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*fd3j1OatKJRQB9pna7sUOg.png" /></figure><p>If you experience <strong>problems</strong> with the <strong>vault</strong>, follow these commands:</p><pre>docker stop issuer-vault-1 // Stops the container issuer-vault-1<br>docker rm issuer-vault-1 // Removes container issuer-vault-1<br>make clean-vault // Removes all the data in the vault, including the token<br>make up // Starts the database, cache and vault storage (i.e, postgres, redis and vault)</pre><p>Enable vault authentication:</p><p>simply run command</p><pre>make add-vault-token</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*vBidjq7jNDiXkDwzzZM_DQ.png" /></figure><p>get the private key, you can find it on your Metamask (account details &gt; show private key)</p><pre>make private_key=xxxx95be56aa4b63b8d3f9cc0ed99513313a658657155a4af3305c0f3adxxxx add-private-key</pre><p>Run issuer Node API</p><pre>make run</pre><p>wait 20 seconds, and then generate issuer DID</p><pre>make generate-issuer-did</pre><p>check last line on .env-api</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*dTB-gVbkf89_z-IaJ5TBlA.png" /></figure><p>now we got ISSUER_API_UI_ISSUER_DID</p><blockquote>did:polygonid:polygon:amoy:2qa7tA11V4Df2xAxb43HiX86y3Qb1JEWFYkfPQ19D5</blockquote><h3>Start Web UI</h3><pre>make run-ui</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*2NdincUuqvpqe01RCj1FoA.png" /></figure><p>open the web UI on <a href="http://http//localhost:8088">http://localhost:8088</a>.</p><p>since I tunnel port 8088, I can access it via <a href="https://issuer-ui-ucup.brixzen.my.id/">https://issuer-ui-ucup.brixzen.my.id/</a></p><p>input password from .env-ui file (default is user-ui &amp; password-ui)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*lodQcSJWgkReO5uR4cuE2A.png" /></figure><p>Now, let’s start with the import schema. We can find the schema at <a href="https://schema-builder.polygonid.me/">https://schema-builder.polygonid.me</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42FOPTgP7IypvyZnsGa5uQ.png" /></figure><p>for example, I’m using this schema (<a href="https://tools.privado.id/schemas/a0b6936d-b4de-4078-a2e7-daea56609dc5">https://tools.privado.id/schemas/a0b6936d-b4de-4078-a2e7-daea56609dc5</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xa7BYGBL3HsGgIXXF4ns-Q.png" /></figure><p>let’s copy JSON schema URL, and then put it here. then click Preview Import &gt; Import</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHiay1PJdX-u66ReBK8YTw.png" /></figure><p>Now our schema is imported</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Ow7H1X2U52IbZVU6jaigQ.png" /></figure><p>Let’s continue to issue the credential. Click issue action.</p><p>In this case, I’m trying to use credential link, so anyone can issue these credentials by creating QRCode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*E2n8_PGr1xZCFtGyiRUpAg.png" /></figure><p>For the GenderDisclose, we will set that this credentials is for person with gender Male and date of birth 4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*yQoiJww08icuZ1oMUFDwHQ.png" /></figure><p>Now let’s click create credential link</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*eKMG3j1FXHSMER8tIdEfpA.png" /></figure><p>Click View link, and it will redirect to new tab with qrcode credentials</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*jork7P19SZv3LhmsoYflIA.png" /></figure><p>Now let’s scan the QRCode with our PolygonID Wallet (you can download it on Playstore or Appstore), don’t forget to change the network to Polygon Amoy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*qgwQwdwccP50MSN-JuW9zg.png" /></figure><p>Now we already claim the credential on our wallet</p><h3>Run the Polygon Verifier Backend</h3><p>Pull this repository</p><p><a href="https://github.com/0xPolygonID/verifier-backend">GitHub - 0xPolygonID/verifier-backend: Verifier Backend</a></p><p>Create a file named .env in the root directory of the project. .env-example is provided as an example. Change the Verifier Backend Host Url with our public URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*2PHOJFgcNkk25ussBTyhAw.png" /></figure><p>Change the networkURL on resolvers_settings.yaml with polygon amoy network URL from Alchemy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*xbx52Tj037z90zwsur6XhQ.png" /></figure><p>run the server with command</p><pre>make run</pre><p>Let’s try verification our credentials using query builder on</p><p><a href="https://tools.privado.id/query-builder">https://tools.privado.id/query-builder</a></p><p>Copy the JSON-LD context of our credentials (Gender Age Verify) schema. And select the attribut field that we need to verify (I select for gender atrribute)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*5yWMZYgxBHKL1cDQug5J3g.png" /></figure><p>In this case, I’m going to use Selective Disclosure, so that the verifier can see the value of chosen attribute (gender)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*CCA8RM2Q8KUMNwVefIyjrQ.png" /></figure><p>Now let’s create the query, and it will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*El67Hsk_l_am7izmQn_zlg.png" /></figure><p>since we are going to test it with our verifier node, then let’s copy the code snippet</p><p>Open our verifier URL, in this case, my verifier URL is <br><a href="https://verifier-ucup.brixzen.my.id/">https://verifier-ucup.brixzen.my.id/</a></p><p>Navigate to the Sign-in section and paste the code inside the scope, then click try button, and it will return the response with qrCode and sessionID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*t6gk-og9QTRzbnOyzmiOcg.png" /></figure><p>Let’s convert iden3comm from qrCode and paste it on QRCode builder (<a href="https://qrfy.com/">https://qrfy.com/</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*ct7nd34ighPngWcTlnzHVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*JNDXrmGJJCZew8vA-NNPGw.png" /></figure><p>And then, scan the qrcode using PolygonID Wallet App. It will show a verification page, that the Verifier Backend is request the proof of Gender Disclose (gender)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*Y6hmAkwZZoLgJYFYDvGQyQ.png" /></figure><p>continue by click verify button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*EYm3YGxwo9FZI6ImbZxVCg.png" /></figure><p>Wait until the loading is finished, and it will show a popup saying that the proof generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*fG56gzvN4Xkf9vCjKruxkg.png" /></figure><p>Now back to the verifier page to get the status of session ID. Let’s copy the sessionID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*_DOHGVK5K_n_uTPkP0Gxmg.png" /></figure><p>and paste it into Get Status Section, and the verifier can get the jwz value and Metadata</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*gaxEqOU2QvfsEXGAv6rcyQ.png" /></figure><p>we can also verify the jwz value by copy and paste it on <a href="https://jwz.polygonid.me/">https://jwz.polygonid.me/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*1Y-FjAPJdtq5R-MiMXfEBQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a901ac280875" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing SSL Pinning for Enhanced Security in Flutter Applications]]></title>
            <link>https://ahmedyusuf.medium.com/secure-flutter-project-with-ssl-pinning-45b18458022e?source=rss-8ef59354fdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/45b18458022e</guid>
            <category><![CDATA[ssl-pinning]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Yusuf Fachroni]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 14:36:52 GMT</pubDate>
            <atom:updated>2023-07-04T05:18:03.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-OopMIeE2jei376rT1erg.png" /><figcaption>source: <a href="https://www.appsealing.com/mitm-attacks/">https://www.appsealing.com/mitm-attacks/</a></figcaption></figure><p><strong>What is SSL Pinning?<br></strong><br>SSL Pinning revolves around the fundamental notion of verifying the certificate during the application’s API request. To thwart the perils of the Man In The Middle Attack (MITM), the esteemed <a href="https://owasp.org/www-community/controls/Certificate_and_Public_Key_Pinning">OWASP</a> highly endorses the adoption of SSL Pinning.</p><p>When employing HTTPS, the server generates a certificate and transmits it to the application. Nonetheless, the application readily accepts any certificate bestowed upon it, thereby rendering itself susceptible to a malicious man-in-the-middle attack (MITM). This form of attack entails an adversary intercepting the communication between the client and the server, introducing illicit certificates that pave the way for unauthorized access to sensitive user data, thereby compromising their privacy. As such, this scenario poses a significant security risk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lbCR-EVXxJvPxK3jtwK-w.png" /><figcaption><a href="https://approov.io/blog/steal-that-api-key-with-a-man-in-the-middle-attack">https://approov.io/blog/steal-that-api-key-with-a-man-in-the-middle-attack</a></figcaption></figure><p>SSL Pinning establishes a reliable SSL certificate connection between the server and the client, instilling a sense of trust. Consequently, an extra layer of validation is implemented to verify if the certificate stored within the application corresponds to the one utilized by the server. In the event of a mismatch, the application possesses the capability to outrightly reject the certificate, safeguarding against potential security breaches.</p><p><strong>Limitation</strong></p><p>Due to the time-limited nature of SSL certificates, they necessitate regular renewal to ensure their validity. Consequently, each time a new certificate is issued, regardless of whether there are any modifications to our application, it becomes imperative to update the app accordingly. This practice ensures that the app remains synchronized with the latest certificate, thereby maintaining a secure and uninterrupted connection.</p><p><strong>Get perm cert file</strong></p><p>Here is the example in Chrome, click this button, then select “Connection is Secure” &gt; “Certificate is Valid” &gt; Details &gt; Export</p><p>This is an example how I get a cert file on themoviedb.org</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5NfxdflXlgPL_MZSB5b1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r0xQzzUI5GRGem4bIXzaMQ.png" /></figure><p>Then save the cer file to your project</p><ul><li>assets/cert/themoviedb.cer</li></ul><p>don’t forget to register it to pubspec.yml</p><p>Create class for load cer file</p><pre>import &#39;dart:convert&#39;;<br><br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br><br>abstract class CertReader {<br>  static ByteData? cert;<br><br>  static Future&lt;void&gt; initialize() async {<br>    cert = await rootBundle.load(&#39;assets/cert/themoviedb.cer&#39;);<br>  }<br><br>  static ByteData? getCert() {<br>    return cert;<br>  }<br>}</pre><p>Call this class on your main, make sure it’s called before you create http instance</p><pre>Future&lt;void&gt; main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await ConfigReader.initialize(env);<br>}</pre><p>Then you can call cert to your SecurityContext. By configuring the SecurityContext with our specific certificate, we establish a mechanism wherein the SecurityContext no longer relies on the operating system’s default certificate. Instead, it loads our designated certificate file and places trust solely in our own certificate.</p><p>This approach allows us to exercise greater control over the trust and validation process, enabling us to prioritize our own certificate over the system’s certificates.</p><pre>SecurityContext securityContext = SecurityContext(withTrustedRoots: false);<br>securityContext.setTrustedCertificatesBytes(ConfigReader.getCert().buffer.asInt8List());<br>HttpClient client = HttpClient(context: await securityContext);<br> client.badCertificateCallback =<br>      (X509Certificate cert, String host, int port) =&gt; false;<br>IOClient ioClient = IOClient(client);</pre><p>If you are using Getx GetConnect, you can set cert in the list of TrustedCertificate, make sure these codes are placed before you call httpClient</p><pre>ByteData? cert = ConfigReader.getCert();<br>List&lt;int&gt; trustedCert = [];<br>if (cert != null) {<br>  trustedCert = cert.buffer.asInt8List();<br>  trustedCertificates = [TrustedCertificate(trustedCert)];<br>}<br>httpClient.baseUrl = &quot;https://api.themovie.db/&quot;;<br>httpClient.timeout = const Duration(minutes: 5);</pre><p>And if you are using Dio, you can set the cert file using this</p><pre>Dio dio = Dio();<br>ByteData bytes = ConfigReader.getCert()!;<br>(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =<br>    (client) {<br>  SecurityContext sc = SecurityContext();<br>  sc.setTrustedCertificatesBytes(bytes.buffer.asUint8List());<br>  HttpClient httpClient = HttpClient(context: sc);<br>  return httpClient;<br>};</pre><p><strong>Summary</strong></p><p>SSL pinning serves as an effective method to enhance the security of communication between mobile devices and servers. It addresses the vulnerability present in the default behavior of apps, where they accept any certificate received via HTTPS, thereby exposing themselves to potential man-in-the-middle attacks.</p><p>By implementing SSL pinning, a reliable SSL certificate connection is established between the server and the client. This introduces an extra layer of validation to ensure that the certificate stored within the application matches the one employed by the server.</p><p>Reference:<br><a href="https://dwirandyh.medium.com/securing-your-flutter-app-by-adding-ssl-pinning-474722e38518">https://dwirandyh.medium.com/securing-your-flutter-app-by-adding-ssl-pinning-474722e38518</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45b18458022e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter iOS — Setup Flavors with different Firebase Config]]></title>
            <link>https://ahmedyusuf.medium.com/setup-flavors-in-ios-flutter-with-different-firebase-config-43c4c4823e6b?source=rss-8ef59354fdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/43c4c4823e6b</guid>
            <category><![CDATA[flavor]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Yusuf Fachroni]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 13:58:42 GMT</pubDate>
            <atom:updated>2023-06-04T14:14:33.524Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*Wp1kse2s9KKIHxLO1ZX3pQ.png" /></figure><p>What is the purpose of flavors? Flavors serve as a means to customize your application for different contexts, including development and production. Let’s consider an illustration:</p><ul><li>During the development phase, you may desire your app to establish a connection with the API host at <a href="https://dev.mobileapp.com/v1/"><strong>https://dev.mobileapp.com/v1/</strong></a> using the project ID <strong>com.mobileapp.dev</strong>.</li><li>Conversely, when it’s time to release the app, the production version should connect to <a href="https://api.mobileapp.com/v1/"><strong>https://api.mobileapp.com/v1/</strong></a> using the project ID <strong>com.mobileapp.prod</strong>.</li></ul><p>Instead of manually coding these values into variables and creating separate app builds for each environment, it is recommended to utilize flavors. By employing flavors, you can provide these values as build-time configurations, streamlining the process.</p><p>In this tutorial, we will follow a methodology that involves creating a sample application with two flavors: “dev” and “prod”. After each step, commits will be made to the sample app, enabling you to review code differences and grasp the modifications made.</p><p>Additionally, I will provide detailed instructions to ensure a user-friendly experience, making it simple to apply these instructions to an existing app without any hassle.</p><p><strong>Step 1: Create a Flutter application project</strong></p><p><strong>Step 2: Configure the application to integrate with Firebase</strong></p><p>To begin, establish <strong>two distinct Firebase projects </strong>— one for development and another for production. Within the Firebase console, create an Android application for each project. Let’s assume the development app has the ID <strong>com.mobileapp.dev</strong>, while the production app has the ID <strong>com.mobileapp.prod</strong>. Ensure that you download the respective G<strong>oogleServices-Info.plist</strong> files for these two applications. For detailed instructions on how to integrate Firebase into your Flutter project, refer to the <a href="https://firebase.google.com/docs/flutter/setup">Firebase Flutter Setup Guide</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KE5SV2qcLCmbVQzTO_VWeA.png" /><figcaption>Create 2 Firebase Project for Dev &amp; Prod</figcaption></figure><p>Next, copy the G<strong>oogleServices-Info.plist</strong> files for the development and production applications into separate folders within the <em>ios/config/</em> directory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*6Dx4L8sHpIr-cEhYsy2DLA.png" /></figure><p><strong>Step 3: Create 2 configuration file in root project directory for set pointing to different api endpoint</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*wV852Uweh5PJG3oQ.png" /></figure><p>dev.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*p_2TmZQ4zQ8RBXYl.png" /></figure><p>prod.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*23cVgkyJDlioc3H_.png" /></figure><p><strong>Step 4: Create multiple Runner on XCode</strong></p><p>Lets open ios folder on XCode, simply right click on ios folder and you can find Open in Xcode option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*CTnBTiqG_bBwMS6NnrNZxw.png" /></figure><p>Xcode introduces the concept of schemes and build configurations as counterparts to product flavors in Android. Let’s create custom scheme for Dev and Prod</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*OE7e4r2CbOJ1mue4mzfMTg.gif" /></figure><p>Then, let’s create 3 configurations named Debug-Dev, Release-Dev, and Profile-Dev</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5KlPoqD-amdcgurzjTVulA.gif" /></figure><p>We also need to rename for prod <em>build configuration</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*74RaOwzLGWilIM5LkzVi1A.gif" /></figure><p>Ok, now let’s set Dev schemes by Dev<em> build configuration</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*9FqzXYzM4USJiBaFjf3dbA.gif" /></figure><ul><li>Set Bundle ID based on flavor</li></ul><p>We now have two schemes linked to their respective build configurations. This allows us to tailor customizations for each scheme. To begin, let’s modify the app bundle identifier to be distinct for both schemes.</p><p>click Runner on Targets section &gt; Build Settings &gt; type Bundle on filter top-right field &gt; fill all Product Bundle Identifier</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nrryNGiEbU-DemI9owJG6w.png" /></figure><ul><li>Set AppName based on flavors</li></ul><p>We would like to utilize distinct Display Names for the app. However, the Display Name parameter is not available in the Build Settings for the target. As a workaround, we can create a user-defined parameter and utilize it in place of the Display Name parameter.</p><p>click Build Settings &gt; Info</p><p>set <em>Bundle display name</em> to $(APP_DISPLAY_NAME)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYZzNehhXN9Dcincvkttyw.png" /></figure><p>click Build Settings &gt; Click add button (+) &gt; Add User-Defined Setting and type APP_DISPLAY_NAME</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdaYdOckN1iijEwHpL20ag.png" /></figure><p>and set like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnGoHYbpxL1nIclfYD5WLA.png" /></figure><ul><li>Add config folder to Runner</li></ul><p>Finally, we need to find a solution to utilize a different <em>GoogleServices-Info.plist</em> file based on the build configuration. Some suggestions propose handling this at runtime during app startup by explicitly specifying the desired configuration file when initializing Firebase (as mentioned in the Firebase documentation: <a href="https://firebase.google.com/docs/projects/multiprojects">https://firebase.google.com/docs/projects/multiprojects</a>). However, another option I prefer is to copy the appropriate file to the default location during build time. This way, when the app bundle is generated, it automatically uses the correct file.</p><p>To achieve this, we will start by organizing the <em>GoogleServices-Info.plist</em> files for each flavor in separate folders, and add to Runner</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*x4yGjohfV_JUafeoPOw1Aw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxQGC5SUkHFl2Nc2FPE9-A.png" /><figcaption>Result config folder inside Runner</figcaption></figure><ul><li>Add runner script to copy GoogleService-info.plist on build phase</li></ul><p>Next, we need to determine how to include a step in the build process to ensure that the corresponding GoogleServices-Info.plist file is copied to the appropriate location, specifically within the Runner directory. This can be achieved by adding a new Run script Build Phase to the target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*TFJl5ZZVrS0f1gIuB3zajQ.gif" /></figure><pre>environment=&quot;default&quot;<br><br># Regex to extract the scheme name from the Build Configuration<br># We have named our Build Configurations as Debug-dev, Debug-prod etc.<br># Here, dev and prod are the scheme names. This kind of naming is required by Flutter for flavors to work.<br># We are using the $CONFIGURATION variable available in the XCode build environment to extract <br># the environment (or flavor)<br># For eg.<br># If CONFIGURATION=&quot;Debug-prod&quot;, then environment will get set to &quot;prod&quot;.<br>if [[ $CONFIGURATION =~ -([^-]*)$ ]]; then<br>environment=${BASH_REMATCH[1]}<br>fi<br><br>echo $environment<br><br># Name and path of the resource we&#39;re copying<br>GOOGLESERVICE_INFO_PLIST=GoogleService-Info.plist<br>GOOGLESERVICE_INFO_FILE=${PROJECT_DIR}/config/${environment}/${GOOGLESERVICE_INFO_PLIST}<br><br># Make sure GoogleService-Info.plist exists<br>echo &quot;Looking for ${GOOGLESERVICE_INFO_PLIST} in ${GOOGLESERVICE_INFO_FILE}&quot;<br>if [ ! -f $GOOGLESERVICE_INFO_FILE ]<br>then<br>echo &quot;No GoogleService-Info.plist found. Please ensure it&#39;s in the proper directory.&quot;<br>exit 1<br>fi<br><br># Get a reference to the destination location for the GoogleService-Info.plist<br># This is the default location where Firebase init code expects to find GoogleServices-Info.plist file<br>PLIST_DESTINATION=${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app<br>echo &quot;Will copy ${GOOGLESERVICE_INFO_PLIST} to final destination: ${PLIST_DESTINATION}&quot;<br><br># Copy over the prod GoogleService-Info.plist for Release builds<br>cp &quot;${GOOGLESERVICE_INFO_FILE}&quot; &quot;${PLIST_DESTINATION}&quot;</pre><p><strong>Step 5: Create some dart files to handle configuration based on flavor</strong></p><p><em>lib/utils/environment.dart</em></p><pre>abstract class Environment {<br>  static const dev = &#39;dev&#39;;<br>  static const prod = &#39;prod&#39;;<br>}</pre><p><em>lib/utils/config_reader.dart</em></p><pre>import &#39;dart:convert&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>abstract class ConfigReader {<br> static Map&lt;String, dynamic&gt;? _config;<br> static bool _isDevMode = false;<br> static Future&lt;void&gt; initialize(String env) async {<br> var configString = &#39;{}&#39;;<br> try {<br> configString = await rootBundle.loadString(&#39;config/$env.json&#39;);<br> } catch (_) {<br> configString = await rootBundle.loadString(&#39;config/dev.json&#39;);<br> }<br> _config = json.decode(configString) as Map&lt;String, dynamic&gt;;<br> _isDevMode = env == &quot;dev&quot;;<br> }<br> static bool isDevMode() {<br> return _isDevMode;<br> }<br> static String getBaseUrl() {<br> return _config![&#39;baseUrl&#39;] as String;<br> }<br>}</pre><p><strong>Step 6: Create 3 different main dart files to manage flavor</strong></p><p><em>lib/main_dev.dart</em></p><pre>Future&lt;void&gt; main() async {<br>  await mainCommon(Environment.dev);<br>}</pre><p><em>lib/main_prod.dart</em></p><pre>Future&lt;void&gt; main() async {<br>  await mainCommon(Environment.prod);<br>}</pre><p><em>lib/main_common.dart</em></p><pre>Future&lt;void&gt; mainCommon(String env) async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await ConfigReader.initialize(env);<br>  runApp(const MyApp());<br>}</pre><p><strong>Step 6: Get a variable based on flavor</strong></p><p>You can get variables from config like this</p><pre>debugShowCheckedModeBanner: ConfigReader.isDevMode(),</pre><p>And get base_url for connection class file like this</p><pre>class HttpGetConnect extends GetConnect {<br>  final _baseUrl = ConfigReader.getBaseUrl();<br>  static HttpGetConnect? _instance;<br>  HttpGetConnect._internal() {<br>    _instance = this;<br>    httpClient.baseUrl = _baseUrl;<br>  }<br>}</pre><p><strong>Step 7: Add vscode launcher config</strong></p><p>create .vscode/lunch.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/0*DGrCHjmKkszF1GpS.png" /></figure><p>change launch.json to this code</p><pre>{<br>    // Use IntelliSense to learn about possible attributes.<br>    // Hover to view descriptions of existing attributes.<br>    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387<br>    &quot;version&quot;: &quot;0.2.0&quot;,<br>    &quot;configurations&quot;: [<br>        {<br>            &quot;name&quot;: &quot;[Debug] Development App&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;type&quot;: &quot;dart&quot;,<br>            &quot;program&quot; : &quot;lib/main_dev.dart&quot;,<br>            &quot;args&quot;: [<br>                &quot;--flavor&quot;,<br>                &quot;Dev&quot;<br>            ]<br>        },<br>        {<br>            &quot;name&quot;: &quot;[Debug] Production App&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;type&quot;: &quot;dart&quot;,<br>            &quot;program&quot; : &quot;lib/main_prod.dart&quot;,<br>            &quot;args&quot;: [<br>                &quot;--flavor&quot;,<br>                &quot;Prod&quot;<br>            ]<br>        },<br>        {<br>            &quot;name&quot;: &quot;[Release] Production App&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;type&quot;: &quot;dart&quot;,<br>            &quot;flutterMode&quot;: &quot;release&quot;,<br>            &quot;program&quot; : &quot;lib/main_prod.dart&quot;,<br>            &quot;args&quot;: [<br>                &quot;--flavor&quot;,<br>                &quot;Prod&quot;<br>            ]<br>        },<br>    ]<br>}</pre><p>and now you can launch your app using dev flavor or prod flavor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*67jiuT7CNKBS5JiwacEQGw.png" /></figure><p>and here is the result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2rOO_lLx5u_tQKID3u3QQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBBxHibArJ7XrQyh5CzgMw.png" /><figcaption>Left: Running production in debug mode | Right: Running development in debug mode</figcaption></figure><p><strong>Step 8: Build xcarchive</strong></p><p>Open XCode, then select Target Runners &gt; Signing &amp; Capabilities, make sure you already have <strong>Apple Developer Account, </strong>then simply run this script and you can find the output file in <em>build/ios/</em> folder</p><pre>flutter build xcarchive --flavor prod -t lib/main_prod.dart</pre><p><strong>Would you like to proceed with setting up flavors in Android? Let’s move on to the </strong><a href="https://ahmedyusuf.medium.com/how-to-build-flavor-in-flutter-android-with-different-firebase-config-96b259e5572e"><strong>next step</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*kQRXkAxJm1F_vqarqH-BaQ.png" /><figcaption><a href="https://ahmedyusuf.medium.com/how-to-build-flavor-in-flutter-android-with-different-firebase-config-96b259e5572e">https://ahmedyusuf.medium.com/how-to-build-flavor-in-flutter-android-with-different-firebase-config-96b259e5572e</a></figcaption></figure><p>Github Project</p><p><a href="https://github.com/c0deslinger/flutter-learn-flavor">https://github.com/c0deslinger/flutter-learn-flavor</a></p><p>Reference:</p><p><a href="https://medium.com/flutter-community/flutter-ready-to-go-e59873f9d7de">https://medium.com/flutter-community/flutter-ready-to-go-e59873f9d7de</a></p><p><a href="https://medium.com/@animeshjain/build-flavors-in-flutter-android-and-ios-with-different-firebase-projects-per-flavor-27c5c5dac10b">https://medium.com/@animeshjain/build-flavors-in-flutter-android-and-ios-with-different-firebase-projects-per-flavor-27c5c5dac10b</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43c4c4823e6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Android — Setup flavor with different Firebase Config]]></title>
            <link>https://ahmedyusuf.medium.com/how-to-build-flavor-in-flutter-android-with-different-firebase-config-96b259e5572e?source=rss-8ef59354fdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/96b259e5572e</guid>
            <dc:creator><![CDATA[Yusuf Fachroni]]></dc:creator>
            <pubDate>Mon, 15 May 2023 09:32:39 GMT</pubDate>
            <atom:updated>2023-06-04T14:13:33.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Google Sign-In for Android using Firebase | by Ari SWS | DOT Intern | Medium" src="https://cdn-images-1.medium.com/proxy/1*rbM2zC4uxHQOH9F56e1L_w.gif" /></figure><p>What is the purpose of flavors? Flavors serve as a means to tailor your application for various contexts, including development and production. Let’s consider an example:</p><ul><li>During the development phase, you may want your app to connect with the API host at <a href="https://dev.mobileapp.com/v1/"><strong>https://dev.mobileapp.com/v1/</strong></a><strong> </strong>with project ID <strong>com.mobileapp.dev</strong></li><li>Conversely, when you’re ready to release the app, the production version should connect to <a href="https://api.mobileapp.com/v1/"><strong>https://api.mobileapp.com/v1/</strong></a><strong> </strong>with project ID <strong>com.mobileapp.prod</strong></li></ul><p>Rather than manually coding these values into variables and creating separate app builds for each environment, the recommended approach is to utilize flavors. By employing flavors, you can provide these values as build-time configurations, streamlining the process.</p><p>The methodology employed in this tutorial involves creating a sample application with two flavors: dev and prod. Throughout the tutorial, the sample app will have commits after each step, enabling you to examine code differences and comprehend the changes made.</p><p>Furthermore, I will provide comprehensive instructions to ensure ease of use, making it effortless to apply these instructions to an already existing app.</p><p><strong>Step 1: Initialize a default Flutter app</strong></p><p><strong>Step 2: Configure the app to connect to Firebase<br></strong><br>Create 2 Firebase projects, one is for dev and one is for prod. Create an app for Android in the Firebase console for each project, let&#39;s say for dev is using app ID <strong>com.mobileapp.dev</strong> and for prod is <strong>com.mobileapp.prod</strong>. You will need to download the google-services.json files for those 2 apps. Detailed instructions on how to add Firebase to your Flutter project can be found here: <a href="https://firebase.google.com/docs/flutter/setup">Firebase Flutter Setup Guide</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KE5SV2qcLCmbVQzTO_VWeA.png" /><figcaption>Create 2 Firebase Project for Dev &amp; Prod</figcaption></figure><p>Copy google-services.json on dev and prod to separate folder in <em>android/app/src</em> folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*QTU1wssK188Fic8y7LG1hQ.png" /></figure><p>You also can set different name for dev and prod App like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGVrUXUdjT6Xn3hMi4SvRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*_yFyBOYwvGlP_CKJ8ahtYg.png" /></figure><p><strong>Step 3: Create 2 configuration file in root project directory for set pointing to different api endpoint</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*Rl0a-w-WsePD-1uoCYiT-Q.png" /></figure><p>dev.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*PwCP8R94Ai7xZImY-yHTog.png" /></figure><p>prod.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*cJs2lruCXMfUin32K4UWyw.png" /></figure><p>Set on product flavors on build.gradle</p><p>add these line to android/app/build.gradle inside android { }</p><pre>    flavorDimensions &quot;env&quot;<br><br>    productFlavors {<br><br>        dev {<br>            dimension &quot;env&quot;<br>            applicationId &quot;com.mobileapp.dev&quot;<br>        }<br><br>        prod {<br>            dimension &quot;env&quot;<br>            applicationId &quot;com.mobileapp.prod&quot;<br>        }<br>    }</pre><p><strong>Step 4: Create some dart file to handle configuration based on flavor</strong></p><p><em>lib/utils/environment.dart</em></p><pre>abstract class Environment {<br>  static const dev = &#39;dev&#39;;<br>  static const prod = &#39;prod&#39;;<br>}</pre><p><em>lib/utils/config_reader.dart</em></p><pre>import &#39;dart:convert&#39;;<br><br>import &#39;package:flutter/services.dart&#39;;<br><br>abstract class ConfigReader {<br>  static Map&lt;String, dynamic&gt;? _config;<br>  static bool _isDevMode = false;<br><br>  static Future&lt;void&gt; initialize(String env) async {<br>    var configString = &#39;{}&#39;;<br>    try {<br>      configString = await rootBundle.loadString(&#39;config/$env.json&#39;);<br>    } catch (_) {<br>      configString = await rootBundle.loadString(&#39;config/dev.json&#39;);<br>    }<br>    _config = json.decode(configString) as Map&lt;String, dynamic&gt;;<br>    _isDevMode = env == &quot;dev&quot;;<br>  }<br><br>  static bool isDevMode() {<br>    return _isDevMode;<br>  }<br><br>  static String getBaseUrl() {<br>    return _config![&#39;baseUrl&#39;] as String;<br>  }<br>}</pre><p><strong>Step 5: Create 3 different main dart file to manage flavor</strong></p><p><em>lib/main_dev.dart</em></p><pre>Future&lt;void&gt; main() async {<br>  await mainCommon(Environment.dev);<br>}</pre><p><em>lib/main_prod.dart</em></p><pre>Future&lt;void&gt; main() async {<br>  await mainCommon(Environment.prod);<br>}</pre><p><em>lib/main_common.dart</em></p><pre>Future&lt;void&gt; mainCommon(String env) async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await ConfigReader.initialize(env);<br>  runApp(const MyApp());<br>}</pre><p><strong>Step 6: Get variable based on flavor</strong></p><p>You can get variable from config like this</p><pre>debugShowCheckedModeBanner: ConfigReader.isDevMode(),</pre><p>And get base_url for connection class file like this</p><pre>class HttpGetConnect extends GetConnect {<br>  final _baseUrl = ConfigReader.getBaseUrl();<br><br>  static HttpGetConnect? _instance;<br><br>  HttpGetConnect._internal() {<br>    _instance = this;<br>    httpClient.baseUrl = _baseUrl;<br>  }<br>}</pre><p><strong>Step 7: Edit vscode launcher config</strong></p><p>open .vscode/lunch.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*JlXQrNdy9kfGq_69JNk0Yw.png" /></figure><p>change launch.json to this code</p><pre>{<br>    // Use IntelliSense to learn about possible attributes.<br>    // Hover to view descriptions of existing attributes.<br>    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387<br>    &quot;version&quot;: &quot;0.2.0&quot;,<br>    &quot;configurations&quot;: [<br>        {<br>            &quot;name&quot;: &quot;[Debug] Development App&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;type&quot;: &quot;dart&quot;,<br>            &quot;program&quot; : &quot;lib/main_dev.dart&quot;,<br>            &quot;args&quot;: [<br>                &quot;--flavor&quot;,<br>                &quot;Dev&quot;<br>            ]<br>        },<br>        {<br>            &quot;name&quot;: &quot;[Debug] Production App&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;type&quot;: &quot;dart&quot;,<br>            &quot;program&quot; : &quot;lib/main_prod.dart&quot;,<br>            &quot;args&quot;: [<br>                &quot;--flavor&quot;,<br>                &quot;Prod&quot;<br>            ]<br>        },<br>        {<br>            &quot;name&quot;: &quot;[Release] Production App&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;type&quot;: &quot;dart&quot;,<br>            &quot;flutterMode&quot;: &quot;release&quot;,<br>            &quot;program&quot; : &quot;lib/main_prod.dart&quot;,<br>            &quot;args&quot;: [<br>                &quot;--flavor&quot;,<br>                &quot;Prod&quot;<br>            ]<br>        },<br>    ]<br>}<br><br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*67jiuT7CNKBS5JiwacEQGw.png" /><figcaption>and now you can launch your app using dev flavor or prod flavor</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgYLyT6esI2LqHrG2Ztg_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m0xzsi3Xr93qCz1CkNZlnA.png" /><figcaption>Left: Running production in debug mode | Right: Running development in debug mode</figcaption></figure><p><strong>Step 8: Create apk for dev / aab for production</strong></p><p>You can build apk for dev using this command</p><pre>flutter build apk --flavor dev -t lib/main_dev.dart</pre><p>And aab for prod using this command</p><pre>flutter build appbundle --flavor prod -t lib/main_prod.dart</pre><p><strong>Would you like to proceed with setting up flavors in iOS? Let’s move on to the </strong><a href="https://ahmedyusuf.medium.com/setup-flavors-in-ios-flutter-with-different-firebase-config-43c4c4823e6b"><strong>next step</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*XOuT3CGavt5QhW6kEsMpoA.png" /><figcaption><a href="https://ahmedyusuf.medium.com/setup-flavors-in-ios-flutter-with-different-firebase-config-43c4c4823e6b">https://ahmedyusuf.medium.com/setup-flavors-in-ios-flutter-with-different-firebase-config-43c4c4823e6b</a></figcaption></figure><p>Github Project</p><p><a href="https://github.com/c0deslinger/flutter-learn-flavor">https://github.com/c0deslinger/flutter-learn-flavor</a></p><p>Reference:</p><p><a href="https://medium.com/flutter-community/flutter-ready-to-go-e59873f9d7de">https://medium.com/flutter-community/flutter-ready-to-go-e59873f9d7de</a></p><p><a href="https://medium.com/@animeshjain/build-flavors-in-flutter-android-and-ios-with-different-firebase-projects-per-flavor-27c5c5dac10b">https://medium.com/@animeshjain/build-flavors-in-flutter-android-and-ios-with-different-firebase-projects-per-flavor-27c5c5dac10b</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96b259e5572e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cara CI/CD Project Maven dengan Jenkins dan GitLab menggunakan Docker]]></title>
            <link>https://ahmedyusuf.medium.com/cara-ci-cd-project-maven-dengan-jenkins-dan-gitlab-menggunakan-docker-7b1096996bfc?source=rss-8ef59354fdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b1096996bfc</guid>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Yusuf Fachroni]]></dc:creator>
            <pubDate>Sun, 18 Apr 2021 15:45:45 GMT</pubDate>
            <atom:updated>2024-06-21T02:25:31.419Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Step-by-Step Guide for CI/CD with Maven, Jenkins, and GitLab Docker</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*e5U2IOZV67mt6dJh.png" /></figure><p>Lately, CI/CD mechanisms have become the most commonly used process in development. Here, I will try to share a simple CI/CD pipeline using Jenkins to perform a git push to an online repository.</p><p>The scenario is that when a developer performs a git push to the testbed server, a Maven install check will be carried out in Jenkins. If the Maven install is successful, it will proceed with a git push to the online GitLab. In the future, we can add more actions in Jenkins, such as deploying to a Docker server or automatic testing, but here we will try a simple integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*ArYbIcw5ysFsudStvNn_zQ.png" /><figcaption>skenario</figcaption></figure><p>First, we need Jenkins and GitLab offline images, which we will deploy on the testbed server.</p><p>A. Create a Docker Compose file for Jenkins, here I will listen on port 8080.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3li5LzbVaUgD6wbUIR3NWQ.png" /></figure><p>B. Also, deploy the GitLab image. Here, I am using the default settings where it will run on port 80 with the container name “gitlab”.</p><p>After the GitLab offline container is successfully running in Docker, we can access it directly at the URL <a href="http://localhost./">http://localhost.</a> When accessing the website for the first time, a form will appear to set a new password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ta5hIwQ6K413vNm4fjFvZQ.png" /></figure><p>After setting up the GitLab password, we need to configure network settings:</p><p>1. <strong>Access GitLab</strong>:</p><p>• Open your browser and navigate to <a href="http://localhost./">http://localhost.</a></p><p>• Log in with the root user and the password you set during the initial setup.</p><p>2. <strong>Navigate to Admin Area</strong>:</p><p>• After logging in, click on the profile icon in the top-right corner.</p><p>• Select Admin Area from the dropdown menu.</p><p>3. <strong>Go to Network Settings</strong>:</p><p>• In the Admin Area, look for the Settings menu in the left sidebar.</p><p>• Scroll down and select Network.</p><p>You should now be in the Network settings area where you can configure various network-related settings for your GitLab instance.</p><p>This will allow you to customize network settings such as outbound requests, inbound email settings, and more according to your requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Otz53TcAK-k9iX9S08sN3Q.png" /></figure><p>Check “Allow requests to the local network from hooks and services” to enable access for services running on the local network. In this case, the Jenkins container we set up earlier will perform the webhooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOZPRLavwAnKynzmGHcBkg.png" /></figure><p>Log out, then register a new account which we will use as the developer user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KzXHZtAIl16wK63KonTqJw.png" /></figure><p>After the user is successfully created, log out and log back in with the root user. Then select “Create new group”. Here, I will create an example group named “Jenkins Group”; you can adjust the name based on your team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dakMKhbBnTsFyuo2ybDiWw.png" /></figure><p>Select the user that was previously registered and make them the owner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PS8HaVlSp2R5i-BdPy_PMA.png" /></figure><p>Log out, then log in using the user we registered (ahmedyusuf). Enter the Jenkins Group. After that, create a project named “belajar-jenkins”; you can adjust the name based on the project you are working on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEyXPAJXqA7dKS76mmBKmg.png" /></figure><p>After that, go to the profile page (top right corner) &gt; Settings &gt; Access Tokens, then create a token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oVfhehgJAFAPaISg-gwwaA.png" /></figure><p>Here we will obtain an access token that will be used for the webhook. Copy the access token and note it down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*15O1wNMrIArwD3TMzzSuTg.png" /></figure><p>C. GitLab Online</p><p>Open the GitLab website at <a href="http://gitlab.com/">http://gitlab.com</a>, select Account &gt; Settings, then select the Access Tokens menu on the left. Create a token and copy it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wjb74w4fkI8amVSRzKmFGA.png" /></figure><p>Click “Create personal access token”, and immediately save the token key in a note. This way, we have saved the tokens from both GitLab offline (docker) and GitLab online in our note.D. Setting Jenkins</p><p>Go back to the Jenkins container, open the Jenkins container logs to get the initial password for login.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SuMQcD82FMZhsZ-eN5q_bg.png" /></figure><p>Open the Jenkins website at <a href="http://localhost:8080/">http://localhost:8080</a> and enter the password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Nqi1YXlcd39zq-V-FS-vQ.png" /></figure><p>After logging in, proceed by installing the suggested plugins. Here, we will need several plugins to be installed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TV4zDzotcEcCAabRa1Axjg.png" /></figure><p>Wait for the loading to complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNyqfUI4YuLWIsrkSRH4lg.png" /></figure><p>Next, install the Maven Integration plugin from the Plugin Manager menu to integrate our Maven project with Jenkins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtdJ6R6DZIDpoyJ_ieIURA.png" /></figure><p>Also install the GitLab Hook plugin to enable the GitLab webhooks feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8T9jPE7vGXenlr4pPmngQ.png" /></figure><p>E. Create credential</p><p>Here we will need credentials for both GitLab online and offline (docker). Enter the two API tokens for GitLab Offline and GitLab Online that we generated earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5X3ihaSnjxUQ1vZU-JgXcw.png" /></figure><p>Also create a GitLab username and password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BiyfCCACYKGLMNyoIWIefw.png" /></figure><p>So we have 2 credentials for GitLab online and 2 credentials for GitLab docker, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-RRVF8CZ4RkEg2JGGjilg.png" /></figure><p>F. Setup connection</p><p>Next, we need to ensure that the API tokens we entered can connect to both GitLab Online and GitLab Offline (Docker). For GitLab Docker, I am using the host URL <a href="http://gitlab/">http://gitlab</a> because the container runs with the name gitlab, so we can access it based on the container name. Make sure both connections are successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPL3yAoxYQKQtGDIiTmTRA.png" /></figure><p>G. Open gitlab docker</p><p>Copy the project URL from the top right corner by clicking the “Clone” button, then choose the “Git” option (not the SSH one).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dU1XIS9EmAAwmtNQBmsAiA.png" /></figure><p>Create a project in Jenkins, and select Git for source code management. Enter both repository URLs based on the URLs from GitLab online and offline. Here, in the first form, I set GitLab offline as the origin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWH-ZXH1z_4iWejHXFr4gQ.png" /></figure><p>In the Build Trigger section, set “Build when a change is pushed to GitLab” so that if there is a push to the GitLab offline repository, a push event trigger will occur to GitLab online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2plBaL6OCcF8ZV8U9kCJQ.png" /></figure><p>In the Build section, set Maven as follows. This ensures that before pushing to GitLab online, a Maven install will be performed to verify that the source code can be installed successfully and the unit tests run normally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbu1S6nkwfy6u2pgJQ-eZA.png" /></figure><p>In the Post-build Actions section, add Git Publisher. Here, we will configure it to push to the remote GitLab online repository only if the source code is successfully built.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TnbheRkHRidQp6dCUKVt7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ANjhYJDcceJYdoWZ2WQCiw.png" /></figure><p>H. Setting Webhook in GitLab docker</p><p>Go back to GitLab offline, navigate to Settings &gt; Integration.</p><p>Enter the URL as specified in the build trigger section in the previous Jenkins menu. Here, we will set up the webhook URL configuration in Jenkins. For the URL format, enter it as follows: <a href="http://[username_developer]:[password]@[jenkins_container_name]:[jenkins_port]/[project_name].">http://[username_developer]:[password]@[jenkins_container_name]:[jenkins_port]/[project_name].</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8T6x_ckMdF2_vI6EflxFsQ.png" /></figure><p>Test the webhook and ensure you get a 200 status code.</p><p>I. Setup Git in the Jenkins Docker container</p><p>To allow Jenkins to push to GitLab online, we need to generate an RSA key as a credential to enable connectivity.</p><p>Enter the Jenkins container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eis1Zu5OHK9mc5rL_vQBSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d67Z23A7c9qzvyfQEwR2pA.png" /></figure><p>Generate an RSA key using your GitLab online username and password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFq0XjOovjwoIMO5CXmRZA.png" /></figure><p>Add the public key to SSH keys in GitLab online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQZUpq_54obzdF0RdniZew.png" /></figure><p>Perform a git clone test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HiGSHDA1wT48mOszuafTw.png" /></figure><p>Create a README file and push it to the master branch. Ensure the master branch is successfully created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4Bcu14L0ng3iYLPKpH4PA.png" /></figure><p>Change the setting to unprotect the master branch in GitLab Online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLlvbPGEEefUOaV8muxFYA.png" /></figure><p>II. Setup project on the host PC</p><p>Here we will test pushing a Maven project to GitLab offline. The expectation is that Jenkins will receive an event from GitLab offline through webhooks and then perform a git push to GitLab online. I already have the source code on my local laptop, and it has been initialized with the GitLab offline project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TSjDrGRSc44Mx9z-EPXYdA.png" /></figure><p>Perform a git push.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BacMjjgg3Z15e__Y6SDyoA.png" /></figure><p>Check in the Jenkins console. There will be a message indicating that the Maven project was successfully built and pushed to GitLab online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FvYmieLgkouGecvLxsmSrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qweOfTeWDScH9HXzSHTBxw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b1096996bfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cara Monitoring Service Springboot dengan Micrometer, Prometheus dan Grafana]]></title>
            <link>https://ahmedyusuf.medium.com/cara-monitoring-service-springboot-dengan-micrometer-prometheus-dan-grafana-ef51c96f55eb?source=rss-8ef59354fdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef51c96f55eb</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Yusuf Fachroni]]></dc:creator>
            <pubDate>Fri, 12 Mar 2021 16:04:32 GMT</pubDate>
            <atom:updated>2021-03-25T02:02:38.652Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cara Monitoring Java Spring Boot dengan Micrometer, Prometheus dan Grafana</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFmRzOieEN4IrtqL4tJxHg.png" /><figcaption>contoh monitoring pada Grafana</figcaption></figure><p>Dalam lingkup dunia programming, pasti semuanya pernah mengalami masa-masa dimana servicenya mengalami kendala pada performa, mulai dari naiknya CPU, Memory, dan sebagainya, sehingga mengakibatkan service mengalami penurunan jumlah traksaksi per detik (TPS) atau bahkan sampai hang.</p><p>Banyak faktor yang menyebabkan menurunnya performa sebuah service, mulai dari faktor eksternal seperti kondisi kesehatan server dan jaringan, juga faktor internal yaitu pada service itu sendiri.</p><p>Monitoring adalah hal yang sangat penting untuk mengetahui metrics dan health service kita pada server lab maupun production, sehingga apabila terjadi penurunan performa kita bisa lebih mudah untuk mencari tahu pola yg membuat aplikasi tidak berjalan secara optimal, serta memberi tahu jika terjadi perilaku yang tidak wajar, untuk itulah kita perlu menambahkan fitur monitoring pada service kita, salah satunya menggunakan Micrometer, Prometheus, dan Grafana. <a href="https://micrometer.io/">Micrometer</a> untuk mengekspos metrics pada aplikasi kita, <a href="https://prometheus.io/">Prometheus</a> untuk menampung metrics data, dan G<a href="https://grafana.com/">rafana</a> untuk mempermudah membaca metricsnya dengan memvisualisasikan pada tampilan grafis.</p><p>Disini kita akan belajar cara setup Micrometer, Prometheus dan Grafana pada service Java Spring boot, pastikan anda sudah punya terbiasa dalam membuat aplikasi Java menggunakan framework Spring Boot serta menjalankan docker.</p><p>Pertama, tambahkan dependency Prometheus dan Springboot Actuator di pom.xml</p><pre><em>&lt;! — spring actuator →<br> </em>&lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;<br> &lt;/dependency&gt;</pre><pre><em>&lt;! — micrometer →<br></em> &lt;dependency&gt;<br> &lt;groupId&gt;io.micrometer&lt;/groupId&gt;<br> &lt;artifactId&gt;micrometer-registry-prometheus&lt;/artifactId&gt;<br> &lt;/dependency&gt;</pre><p>Kemudian tambahkan baris berikut di application.properties, anda bisa melimitasi beberapa sesuai dengan kebutuhan misal health, info, metric, dll. Namun disini kita akan melakukan include all</p><pre><em>management.endpoints.web.exposure.include</em>=*</pre><p>Jalankan modul java, dan cek pada endpoint actuator. Disini port tomcat http server saya ubah ke port 5000 karena port default (8080) sudah digunakan pada program lain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0p4BOUBMX5oGakcAxP3wdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qaFrzPy8ByK6f356qEcxaw.png" /><figcaption>Endpoint actuator aktif, kita bisa mengakses beberapa fungsi pada daftar link endpoint yang ditampilkan</figcaption></figure><p>Buat sebuah file bernama prometheus.yml dengan isi berikut</p><pre>global:<br>  scrape_interval: 10s</pre><pre>scrape_configs:<br>  - job_name: &#39;spring_micrometer&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    scrape_interval: 5s<br>    static_configs:<br>      - targets: [&#39;192.168.1.10:5000&#39;]</pre><p>Disini kita akan mengkonfigurasikan endpoint target yang akan di scrape, yaitu url http actuator pada service java kita (192.168.1.10:5000). Kemudian buat file docker-compose.prometheus-grafana.yml dengan isi berikut</p><pre>version: &quot;3.7&quot;<br>services:<br>  # -------------------<br>  # PROMETHEUS<br>  # -------------------<br>  prometheus:<br>    container_name: prometheus<br>    image: prom/prometheus<br>    ports:<br>      - 9090:9090<br>    volumes:<br>      - $PWD/prometheus.yml:/etc/prometheus/prometheus.yml<br>    environment:<br>      TZ: Asia/Jakarta<br>    networks:<br>      - c0deslinger</pre><pre>  # -------------------<br>  # GRAFANA<br>  # -------------------<br>  grafana:<br>    container_name: grafana<br>    image: grafana/grafana<br>    ports: <br>      - 9100:3000<br>    environment:<br>      TZ: Asia/Jakarta<br>    networks:<br>      - c0deslinger</pre><pre>networks: <br>  c0deslinger:<br>    name: c0deslinger</pre><p>Pastikan kedua file tersebut berada di dalam folder yang sama, lalu jalankan docker Prometheus dan Grafana dengan perintah</p><pre>docker-compose -f docker-compose.prometheus-grafana.yml up -d</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1GnQKe5bqZAum994O1Fgw.png" /></figure><p>Cek endpoint Prometheus, lalu masuk ke tab Status &gt; Targets. Disini kita bisa melihat bahwa Prometheus dan Actuator berhasil terkoneksi</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgumIcnxoFf0GKsyPB2f6Q.png" /></figure><p>Selanjutnya kita coba cek endpoint grafana</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lieqcKeA8sypae88kDxiHA.png" /></figure><p>Saat pertama kali login, masukkan user &amp; password admin:admin, kemudian nanti akan muncul form lagi untuk mengatur ulang password, anda bisa memasukkan password baru atau skip. Berikut adalah tampilan dashboard pertama kali masuk ke Grafana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32FE5_MFOaH5WlkBIgXDcw.png" /></figure><p>Selanjutnya mari kita atur dashboard untuk monitor program kita. pertama-tama, masuk ke Configuration &gt; Data Source. Klik add datasource, lalu pilih Prometheus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJNxb4E3eXvyYVxMtG3Mlg.png" /></figure><p>Pada form ini, kita perlu mengisi url Prometheus. Pada file docker compose yang kita gunakan sebelumnya, kita sudah mengatur agar container Prometheus dan Grafana berjalan di satu network yang sama, yaitu network c0deslinger, sehingga kita bisa memanggil endpoint Prometheus berdasarkan nama container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nkg7KO4-SiXJZtIA_K2hg.png" /></figure><p>Setelah itu klik tombol Save &amp; Test, dan pastikan muncul notifikasi “Data source is working”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZtvYh2_Dt26nYox6nvvnA.png" /></figure><p>Selanjutnya kita buat dashboard, masuk ke menu Dashboard &gt; Manage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIr0BqMtYcgeBz4PfKiMDw.png" /></figure><p>Buat panel</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKfDBs7-EwoVCiadx651Kg.png" /></figure><p>Selanjutnya, di menu ini kita bisa menambahkan metric apa saja yg akan di monitor, misal kita menambahkan process cpu usage</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3N2s1a1OcdWZjJZ-YrZY0A.png" /></figure><p>Selanjutnya simpan dashboard, beri nama sesuai project atau konteks dari project tersebut</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZvaDw0UBfPDJG9Wp5gEIA.png" /></figure><p>Sehingga pada dashboard akan muncul display yg sudah kita tambahkan tadi</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bqDyRPXkxGCGlWklSYtUw.png" /></figure><p>Kita juga bisa menambahkan dan mengubah nama panel agar mudah dalam memonitor program kita</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3T4WvJ_BO-SGfVQoP3JRCA.png" /></figure><p>Selain itu, kita juga bisa menggunakan template dashboard yang sudah tersedia di website <a href="https://grafana.com/grafana/dashboards">Grafana Community</a>, sehingga kita bisa memonitor secara langsung tanpa repot-repot membuat panel satu-satu. Berhubung disini kita menggunakan Java Springboot, kita bisa menggunakan template <a href="https://grafana.com/grafana/dashboards/4701">dashboard ini</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpaaBKGyOu8mMYyuHem8bQ.png" /></figure><p>Klik download JSON di pojok kanan bawah, lalu kita import ke Grafana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*1md_vW49CVNcJkHVT2qaOQ.png" /></figure><p>Dan berikut hasilnya, mudah bukan?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFmRzOieEN4IrtqL4tJxHg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef51c96f55eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Simple Http Server with Kotlin]]></title>
            <link>https://ahmedyusuf.medium.com/build-simple-http-server-with-kotlin-48e01cf48218?source=rss-8ef59354fdda------2</link>
            <guid isPermaLink="false">https://medium.com/p/48e01cf48218</guid>
            <category><![CDATA[http-server]]></category>
            <category><![CDATA[spark-java]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Yusuf Fachroni]]></dc:creator>
            <pubDate>Sat, 05 Oct 2019 08:05:21 GMT</pubDate>
            <atom:updated>2019-10-05T08:15:34.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YK5PLgDKciZ0J66Ilvb9wQ.png" /></figure><p>Add Sparkjava and SLF4J dependencies on your pom.xml</p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;com.sparkjava&lt;/groupId&gt;<br>        &lt;artifactId&gt;spark-kotlin&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0-alpha&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.slf4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;<br>        &lt;version&gt;1.7.5&lt;/version&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.slf4j&lt;/groupId&gt;<br>        &lt;artifactId&gt;slf4j-simple&lt;/artifactId&gt;<br>        &lt;version&gt;1.6.4&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>Now, let’s create the MyHttpServer class. This class will used for configuring the http server it self.</p><pre>class MyHttpServer {<br>    companion object{<br>        var instance = MyHttpServer()<br>    }<br><br>    init {<br>        val port = 1337<br>        val httpService = Service.ignite()<br>        httpService.port(port)<br>        httpService.threadPool(350)<br>        httpService.internalServerError(&quot;Error : 500 internal error&quot;)<br><br>        httpService.get(&quot;/myhttpserver&quot;, MyHttpRoute())<br>        <em>println</em>(&quot;Http server running on port : &quot;+port)<br>    }<br>}</pre><p>As you can see, we are using port 1337 for port binding of http server, and set 350 thread’s maximum for thread pooling in every request.</p><p>Let’s continue with create MyHttpRoute class. This class will used to handle http request and response. Below is the example how to fetch all http get request params and do process for each of the items.</p><pre>class MyHttpRoute : Route {<br>    override fun handle(request: Request, response: Response): Any {<br>        var respBody = &quot;Params: &lt;br&gt;&quot;<br>        var sumResult = 0<br>        request.queryParams().<em>forEach </em><strong>{<br>            </strong>respBody += <strong>it</strong>+&quot; &quot;+request.queryParams(<strong>it</strong>)+&quot;&lt;br&gt;&quot;<br>            sumResult = Process.sum(sumResult, request.queryParams(<strong>it</strong>).<em>toInt</em>())<br>        <strong>}<br>        </strong>response.body(respBody+&quot;Sum result: &quot;+sumResult)<br>        return response.body()<br>    }<br>}</pre><p>And here is the Process class. This class has one static method “sum” for return sum the value of 2 variables.</p><pre>class Process {<br>    companion object{<br>        fun sum(num1 : Int, num2 : Int) : Int {<br>            return num1 + num2<br>        }<br>    }<br>}</pre><p>So, when we access the http with param of integer, the server with give return the sum of all parameter. Let’s check it out</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*98T1wu6ZeztURo6c0YLzeg.png" /></figure><p>You can see the full project on: <br><a href="https://github.com/c0deslinger/kotlin-httpserverspark">https://github.com/c0deslinger/kotlin-httpserverspark</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48e01cf48218" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>