Gopress, a blog in Golang (part 8)
Hello everyone! We continue with our series on how to build a blog using Golang, the programming language created by Google that is becoming increasingly popular. If you missed the previous parts, I invite you to go to our previous articles and catch up. Today, in the eighth installment of our series, we will focus on authentication and security. Let’s get started!
Checkboxes
Authentication and security
So far, we have created our blog, Gopress, with basic functionalities, but we have not yet implemented any authentication mechanism. We do not want just anyone to be able to publish, edit, or delete content on our blog. To prevent that, we need to implement an authentication system.
In Golang, there are several libraries available to help us with authentication, but for this tutorial, we will use "gorilla/sessions" to handle user sessions and "golang.org/x/crypto/bcrypt" for password hashing.
Implementing Sessions with Gorilla/Sessions
To begin, we need to install the Gorilla Sessions package. If you are using go modules, you can do it with the following command:
bashCopy codego get github.com/gorilla/sessions
First, let's define a global variable for our session store:
goCopy codevar (
key = []byte("super-secret-key")
store = sessions.NewCookieStore(key)
)
Once this is done, we can implement a function to set a session after a successful login:
goCopy codefunc setSession(userName string, w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "cookie-name")
session.Values["authenticated"] = true
session.Values["username"] = userName
session.Save(r, w)
}
And another function to check if a user is authenticated:
goCopy codefunc checkSession(r *http.Request) bool {
session, _ := store.Get(r, "cookie-name")
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
return false
}
return true
}
Password hashing with bcrypt
Now, we will handle passwords securely with bcrypt. You can get bcrypt with the following command:
bashCopy codego get golang.org/x/crypto/bcrypt
When a user registers or changes their password, we must ensure not to store the password in plain text. Instead, we will store a hash of the password. Here is the function to generate the password hash:
goCopy codefunc hashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
And when a user logs in, we can verify the entered password with the stored hash:
goCopy codefunc checkPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
And that's it for today! Now you have the tools to implement authentication in your Gopress blog. In the next post, we will focus on handling roles and permissions for users. As always, if you have any questions or problems, feel free to leave us a comment.
Role and permission management
Now that we have authentication, we might want to implement roles and permissions. For example, maybe we want an "editor" role that can review and approve posts before they are published, and an "author" role that can write and edit their own posts, but not those of others.
To implement this, we first need to extend our user model to include a role field:
goCopy codetype User struct {
ID int
Username string
Password string
Role string
}
Then, we can check the user's role during authentication. Here is an example function that checks if a user is an editor:
goCopy codefunc checkRole(r *http.Request) string {
session, _ := store.Get(r, "cookie-name")
role := session.Values["role"].(string)
return role
}
We can use this function in our controllers to restrict access to certain functions based on the user's role. For example:
goCopy codefunc editPostHandler(w http.ResponseWriter, r *http.Request) {
if !checkSession(r) {
http.Redirect(w, r, "/login", 302)
return
}
if checkRole(r) != "editor" {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
// ... código para editar la publicación ...
}
In this code, we redirect unauthenticated users to the login page. If the user is authenticated but not an editor, we return a 403 Forbidden error. Only editors can access the post editing functionality.
We hope this article has been helpful for you to understand how to implement authentication and roles in your Gopress blog. In the next post, we will explore how to implement a search functionality in the blog. See you in the next installment!
Comentarios