Skip to content

Commit

Permalink
♻️ refactor: added csrf token utils #9
Browse files Browse the repository at this point in the history
  • Loading branch information
pnguyen215 committed Nov 5, 2023
1 parent 999d37a commit c7f567f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
16 changes: 16 additions & 0 deletions utils/converters.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package utils

import (
"bytes"
"encoding/json"
)

// Convert bytes to buffer helper
func Convert2BytesBuffer(i interface{}) (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(i)
if err != nil {
return buf, err
}
return buf, nil
}
25 changes: 25 additions & 0 deletions utils/csrf.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package utils

import (
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
)

// Create CSRF token
func CreateCSRFToken(sid, salt string) (string, error) {
hash := sha256.New()
_, err := io.WriteString(hash, fmt.Sprintf("%s%s", salt, sid))
if err != nil {
return "", err
}
token := base64.RawStdEncoding.EncodeToString(hash.Sum(nil))
return token, nil
}

// Validate CSRF token
func VerifyCSRFToken(token string, sid, salt string) bool {
t, _ := CreateCSRFToken(sid, salt)
return token == t
}

0 comments on commit c7f567f

Please sign in to comment.