This commit is contained in:
@@ -116,12 +116,14 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
if err := s.db.First(&user).Error; err != nil {
|
||||
fmt.Fprint(w, "user not found")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprint(w, "user not found")
|
||||
return
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword(user.Password, []byte(login.Password)); err != nil {
|
||||
fmt.Fprint(w, "Invalid Password")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprint(w, "Invalid Password")
|
||||
return
|
||||
}
|
||||
|
||||
token, err := s.createJWT(&user)
|
||||
@@ -134,8 +136,8 @@ func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
|
||||
Token: token,
|
||||
})
|
||||
if err != nil {
|
||||
log.Println("Error: ", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
log.Println("Error: ", err)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -8,11 +8,16 @@ import (
|
||||
)
|
||||
|
||||
// Authenticated: This function is a middleware that authenticates incoming HTTP requests using JWT tokens and role-based access control.
|
||||
func (s *Service) Authenticated(next http.HandlerFunc, roles ...model.Role) http.Handler {
|
||||
func (s *Service) Authenticated(next http.HandlerFunc, mustauth bool, 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 {
|
||||
if !mustauth {
|
||||
r = writeToContext(r, nil)
|
||||
next(w, r)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user