feat: first version.

This commit is contained in:
tx7do
2023-05-18 13:06:55 +08:00
parent 75fcd82de5
commit ba93a75c5a
20 changed files with 1703 additions and 1 deletions

17
crypto/crypto.go Normal file
View File

@@ -0,0 +1,17 @@
package crypto
import (
"golang.org/x/crypto/bcrypt"
)
// HashPassword 加密密码
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 10)
return string(bytes), err
}
// CheckPasswordHash 校验密码
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}

32
crypto/crypto_test.go Normal file
View File

@@ -0,0 +1,32 @@
package crypto
import (
"fmt"
"github.com/stretchr/testify/assert"
"strings"
"testing"
)
func TestHashPassword(t *testing.T) {
text := "admin"
hash, _ := HashPassword(text)
fmt.Println(hash)
}
func TestCheckPasswordHash(t *testing.T) {
text := "123456"
hash3 := "$2a$10$ygWrRwHCzg2GUpz0UK40kuWAGva121VkScpcdMNsDCih2U/bL2qYy"
bMatched := CheckPasswordHash(text, hash3)
assert.True(t, bMatched)
bMatched = CheckPasswordHash(text, hash3)
assert.True(t, bMatched)
}
func TestJwtToken(t *testing.T) {
const bearerWord string = "Bearer"
token := "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjowfQ.XgcKAAjHbA6o4sxxbEaMi05ingWvKdCNnyW9wowbJvs"
auths := strings.SplitN(token, " ", 2)
assert.Equal(t, len(auths), 2)
assert.Equal(t, strings.EqualFold(auths[0], bearerWord), true, "JWT token is missing")
}