-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
♻️ refactor: added csrf token utils #9
- Loading branch information
1 parent
999d37a
commit c7f567f
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |