Going with Go: Authentication & Route Protection

Abiral Sthapit
4 min readMar 2, 2024

--

Project: myMoneytracker
Features: Go server, authentication(jwt), db(TBD), Clean Architecture

phase_1: A simple wallet application where users can track their expenses

As with all applications we need the user to have users, so we need to store our users. Let's quickly set up our user structure on our store.

I was thinking of creating a simpler role-based authentication for now, but the code would work similarly with a more complex RBAC (Role Based Access Control) System minus some extra computation.

Now our user repository should have at least these basic functionalities.

For instance the GetAll() the method could have some more parameters like pagination props, number of items to limit props, filter props, etc and we can come here and add extra functionalities say find a user with a valid username and password combination.

Here I added the password hashing functionality and password verification functionality which will be used while verifying the user, With this in place we can now think about our routes (use cases).

Here I made some changes to the address of the user, as in the future I want to add a functionality of finding the users from specific locations.

so I also added a specific address ID to be able to select the specific address for update and deletion. Since we will be dealing with IDs we need some mechanism to generate it. I am going to use ksuid as it provides a sortable ID.

go get -u github.com/segmentio/ksuid

Now with these in place, it's only the actual implementation that is left, so let's create our user provider in the infrastructure.

Now for the forgot password feature, all we need is to generate a random number with x digits (OTP code) and store it in our db, for simplicity I am going to use the user store itself to store the forget password token(OTP code).

And finally adding the domain implementation.

with our helper functions for generating otp, simple update helper, which will not be necessary if using a real b client, and finally the jwt token creator and validator functions.

Now creating our middleware for simple UserProtection,

And Finally Updating our Routes

With this we have created a whole authentication flow for our users. Next we will refactor some of our vault code and simplify our middleware for adminroute support.
👋 Until then Stay caffeinated. ☕

--

--

Responses (1)