46 lines
1.3 KiB
Go
46 lines
1.3 KiB
Go
package restserver
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
|
|
"git.ukamnya.ru/stulyaganov/RestApiv2/pkg/utils/jwt"
|
|
)
|
|
|
|
func (r *RestServer) checkJwtAccess(next http.HandlerFunc) http.HandlerFunc {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, res *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
str := res.Header.Values("Authorization")
|
|
if str == nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
io.WriteString(w, `{"data":"Ошибка Авторизации"}`)
|
|
return
|
|
}
|
|
|
|
token := strings.Split(str[0], " ")
|
|
chek, err := jwt.ValidateToken(token[1], []byte(os.Getenv("JWT_SECRET_KEY_ACCESS")))
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
io.WriteString(w, `{"data":"Ошибка Авторизации"}`)
|
|
r.logger.Error(err)
|
|
return
|
|
}
|
|
payload, err := jwt.GetPayload(token[1], []byte(os.Getenv("JWT_SECRET_KEY_ACCESS")))
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
io.WriteString(w, `{"data":"Ошибка Авторизации"}`)
|
|
r.logger.Error(err)
|
|
}
|
|
if chek {
|
|
next(w, res.WithContext(context.WithValue(res.Context(), ContextKeyPayload, payload)))
|
|
} else {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
io.WriteString(w, `{"data":"Ошибка Авторизации"}`)
|
|
}
|
|
|
|
})
|
|
}
|