Skip to content

Commit

Permalink
fix handler
Browse files Browse the repository at this point in the history
  • Loading branch information
Ugarov Ruslan Denisovich committed Nov 5, 2024
1 parent ac76885 commit 210a471
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 15 deletions.
12 changes: 9 additions & 3 deletions internal/app/secur/csrf/handlers/csrf.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package handlers

import (
"encoding/json"
errVals "github.com/go-park-mail-ru/2024_2_GOATS/internal/app/errors"
token_gen "github.com/go-park-mail-ru/2024_2_GOATS/internal/app/secur/csrf/token"
"log"
"net/http"
)

// GenerateCSRFTokenHandler создает CSRF-токен и отправляет его клиенту
// GenerateCSRFTokenHandler создает CSRF-токен и отправляет его клиенту в теле ответа
func GenerateCSRFTokenHandler(w http.ResponseWriter, r *http.Request) {
token, err := token_gen.GenerateToken()
if err != nil {
Expand All @@ -16,7 +17,12 @@ func GenerateCSRFTokenHandler(w http.ResponseWriter, r *http.Request) {
return
}

token_gen.SetCSRFTokenCookie(w, token)

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)

response := map[string]string{"csrf_token": token}
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, "Failed to encode CSRF token", http.StatusInternalServerError)
log.Println("Error encoding response:", err)
}
}
12 changes: 0 additions & 12 deletions internal/app/secur/csrf/token/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package token
import (
"crypto/rand"
"encoding/base64"
"net/http"
)

// GenerateToken генерирует случайный CSRF-токен
Expand All @@ -15,14 +14,3 @@ func GenerateToken() (string, error) {
}
return base64.StdEncoding.EncodeToString(token), nil
}

// SetCSRFTokenCookie сохраняет CSRF-токен в cookie
func SetCSRFTokenCookie(w http.ResponseWriter, token string) {
http.SetCookie(w, &http.Cookie{
Name: "csrf_token",
Value: token,
Path: "/",
HttpOnly: true,
Secure: true, // Для прода
})
}

0 comments on commit 210a471

Please sign in to comment.