54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"git.schreifuchs.ch/schreifuchs/ng-blog/backend/internal/model"
|
|
)
|
|
|
|
func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
|
|
login := model.Login{}
|
|
if err := json.NewDecoder(r.Body).Decode(&login); err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
if login.Name == s.cfg.AdminName && login.Password == s.cfg.AdminPassword {
|
|
token, err := createJWT([]byte(s.cfg.Secret))
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
err = json.NewEncoder(w).Encode(&model.LoginResponse{
|
|
Token: token,
|
|
})
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
return
|
|
}
|
|
}
|
|
|
|
func (s *Service) Authenticated(next http.HandlerFunc) 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
|
|
}
|
|
|
|
err = validateJWT(token, []byte(s.cfg.Secret))
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
next(w, r)
|
|
})
|
|
}
|