added comments
This commit is contained in:
@ -6,7 +6,6 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
@ -14,6 +13,7 @@ import (
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/model"
|
||||
)
|
||||
|
||||
// Signup handles user signup by decoding request body, hashing the password, and saving user data to the database.
|
||||
func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
|
||||
var err error
|
||||
var login Login
|
||||
@ -50,6 +50,7 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// Login handles user login by decoding request body, verifying credentials, and returning a JWT token.
|
||||
func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
|
||||
var login Login
|
||||
var user model.User
|
||||
@ -86,6 +87,7 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write(res)
|
||||
}
|
||||
|
||||
// Logout handles user logout by invalidating the JWT and saving it to the database.
|
||||
func (s *Service) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
token, err := extractToken(r)
|
||||
if err != nil {
|
||||
@ -109,28 +111,3 @@ func (s *Service) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Service) Authenticated(next http.HandlerFunc, roles ...model.Role) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Our middleware logic goes here...
|
||||
token, err := extractToken(r)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := s.validateJWT(token)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// if roles specified check if satisfied
|
||||
if len(roles) > 0 && !slices.Contains(roles, claims.Role) {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
r = writeToContext(r, &claims)
|
||||
next(w, r)
|
||||
})
|
||||
}
|
||||
|
Reference in New Issue
Block a user