Adding authorization to our API
The good news is that almost everything we need is already done. We have users, we have sessions, we have roles, and we only need to check everything together, so let’s build a middleware for that:
func adminRequired(next http.HandlerFunc) http.HandlerFunc {
return authRequired(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
token = token[7:]
user := allUsers[sessions[token].Username]
if user.Role != "admin"
http.Error(w, "forbidden", http.StatusForbidden)
return
}
next(w, r)
})
}
We are creating a middleware but are already using the existing one to ensure the session is already there. That is why I’m only checking the user role. If it is an admin, I keep going. If not, I return a 403 Forbidden status code.
Now, we only need to apply the right middleware to my endpoints. In this case, we can apply this to all modifications...