<?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 Sumit Sapkota on Medium]]></title>
        <description><![CDATA[Stories by Sumit Sapkota on Medium]]></description>
        <link>https://medium.com/@sumitsapkota?source=rss-4f45602cb62f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g_TheEHtcbVsT7nIEI-a_A.jpeg</url>
            <title>Stories by Sumit Sapkota on Medium</title>
            <link>https://medium.com/@sumitsapkota?source=rss-4f45602cb62f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:40:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumitsapkota/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[Complete Guide to Build Authentication system with Amplify and Next.js]]></title>
            <link>https://articles.readytowork.jp/complete-guide-to-build-authentication-system-with-amplify-and-next-js-51a9ab218f2d?source=rss-4f45602cb62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/51a9ab218f2d</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[aws-amplify]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Sumit Sapkota]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 02:56:42 GMT</pubDate>
            <atom:updated>2023-09-26T02:56:42.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAl2R87YVquElIMTzxN1ug.jpeg" /></figure><p>An efficient authentication system is essential to the security and usability of online applications in today’s networked digital environment. This post will show you how to utilize AWS Amplify and Next.js to easily develop a strong authentication system, giving you the power to design a frictionless registration and login process that improves both security and developer experience.</p><p>Are you sick of battling web app authentication? Would you like to integrate Amplify into your Next.js projects? You’re in the proper location! This thorough guide explains how to use AWS Amplify to implement an authentication mechanism into your Next.js applications. You can quickly create an authentication flow with the help of these step-by-step instructions!</p><p><strong>Table of Contents:</strong></p><ol><li>Setting up AWS Amplify CLI</li><li>Build Amplify Authentication Service</li><li>Creating a Next.js Project</li><li>Implementing Amplify Default User Sign-In and Sign-Up</li><li>Implementing Custom User Sign-In and Sign-Up</li><li>Retrieving User Information</li></ol><p><strong>Make sure you have the following prerequisites in place before we start the implementation:</strong></p><ul><li>Basic Understanding of React.js and Next.js</li><li>An AWS account</li><li>Nodejs and NPM in your local machine</li></ul><h3>Setting up AWS Amplify CLI</h3><p>First, you need to have an AWS account. Now you need to install amplify CLI on your local machine, to do that runnpm install -g @aws-amplify/cli Next, run amplify configure This will automatically open up the AWS console to make sure you have an account and are signed in. After that, you can switch back to your code editor, press <strong>enter</strong>, and select your region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRbhMKxovf_R_u8Rg9W6vw.jpeg" /></figure><p>And you will be redirected to complete the user creation in the AWS console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JLZoI5TQXCi31sZVJaZSA.jpeg" /></figure><p>In the next step, you will see the permission level. Select attach policies directly, For our Amplify app, we will go with AdministratorAccess-Amplify (set by default). Select <strong>Next </strong>to continue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EqiR4nMSYkQsVihcjvILHQ.jpeg" /></figure><p>Finally, review the changes the confirm the IAM user Creation by clicking in Create User.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdXGrd-w2OcW6oAM-JDi1A.jpeg" /></figure><p>In the next page, you will see the IAM users and you can find recently created user in this page called auth-root</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ICr8mVOUkeB5WrFSZt4ww.jpeg" /></figure><p>Now we need to generate Access Key and Secret Key in order to authenticate Amplify CLI.</p><p>Click on your IAM user and select Security Credential tab and scroll down till you see Access Keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6BP4L649RLWl4cKFKz9__w.jpeg" /></figure><p>Now create a new Access Key and Select the use case Command Line Interface (CLI) . It will generate an Access Key and Access Secret Key for your IAM user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gTnRjqa0dnjamJG3YUl-_Q.jpeg" /></figure><p>Now use these keys in your CLI to authenticate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jug4GbIye3vkti3jIO1YpQ.jpeg" /></figure><p>That’s it for the Amplify CLI configuration in your Terminal.</p><p>Now we can move on to the next step.</p><h3>Build Amplify Authentication Service</h3><p>Now, login to the AWS console and Search for Amplify service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9Wc_HFYDflGDs8I-dwmmw.jpeg" /></figure><p>Now click on Get Started and start creating your new Amplify App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-_bKZLB6KHQ2K7diUuadw.jpeg" /></figure><p>Let&#39;s get started with building our App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZcPZqmmgI4k4HEl4WQfxg.jpeg" /></figure><p>Now Give your app a name and confirm the deployment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGZ2ALmJG1aA5MO0J_y7Dw.jpeg" /></figure><p>After deployment is successful you will see the below screen now you need to launch Amplify studio</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2BGs5xtSXWqXA73doCd_w.jpeg" /></figure><p>Launching Studio will bring you to the Amplify Studio page. Amplify studio has many other functions like Data, Functions, Storage etc but for now we will go into authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JlSJOxThYJdZupFBQlfRFA.jpeg" /></figure><p>Now Enable Authentication and It will redirect you to the Auth setup page.</p><p>Next, you need to configure your authentication system. In the first step, you can configure the Login mechanism and you can add as many mechanisms as you want like login with email, google, apple, facebook etc. In the Second part, you need to configure user signup attributes, these are the fields that the user is required to fill during signup. It provides many more config settings like password requirements and verification message settings. So, feel free to express the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GONT2oRo0DKIdV6s3fWVqw.jpeg" /></figure><p>Here I have enabled email and Google login, For Google login you need to provide Client ID and Client Secret. And I have added two attributes Phone Number and Name for Signup.</p><p>Next, Deploy the authentication service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOp9uKR-G74Kz24kNW33Hg.jpeg" /></figure><p>After your Authentication service has been deployed to the AWS server. Now you can pull this service in your next.js app and use the service.</p><h3>Creating and Configuring Next.js Project</h3><p>Let’s create a next.js project by using the command npx create-next-app@v12 . After successfully creating a Next.js project let’s install the amplify dependencies.</p><p>npm install aws-amplify @aws-amplify/ui-react</p><p>@aws-amplify/ui-react Is the UI component library provided by the AWS which makes building UI seamless for us.</p><p>Now, it’s time to pull the auth configuration we created in the previous app to our app. Using the below command, this command was given to us when the auth service was deployed successfully. Look at the most recent image above.</p><pre>amplify pull - appId d3u3ibrthnx3za - envName staging</pre><p>This code will pull all the auth configurations to your next.js app but before pulling it will ask some question</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0l4lIVkPXYGY-DJV7euo8A.jpeg" /></figure><p>This will add amplify directory in your project root and also a file called aws-exports.js which contains the credentials for AWS auth app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O8PLMG3YBQAq0FMhkTR79g.jpeg" /></figure><p>Now, let’s get started with the Coding part.</p><p>First, we need to add some configuration to your pages/_app.tsx file. This will add amplify to your Project and we have also imported aws-amplify css which will help us build beautiful UI easily.</p><pre>import &#39;../styles/globals.css&#39;<br>import type { AppProps } from &#39;next/app&#39;<br>import { Amplify } from &#39;aws-amplify&#39;<br>import awsconfig from &quot;../aws-exports&quot;<br>import &quot;@aws-amplify/ui-react/styles.css&quot;;<br><br><br>Amplify.configure({ ...awsconfig, ssr: true });<br><br>function MyApp({ Component, pageProps }: AppProps) {<br>  return &lt;Component {...pageProps} /&gt;<br>}<br><br>export default MyApp</pre><p>Let’s create a page called auth/index.tsx in pages directory and add the following code.</p><pre>import React from &quot;react&quot;;<br>import styled from &quot;styled-components&quot;;<br>import { Authenticator } from &quot;@aws-amplify/ui-react&quot;;<br><br>const Container = styled.div`<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>  height: 100vh;<br>`;<br><br>const Authentication = () =&gt; {<br>  return (<br>    &lt;Container&gt;<br>      &lt;Authenticator&gt;<br>        {({ signOut, user }) =&gt; (<br>          &lt;main&gt;<br>            &lt;h1&gt;Hello, {user?.username}!&lt;/h1&gt;<br>            &lt;button onClick={signOut}&gt;Sign out&lt;/button&gt;<br>          &lt;/main&gt;<br>        )}<br>      &lt;/Authenticator&gt;<br>    &lt;/Container&gt;<br>  );<br>};<br><br>export default Authentication;</pre><p>We created an Authenticator component for the homepage so that the user is required to create an account or log in to see the content. Run npm run dev to start the developer server again and open <a href="http://localhost:3000/">http://localhost:3000</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NDHy2zGAdZZxKNG3kk6Vw.jpeg" /></figure><p>Now, create an account using the attributes you provided in your auth service and try to sign in. You will be presented with the greeting indicating that you have successfully authenticated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NDHy2zGAdZZxKNG3kk6Vw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0JQ5U-r2mTA9Qay2XcwOw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vVQdbt32yDDpYZEuv9VBA.jpeg" /></figure><p>Tada, You have successfully implemented an Authentication service using Amplify and Next.js.</p><p>However, we will not stop here. If you have a pre-built login and signup page. You can implement login and signup in your own components. We will see how!</p><h3>Implementing Custom User Sign-In and Sign-Up</h3><p>For this, I have created custom-signup , confirm-email, custom-login pages in my project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Rdu-SDfkLIRzFXr7xPPNA.jpeg" /></figure><p>For Custom Signup Page:</p><pre>import { Button, Input, Link } from &quot;@aws-amplify/ui-react&quot;;<br>import { notification } from &quot;antd&quot;;<br>import { Auth } from &quot;aws-amplify&quot;;<br>import { useRouter } from &quot;next/router&quot;;<br>import React, { useState } from &quot;react&quot;;<br>import styled from &quot;styled-components&quot;;<br><br>const Container = styled.div`<br>  display: flex;<br>  flex-direction: column;<br>  justify-content: center;<br>  align-items: center;<br>  height: 100vh;<br>  background-color: white;<br>  color: black;<br>  form {<br>    width: 50%;<br>  }<br>  input {<br>    margin-top: 20px;<br>    margin-bottom: 20px;<br>  }<br>`;<br><br>const Signup = () =&gt; {<br>  const [email, setemail] = useState(&quot;&quot;);<br>  const [password, setPassword] = useState(&quot;&quot;);<br>  const [name, setname] = useState(&quot;&quot;);<br>  const [phone, setPhone] = useState(&quot;&quot;);<br>    const router = useRouter()<br>  const handleSubmit = async (e: any) =&gt; {<br>    e.preventDefault();<br>    try {<br>      await Auth.signUp({<br>        username: email,<br>        password: password,<br>        attributes: {<br>          email: email,<br>          name: name,<br>          phone_number: phone,<br>        },<br>      });<br>      notification.success({<br>        message: &quot;User created successfully&quot;,<br>      });<br>      router.push(`/confirm-email?user=${email}`)<br>    } catch (error) {<br>      notification.error({<br>        message: `Failed to create user ${error}`,<br>      });<br>    }<br>  };<br>  return (<br>    &lt;Container&gt;<br>      &lt;div&gt;AWS custom signup&lt;/div&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;Input<br>          name=&quot;Name&quot;<br>          placeholder=&quot;Enter Name&quot;<br>          required={true}<br>          type=&quot;text&quot;<br>          onChange={(e) =&gt; setname(e.target.value)}<br>        /&gt;<br>        &lt;Input<br>          name=&quot;Email&quot;<br>          placeholder=&quot;Enter Email&quot;<br>          required={true}<br>          type=&quot;email&quot;<br>          onChange={(e) =&gt; setemail(e.target.value)}<br>        /&gt;<br>        &lt;Input<br>          name=&quot;Password&quot;<br>          placeholder=&quot;Enter Password&quot;<br>          required={true}<br>          type=&quot;password&quot;<br>          onChange={(e) =&gt; setPassword(e.target.value)}<br>        /&gt;<br>        &lt;Input<br>          name=&quot;Phone&quot;<br>          placeholder=&quot;Enter Phone number&quot;<br>          required={true}<br>          type=&quot;text&quot;<br>          onChange={(e) =&gt; setPhone(e.target.value)}<br>        /&gt;<br>        &lt;Button type=&quot;submit&quot;&gt;Create Account&lt;/Button&gt;<br>      &lt;/form&gt;<br>      &lt;Link href={&quot;/custom-login&quot;}&gt;Go to Login page&lt;/Link&gt;<br>    &lt;/Container&gt;<br>  );<br>};<br><br>export default Signup;</pre><p>We will make user of Auth method that is imported from amplify library to the Signup user.</p><p>After signup is complete, we will redirect the user to the email verification page, Verification code will be sent to the registered email.</p><pre>import { Button, Input } from &quot;@aws-amplify/ui-react&quot;;<br>import { notification } from &quot;antd&quot;;<br>import { Auth } from &quot;aws-amplify&quot;;<br>import { useRouter } from &quot;next/router&quot;;<br>import React, { useState } from &quot;react&quot;;<br>import styled from &quot;styled-components&quot;;<br><br>const Container = styled.div`<br>  display: flex;<br>  flex-direction: column;<br>  justify-content: center;<br>  align-items: center;<br>  height: 100vh;<br>  background-color: white;<br>  color: black;<br>  form {<br>    width: 50%;<br>  }<br>  input {<br>    margin-top: 20px;<br>    margin-bottom: 20px;<br>  }<br>`;<br><br>const Login = () =&gt; {<br>  const [code, setCode] = useState(&quot;&quot;);<br>  const router = useRouter()<br>  const {query} = router<br>  const user = query.user<br>  const handleSubmit = async (e: any) =&gt; {<br>    e.preventDefault();<br>    try {<br>      await Auth.confirmSignUp(user, code);<br>      notification.success({<br>        message: `User verified successfully, now you can login`,<br>      });<br>      router.push(&quot;/custom-login&quot;)<br>    } catch (error) {<br>      notification.error({<br>        message: `Failed to verify user ${error}`,<br>      });<br>    }<br>  };<br>  return (<br>    &lt;Container&gt;<br>      &lt;div&gt;Confirm Email&lt;/div&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;Input<br>          name=&quot;Verification COde&quot;<br>          placeholder=&quot;Enter Verification Cdde&quot;<br>          required={true}<br>          type=&quot;text&quot;<br>          onChange={(e) =&gt; setCode(e.target.value)}<br>        /&gt;<br>        &lt;Button type=&quot;submit&quot;&gt;Verify My Account&lt;/Button&gt;<br>      &lt;/form&gt;<br>    &lt;/Container&gt;<br>  );<br>};<br><br>export default Login;</pre><p>Similarly, custom-login page</p><pre>import { Button, Input } from &quot;@aws-amplify/ui-react&quot;;<br>import { notification } from &quot;antd&quot;;<br>import { Auth } from &quot;aws-amplify&quot;;<br>import Link from &quot;next/link&quot;;<br>import React, { useEffect, useState } from &quot;react&quot;;<br>import styled from &quot;styled-components&quot;;<br><br>const Container = styled.div`<br>  display: flex;<br>  flex-direction: column;<br>  justify-content: center;<br>  align-items: center;<br>  height: 100vh;<br>  background-color: white;<br>  color: black;<br>  form {<br>    width: 50%;<br>  }<br>  input {<br>    margin-top: 20px;<br>    margin-bottom: 20px;<br>  }<br>`;<br><br>const Login = () =&gt; {<br>  const [email, setemail] = useState(&quot;&quot;);<br>  const [password, setPassword] = useState(&quot;&quot;);<br>  const [isLoggedIn, setisLoggedIn] = useState(false);<br>  const [user, setUser] = useState&lt;{name:string} | null&gt;(null)<br>  const handleSubmit = async (e: any) =&gt; {<br>    e.preventDefault();<br>    try {<br>      await Auth.signIn(email, password);<br>      notification.success({<br>        message: &quot;Logged in successfully&quot;,<br>      });<br>      setisLoggedIn(true);<br>    } catch (error) {<br>      notification.error({<br>        message: `Failed to login ${error}`,<br>      });<br>    }<br>  };<br>  useEffect(() =&gt; {<br>    const fetchUsers = async () =&gt; {<br>      const {attributes} = await Auth.currentUserInfo();<br>      setUser(attributes)<br>    };<br>    fetchUsers();<br>  }, [isLoggedIn]);<br><br>  if (isLoggedIn) {<br>    return &lt;Container&gt;Hello, {user?.name}!!!!&lt;/Container&gt;;<br>  }<br><br>  return (<br>    &lt;Container&gt;<br>      &lt;div&gt;AWS custom Login&lt;/div&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;Input<br>          name=&quot;Email&quot;<br>          placeholder=&quot;Enter Email&quot;<br>          type=&quot;email&quot;<br>          onChange={(e) =&gt; setemail(e.target.value)}<br>        /&gt;<br>        &lt;Input<br>          name=&quot;Password&quot;<br>          placeholder=&quot;Enter Password&quot;<br>          type=&quot;password&quot;<br>          onChange={(e) =&gt; setPassword(e.target.value)}<br>        /&gt;<br>        &lt;Button type=&quot;submit&quot;&gt;Login&lt;/Button&gt;<br>      &lt;/form&gt;<br>      &lt;Link href={&quot;/custom-signup&quot;}&gt;Go to Signup page&lt;/Link&gt;<br>    &lt;/Container&gt;<br>  );<br>};<br><br>export default Login;</pre><p>Let’s see the above code output in UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wT_zEQD3Zb7pk9Px3xDD3Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEVsdFw0cKahTwv6Cn-g1A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0wowGg_WD9jwDUjlsbVeg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBlUrD8Ul4C13nxojIxs2A.jpeg" /></figure><p>That’s all for building a complete authentication system using Amplify and Next.js.</p><p>You can find the code in the below GitHub repository for references.</p><p><a href="https://github.com/sumitsapkota75/amplify-next.js-auth">GitHub - sumitsapkota75/amplify-next.js-auth: Complete Authentication system build with Amplify and Next.js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51a9ab218f2d" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/complete-guide-to-build-authentication-system-with-amplify-and-next-js-51a9ab218f2d">Complete Guide to Build Authentication system with Amplify and Next.js</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elevating Code Quality: Ultimate Guide To Integrate SonarQube with CircleCI for Effective Code…]]></title>
            <link>https://articles.readytowork.jp/elevating-code-quality-ultimate-guide-to-integrate-sonarqube-with-circleci-for-effective-code-2cd9fcedb9ee?source=rss-4f45602cb62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cd9fcedb9ee</guid>
            <category><![CDATA[circleci]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[sonarqube]]></category>
            <dc:creator><![CDATA[Sumit Sapkota]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 20:32:25 GMT</pubDate>
            <atom:updated>2023-08-29T20:32:25.909Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elevating Code Quality: Ultimate Guide To Integrate SonarQube with CircleCI for Effective Code Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZoXw4pbFD_SHN8PQ3KEZw.jpeg" /></figure><p>In today’s fast-paced software landscape, ensuring your codebase&#39;s reliability, maintainability, and security is paramount. This is where SonarQube comes into play as an invaluable tool that empowers developers to detect and address issues early in the development process, ultimately leading to higher-quality software.</p><p>This article will walk you through the process of seamlessly incorporating SonarQube into your coding routine, allowing you to proactively identify code smells, bugs, vulnerabilities, and other potential pitfalls. Whether you’re a seasoned developer or just starting your coding journey, this guide will equip you with the knowledge and skills to harness the full potential of SonarQube and elevate your coding standards to new heights. Let’s embark on this journey to improve code quality, one line at a time.</p><h3>What is <a href="http://sonarqube.org/">SonarQube</a>?</h3><p>SonarQube is an open-source platform designed to enhance code quality by performing static code analysis and uncovering a wide array of issues and vulnerabilities in software projects. It offers developers and teams an automated way to assess and maintain the health of their codebase throughout the development lifecycle.</p><p>By scanning source code for patterns that indicate potential bugs, security vulnerabilities, code smells, and other code quality issues, SonarQube helps teams identify areas that require improvement, ensuring that best practices are followed. It supports multiple programming languages and integrates seamlessly with various build and Continuous Integration/Continuous Deployment (CI/CD) tools.</p><p>Sonarqube solution provides various features such as:</p><ul><li><a href="https://www.sonarsource.com/products/sonarlint/">SonarLint</a> provides immediate feedback in your IDE as you write code so you can find and fix issues before a commit.</li><li>SonarQube’s <a href="https://docs.sonarsource.com/sonarqube/latest/analyzing-source-code/pull-request-analysis/">PR analysis</a> fits into your CI/CD workflows with SonarQube’s PR analysis and use of quality gates.</li><li><a href="https://docs.sonarsource.com/sonarqube/latest/user-guide/quality-gates/">Quality gates</a> keep code with issues from being released to production, a key tool in helping you incorporate the Clean as You Code methodology.</li><li>The <a href="https://docs.sonarsource.com/sonarqube/latest/user-guide/clean-as-you-code/">Clean as You Code</a> approach helps you focus on submitting new, clean code for production, knowing that your existing code will be improved over time.</li></ul><h3>Sonar Scanner</h3><p>SonarScanner is a command-line tool used to initiate and perform the actual code analysis on your source code. It’s responsible for collecting code and project information, running various code analyzers, and sending the analysis results to the SonarQube platform for aggregation and reporting. SonarScanner can be integrated into your build and CI/CD pipelines, allowing for automated and consistent code analysis as part of your development process.</p><p>In essence, SonarScanner is the tool that you run locally or integrate into your build process to conduct the code analysis, while SonarQube is the platform where the analysis results are aggregated, visualized, and managed. Both components work together to provide developers and teams with the insights needed to improve code quality, identify issues, and make informed decisions regarding code improvements.</p><h3>Quality Gate</h3><p>Quality Gate Profiles in SonarQube define the set of criteria and thresholds that code must meet to be considered of acceptable quality. They serve as a crucial mechanism to ensure that software projects maintain a certain level of quality, security, and reliability throughout their development lifecycle. Quality gates are essential because they prevent the introduction of code with significant issues, vulnerabilities, or technical debt into the codebase. These profiles typically include metrics related to code coverage, code duplication, code complexity, and adherence to coding standards.</p><p>We can fail the CI process if our code does not meet the minimum threshold specified in the Quality gate profile.</p><h4>Sonarqube Server Instance Components</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*FNlvJOSonqOj_N9b6V5CtQ.jpeg" /></figure><ol><li>The SonarQube server runs the following processes:</li></ol><ul><li>A web server that serves the SonarQube user interface.</li><li>A search server based on Elasticsearch.</li><li>The compute engine is in charge of processing code analysis reports and saving them in the SonarQube database.</li></ul><p>2. The database to store the following:</p><ul><li>Metrics and issues for code quality and security generated during code scans.</li><li>The SonarQube instance configuration.</li></ul><p>3. One or more scanners running on your build or continuous integration servers to analyze projects.</p><h3>Integrating SonarQube and SonarScanner into your CircleCI pipeline</h3><ol><li><strong>Set Up SonarQube:</strong></li></ol><p>To set up a sonarqube server I am going to use Compute Engine service in Google Cloud Platform, we can use any cloud service provider for setting up sonarqube server in VPS.</p><p>You can find references for creating Compute Engine in GCP <a href="https://cloud.google.com/compute/docs/instances/create-start-instance">here</a>.</p><p>After creating Compute Engine, SSH into it because we need to install a few things in order to run sonarqube server.</p><p><strong>a. Install Docker and Docker Compose in the Machine/Cloud Instance</strong></p><p>Ref: <a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-compose-on-ubuntu-22-04">https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-compose-on-ubuntu-22-04</a></p><p><strong>b. Upload the following docker-compose code to the Cloud Instance</strong></p><p>Create a file named <em>docker-compose.yml and paste the following code.</em></p><pre>version: &#39;3.9&#39;<br>services:<br>  sonarqube:<br>    image: sonarqube:latest<br>    ports:<br>      - &quot;9000:9000&quot;<br>    environment:<br>      - SONARQUBE_JDBC_USERNAME=sonar<br>      - SONARQUBE_JDBC_PASSWORD=passw0rd<br>      - SONARQUBE_JDBC_URL=jdbc:postgresql://postgres:5432/sonar<br>    networks:<br>      - sonarqube_network<br>postgres:<br>    image: postgres:latest<br>    environment:<br>      - POSTGRES_USER=sonar<br>      - POSTGRES_PASSWORD=passw0rd<br>      - POSTGRES_DB=sonar<br>    networks:<br>      - sonarqube_network<br>networks:<br>  sonarqube_network:</pre><p>The code is pretty straightforward, We have two services called Sonarqube and Postgres we fetch their latest image and map Sonarqube service to use Postgres as a database service. And Sonarqube server will run in port 9000.</p><p><strong>c. Spin up the container</strong></p><p>Now we need to build and run the container using the following command in the directory container <em>docker-compose.yml</em> file and Sonarqube server will run in port 9000</p><pre>sudo docker compose up --buid</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnGqyiUo_N4hVE7EqwSzbQ.jpeg" /></figure><p>The default username and password are “admin” and “admin”</p><p>After successful login, we can see the Sonarqube server Dashboard.</p><p>Now let us create a new project by selecting <strong>“Manually”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMn6d4F7KrCSUKyZmyuDGw.jpeg" /></figure><p>Let us create a new project called “ikata-api”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lswez1B-ZQhRSNJ7C-oxXA.jpeg" /></figure><p>After setting up, it gives the option to analyze the repository. Since CircleCI is not on the options list we will choose the Other CI option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1eovohPpua0kg-rVKfVmig.jpeg" /></figure><p>Now we get some important information about project confirmation. We will need some information from here like SONAR_TOKEN and host_url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9HHmpa038xIfwxdTAMCRg.jpeg" /></figure><p>We are done with the sonarqube server config. Let’s move to the next part setting up circleCI.</p><ol><li><strong>Setup CircleCI and Codebase</strong></li></ol><p>On this side, first, we need to create <em>sonar-project.properties </em>file in the root directory of the project.</p><p>The content of this file will be something like this.</p><pre># Required metadata<br>sonar.projectKey=ikata-api<br>sonar.projectName= ikata api<br>sonar.projectVersion=1.0<br># Comma-separated paths to directories with your source code (excluding test code) and test path<br># . indicates all directories<br>sonar.sources=.<br>sonar.tests=src/test<br>// IP of cloud instance <br>sonar.host.url=http://34.84.156.66:9000<br>// SONAR_TOKEN obtained in previous step<br>sonar.login=sqp_6352eb9f880ea30631e40b831e7f8e8a8c6b974a<br># Comma-separated list of file suffixes for your source code files<br>sonar.sources.inclusions=**/*.go</pre><p>Now let’s create the circleci config file</p><pre>version: 2.1<br>jobs:<br>  build:<br>    docker:<br>      - image: cimg/go:1.16<br>      - image: cimg/mysql:8.0<br>        environment:<br>          MYSQL_ROOT_PASSWORD: password<br>          MYSQL_DATABASE: test_db<br>          MYSQL_USER: user<br>          MYSQL_PASSWORD: passw0rd<br>    parallelism: 1<br>    steps:<br>      - checkout<br>      <br>    # Below two steps are required to setup sonarqube and run sonar scanner<br>      - run:<br>          name: Install SonarQube Scanner<br>          command: |<br>            wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.6.2.2472-linux.zip<br>            unzip sonar-scanner-cli-4.6.2.2472-linux.zip<br>            mv sonar-scanner-4.6.2.2472-linux /home/circleci/sonar-scanner<br>            echo &#39;export SONAR_SCANNER_HOME=/home/circleci/sonar-scanner&#39; &gt;&gt; $BASH_ENV<br>            echo &#39;export PATH=$PATH:$SONAR_SCANNER_HOME/bin&#39; &gt;&gt; $BASH_ENV<br>            source $BASH_ENV<br>            rm sonar-scanner-cli-4.6.2.2472-linux.zip<br>      <br>      # Run SonarQube analysis<br>      - run:<br>          name: SonarQube Analysis<br>          command: |<br>            # You can specify the path to the sonar-project.properties file if not in the root directory:<br>            sonar-scanner -Dsonar.projectSettings=sonar-project.properties<br>      - restore_cache:<br>          keys:<br>            - go-mod-v4-{{ checksum &quot;go.sum&quot; }}<br>      - run:<br>          name: Waiting for MYSQL to be ready<br>          command: |<br>            for i in `seq 1 10`;<br>            do<br>              nc -z 127.0.0.1 3306 &amp;&amp; echo Success &amp;&amp; exit 0<br>              echo -n .<br>              sleep 1<br>            done<br>            echo Failed waiting for MySQL &amp;&amp; exit 1<br>      - run:<br>          name: Build repo<br>          command: |<br>            go build main.go<br>      - save_cache:<br>          key: go-mod-v4-{{ checksum &quot;go.sum&quot; }}<br>          paths:<br>            - &quot;go/pkg/mod&quot;<br>      - run:<br>          name: Start the service<br>          command: ./main<br>          background: true<br>      - run:<br>          name: Validate if the service is working or not.<br>          command: |<br>            sleep 5<br>            curl http://localhost:8080/health-check<br>            <br>workflows:<br>  version: 2<br>  workflow:<br>    jobs:<br>      - build:<br>          context: ikata_api_dev<br>          filters:<br>            branches:<br>              only:<br>                - develop</pre><p>In the above code snippet, we need to look at the first two steps of the build job Install SonarQube Scanner and SonarQube Analysis. Other steps are just regular steps to build and test the service for Golang code.</p><p>Install SonarQube Scanner: This step downloads the Sonarqube binary installs it in the circlci runner and updates the path for the sonar scanner as well.</p><p>SonarQube Analysis : This step runs the sonar scanner by pointing to the Sonarqube configuration file in the project directory.</p><p>Now, whenever we push the code to the develop branch, the Sonarqube analysis will be run in our Sonarqube server.</p><p>After the analysis is completed, we can see a detailed report in the Sonarqube server dashboard in my case it is:</p><p><a href="http://35.190.235.115:9000/">http://35.190.235.115:9000</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KJg9q-FClT6uuxQZWQaGg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykkWOoSYhW_DZCEHBDGr5g.jpeg" /></figure><p>We can see details on each issue create tasks and start working on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPHCOrNO1txj5HthwzGtTg.jpeg" /></figure><p>Now, every time our build job is run code analysis will occur in the Sonarqube server through Circleci.</p><blockquote>If you wanna take a look at the Sonarqube server dashboard below are the credentials</blockquote><blockquote>URL: <a href="http://35.190.235.115:9000/">http://35.190.235.115:9000</a></blockquote><blockquote>Username: admin</blockquote><blockquote>Password: passw0rd</blockquote><p>References:</p><p><a href="https://docs.sonarsource.com/sonarqube/latest/?_gl=1*z6ruj7*_gcl_aw*R0NMLjE2ODk5MzA0OTYuQ2owS0NRancyZWlsQmhDQ0FSSXNBRzBQZjh2WlZYZFZUMUVNbzBYYmQzT3oyc0hZWWVsdmxXbzEtT3hCbjBlLW9DcGhMbzJJcDJwc1Vud2FBdDlNRUFMd193Y0I.*_gcl_au*MTE3NjQwNDYxMi4xNjkwOTgwOTIw*_ga*MjA5MDgyNDc1My4xNjc0NzIzNjYw*_ga_9JZ0GZ5TC6*MTY5MjA3NTk5My4zMC4xLjE2OTIwODEwNzAuNTYuMC4w">Sonarqube Official Docs</a></p><p><a href="https://docs.docker.com/engine/install/debian/">Install Docker and Docker compose in Linux</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cd9fcedb9ee" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/elevating-code-quality-ultimate-guide-to-integrate-sonarqube-with-circleci-for-effective-code-2cd9fcedb9ee">Elevating Code Quality: Ultimate Guide To Integrate SonarQube with CircleCI for Effective Code…</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Allow single email to signup as multiple users in a Firebase project (Google Identity platform)]]></title>
            <link>https://articles.readytowork.jp/allow-single-email-to-signup-as-multiple-users-in-a-firebase-project-google-identity-platform-25fba64599d4?source=rss-4f45602cb62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/25fba64599d4</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[multi-tenant-architecture]]></category>
            <dc:creator><![CDATA[Sumit Sapkota]]></dc:creator>
            <pubDate>Wed, 14 Dec 2022 19:26:49 GMT</pubDate>
            <atom:updated>2022-12-14T19:26:49.890Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vk0oFUMb0fo8rnXI9Iswrg.jpeg" /><figcaption>single tenant vs multi-tenant</figcaption></figure><p>When using firebase as a default authentication service provider in our project we have noticed that an email can only be used once to signup a user. Most of the time, it’s okay. But when the project’s complexity grows, we might need multiple types of users with a single email address.</p><p>Let me explain it with an example,</p><p>Suppose, We have a system where we have a web app for admin and a mobile app for users. Admin can post content from the web app and users can browse those content in a mobile app.</p><p>And our system should allow registering admin and users with the same email address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjWaGdkLQMSjhk3orPnIbw.png" /></figure><p>This is where <em>multi-tenancy</em> comes in.</p><p>Multi tenancy basically allows to reside different component/tenant within same resource.</p><h4>Then what is multi-tenancy?</h4><p>Multi-tenancy is an architecture in which a single instance of a software application serves multiple customers. Each customer is called a <em>tenant</em>. Tenants can be given the ability to customize some parts of the application and restrict from other parts.</p><h3>GCP provides multi-tenancy features through the Google Identity Platform.</h3><p>Identity Platform lets you add Google-grade authentication to your apps and services, making it easier to secure user accounts and securely manage credentials.</p><p>Multi-tenancy takes this concept one step further. Using tenants, you can create unique silos of users and configurations within a single Identity Platform project. These silos might represent different customers, business units, subsidiaries, or some other division. Multi-tenancy is most commonly used in business-to-business (B2B) apps.</p><h4>Coming back to where we started</h4><p>We have to create a system where multiple types of users can signup with a single email in our firebase project with the help of multi-tenancy.</p><h3>Let’s take a look at an example</h3><p>We will be creating two tenants namely clients and users. So, what happens when we signup two users with different tenant Id is it creates user according to the tenant Id and it maintains the individual state with the help of separating tenant Id. When the firebase token is generated while logging in, the provided token contains tenant Id in encoded form just like other properties as claims.</p><p>Prerequisites:</p><ul><li>basic knowledge of firebase authentication</li><li>firebase project with GCP identity platform enabled</li></ul><h3>GCP Setup</h3><ol><li>First things first, we need to enable Identity Platform from Google cloud console.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6SbXyd-NtMLQ-KSHA8Ltuw.jpeg" /></figure><p>2. After enabling the identity platform, we have to enable the desired provider from the providers section. Here I have enabled Email/Password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5u7H9eNlxv0dyCJu4qj3A.jpeg" /></figure><p>3. Now, let’s create multiple tenants according to our requirements. In this case, I am creating two tenants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYMrtPsanuj-GAoXZd2Zrg.jpeg" /></figure><p>We can add multiple tenants which can consist of the same Tenant name and are separated by TenantID.</p><p>The setup related to GCP is almost completed. Now let’s take a look at code implementation.</p><h3>Code Implementation</h3><p>Here, all the operations are similar to the firebase user authentication handler. But instead of performing operations with the firebase client manager, we use the firebase client Tenant Manager.</p><p>We handle all operations like Create user, update user, delete user, send password reset email, set custom claims with firebase Tenant Manager instead of firebase client manager.</p><h4>1. Creating user</h4><p>Let us define a struct called FirebaseService</p><pre>// FirebaseService structure<br>type FirebaseService struct {<br> client *auth.Client<br> logger infrastructure.Logger<br> env    infrastructure.Env<br>}</pre><pre>// CreateUser creates a new user with email and password<br>func (fb *FirebaseService) CreateUser(newUser models.FirebaseAuthUser) (string, error) {<br> TenantID := fb.env.ClientTenantID<br> if newUser.Role == constants.RoleUser {<br>  TenantID = fb.env.UserTenantID<br> }<br> tenantClient, err := fb.client.TenantManager.AuthForTenant(TenantID)<br> if err != nil {<br>  fb.logger.Zap.Errorf(&quot;error initializing tenant client: %v\n&quot;, err)<br>  return &quot;&quot;, err<br> }<br><br> params := (&amp;auth.UserToCreate{}).<br>  Email(newUser.Email).<br>  Password(newUser.Password).<br>  DisplayName(newUser.DisplayName)<br><br> if newUser.Enabled == 0 {<br>  params = params.Disabled(true)<br> }<br> if newUser.Enabled == 1 {<br>  params = params.Disabled(false)<br> }<br> // All tenant-specific operations are exposed via auth.TenantClient<br> user, err := tenantClient.CreateUser(context.Background(), params)<br> if err != nil {<br>  fb.logger.Zap.Errorf(&quot;error creating user: %v\n&quot;, err)<br>  return &quot;&quot;, err<br><br> }<br><br> claims := map[string]interface{}{<br>  &quot;role&quot;:   newUser.Role,<br>  &quot;fb_uid&quot;: user.UID,<br>  &quot;id&quot;:     newUser.UserId,<br> }<br> err = tenantClient.SetCustomUserClaims(context.Background(), user.UID, claims)<br> if err != nil {<br>  return &quot;Error setting custom user claims&quot;, err<br> }<br> return user.UID, err<br>}</pre><p>Here we can see, initially in CreateUser function we get role of user and assign tenant ID as per role. This is to differentiate either “client or user” is being created.</p><p>After that we initialize the tenant client with below line of code</p><pre>tenantClient, err := fb.client.TenantManager.AuthForTenant(TenantID)</pre><p>and then finally we create using with the help of tenant client we just created.</p><pre>user, err := tenantClient.CreateUser(context.Background(), params)<br> if err != nil {<br>  fb.logger.Zap.Errorf(&quot;error creating user: %v\n&quot;, err)<br>  return &quot;&quot;, err<br> }</pre><h4>2. Updating User</h4><pre>// UpdateUser -&gt; update firebase user.<br>func (fb *FirebaseService) UpdateFirebaseAuthUser(uid string, newData models.FirebaseAuthUser) error {<br> TenantID := fb.env.UserTenantID<br> if newData.Role == constants.RoleClient || newData.Role == constants.RoleClientAdmin || newData.Role == constants.RoleClientGeneral {<br>  TenantID = fb.env.ClientTenantID<br> }<br> tenantClient, err := fb.client.TenantManager.AuthForTenant(TenantID)<br> if err != nil {<br>  fb.logger.Zap.Errorf(&quot;error initializing tenant client: %v\n&quot;, err)<br>  return err<br> }<br> user, err := tenantClient.GetUser(context.Background(), uid)<br> if err != nil {<br>  return err<br> }<br> authParams := (&amp;auth.UserToUpdate{})<br> if newData.Email != &quot;&quot; &amp;&amp; newData.Email != user.Email {<br>  authParams = authParams.Email(newData.Email)<br> }<br> if newData.Password != &quot;&quot; {<br>  authParams = authParams.Password(newData.Password)<br> }<br> if newData.DisplayName != &quot;&quot; &amp;&amp; newData.DisplayName != user.DisplayName {<br>  authParams = authParams.DisplayName(newData.DisplayName)<br> }<br> if newData.Enabled == 0 {<br>  authParams = authParams.Disabled(true)<br> }<br> if newData.Enabled == 1 {<br>  authParams = authParams.Disabled(false)<br> }<br> if newData.Role != &quot;&quot; {<br>  claims := map[string]interface{}{<br>   &quot;role&quot;:   newData.Role,<br>   &quot;fb_uid&quot;: uid,<br>   &quot;id&quot;:     newData.UserId,<br>  }<br>  err = tenantClient.SetCustomUserClaims(context.Background(), uid, claims)<br>  if err != nil {<br>   fb.logger.Zap.Info(&quot;Error setting custom user claims::::&quot;, err.Error())<br>   return err<br>  }<br> }<br><br> _, err = tenantClient.UpdateUser(context.Background(), uid, authParams)<br> if err != nil {<br>  fb.logger.Zap.Error(&quot;Update User Firebaser (UpdateUserAuth) ::&quot;, err.Error())<br>  return err<br> }<br> return nil<br>}</pre><p>If we see above block of code and compare with first block there is not much of difference.</p><p>Similar to creating user, we get the updated value of user and then update it with help of tenant manager.</p><pre>_, err = tenantClient.UpdateUser(context.Background(), uid, authParams)<br> if err != nil {<br>  fb.logger.Zap.Error(&quot;Update User Firebaser (UpdateUserAuth) ::&quot;, err.Error())<br>  return err<br> }</pre><h4>3. Set Custom Claims</h4><p>Claims are some variables which are stored as key value pair while creating user and can be extracted later through firebase tokens.</p><p>In order to set custom claims for the multi-tenant user.</p><p>First, let’s create the user with tenant client and after user is created we set custom claim defined as map to the created user thorough tenant client.</p><pre>// All tenant-specific operations are exposed via auth.TenantClient<br> user, err := tenantClient.CreateUser(context.Background(), params)<br> if err != nil {<br>  fb.logger.Zap.Errorf(&quot;error creating user: %v\n&quot;, err)<br>  return &quot;&quot;, err<br><br> }<br><br> claims := map[string]interface{}{<br>  &quot;role&quot;:   newUser.Role,<br>  &quot;fb_uid&quot;: user.UID,<br>  &quot;id&quot;:     newUser.UserId,<br> }<br> err = tenantClient.SetCustomUserClaims(context.Background(), user.UID, claims)<br> if err != nil {<br>  return &quot;Error setting custom user claims&quot;, err<br> }<br> return user.UID, err</pre><h4>4. Generate password reset email</h4><pre>func (fb *FirebaseService) GeneratePasswordResetEmailForUser(email string) (string, error) {<br> tenantClient, err := fb.client.TenantManager.AuthForTenant(fb.env.UserTenantID)<br> if err != nil {<br>  fb.logger.Zap.Errorf(&quot;error initializing tenant client: %v\n&quot;, err)<br>  return &quot;&quot;, err<br> }<br> actionCodeSettings := &amp;auth.ActionCodeSettings{}<br> actionCodeSettings.URL = &quot;http://localhost:3000&quot;<br> actionCodeSettings.HandleCodeInApp = true<br><br> resp, err := tenantClient.PasswordResetLinkWithSettings(context.Background(), email, actionCodeSettings)<br><br> return resp, err<br>}</pre><p>Same goes here, first we initialize tenant client and call method “PasswordResetLinkWithSettings” through tenant client.</p><p>After creating multiple users with single email address, we can update email, change passwords for individual email. There will be no side effects to other email if one is changed.</p><h4>For the frontend implementation:</h4><p>Here I am using Next.js and the config will be as shown below:</p><pre>import { getApps, initializeApp } from &quot;firebase/app&quot;<br>import { getAuth } from &quot;firebase/auth&quot;<br>import { getAnalytics } from &quot;firebase/analytics&quot;<br><br>if (!getApps.length) {<br>  initializeApp({<br>    apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,<br>    authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,<br>    databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,<br>    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,<br>    storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,<br>    messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGE_SENDER_ID,<br>    appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,<br>    measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,<br>  })<br>}<br><br>const tenantId = process.env.CLIENT_TENANT_ID<br><br>const auth = getAuth()<br>auth.tenantId = tenantId</pre><p>We simply attach our desired tenant ID with the firebase auth instance. After this we will be able to login to the created multi-tenant user simply using signInWithEmailAndPassword() method available by firebase client library.</p><h4>Flutter Implementation</h4><p>In order to allow to login the multi tenant user in flutter.</p><p>we can set up code as below, we can see we are attaching the user tenant id to firebase auth instance.</p><pre>Future&lt;UserCredential&gt; login(Map&lt;String, dynamic&gt;? data) {<br>    firebaseAuth.tenantId = Config.userTenantId;<br>    return firebaseAuth.signInWithEmailAndPassword(<br>      email: data![&quot;email&quot;],<br>      password: data[&quot;password&quot;],<br>    );<br>  }</pre><h4>Testing in Postman</h4><p>After creating our user, we can log in through postman to get an id token.</p><p>Send <em>Post</em> request to the below URL</p><pre>https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={{FirebaseAPIKey}}</pre><p>with body:</p><pre>{<br>    &quot;email&quot;: &quot;test.dev19@mailinator.com&quot;,<br>    &quot;password&quot;: &quot;password&quot;,<br>    &quot;returnSecureToken&quot;: true,<br>    &quot;tenantId&quot;:&quot;user-2pn4v&quot;<br>}</pre><p>and it will return a id token that can be used to verify and extract info such as tenant id, claims, and others.</p><p>Note: here I am passing tenantID as “user-2pn4v”. You must pass the tenant ID with which the user is created otherwise it will throw an error like “USER NOT FOUND”</p><p>Thank you for reading !!!</p><p>References:</p><ul><li><a href="https://cloud.google.com/identity-platform/docs/multi-tenancy-quickstart">Set up multi-tenancy | Identity Platform Documentation | Google Cloud</a></li><li><a href="https://cloud.google.com/identity-platform/docs/multi-tenancy">Identity Platform multi-tenancy | Identity Platform Documentation | Google Cloud</a></li><li><a href="https://medium.com/firebase-developers/multi-tenant-applications-with-firebase-and-google-cloud-4d0d02b7d859">Multi-tenant applications with Firebase and Google Cloud</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25fba64599d4" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/allow-single-email-to-signup-as-multiple-users-in-a-firebase-project-google-identity-platform-25fba64599d4">Allow single email to signup as multiple users in a Firebase project (Google Identity platform)</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete GitHub Actions & Workflows Guide]]></title>
            <link>https://articles.readytowork.jp/the-complete-github-actions-workflows-guide-14eb627c932d?source=rss-4f45602cb62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/14eb627c932d</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[circleci]]></category>
            <dc:creator><![CDATA[Sumit Sapkota]]></dc:creator>
            <pubDate>Fri, 15 Jul 2022 08:14:02 GMT</pubDate>
            <atom:updated>2022-07-15T08:14:02.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtWbCHhIw6MMMXCil7lZ0g.png" /></figure><p>GitHub Actions helps you automate tasks within your software development life cycle. GitHub Actions are event-driven, meaning that you can run a series of commands after a specified event has occurred. For example, every time someone creates a pull request for a repository, you can automatically run a command that executes a software testing script.</p><p>This enables you to include Continuous Integration (CI) and continuous deployment (CD) capabilities and many other features directly in your repository.</p><p>In this article, we are going to look at the core concepts of Github Actions and even dive into creating your own custom workflows.</p><h3>Why Github actions?</h3><p><strong>Build into GitHub:</strong></p><p>Github Actions is fully integrated into Github and therefore doesn’t require other CI/CD tools like CircleCI and Jenkins. This means that it can be managed in the same place as all your other repository-related features like pull requests and issues.</p><p><strong>Multi-container testing:</strong></p><p>Actions allow you to test multi-container setups by adding support for Docker and docker-compose files to your workflow.</p><p><strong>Multiple CI Templates:</strong></p><p>Github provides multiple templates for all kinds of CI (Continuous Integration) configurations which make it extremely easy to get started. You can also create your own templates which you can then publish as an Action on the Github Marketplace.</p><p><strong>Great free plan:</strong></p><p>Actions are entirely free for every open-source repository and include 2000 free build minutes per month for all your private repositories which is comparable with most CI/CD free plans. If that is not enough for your needs you can pick another plan or go the self-hosted route.</p><h3>Core Concepts on Github Actions</h3><h4>Workflow:</h4><p>A Workflow is an automated process that is made up of one or multiple jobs and can be triggered by an event. Workflows are defined using a YAML file in the .github/workflows directory.</p><h4>Event:</h4><p>Events are specific activities that trigger a workflow run. For example, a workflow is triggered when somebody pushes to the repository or when a pull request is created. Events can also be configured to listen to external events using Webhooks.</p><pre>on: <br>   push:<br>       branches:<br>         - develop</pre><h4>Job:</h4><p>By default, a workflow with multiple jobs will run those jobs in parallel. You can also configure a workflow to run jobs sequentially. For example, a workflow can have two sequential jobs that build and test code, where the test job is dependent on the status of the build job. If the build job fails, the test job will not run.</p><h4><strong>Step:</strong></h4><p>A step is an individual task that can run commands in a job. A step can be either an <em>action</em> or a shell command. Each step in a job executes on the same runner, allowing the actions in that job to share data with each other.</p><p>Each step can be provided with the name.</p><h4><strong>Actions:</strong></h4><p><em>Actions</em> are standalone commands that are combined into <em>steps</em> to create a <em>job</em>.</p><p>Actions are the smallest portable building block of a workflow and can be combined as steps to create a job. You can create your own Actions or use publicly shared Actions from the Marketplace.</p><h4><strong>Runner:</strong></h4><p>A runner is a machine with the Github Actions runner application installed. Then runner waits for available jobs it can then execute. After picking up a job they run the job’s actions and report the progress and results back to Github. Runners can be hosted on Github or self-hosted on your own machines/servers.</p><h3>The components of GitHub Actions</h3><p>Below is a list of the multiple GitHub Actions components that work together to run jobs. You can see how these components interact with each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*LWxRdtZasEm7DzNfGV0PFA.jpeg" /></figure><h4><strong>An example workflow for Github Actions</strong></h4><p>1 . Let’s create .github/workflows directory in our project root</p><p>2. Inside workflows directory lets create github-actions.yaml file</p><pre>name: learn-github-actions<br>on: [push]<br>  branches:<br>    - develop<br>jobs:<br>  check-bats-version:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v2<br>        <br>      - name: Setup node<br>        uses: actions/setup-node@v2<br>        with:<br>          node-version: &#39;14&#39;<br>          <br>      - run: npm install -g bats<br>      - run: bats -v</pre><p>3. Commit these changes and push them to your GitHub repository</p><h4>Understanding the above workflow file</h4><pre>name: learn-github-actions</pre><p><em>Optional</em> — The name of the workflow as will appear in the Actions tab of the GitHub repository.</p><pre>on: [push]</pre><p>Specify the event that automatically triggers the workflow file. This example uses the push event so that the jobs run every time someone pushes a change to the repository. You can set up the workflow to only run on certain branches, paths, or tags. For syntax examples including or excluding branches, paths, or tags, see <a href="https://docs.github.com/actions/reference/workflow-syntax-for-github-actions#onpushpull_requestpaths">“Workflow syntax for GitHub Actions.”</a></p><pre>jobs:</pre><p>Groups together all the jobs that run in the learn-github-actions workflow file.</p><pre>check-bats-version:</pre><p>Defines the name of the check-bats-version job stored within the jobs section.</p><pre>runs-on: ubuntu-latest</pre><p>Configures the job to run on an Ubuntu Linux runner. This means that the job will execute on a fresh virtual machine hosted by GitHub. For syntax examples using other runners, see <a href="https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idruns-on">“Workflow syntax for GitHub Actions.”</a></p><pre>steps:</pre><p>Groups together all the steps that run in the check-bats-version job. Each item nested under this section is a separate action or shell command.</p><pre>- uses: actions/checkout@v2</pre><p>The uses keyword tells the job to retrieve v2 of the community action named actions/checkout@v2. This action checks out your repository and downloads it to the runner, allowing you to run actions against your code (such as testing tools). You must use the checkout action any time your workflow will run against the repository’s code or you are using an action defined in the repository.</p><pre>- uses: actions/setup-node@v2<br>      with:<br>        node-version: &#39;14&#39;</pre><p>This step uses the actions/setup-node@v2 action to install the specified version of the node software package on the runner, which gives you access to the npm command.</p><pre>- run: npm install -g bats</pre><p>The run keyword tells the job to execute a command on the runner. In this case, you are using npm to install the bats software testing package.</p><pre>- run: bats -v</pre><p>Finally, you’ll run the bats command with a parameter that outputs the software version.</p><h3>Visualizing the workflow file</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*3GjvmuK2uTXp0hnyILJTKg.jpeg" /></figure><h4>Once your job has started running, you can see a visualization graph of the run’s progress and view each step’s activity on GitHub.</h4><ol><li>On <a href="http://github.com/">GitHub.com</a>, navigate to the main page of the repository.</li><li>Under your repository name, click <strong>Actions</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nx7mSEMtjLbBoYPpxcF_w.jpeg" /></figure><p>3. In the left sidebar, click the workflow you want to see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9vjjS8LsmOSzBB2dw2ecQ.jpeg" /></figure><p>4. Under “Workflow runs”, click the name of the run you want to see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFkcTa7bachKDQe8qD_rkA.jpeg" /></figure><p>5. Under <strong>Jobs</strong> or in the visualization graph, click the job you want to see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMznCQWKILjt5BEZcMkrzg.jpeg" /></figure><p>6. View the results of each step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZ725i1_lNdFopoF6mPPOw.jpeg" /></figure><h3>Other Important Topics</h3><p><strong>Dependent Jobs:</strong></p><p>By default, a workflow with multiple jobs will run those jobs in parallel. You can also configure a workflow to run jobs sequentially. Suppose we have 3 jobs but need to run jobs sequentially.</p><pre>jobs:<br>  job1:<br>  job2:<br>    needs: job1<br>  job3:<br>    needs: [job1, job2]</pre><p><strong>Add Github Secrets</strong></p><p>We can add our environment variables to the GitHub secret as follows:</p><ol><li>Go to your project on Github</li><li>Select the Settings tab</li><li>Click the Secrets section in the left-hand menu</li></ol><p>Add a new secret and provide a name (e.g. SLACK_WEBHOOK_URL) and a value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eqaJ-FgkRj-T9x1mvQiFlQ.jpeg" /></figure><p><strong>Environment segregation</strong></p><p>We can create different environments in our repository and segregate secrets(environment variables) to specific environments.</p><p>Let’s create environments: development, Preview, and Production by going into repository &gt; settings &gt; Environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y3Zth59j2EnQjQ28VDO2Ow.jpeg" /></figure><p>Then under your desired environment, you can add environment variables as secrets. And then for a specific job in your workflow, you can specify the environment and the secrets we use in that specific job are retrieved from the environment specified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcKBDebF9lWdDwaXo-Z4Vg.jpeg" /></figure><p>To access these secrets(environment variables) stored under our environment file, we need to specify the environment we are going to use in our ‘job’ just under the ‘runs-on’ as below.</p><p>Then you can access the environment secrets just like we accessed normal secrets stored in our Github Repository.</p><pre>name: build-app<br><br>on:<br>  push: <br>    branches: [develop]<br><br>jobs:<br>  build-the-app: <br>    runs-on: ubuntu-latest<br>    environment: development<br>    steps: <br>      - name: Checkout code<br>        uses: actions/checkout@v2<br><br>      - name: Get environment variables<br>        run: echo ${{ secrets.SLACK_WEBHOOK_URL }}</pre><h3>Conclusion</h3><p>The best platform for you all depends on your specific needs. If you host your code somewhere other than <a href="http://github.com/">GitHub.com</a> or GitHub Enterprise, you will be better off using CircleCI. However, if you host your code on <a href="http://github.com/">GitHub.com</a> or GitHub Enterprise, the choice can be a little more difficult.</p><p>If you have complex projects or projects that need the hefty boost of GPU builds, I would suggest trying out or sticking with CircleCI. They have a few more options to help with more complex build scenarios since they are the mature CI/CD, service provider.</p><p>For most people, if they have a small number of projects whose CI/CD config files are relatively simple, I would suggest moving over to try GitHub Actions. Don’t disconnect or delete your current pipelines until you try GA out for a project or two, however. Just add the config files in for GA and see how you like the flow and feel of it. Once you verify that GA has everything you need to do your builds properly and successfully, and they have been running for at least a week or two successfully, you can delete your other config files and cancel your previous CI/CD service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14eb627c932d" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/the-complete-github-actions-workflows-guide-14eb627c932d">The Complete GitHub Actions &amp; Workflows Guide</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Logs in GCP Logs Explorer for Compute Engine on Golang]]></title>
            <link>https://articles.readytowork.jp/writing-logs-in-gcp-logs-explorer-for-compute-engine-on-golang-63b6c753770a?source=rss-4f45602cb62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/63b6c753770a</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[google-compute-engine]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[cloud-logging]]></category>
            <dc:creator><![CDATA[Sumit Sapkota]]></dc:creator>
            <pubDate>Fri, 24 Jun 2022 11:20:20 GMT</pubDate>
            <atom:updated>2022-06-24T11:20:20.370Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxMZg-fFwG6rMDjjNUbNYg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@adoris_photography">Dorelys Smits</a></figcaption></figure><p>The Cloud Logging API lets you programmatically accomplish logging-related tasks, including reading and writing log entries and creating log-based metrics.</p><p>If our project is deployed in Google App Engine(GAE), program logs are automatically logged by GAE in Logs Explorer. But in the case of deploying project in Google Compute Engine(GCE) it is a hassle to see program logs. So we have to manually write program logs in order to display in Logs explorer.</p><blockquote>We can write Request logs or Specific logs according to our desire using cloud logging API</blockquote><p>You should have project deployed in GCP compute engine or App engine</p><p>We will follow the below steps to write logs:</p><ul><li>Create a GCP project</li><li>Create a VM instance in Compute engine</li><li>Deploy your app in Compute engine</li><li>Understanding Logging API</li><li>Create service Account</li><li>Generate Service Account Key to authenticate API request</li><li>Using Cloud Logging Client Library</li><li>Writing Request Logs</li><li>List Logs Entries</li><li>Delete Logs Entries</li></ul><p>I am assuming that you have completed first three steps already. So, we are skipping these steps and follow other steps.</p><h3>Understanding Logging API</h3><p>The Logging API must be enabled before it can be used. You can check the status of the API and, if necessary, enable the API if necessary by using either the Google Cloud console or Google Cloud CLI.</p><h4>Enable Logging API</h4><ol><li>In the Cloud console, select the Cloud project for which you want to enable the API, and then go to the <strong>APIs &amp; Services</strong> page:</li><li><a href="https://console.cloud.google.com/apis/dashboard">Go to <strong>APIs &amp; Services</strong></a></li><li>Click the <strong>Enable APIs and Services</strong> button.</li><li>Search for “Logging”.</li><li>In the search results, click <strong>Cloud Logging API</strong>.</li><li>If “API enabled” is displayed, then the API is already enabled. If not, then click <strong>Enable</strong>.</li></ol><h4><strong>Authorize use of the API</strong></h4><p>Before you can use the Cloud Logging API, you must authorize users to access it. Here we are going to authorize user using Service Account Key.</p><blockquote><em>Access to the API is controlled by Identity and Access Management (IAM) roles and permissions. There is a permission associated with each method, and permissions for related methods are clustered into roles, which can then be granted to users.</em></blockquote><p>In GCP console, Select a project navigate to <a href="https://console.cloud.google.com/iam-admin/iam">IAM and admin</a> section and then navigate to Service Account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDK4TUpKOopNAlEvr5yVkQ.jpeg" /></figure><p>Here you can see list of available or already created service accounts. You can either use default service account key or create a new service account key.</p><h3>Create Service Account</h3><h4>Enter service account details</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRlfBg6pw00thI4gTsbwgw.jpeg" /></figure><p><strong>Grant the service account access to project</strong></p><p>In this step, We assign role to grant service account access to project. Here we are giving role <strong>Logging admin </strong>, this role can read, write, delete logs and other logger bucket related tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YRTTtYmOmhpGV4Qo-qYNjw.jpeg" /></figure><p>We can also specify other roles such as <strong>Logs writer </strong>which has only access to write logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5TzJOevDDM-Q5IY3pJbQw.jpeg" /></figure><p><strong>Grant users access to this service account </strong>(optional)</p><p>In this step we specify the users access to this service account. We can specify user emails which will have access to this service account. For now, let’s keep it blank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-xClooTIJbL2d-yvPwv2w.jpeg" /></figure><h3>Generate Service Account Key to authenticate API request</h3><p>After successfully creating service account. Next step is to generate the Service Account Key.</p><p>Now from the service account list page we select the recently created service account and navigate to <strong>keys </strong>tab and add a new key as shown in screenshot below and <strong>you will be promoted to download json file</strong>, download the file and save into your machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B0TSAzPSaksIEx08rWBtUQ.jpeg" /></figure><p>Till now, we have created Service Account and generated the key to authenticate our Logging API.</p><p>To use the service account key in the project, create a file named cloudApiKey.json in project’s root directory and Copy the content of previously downloaded json file and paste into the cloudApiKey.json file</p><h3>Using Cloud Logging Client Library</h3><h4>Install the client library</h4><pre>go get cloud.google.com/go/logging</pre><h4>Writing structured logs</h4><pre>package main</pre><pre>import (<br>        &quot;context&quot;<br>        &quot;fmt&quot;<br>        &quot;log&quot;<br>        &quot;cloud.google.com/go/logging&quot;<br>)</pre><pre>func main() {<br>        ctx := context.Background()</pre><pre>        // Sets your Google Cloud Platform project ID<br>        projectID := &quot;YOUR_PROJECT_ID&quot;<br>        // load the file from root path to authenticate<br>        cloudApiKey, err := filepath.Abs(&quot;./cloudApiKey.json&quot;)<br>		if err != nil {<br>		logger.Zap.Panic(&quot;Unable to load             cloudApiKey.json file&quot;)<br>		}<br>		option := option.WithCredentialsFile(cloudApiKey)<br>		// Creates a client with credential file<br>		client, err := logging.NewClient(ctx, projectID, option)<br>        if err != nil {<br>                log.Fatalf(&quot;Failed to create client: %v&quot;, err)<br>        }</pre><pre>        // Sets or create the name of the log to write to <br>        logName := &quot;my-log&quot;</pre><pre>        // Selects the log to write to.<br>        logger := client.Logger(logName)</pre><pre>        defer logger.Flush() // Ensure the entry is written.</pre><pre>        logger.Log(logging.Entry{<br>        // Log anything that can be marshaled to JSON.<br>        Payload: struct{ Anything string }{<br>                Anything: &quot;The payload can be any type!&quot;,<br>        },<br>        Severity: logging.Debug,<br>        })<br>}</pre><h3><strong>Writing the request Logs</strong></h3><pre>import (<br>        &quot;context&quot;<br>        &quot;log&quot;<br>        &quot;net/http&quot;<br>        &quot;os&quot;</pre><pre>        &quot;cloud.google.com/go/logging&quot;)</pre><pre>func main() {<br>        ctx := context.Background()</pre><pre>        // Creates a client.<br>        projectID := os.Getenv(&quot;GOOGLE_CLOUD_PROJECT&quot;)<br>        client, err := logging.NewClient(ctx, projectID)<br>        if err != nil {<br>                log.Fatalf(&quot;Failed to create client: %v&quot;, err)<br>        }<br>        defer client.Close()</pre><pre>        // Sets the name of the log to write to.<br>        logger := client.Logger(&quot;my-log&quot;)</pre><pre>        // Logs a basic entry.<br>        logger.Log(logging.Entry{Payload: &quot;hello world&quot;})</pre><pre>        // TODO(developer): replace with your request value.<br>        r, err := http.NewRequest(&quot;GET&quot;, &quot;http://example.com&quot;, nil)</pre><pre>        // Logs an HTTPRequest type entry.<br>        httpEntry := logging.Entry{<br>                Payload: &quot;optional message&quot;,<br>                HTTPRequest: &amp;logging.HTTPRequest{<br>                        Request: r,<br>                },<br>        }<br>        logger.Log(httpEntry)}</pre><h3><strong>List Log Entries</strong></h3><pre>var entries []*logging.Entryconst name = &quot;log-example&quot;<br>lastHour := time.Now().Add(-1 * time.Hour).Format(time.RFC3339)</pre><pre>iter := adminClient.Entries(ctx,<br>        // Only get entries from the &quot;log-example&quot; log within the last hour.<br>        logadmin.Filter(fmt.Sprintf(`logName = &quot;projects/%s/logs/%s&quot; AND timestamp &gt; &quot;%s&quot;`, projID, name, lastHour)),<br>        // Get most recent entries first.<br>        logadmin.NewestFirst(),)<br>        // Fetch the most recent 20 entries.for len(entries) &lt; 20 {<br>        entry, err := iter.Next()<br>        if err == iterator.Done {<br>                return entries, nil<br>        }<br>        if err != nil {<br>                return nil, err<br>        }<br>        entries = append(entries, entry)}return entries, nil</pre><h3>Delete Log Entries</h3><pre>const name = &quot;log-example&quot;if err := adminClient.DeleteLog(ctx, name); err != nil {<br>        return err<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IvKB5WPj7It_l_VcKe5wiA.jpeg" /></figure><p>So, this is how we can write any kinds of logs to GCP log explorer for the programs deployed in Google Compute Engine (GCE).</p><p>References: <a href="https://cloud.google.com/logging/docs/apis">https://cloud.google.com/logging/docs/apis</a></p><p>Happy coding 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63b6c753770a" width="1" height="1" alt=""><hr><p><a href="https://articles.readytowork.jp/writing-logs-in-gcp-logs-explorer-for-compute-engine-on-golang-63b6c753770a">Writing Logs in GCP Logs Explorer for Compute Engine on Golang</a> was originally published in <a href="https://articles.readytowork.jp/">readytowork, Inc.</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>