Tugas
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package auth
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestPasswordAndToken(t *testing.T) {
|
||||
pass := "secret123"
|
||||
hash, err := HashPassword(pass)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error hashing: %v", err)
|
||||
}
|
||||
if !CheckPassword(pass, hash) {
|
||||
t.Fatal("expected password check to succeed")
|
||||
}
|
||||
if CheckPassword("wrongpass", hash) {
|
||||
t.Fatal("expected wrong password to fail")
|
||||
}
|
||||
|
||||
tok, err := GenerateToken()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error generating token: %v", err)
|
||||
}
|
||||
if len(tok) != 64 {
|
||||
t.Fatalf("expected 64 hex chars, got %d", len(tok))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(bytes), nil
|
||||
}
|
||||
|
||||
func CheckPassword(password, hash string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
func GenerateToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
Reference in New Issue
Block a user