Improve comments and code readability

This commit is contained in:
Marco Realacci 2023-01-10 01:21:53 +01:00
parent f6ad6db2f7
commit 3de158e5a5
19 changed files with 84 additions and 43 deletions

View file

@ -10,6 +10,7 @@ import (
"github.com/sirupsen/logrus"
)
// BuildAuth returns an Authorization implementation for the currently logged in user
func BuildAuth(header string) (reqcontext.Authorization, error) {
auth, err := BuildBearer(header)
if err != nil {
@ -21,6 +22,8 @@ func BuildAuth(header string) (reqcontext.Authorization, error) {
return auth, nil
}
// Given a user authorization function, if the function returns some error, it sends the error to the client and return false
// Otherwise it returns true without sending anything to the client
func SendAuthorizationError(f func(db database.AppDatabase, uid string) (reqcontext.AuthStatus, error), uid string, db database.AppDatabase, w http.ResponseWriter, l logrus.FieldLogger, notFoundStatus int) bool {
auth, err := f(db, uid)
if err != nil {
@ -28,21 +31,25 @@ func SendAuthorizationError(f func(db database.AppDatabase, uid string) (reqcont
return false
}
if auth == reqcontext.UNAUTHORIZED {
// The token is not valid
helpers.SendStatus(http.StatusUnauthorized, w, "Unauthorized", l)
return false
}
if auth == reqcontext.FORBIDDEN {
// The user is not authorized for this action
helpers.SendStatus(http.StatusForbidden, w, "Forbidden", l)
return false
}
// requested user is not found -> 404 as the resource is not found
if auth == reqcontext.USER_NOT_FOUND {
// Attempting to perform an action on a non-existent user
helpers.SendStatus(notFoundStatus, w, "User not found", l)
return false
}
return true
}
// Given a function that validates a token, if the function returns some error, it sends the error to the client and return false
// Otherwise it returns true without sending anything to the client
func SendErrorIfNotLoggedIn(f func(db database.AppDatabase) (reqcontext.AuthStatus, error), db database.AppDatabase, w http.ResponseWriter, l logrus.FieldLogger) bool {
auth, err := f(db)
@ -53,6 +60,7 @@ func SendErrorIfNotLoggedIn(f func(db database.AppDatabase) (reqcontext.AuthStat
}
if auth == reqcontext.UNAUTHORIZED {
// The token is not valid
helpers.SendStatus(http.StatusUnauthorized, w, "Unauthorized", l)
return false
}