Building a Website Builder: Login Logic with GoLang

When you log into a website, do you ever wonder what’s happening behind the curtain? 🤔 While I can’t speak to all websites, I can walk you through how I set up authentication on the Coding with Callie website builder 🚀

My website builder API has a ‘/login’ route that I can send POST requests to with my username and password. I need the username to look up my specific user details in the database. If that username isn’t associated with a user, then I throw an error 🧨

Otherwise, I check if the found user’s password matches the password in the request body. This step is a little bit more complicated than just checking if `req.body.password == user.password` since it’s not a safe idea to save a password in plaintext 🥴

When the user is initially created, its plaintext password is hashed prior to saving it in the database. So, we need to compare the hashed password with its possible plaintext equivalent. Luckily, bcrypt has a function that does just that 🌟

If the passwords don’t match, we throw an error 🧨

If they do match, however, we can create a JSON Web Token (JWT) using a secret retrieved from an environment variable and an expiration time where the JWT will no longer be valid. That token will be saved in the Set-Cookie response header for future requests to use ⏳

One thing that I really like about Golang is its mandate to handle errors. I can get lazy when I code. I often rush to get something working and think “oh I’ll add X, Y, and Z later”…and then completely forget. So, I really appreciate that Go keeps me in line and keeps my errors handled 👯‍♀️

What do you think?! 💡

Want to develop your codings skills and network with other developers? Join the Coding with Callie community!

Coding with Callie – https://coding-with-callie.com/
LinkedIn – https://www.linkedin.com/company/coding-with-callie/

You May Also Like