<?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"><channel><title><![CDATA[Drate Tech  Blog]]></title><description><![CDATA[Drate Tech  Blog]]></description><link>https://dragostemelie.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1701434325741/zBvslBA8U.png</url><title>Drate Tech  Blog</title><link>https://dragostemelie.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 24 Nov 2026 13:28:15 GMT</lastBuildDate><atom:link href="https://dragostemelie.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Secure authentication using Go]]></title><description><![CDATA[Let's take a look at how authentication works on many modern websites by implementing it ourselves step by step.]]></description><link>https://dragostemelie.hashnode.dev/secure-authentication-using-go</link><guid isPermaLink="true">https://dragostemelie.hashnode.dev/secure-authentication-using-go</guid><category><![CDATA[golang]]></category><category><![CDATA[authentication]]></category><dc:creator><![CDATA[Dragos Temelie]]></dc:creator><pubDate>Sun, 03 Nov 2024 07:50:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730619767606/49137469-b180-451e-a64d-9df932912eba.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Full code source: <a target="_blank" href="https://github.com/dragostemelie/secure-login-go">secure-login-go</a></p>
<p>Let's take a look at how authentication works on many modern websites by implementing it ourselves step by step. We're going to take a look at how sessions, cookies, CSRF tokens and of course username and passwords all work together to produce secure authentication for a website.</p>
<p>We're going to make 4 different endpoints:</p>
<ul>
<li><p>one to <strong>CREATE</strong> an account</p>
</li>
<li><p>one to <strong>LOG IN</strong></p>
</li>
<li><p>one to <strong>LOG OUT</strong></p>
</li>
<li><p>and a <strong>PROTECTED</strong> endpoint which will be only accessible to logged in users</p>
</li>
</ul>
<p>We'll store the user name as a key in a map which maps usernames to log information so this is our in-memory database which we'll use as a stand-in for a real database.</p>
<p>For now the functions which are going to handle these endpoint requests are going to be empty.</p>
<pre><code class="lang-go"><span class="hljs-comment">// main.go</span>

<span class="hljs-keyword">var</span> users = <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]Login{}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    http.HandleFunc(<span class="hljs-string">"/register"</span>, register)
    http.HandleFunc(<span class="hljs-string">"/login"</span>, login)
    http.HandleFunc(<span class="hljs-string">"/logout"</span>, logout)
    http.HandleFunc(<span class="hljs-string">"/protected"</span>, protected)
    http.ListenAndServe(<span class="hljs-string">":8080"</span>, <span class="hljs-literal">nil</span>)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">register</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">login</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">logout</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {}
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">protected</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {}
</code></pre>
<h3 id="heading-registration">Registration</h3>
<p>The registration function will handle a POST request. POST methods are generally used for requests which send data and create new resources, which is exactly what we're going to do here.</p>
<p>We're going to grab the username and password from the payload form value we'll do some basic length checks as well as check if the user already exists.</p>
<pre><code class="lang-go"><span class="hljs-comment">// main.go</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">register</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    <span class="hljs-keyword">if</span> r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, <span class="hljs-string">"Invalid method"</span>, er)
    }

    username := r.FormValue(<span class="hljs-string">"username"</span>)
    password := r.FormValue(<span class="hljs-string">"password"</span>)

    <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(username) == <span class="hljs-number">0</span> || <span class="hljs-built_in">len</span>(password) == <span class="hljs-number">0</span> {
        er := http.StatusNotAcceptable
        http.Error(w, <span class="hljs-string">"Invalid username or password"</span>, er)
        <span class="hljs-keyword">return</span>
    }

}
</code></pre>
<p>It's common practice to send passwords in plain text since most public APIs use HTTPS. This encrypts the data during transmission. However passwords are always stored in an ofuscated form. This ensures that even if somebody gains access to the database they won't have direct access to the user's passwords.</p>
<h3 id="heading-hashing">Hashing</h3>
<p>To obfuscate a password we use a hashing function. A hashing function is an algorithm that converts data into a fixed size irreversible string of characters used primarily for data integrity and secure storage like password protection.</p>
<p>The hashing function we'll use is a very commonly used one which is called <strong>bcrypt</strong>. In a new <code>utils.go</code> file we will import <strong>bcrypt</strong> from the golang crypto module. The hash password function will take in the password as a string and we'll call <code>bcript.GenerateFromPassword</code>. This takes a bite representation of the password and a cost factor.</p>
<pre><code class="lang-go"><span class="hljs-comment">// utils.go</span>

<span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"golang.org/x/crypto/bcrypt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">hashPassword</span><span class="hljs-params">(password <span class="hljs-keyword">string</span>)</span> <span class="hljs-params">(<span class="hljs-keyword">string</span>, error)</span></span> {
    bytes, err := bcrypt.GenerateFromPassword([]<span class="hljs-keyword">byte</span>(password), <span class="hljs-number">10</span>)
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">string</span>(bytes), err
}
</code></pre>
<p>The cost factor essentially just controls how slow the algorithm is. A cost factor of 10 means the password is hashed 2 to the power of 10 times. So we hash the password and then hash the hash many many times.</p>
<p>The point of this is to make it slow to generate a hash. This way, if somebody got a hold of the hash passwords they couldn't just quickly run millions of guesses through the hashing function until they found a match.</p>
<p>All right so then the hash is what we store in the database:</p>
<pre><code class="lang-go"><span class="hljs-comment">// main.go</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">register</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    <span class="hljs-keyword">if</span> r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, <span class="hljs-string">"Invalid method"</span>, er)
    }

    username := r.FormValue(<span class="hljs-string">"username"</span>)
    password := r.FormValue(<span class="hljs-string">"password"</span>)

    <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(username) == <span class="hljs-number">0</span> || <span class="hljs-built_in">len</span>(password) == <span class="hljs-number">0</span> {
        er := http.StatusNotAcceptable
        http.Error(w, <span class="hljs-string">"Invalid username or password"</span>, er)
        <span class="hljs-keyword">return</span>
    }

    <span class="hljs-keyword">if</span> _, ok := users[username]; ok {
        er := http.StatusConflict
        http.Error(w, <span class="hljs-string">"User already exists"</span>, er)
        <span class="hljs-keyword">return</span>
    }

    hashedPassword, _ := hashPassword(password)
    users[username] = Login{
        HashedPassword: hashedPassword,
    }

    fmt.Fprintln(w, <span class="hljs-string">"User registered successfully"</span>)

}
</code></pre>
<p>Let's try this endpoint out and create a user. So our database now looks like this:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"username"</span>: {
        <span class="hljs-attr">"HashedPassword"</span>: <span class="hljs-string">"$2a$10$JhuoEe8X..."</span>,
        <span class="hljs-attr">"SessionToken"</span>: <span class="hljs-string">""</span>,
        <span class="hljs-attr">"CSRFToken"</span>: <span class="hljs-string">""</span>        
    }
}
</code></pre>
<h3 id="heading-logging-in">Logging in</h3>
<p>Let's see how we would log in a user. This is where we start to use our session and CSRF tokens. We're going to use a POST method again and grab our password and username in the same way as before. If the username doesn't exist just return an error.</p>
<pre><code class="lang-go"><span class="hljs-comment">// main.go</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">login</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    <span class="hljs-keyword">if</span> r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, <span class="hljs-string">"Invalid method"</span>, er)
    }

    username := r.FormValue(<span class="hljs-string">"username"</span>)
    password := r.FormValue(<span class="hljs-string">"password"</span>)

    user, ok := users[username]
    <span class="hljs-keyword">if</span> !ok || {
        er := http.StatusUnauthorized
        http.Error(w, <span class="hljs-string">"Invalid username or pasword"</span>, er)
        <span class="hljs-keyword">return</span>
    }

}
</code></pre>
<p>To check the password we got to hash it and compare it to the hash that we have in our database. So let's go back to our util file and create a check password hash function.</p>
<pre><code class="lang-go"><span class="hljs-comment">// utils.go</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">checkPasswordHash</span><span class="hljs-params">(password, hash <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">bool</span></span> {
    err := bcrypt.CompareHashAndPassword([]<span class="hljs-keyword">byte</span>(hash), []<span class="hljs-keyword">byte</span>(password))
    <span class="hljs-keyword">return</span> err == <span class="hljs-literal">nil</span>
}
</code></pre>
<p>The <strong>bcrypt</strong> package we imported has a <code>CompareHashAndPassword</code> function. This will hash the plain text password and compare it to the hash we have stored, all in one line. If there's an error this means that the passwords didn't match.</p>
<p>Let's now add this check to our if statement.</p>
<pre><code class="lang-go"><span class="hljs-comment">// main.go</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">login</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    <span class="hljs-keyword">if</span> r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, <span class="hljs-string">"Invalid method"</span>, er)
    }

    username := r.FormValue(<span class="hljs-string">"username"</span>)
    password := r.FormValue(<span class="hljs-string">"password"</span>)

    user, ok := users[username]
    <span class="hljs-keyword">if</span> !ok || !checkPasswordHash(password, user.HashedPassword) {
        er := http.StatusUnauthorized
        http.Error(w, <span class="hljs-string">"Invalid username or pasword"</span>, er)
        <span class="hljs-keyword">return</span>
    }

    fmt.Fprintln(w, <span class="hljs-string">"Login successful!"</span>)
}
</code></pre>
<p>If we stopped here we'd face a major issue. Each time a request is made to the backend, like fetching or updating user data, the client would need to send the username and password for authentication. This would either require the user repeatedly enter their credentials for the website. Or the web page to store them. Both of which are let's say bad.</p>
<p>This is where session tokens come in. A session token is generated randomly, in a function like this:</p>
<pre><code class="lang-go"><span class="hljs-comment">// utils.go</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">generateToken</span><span class="hljs-params">(length <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">string</span></span> {
    bytes := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">byte</span>, length)
    <span class="hljs-keyword">if</span> _, err := rand.Read(bytes); err != <span class="hljs-literal">nil</span> {
        log.Fatalf(<span class="hljs-string">"Failed to generate token: %v"</span>, err)
    }

    <span class="hljs-keyword">return</span> base64.URLEncoding.EncodeToString(bytes)
}
</code></pre>
<p>Here we're using the <code>Rand</code> package to generate a random bite and then returning it as a string in base64 representation.</p>
<p>On a side note, base64 is a binary-to-text encoding schema that converts binary data into a string, where the string contains only characters from a specially chosen list of characters. These characters are uppercase letters, lowercase letters, digits as well as the + and / symbol. This avoids us using reserved characters like &amp; or @ for example in our token, which have special uses in HTTP requests.</p>
<h4 id="heading-session-tokens">Session tokens</h4>
<p>All right so we'll generate a session token in our login handler.</p>
<pre><code class="lang-go">sessionToken := generateToken(<span class="hljs-number">32</span>)
</code></pre>
<p>But what are we going to use it for? Well first we'll store the session token in a cookie which we'll send back to the client.</p>
<pre><code class="lang-go">sessionToken := generateToken(<span class="hljs-number">32</span>)

<span class="hljs-comment">//Set session cookie</span>
http.SetCookie(w, &amp;http.Cookie{
    Name:  <span class="hljs-string">"session_token"</span>,
    Value: sessionToken,
})
</code></pre>
<p>Now the way cookies work is they are automatically sent by the browser to the back end every time a request is made to any endpoint in our database. So this session token will be sent anytime a request is made. Now instead of checking login credentials every time, we can just verify that the session token we get in the cookie is the same with the one that we have in our database.</p>
<pre><code class="lang-go">sessionToken := generateToken(<span class="hljs-number">32</span>)

<span class="hljs-comment">//Set session cookie</span>
http.SetCookie(w, &amp;http.Cookie{
    Name:  <span class="hljs-string">"session_token"</span>,
    Value: sessionToken,
})
</code></pre>
<p>Cool! So let's store the session token in our database. Now there are a couple extra things we want to add to our cookie. First is the expiration date. We'll set this to 24 hours. What happens here is the browser will delete the value under that session token key in the cookie after 24 hours. So any subsequent request after 24 hours will have no session token and hence the user gets automatically logged out.</p>
<pre><code class="lang-go">sessionToken := generateToken(<span class="hljs-number">32</span>)

<span class="hljs-comment">//Set session cookie</span>
http.SetCookie(w, &amp;http.Cookie{
    Name:  <span class="hljs-string">"session_token"</span>,
    Value: sessionToken,
    Expires: time.Now().Add(<span class="hljs-number">24</span> * time.Hour),
    HttpOnly: <span class="hljs-literal">true</span>,
})

<span class="hljs-comment">//Store tokens in the database</span>
user.SessionToken = sessionToken
users[username] = user
</code></pre>
<p>This next key-value pairs and cookies also have a flag called HttpOnly. This HttpOnly flag ensures that the session token can't be accessed by front-end JavaScript on the web page so it's only available to be sent during HTTP requests. So all good, right? Well.. not exactly.</p>
<p>Using session tokens we've actually introduced a vulnerability called cross-site request forgery. Here's how this would work.</p>
<p>Imagine I'm logged into my <a target="_blank" href="http://bank.com">bank.com</a> account hence a cookie is stored on my machine with a session token. Suppose I get a link to a malicious website and click on it since I'm logged into my <a target="_blank" href="http://bank.com">bank.com</a> account. Any requests the malicious site makes, the <a target="_blank" href="http://bank.com">bank.com</a> will have the cookie data for that site automatically sent along with the request so the banking website will get the valid session token and treat any requests from the malicious site as legit. For example transferring all funds out from an account.</p>
<h4 id="heading-csrf-tokens">CSRF tokens</h4>
<p>This is an issue we can solve with CSRF tokens. We can create one in the same way we create a session token. Here similarly we'll put the CSRF token in the cookie except we'll set HttpOnly to false as well. Let's store this token in the database for the user.</p>
<pre><code class="lang-go"><span class="hljs-comment">// main.go</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">login</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    <span class="hljs-keyword">if</span> r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, <span class="hljs-string">"Invalid method"</span>, er)
    }

    username := r.FormValue(<span class="hljs-string">"username"</span>)
    password := r.FormValue(<span class="hljs-string">"password"</span>)

    user, ok := users[username]
    <span class="hljs-keyword">if</span> !ok || !CheckPasswordHash(password, user.HashedPassword) {
        er := http.StatusUnauthorized
        http.Error(w, <span class="hljs-string">"Invalid username or pasword"</span>, er)
        <span class="hljs-keyword">return</span>
    }

    sessionToken := generateToken(<span class="hljs-number">32</span>)
    csrfToken := generateToken(<span class="hljs-number">32</span>)

    <span class="hljs-comment">//Set session cookie</span>
    http.SetCookie(w, &amp;http.Cookie{
        Name:     <span class="hljs-string">"session_token"</span>,
        Value:    sessionToken,
        Expires:  time.Now().Add(<span class="hljs-number">24</span> * time.Hour),
        HttpOnly: <span class="hljs-literal">true</span>,
    })

    <span class="hljs-comment">// Set CSRF cookie</span>
    http.SetCookie(w, &amp;http.Cookie{
        Name:     <span class="hljs-string">"csrf_token"</span>,
        Value:    csrfToken,
        Expires:  time.Now().Add(<span class="hljs-number">24</span> * time.Hour),
        HttpOnly: <span class="hljs-literal">false</span>,
    })

    <span class="hljs-comment">//Store tokens in the database</span>
    user.SessionToken = sessionToken
    user.CSFRToken = csrfToken
    users[username] = user

    fmt.Fprintln(w, <span class="hljs-string">"Login successful!"</span>)
}
</code></pre>
<p>Okay, so now how do we actually use this CSRF token? Well, first we need to understand what <strong>Same-Origin Policy</strong> is. This essentially means that the browser blocks web pages from accessing resources meant for other websites, like cookies for example. So the malicious website can't read the cookie information from <a target="_blank" href="http://bank.com">bank.com</a> even though the cookie is automatically sent for any requests to <a target="_blank" href="http://bank.com">bank.com</a>.</p>
<h3 id="heading-authorization-function">Authorization function</h3>
<p>So let's see how we can use this information in code. We'll create a session file and start writing our authorized function which will authorize requests. So first we'll grab the username and use that to grab the user data from our database.</p>
<p>So let's see how we can use this information in code. We'll create a <code>session.go</code> file and start writing our authorized function which will authorize requests.</p>
<pre><code class="lang-go"><span class="hljs-comment">// session.go</span>

<span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"errors"</span>
    <span class="hljs-string">"net/http"</span>
)

<span class="hljs-keyword">var</span> ErrAuth = errors.New(<span class="hljs-string">"Unauthorized"</span>)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">Authorize</span><span class="hljs-params">(r *http.Request)</span> <span class="hljs-params">(<span class="hljs-keyword">string</span>, error)</span></span> {
    <span class="hljs-keyword">var</span> body RequestBody

    err := json.NewDecoder(r.Body).Decode(&amp;body)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>, ErrAuth
    }

    userName := body.Username
    user, ok := users[userName]
    <span class="hljs-keyword">if</span> !ok {
        fmt.Println(<span class="hljs-string">"User does not exist!"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>, ErrAuth
    }

    st, err := r.Cookie(<span class="hljs-string">"session_token"</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> || st.Value == <span class="hljs-string">""</span> || st.Value != user.SessionToken {
        fmt.Println(<span class="hljs-string">"Invalid session token!"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>, ErrAuth
    }

    csrf := r.Header.Get(<span class="hljs-string">"X-CSRF-Token"</span>)
    <span class="hljs-keyword">if</span> csrf == <span class="hljs-string">""</span> || csrf != user.CSFRToken {
        fmt.Println(<span class="hljs-string">"Invalid CSRF token!"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>, ErrAuth
    }

    <span class="hljs-keyword">return</span> userName, <span class="hljs-literal">nil</span>
}
</code></pre>
<p>So first we'll grab the username and use that to grab the user data from our database. We can grab the session token we sent from the cookie using the request object.</p>
<p>We check it was passed in is not empty and that it matches what we have in our database otherwise we reject the request. Now comes the CSRF token. The difference here is that we'll grab this token from the header of the request and not the cookie.</p>
<p>So we expect the client to send an <strong>X-CSRF-Token</strong> field with the CSRF token we sent in the cookie before. So looking back, remember we set the HttpOnly flag to false for this? This is because we want want to allow the code to actually read the token from the cookie. This way it can add it to the header and send it back. This is important because the browser will only allow this site to read the token from the cookie.</p>
<p>The malicious website can't read this token so if it sends us back the CSRF token as part of the header we know the request is coming from the original site.</p>
<p>Now all we got to do is use this function for any protected routes. In fact, let's Implement our protected route handler.</p>
<pre><code class="lang-go"><span class="hljs-comment">// main.go</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">protected</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    <span class="hljs-keyword">if</span> r.Method != http.MethodPost {
        er := http.StatusMethodNotAllowed
        http.Error(w, <span class="hljs-string">"Invalid request method"</span>, er)
    }

    username, err := Authorize(r)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        er := http.StatusUnauthorized
        http.Error(w, <span class="hljs-string">"Unauthorized"</span>, er)
        <span class="hljs-keyword">return</span>
    }

    fmt.Fprintf(w, <span class="hljs-string">"CSRF valudation succesful! Welcome, %s!"</span>, username)
}
</code></pre>
<p>Here we call the authorized function and deny the request if we get an error back. Otherwise we'll return a welcome message.</p>
<h3 id="heading-logout">Logout</h3>
<p>Lastly, we'll just fill out our logout handler. This is pretty easy. All we do is authorize the request again and if everything's okay we clear the tokens from the cookie. And then clear the tokens from our database.</p>
<pre><code class="lang-go"><span class="hljs-comment">// main.go</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">logout</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    username, err := Authorize(r)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        er := http.StatusUnauthorized
        http.Error(w, <span class="hljs-string">"Unauthorized"</span>, er)
        <span class="hljs-keyword">return</span>
    }

    <span class="hljs-comment">// Clear cookies</span>
    http.SetCookie(w, &amp;http.Cookie{
        Name:     <span class="hljs-string">"session_token"</span>,
        Value:    <span class="hljs-string">""</span>,
        Expires:  time.Now().Add(-time.Hour),
        HttpOnly: <span class="hljs-literal">true</span>,
    })
    http.SetCookie(w, &amp;http.Cookie{
        Name:     <span class="hljs-string">"csrf_token"</span>,
        Value:    <span class="hljs-string">""</span>,
        Expires:  time.Now().Add(-time.Hour),
        HttpOnly: <span class="hljs-literal">false</span>,
    })

    <span class="hljs-comment">// Clear the tokens from the database</span>
    user := users[username]
    user.SessionToken = <span class="hljs-string">""</span>
    user.CSFRToken = <span class="hljs-string">""</span>
    users[username] = user

    fmt.Fprintln(w, <span class="hljs-string">"Logged out successfully!"</span>)
}
</code></pre>
<h3 id="heading-testing">Testing</h3>
<p>All right! Let's test out a secure API and see what happens. For this let's use the Rest Client VSCode extension. It allows sending HTTP request and view the response in VSCode directly.</p>
<p>First we're going to register a user:</p>
<pre><code class="lang-http">### Registration
<span class="hljs-attribute">POST http://localhost:8080/register
Content-Type</span>: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

<span class="solidity"><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span>WebKitFormBoundary7MA4YWxkTrZu0gW
Content<span class="hljs-operator">-</span>Disposition: form<span class="hljs-operator">-</span>data; name<span class="hljs-operator">=</span><span class="hljs-string">"username"</span>

dragos
<span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span>WebKitFormBoundary7MA4YWxkTrZu0gW
Content<span class="hljs-operator">-</span>Disposition: form<span class="hljs-operator">-</span>data; name<span class="hljs-operator">=</span><span class="hljs-string">"password"</span></span>
</code></pre>
<p>Next let's try to hit the protected route so we see we get an unauthorized error.</p>
<pre><code class="lang-http">### Access protected resource
<span class="hljs-attribute">POST http://localhost:8080/protected</span>
</code></pre>
<p>This is because we need to log in so let's do that.</p>
<pre><code class="lang-http">### Login
<span class="hljs-attribute">POST http://localhost:8080/login
Content-Type</span>: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

<span class="solidity"><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span>WebKitFormBoundary7MA4YWxkTrZu0gW
Content<span class="hljs-operator">-</span>Disposition: form<span class="hljs-operator">-</span>data; name<span class="hljs-operator">=</span><span class="hljs-string">"username"</span>

dragos
<span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span>WebKitFormBoundary7MA4YWxkTrZu0gW
Content<span class="hljs-operator">-</span>Disposition: form<span class="hljs-operator">-</span>data; name<span class="hljs-operator">=</span><span class="hljs-string">"password"</span>

password123
<span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span>WebKitFormBoundary7MA4YWxkTrZu0gW<span class="hljs-operator">-</span><span class="hljs-operator">-</span></span>
</code></pre>
<p>When we do that we get back a session token and a CSRF token.</p>
<pre><code class="lang-http">HTTP/1.1 <span class="hljs-number">200</span> OK
<span class="hljs-attribute">Set-Cookie</span>: session_token=XPbVN-rDbPNNIYqM_kryHMA8xhFpmQx1YXd0p0LZILM=; Expires=Mon, 04 Nov 2024 07:26:35 GMT; HttpOnly,csrf_token=tQSH0mKlze3hE_Q88DW07AL734A0Hwndm_mtEbfDm8c=; Expires=Mon, 04 Nov 2024 07:26:35 GMT
<span class="hljs-attribute">Date</span>: Sun, 03 Nov 2024 07:26:35 GMT
<span class="hljs-attribute">Content-Length</span>: 18
<span class="hljs-attribute">Content-Type</span>: text/plain; charset=utf-8
<span class="hljs-attribute">Connection</span>: close

<span class="pgsql"><span class="hljs-keyword">Login</span> successful!</span>
</code></pre>
<p>If we hit the protected route again we get another failure because we didn't pass the CSRF token as part of the header so let's do that.</p>
<pre><code class="lang-http">### Access protected resource
<span class="hljs-attribute">POST http://localhost:8080/protected
X-CSRF-Token</span>: tQSH0mKlze3hE_Q88DW07AL734A0Hwndm_mtEbfDm8c=
<span class="hljs-attribute">Cookie</span>: session_token=XPbVN-rDbPNNIYqM_kryHMA8xhFpmQx1YXd0p0LZILM=
<span class="hljs-attribute">Content-Type</span>: application/json

<span class="json"> {
    <span class="hljs-attr">"username"</span>: <span class="hljs-string">"dragos"</span>
 }</span>
</code></pre>
<p>Trying again and we got our welcome message:</p>
<pre><code class="lang-http">HTTP/1.1 <span class="hljs-number">200</span> OK
<span class="hljs-attribute">Date</span>: Sun, 03 Nov 2024 07:28:16 GMT
<span class="hljs-attribute">Content-Length</span>: 43
<span class="hljs-attribute">Content-Type</span>: text/plain; charset=utf-8
<span class="hljs-attribute">Connection</span>: close

<span class="solidity">CSRF valudation succesful<span class="hljs-operator">!</span> Welcome, dragos<span class="hljs-operator">!</span></span>
</code></pre>
<p>We can also logout and then try the protected route once more. And we get an unauthorized error as expected.</p>
<pre><code class="lang-http">### Logout 
<span class="hljs-attribute">POST http://localhost:8080/logout
X-CSRF-Token</span>: tQSH0mKlze3hE_Q88DW07AL734A0Hwndm_mtEbfDm8c=
<span class="hljs-attribute">Cookie</span>: session_token=XPbVN-rDbPNNIYqM_kryHMA8xhFpmQx1YXd0p0LZILM=
<span class="hljs-attribute">Content-Type</span>: application/json

<span class="json"> {
    <span class="hljs-attr">"username"</span>: <span class="hljs-string">"dragos"</span>
 }</span>
</code></pre>
<p>And that's it! That's an overview of how authentication works in many modern sites and how you can build it yourself.</p>
]]></content:encoded></item><item><title><![CDATA[Popular CSS methodologies]]></title><description><![CDATA[CSS coding conventions aim to serve as guidelines for writing CSS code and help to ensure consistency, maintainability, and scalability across a project…]]></description><link>https://dragostemelie.hashnode.dev/popular-css-methodologies</link><guid isPermaLink="true">https://dragostemelie.hashnode.dev/popular-css-methodologies</guid><category><![CDATA[CSS]]></category><dc:creator><![CDATA[Dragos Temelie]]></dc:creator><pubDate>Sun, 02 Apr 2023 09:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1701421807555/19cf647f-9526-4ecf-8321-46625455a6b7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>CSS coding conventions aim to serve as guidelines for writing CSS code and help to ensure consistency, maintainability, and scalability across a project. Here are some of the most commonly used:</p>
<h3 id="heading-bem-methodology"><strong>BEM Methodology</strong></h3>
<p>The basic idea behind BEM is to create a clear and understandable naming structure for your CSS classes.</p>
<p>It separates your code into three distinct parts:</p>
<ol>
<li><p><strong>Block</strong>: Top-level container - ex: a header;</p>
</li>
<li><p><strong>Element</strong>: Child element within the block - ex: logo within a header;</p>
</li>
<li><p><strong>Modifier</strong>: A variation of a block or element - ex: a disabled button, a highlighted text, or a larger font size for a header.</p>
</li>
</ol>
<p>The naming convention for BEM follows a specific pattern. It uses double underscores (__) to separate elements from blocks and double hyphens (--) to separate modifiers from blocks or elements:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* BLOCK */</span>
<span class="hljs-selector-class">.block</span> {}

<span class="hljs-comment">/* ELEMENT */</span>
<span class="hljs-selector-class">.block__element</span> {}

<span class="hljs-comment">/* MODIFIER */</span>
<span class="hljs-selector-class">.block--modifier</span> {}
</code></pre>
<h3 id="heading-atomic-design-methodology"><strong>Atomic design methodology</strong></h3>
<p>Atomic design breaks down a user interface into smaller, reusable components that can be combined to create more complex interfaces.</p>
<ol>
<li><p><strong>Atoms</strong>: The basic building blocks of a UI, such as buttons, inputs, and icon;</p>
</li>
<li><p><strong>Molecules</strong>: Combinations of atoms that work together to perform specific functions, such as a search bar or a dropdown menu;</p>
</li>
<li><p><strong>Organisms</strong>: Combinations of molecules and atoms that form a more complex component, such as a header, a footer, or a product card;</p>
</li>
<li><p><strong>Templates</strong>: Complete layouts that combine multiple organisms and molecules to create a specific page or view;</p>
</li>
<li><p><strong>Pages</strong>: Instances of a template that contain real content and represent a specific view or state of the application. Pages are the final stage of the design process and are the actual UI that users interact with.</p>
</li>
</ol>
<pre><code class="lang-css"><span class="hljs-comment">/* ATOMS */</span>
<span class="hljs-selector-class">.search-input</span> {}
<span class="hljs-selector-class">.search-button</span> {}
<span class="hljs-selector-class">.search-icon</span> {}

<span class="hljs-comment">/* MOLECULES */</span>
<span class="hljs-selector-class">.search-form</span> {}

<span class="hljs-comment">/* ORGANISMS */</span>
<span class="hljs-selector-class">.search-bar</span> {}

<span class="hljs-comment">/* TEMPLATES */</span>
<span class="hljs-selector-class">.header</span> {}

<span class="hljs-comment">/* PAGES */</span>
<span class="hljs-selector-class">.search-results</span> {}
</code></pre>
<h3 id="heading-smacss-methodology"><strong>SMACSS methodology</strong></h3>
<p>SMACSS (<strong>S</strong>calable and <strong>M</strong>odular <strong>A</strong>rchitecture for <strong>CSS</strong>) was created by front-end developer <strong>Jonathan Snook</strong>, and it emphasizes the importance of consistency, maintainability, and scalability in CSS code.</p>
<p>The key principles of SMACSS are:</p>
<ol>
<li><p>CSS rules are categorized into five types, based on their role in the page: <strong>Base</strong>, <strong>Layout</strong>, <strong>Module</strong>, <strong>State</strong>, and <strong>Theme</strong>.</p>
</li>
<li><p>Use a consistent naming convention for CSS classes, to make it easier to understand the purpose of each class and to avoid naming conflicts.</p>
</li>
<li><p>Avoid overly specific CSS selectors, as they can make it difficult to override styles and maintain consistency across the codebase.</p>
</li>
<li><p>Break down CSS into smaller, reusable components, which can be combined to create larger designs.</p>
</li>
<li><p>Separate the structure (<strong>HTML</strong>) from the skin (<strong>CSS</strong>), to make it easier to update the visual design of a site without affecting its underlying structure.</p>
</li>
</ol>
<pre><code class="lang-css"><span class="hljs-comment">/* BASE */</span>
<span class="hljs-selector-class">.btn</span> {}

<span class="hljs-comment">/* LAYOUT */</span>
<span class="hljs-selector-class">.btn--primary</span> {}
<span class="hljs-selector-class">.btn--secondary</span> {}

<span class="hljs-comment">/* MODULE */</span>
<span class="hljs-selector-class">.btn__icon</span> {}
<span class="hljs-selector-class">.btn__text</span> {}

<span class="hljs-comment">/* STATE */</span>
<span class="hljs-selector-class">.btn</span><span class="hljs-selector-class">.is-active</span> {}

<span class="hljs-comment">/* THEME */</span>
<span class="hljs-selector-class">.theme-dark</span> <span class="hljs-selector-class">.btn--primary</span> {}
<span class="hljs-selector-class">.theme-dark</span> <span class="hljs-selector-class">.btn--secondary</span> {}
</code></pre>
<p>Ultimately, the best CSS methodology for a project will depend on factors like your team's preferences and experience, the size and complexity of your project, and your overall goals for the design and development process.</p>
]]></content:encoded></item><item><title><![CDATA[Common Design Patterns In JavaScript]]></title><description><![CDATA[Design patterns offer a shared language for organizing code, simplifying comprehension and bolstering collaboration among developers. Here are some of the]]></description><link>https://dragostemelie.hashnode.dev/common-design-patterns-in-javascript</link><guid isPermaLink="true">https://dragostemelie.hashnode.dev/common-design-patterns-in-javascript</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Dragos Temelie]]></dc:creator><pubDate>Sat, 25 Mar 2023 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1701426625677/cda4a331-d1d7-40a9-8b52-b7cdf6d9e859.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Design patterns offer a shared language for organizing code, simplifying comprehension and bolstering collaboration among developers. Here are some of the most popular design patterns used in JavaScript.</p>
<h3 id="heading-the-singleton-pattern"><strong>The Singleton Pattern</strong></h3>
<blockquote>
<p>In mathematics, a <strong>singleton</strong>, also known as a <strong>unit set</strong>, is a set with exactly one element. For example, the set {null} is a singleton.</p>
</blockquote>
<p>You can implement the <strong>Singleton pattern</strong> by creating a class with a method that creates a new instance of the class only if one doesn’t already exist. If an instance already exists, it simply returns a reference to that object.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701425857061/5e225c95-34c0-4565-bf55-b9c42a3231ac.png?width=300" alt class="image--center mx-auto" /></p>
<p>ES2015+ allows us to implement the singleton pattern to create <strong>a global instance</strong> of a JavaScript class that is instantiated once. You can expose the singleton instance through a module export.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Instance stores a reference to the Singleton</span>
<span class="hljs-keyword">let</span> instance;

<span class="hljs-keyword">const</span> randomNumber = <span class="hljs-built_in">Math</span>.random();

<span class="hljs-comment">// Singleton</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PhoneSingleton</span> </span>{
  <span class="hljs-comment">// Get the Singleton instance if one exists</span>
  <span class="hljs-comment">// or create one if it doesn't</span>
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-keyword">if</span> (!instance) {
      instance = <span class="hljs-built_in">this</span>;
    }
    <span class="hljs-keyword">return</span> instance;
  }
  <span class="hljs-comment">// Public methods</span>
  getRandomNumber() {
    <span class="hljs-keyword">return</span> randomNumber;
  }
}
<span class="hljs-comment">// [ES2015+] Default export module, without name</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MySingleton;
</code></pre>
<p>What makes the Singleton is the global access to the instance:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Usage:</span>
<span class="hljs-keyword">import</span> PhoneSingleton <span class="hljs-keyword">from</span> <span class="hljs-string">'./PhoneSingleton'</span>;

<span class="hljs-keyword">const</span> singleA = <span class="hljs-keyword">new</span> PhoneSingleton();
<span class="hljs-keyword">const</span> singleB = <span class="hljs-keyword">new</span> PhoneSingleton();
<span class="hljs-built_in">console</span>.log(singleA.getRandomNumber() === singleB.getRandomNumber());
<span class="hljs-comment">// true</span>
</code></pre>
<p>As an example, let’s say that you have a trivial application which is used for counting how many times buttons have been clicked.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701425909888/52aec5f8-f72a-4db0-8caf-97f7372d2f5a.png?width=400" alt class="image--center mx-auto" /></p>
<p>You should keep track of the number of button presses in one object which provides:</p>
<ul>
<li><p>the functionality of counting,</p>
</li>
<li><p>and providing the current number of clicks.</p>
</li>
</ul>
<p>If that object wasn’t a singleton (and the buttons would each get their own instance) the click count wouldn’t be correct.</p>
<h3 id="heading-the-observer-pattern"><strong>The Observer Pattern</strong></h3>
<p>The <strong>observer pattern</strong> is a software design pattern in which an object, called the <strong>subject</strong>, maintains a list of its dependents, called <strong>observers</strong>, and notifies them automatically of any state changes, usually by calling one of their methods.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701426035316/08cf4ff0-50fa-43b1-ba0f-bb60ef6b2511.png?width=400" alt class="image--center mx-auto" /></p>
<p>The nice thing is you don’t have to be the only subscriber. That’s why multiple observers can subscribe to the subject.</p>
<p>Since in JavaScript everything is event-driven rather than always asking if an event happened, you should let the event inform you.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Define the subject (observable)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Subject</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">this</span>.listeners = [];
  }

  addListener(subscriber) {
    <span class="hljs-built_in">this</span>.listeners.push(subscriber);
  }

  removeListener(subscriber) {
    <span class="hljs-built_in">this</span>.listeners = <span class="hljs-built_in">this</span>.listeners.filter(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> item !== subscriber);
  }

  click() {
    <span class="hljs-built_in">this</span>.listeners.forEach(<span class="hljs-function"><span class="hljs-params">subscriber</span> =&gt;</span> subscriber());
  }
}
</code></pre>
<p>In the next code snippet, the <code>Subject</code> class is the observable object that maintains a list of listeners (observers) and notifies them when its <code>click</code> method is called.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Define the observer</span>
<span class="hljs-keyword">const</span> button = <span class="hljs-keyword">new</span> Subject();

<span class="hljs-keyword">const</span> showMessage = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked!"</span>);
}

<span class="hljs-keyword">const</span> showAlert = <span class="hljs-function">() =&gt;</span> {
  alert(<span class="hljs-string">"Button clicked!"</span>);
}

<span class="hljs-comment">// Add subscribers to the subject</span>
button.addListener(showMessage);
button.addListener(showAlert);

<span class="hljs-comment">// Trigger the subject's action</span>
button.click(); 
<span class="hljs-comment">// logs "Button clicked!" and shows an alert box</span>

<span class="hljs-comment">// Remove a subscriber from the subject</span>
button.removeListener(showMessage);

<span class="hljs-comment">// Trigger the subject's action again</span>
button.click(); 
<span class="hljs-comment">// shows an alert box only</span>
</code></pre>
<p><strong>The observer pattern</strong> allows to define a one-to-many relationship between objects so that when one object changes state, all its dependents are notified and updated automatically.</p>
<h3 id="heading-the-decorator-pattern"><strong>The Decorator Pattern</strong></h3>
<p>Decorators are a structural design pattern that aims to promote code reuse. We can use them to modify existing systems where we wish to add additional features to objects without heavily changing the underlying code that uses them.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701426083741/f5e14288-938f-49c1-b161-d6dd8e33b7d2.png?width=400" alt class="image--center mx-auto" /></p>
<p>Decorating Constructors with New Functionality:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// A vehicle constructor</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-keyword">constructor</span>(vehicleType) {
        <span class="hljs-comment">// some sane defaults</span>
        <span class="hljs-built_in">this</span>.vehicleType = vehicleType || <span class="hljs-string">'car'</span>;
        <span class="hljs-built_in">this</span>.model = <span class="hljs-string">'default'</span>;
        <span class="hljs-built_in">this</span>.license = <span class="hljs-string">'00000-000'</span>;
    }
}

<span class="hljs-comment">// Test instance for a basic vehicle</span>
<span class="hljs-keyword">const</span> testInstance = <span class="hljs-keyword">new</span> Vehicle(<span class="hljs-string">'car'</span>);
<span class="hljs-built_in">console</span>.log(testInstance);

<span class="hljs-comment">// Outputs:</span>
<span class="hljs-comment">// vehicle: car, model:default, license: 00000-000</span>
</code></pre>
<p>Lets create a new instance of vehicle, to be decorated:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> truck = <span class="hljs-keyword">new</span> Vehicle(<span class="hljs-string">'truck'</span>);

<span class="hljs-comment">// New functionality we're decorating vehicle with</span>
truck.setModel = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">modelName</span>) </span>{
    <span class="hljs-built_in">this</span>.model = modelName;
};

truck.setColor = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">color</span>) </span>{
    <span class="hljs-built_in">this</span>.color = color;
};

<span class="hljs-comment">// Test the value setters and value assignment works correctly</span>
truck.setModel(<span class="hljs-string">'CAT'</span>);
truck.setColor(<span class="hljs-string">'blue'</span>);

<span class="hljs-built_in">console</span>.log(truck);

<span class="hljs-comment">// Outputs:</span>
<span class="hljs-comment">// vehicle:truck, model:CAT, color: blue</span>
</code></pre>
<p>Here, <code>truck</code> is an instance of the class <code>Vehicle</code>, and we also decorate it with additional methods <code>setColor</code> and <code>setModel</code>.</p>
<h3 id="heading-the-mvc-pattern"><strong>The MVC Pattern</strong></h3>
<p>MVC(stands for <strong>Model-View-Controller</strong>) is an architectural design pattern that encourages improved application organization through a separation of concerns. The pattern aims to separate an application into three interconnected components:</p>
<ol>
<li><p><strong>Model</strong>: represents the data and business logic of the application.</p>
</li>
<li><p><strong>View</strong>: represents the user interface and presentation layer of the application.</p>
</li>
<li><p><strong>Controller</strong>: acts as an intermediary between the model and view components. It receives input from the user and updates the model accordingly. It also updates the view based on changes in the model.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701426137075/43b44bbd-5510-40bb-809c-fb9dd63d1fdb.png?width=400" alt class="image--center mx-auto" /></p>
<p>By separating the application into these three components, the MVC pattern helps developers to achieve a clean and organized codebase, with each component being responsible for a specific task.</p>
<p>The first among these frameworks include <a target="_blank" href="https://backbonejs.org/">Backbone</a>, <a target="_blank" href="https://emberjs.com/">Ember.js</a>, and <a target="_blank" href="https://angularjs.org/">AngularJS</a>. More recently, <strong>React</strong>, <strong>Angular</strong> and <strong>Vue.js</strong> ecosystems have been used to implement different variations of the MVC family of patterns.</p>
<hr />
<p>Familiarity with these patterns enables us to recognize recurring patterns in project requirements and translate them into better reliable solutions.<a target="_blank" href="https://drate.net/image/2a55f4c7-842e-441b-a548-414e25b72b88">  
</a>  </p>
<p><a target="_blank" href="https://drate.net/image/8d34f6be-e415-4d95-a3fd-22cb4c0841f6">  
</a><br /><a target="_blank" href="https://drate.net/image/648a899d-d7a8-42f8-b173-ecddb2b7e96e">  
</a><br /><a target="_blank" href="https://drate.net/image/8fd475b8-2485-442f-ae16-003253e09c3f">  
</a></p>
]]></content:encoded></item><item><title><![CDATA[Page lifecycle API with React custom hook]]></title><description><![CDATA[The web application my team is building needs the users to be logged in, to be able to edit the content. The login is a token-based system with a short…]]></description><link>https://dragostemelie.hashnode.dev/page-lifecycle-api-with-react-custom-hook</link><guid isPermaLink="true">https://dragostemelie.hashnode.dev/page-lifecycle-api-with-react-custom-hook</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Dragos Temelie]]></dc:creator><pubDate>Wed, 17 Feb 2021 22:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1701427895703/e3e16954-b9a5-4b35-a9d3-bd65900be39a.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701427814395/64edada1-6fbf-4111-8fdc-6bfd7ae9ae8a.jpeg" alt class="image--center mx-auto" /></p>
<p>The web application my team is building needs the users to be logged in, to be able to edit the content. The login is a token-based system with a short expiration time and the app is built using React JS.</p>
<p>As you can imagine, users sometimes leave the page open on the browser for several minutes, maybe hours. When they come back to the page, it can happen so that the token expired, but the user doesn't know it yet. He will find out only after making a request.</p>
<p>We needed a way to check if the token is valid every time the user returned to the page. Polling was one way to accomplish this, that is simply hitting an API endpoint to check validity at a set interval of time. But that seems like a lot of unnecessary requests for a simple token check.</p>
<h3 id="heading-observing-page-states"><strong>Observing page states</strong></h3>
<p>It is possible to run JavaScript code that determines the current page state from the existing web platform APIs:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getState = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">document</span>.visibilityState === <span class="hljs-string">'hidden'</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'hidden'</span>;
  }
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">document</span>.hasFocus()) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'active'</span>;
  }
  <span class="hljs-keyword">return</span> <span class="hljs-string">'passive'</span>;
};
</code></pre>
<h3 id="heading-the-hook"><strong>The hook</strong></h3>
<p>One elegant way to check the page state is using a React hook. Inside the hook, we can have an effect which will run on every page state change:</p>
<pre><code class="lang-javascript">useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Set the next state</span>
  <span class="hljs-keyword">const</span> visibilityChange = <span class="hljs-function">() =&gt;</span> {
    setPageState(getState());
  };
  <span class="hljs-comment">// These  events can all use the same listener to observe state</span>
  <span class="hljs-comment">// changes (they call the `getState()` function to determine the next state).</span>
  [<span class="hljs-string">'focus'</span>, <span class="hljs-string">'blur'</span>, <span class="hljs-string">'visibilitychange'</span>, <span class="hljs-string">'resume'</span>].forEach(<span class="hljs-function"><span class="hljs-params">type</span> =&gt;</span> {
    <span class="hljs-built_in">window</span>.addEventListener(type, visibilityChange, {
      <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span>,
    });
  });
  <span class="hljs-comment">//Every next effect we need to remove the previous listeners</span>
  <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
    [<span class="hljs-string">'focus'</span>, <span class="hljs-string">'blur'</span>, <span class="hljs-string">'visibilitychange'</span>, <span class="hljs-string">'resume'</span>].forEach(<span class="hljs-function"><span class="hljs-params">type</span> =&gt;</span> {
      <span class="hljs-built_in">window</span>.removeEventListener(type, visibilityChange);
    });
  };
});
</code></pre>
<p>The above code does two things:</p>
<ul>
<li><p>Sets the pageState using the <code>getState()</code> function.</p>
</li>
<li><p>Adds capturing event listeners for all necessary page events</p>
</li>
</ul>
<h3 id="heading-the-usepagevisibility-hook"><strong>The usePageVisibility hook</strong></h3>
<p>And here we have the complete <code>usePageVisibility</code> code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> getState = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">document</span>.visibilityState === <span class="hljs-string">'hidden'</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'hidden'</span>;
  }
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">document</span>.hasFocus()) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'active'</span>;
  }
  <span class="hljs-keyword">return</span> <span class="hljs-string">'passive'</span>;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> usePageVisibility = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [pageState, setPageState] = useState(getState());

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> visibilityChange = <span class="hljs-function">() =&gt;</span> {
      setPageState(getState());
    };
    <span class="hljs-comment">//add listeners</span>
    [<span class="hljs-string">'focus'</span>, <span class="hljs-string">'blur'</span>, <span class="hljs-string">'visibilitychange'</span>, <span class="hljs-string">'resume'</span>].forEach(<span class="hljs-function"><span class="hljs-params">type</span> =&gt;</span> {
      <span class="hljs-built_in">window</span>.addEventListener(type, visibilityChange, {
        <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span>,
      });
    });
    <span class="hljs-comment">//cleanup</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      [<span class="hljs-string">'focus'</span>, <span class="hljs-string">'blur'</span>, <span class="hljs-string">'visibilitychange'</span>, <span class="hljs-string">'resume'</span>].forEach(<span class="hljs-function"><span class="hljs-params">type</span> =&gt;</span> {
        <span class="hljs-built_in">window</span>.removeEventListener(type, visibilityChange);
      });
    };
  });
  <span class="hljs-keyword">return</span> pageState;
};
</code></pre>
<p>Now every time you leave and come back to the page, the <code>setTokenExpired()</code> will be triggered and update the component state.</p>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>Sometimes you need a simple way to check if a user is still logged in. With React Hooks, and especially the ability to put together custom Hooks, creating a reusable Hook to serve just such a purpose seemed inevitable.</p>
<p>Check <a target="_blank" href="https://developers.google.com/web/updates/2018/07/page-lifecycle-api">this article</a> for a more in-depth look on how page lifecycle works.</p>
]]></content:encoded></item><item><title><![CDATA[Currency convertor using Excel]]></title><description><![CDATA[One of the most time-wasting problems at my former job was to get the currency match for a list of dates. I came up with a solution to this problem by…]]></description><link>https://dragostemelie.hashnode.dev/currency-convertor-using-excel</link><guid isPermaLink="true">https://dragostemelie.hashnode.dev/currency-convertor-using-excel</guid><category><![CDATA[excel]]></category><dc:creator><![CDATA[Dragos Temelie]]></dc:creator><pubDate>Tue, 12 Jan 2021 10:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1701428613803/29ac577a-e37f-4c82-882b-5f2c66593dfe.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One of the most time-wasting problems at my former job was to get the currency match for a list of dates. I came up with a solution to this problem by using VBA, the programming language of the office suite.</p>
<p>Since I am from Romania, the official RON currency rates are published by the National Bank of Romania(<a target="_blank" href="https://www.bnr.ro/">BNR</a>) and all I had to do was to access the records.</p>
<p>The currency lists are grouped by years in XML files:</p>
<ul>
<li><p><a target="_blank" href="https://www.bnr.ro/files/xml/years/nbrfxrates2020.xml">nbrfxrates2020.xml</a></p>
</li>
<li><p><a target="_blank" href="https://www.bnr.ro/files/xml/years/nbrfxrates2021.xml">nbrfxrates2021.xml</a></p>
</li>
<li><p>etc..</p>
</li>
</ul>
<p>I added a new module in the Visual Basic editor window(<strong>Alt + F11</strong>):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701429004186/87299707-2217-4adf-8456-9e95e247edd6.jpeg?width=318" alt class="image--center mx-auto" /></p>
<p>A reference to the Microsoft XML library is needed since we're gonna be dealing with XML file format:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1701429015093/bbabfe3f-ef86-4aa5-a815-71287189de60.jpeg?width=491" alt class="image--center mx-auto" /></p>
<p>And here is the function that reads the XML file, searches for the given currency symbol, and returns the rate. Putting that in the <code>currencyModule</code> and we're good to go:</p>
<pre><code class="lang-basic">Public Function CURS(<span class="hljs-keyword">Data</span> As Date, Symbol As String) As String
    <span class="hljs-comment">'### LOAD XML</span>
    <span class="hljs-keyword">Dim</span> XMLDoc As MSXML2.DOMDocument60
    Set XMLDoc = <span class="hljs-keyword">New</span> MSXML2.DOMDocument60
    XMLDoc.async = False
    XMLDoc.validateOnParse = False
    XMLDoc.SetProperty \<span class="hljs-string">"SelectionNamespaces\", \"xmlns:ns='http://www.bnr.ro/xsd'\"
    XMLDoc.Load (\"https://www.bnr.ro/files/xml/years/nbrfxrates\" &amp; Year(Data) &amp; \".xml\")

    '### CHECK DATE
    Dim currencyDate As String, currencyValue As String
    If IsDate(Data) Then
        currencyDate = Format(Data, \"yyyy-mm-dd\")
    Else
        CURS = \"#VALUE\" 'currency date is invalid
        Exit Function
    End If

    '### GET CURRENCY BY DATE
    If XMLDoc.SelectNodes(\"/ns:DataSet/ns:Body/ns:Cube[@date='\" &amp; currencyDate &amp; \"']/ns:Rate[@currency='\" &amp; UCase(Symbol) &amp; \"']\").Length &gt; 0 Then
        currencyValue = XMLDoc.SelectNodes(\"/ns:DataSet/ns:Body/ns:Cube[@date='\" &amp; currencyDate &amp; \"']/ns:Rate[@currency='\" &amp; UCase(Symbol) &amp; \"']\").Item(0).Text
    Else
        CURS = \"#N/A\" 'currency for that date not found
        Exit Function
    End If
    CURS = currencyValue
End Function</span>
</code></pre>
<p>Making the function <strong>Public</strong> makes it possible to be used inside the workbook cells, like a normal formula:</p>
<p><code>=CURS(\\\"2021-10-01\\\",\\\"EUR\\\")</code>.</p>
<p>The <a target="_blank" href="https://docs.microsoft.com/en-us/office/vba/api/word.xmlnode.selectnodes">XMLDoc.SelectNodes</a> function gets the XML node value that matches the XPath string, in this case:</p>
<p><code>DataSet-&gt;Body-&gt;Cube[@date]-&gt;Rate[@currency]</code></p>
<p>You can download the Excel file <a target="_blank" href="https://drate.go.ro/images/articles/Currency.xlsm">here</a>. Keep in mind you need to have macros enabled for it to work.</p>
]]></content:encoded></item></channel></rss>