restructuring, config and readme
This commit is contained in:
53
backend/internal/auth/controller.go
Normal file
53
backend/internal/auth/controller.go
Normal file
@ -0,0 +1,53 @@
|
||||
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)
|
||||
})
|
||||
}
|
Reference in New Issue
Block a user