-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Task/validation #43
base: dev
Are you sure you want to change the base?
Task/validation #43
Conversation
Только я не все хендлеры обернула, потому что все post put и delete обернуты в MiddlewareAuth, и я не очень понимаю, их в обе нужно обернуть или оставить одну? |
.env
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
файл надо убрать
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Очень усложнила схему, переизобретать jwt не стоит, прокидывать userID доп заголовками тоже не очень, это и не нужно
Login: user.Login, | ||
Email: user.Email, | ||
tokenExpTime := time.Now().Unix() + 3600 | ||
secretKey := os.Getenv("CSRF_SECRET") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Такое лучше конфигурировать при старте сервиса и прокидывать в поля структуры хэндлера
cookies.txt
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
тоже что-то лишнее
internal/pkg/middleware/csrf.go
Outdated
func (tk *HashToken) Create(userUUID uuid.UUID, tokenExpTime int64) (string, error) { | ||
h := hmac.New(sha256.New, tk.Secret) | ||
data := fmt.Sprintf("%s:%d", userUUID.String(), tokenExpTime) | ||
h.Write([]byte(data)) | ||
token := hex.EncodeToString(h.Sum(nil)) + ":" + strconv.FormatInt(tokenExpTime, 10) | ||
return token, nil | ||
} | ||
|
||
func (tk *HashToken) Check(userUUID uuid.UUID, inputToken string) (bool, error) { | ||
tokenData := strings.Split(inputToken, ":") | ||
if len(tokenData) != 2 { | ||
return false, fmt.Errorf("invalid token format") | ||
} | ||
tokenExpStr := strings.TrimSpace(tokenData[1]) | ||
tokenExp, err := strconv.ParseInt(tokenExpStr, 10, 64) | ||
if err != nil { | ||
return false, fmt.Errorf("invalid token expiration") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
И все таки, а чем тебя jwt не устроил?)
} | ||
|
||
response := UserResponseWithCSRF{ | ||
User: user, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Прям с паролем!
internal/pkg/middleware/csrf.go
Outdated
func CSRFMiddleware(tk *HashToken, next http.Handler, logger *slog.Logger) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
csrfToken := r.Header.Get("X-CSRF-Token") | ||
userUUIDStr := r.Header.Get("X-User-UUID") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А зачем этот заголовок, у пользователя разве нет другого способа аутентификации?
Смотри, давай лучше немного шаг назад сделаем и подсветим две проблемы твоего подхода:
|
@@ -33,6 +36,11 @@ type Handler struct { | |||
logger *slog.Logger | |||
} | |||
|
|||
type UserResponseWithToken struct { | |||
User models.User `json:"user"` | |||
Token string `json:"csrf_token"` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это уже называется access_token
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В json можно просто token
или access_token
. CSRF тут уже не при чем
@@ -18,19 +18,19 @@ const ( | |||
|
|||
func MiddlewareAuth(jwtService jwt.JWTInterface, next http.Handler, logger *slog.Logger) http.Handler { | |||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |||
token := r.Header.Get("X-CSRF-Token") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
CSRF тут уже не при чем, ты поменяла механизм передачи токена. Теперь это скорее вот эта схема https://swagger.io/docs/specification/v3_0/authentication/bearer-authentication/
Я тут добавила валидацию полей и заново сделала защиту от xss и csrf