Refactor CSRF secret handling to validate key length and improve error messaging
This commit is contained in:
@ -1,6 +1,7 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
|
||||
@ -137,3 +138,18 @@ func CSRFToken(r *http.Request) string {
|
||||
func CSRFTemplateField(r *http.Request) template.HTML {
|
||||
return csrf.TemplateField(r)
|
||||
}
|
||||
|
||||
// ParseCSRFKey validates and converts a CSRF secret string to the required 32-byte key
|
||||
// It returns the key as a byte slice and an error if the key is invalid
|
||||
func ParseCSRFKey(secret string) ([]byte, error) {
|
||||
if secret == "" {
|
||||
return nil, fmt.Errorf("csrf secret is required and must be exactly 32 bytes")
|
||||
}
|
||||
|
||||
key := []byte(secret)
|
||||
if len(key) != 32 {
|
||||
return nil, fmt.Errorf("csrf secret must be exactly 32 bytes (got %d bytes)", len(key))
|
||||
}
|
||||
|
||||
return key, nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user