fusenapi/utils/auth/user_test.go
2023-10-17 17:25:48 +08:00

129 lines
2.8 KiB
Go

package auth
import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"testing"
"time"
)
func TestCase(t *testing.T) {
info := &UserInfo{
UserId: 1,
}
log.Println(info)
data, _ := json.Marshal(info)
log.Println(string(data))
a := `{"user_id":0,"guest_id":1,"exp":0, "debug": { "exp": 12321213321}}`
err := json.Unmarshal([]byte(a), info)
log.Println(err)
log.Printf("%#v %v", info, info.Debug)
// now := time.Now().UTC().Unix()
v, err := GenerateBaseJwtTokenUint64(DefaultDebugJwtSecret, time.Now().UTC().Unix(), 3600, info.Debug)
log.Println(v, err)
d, err := ParseDebugJwtTokenWithHeader("Debug-Token", &http.Request{
Header: http.Header{
"Debug-Token": []string{v},
},
})
log.Println(d, err)
}
// TestGenJwt 测试jwt序列化
func TestGenJwt(t *testing.T) {
now := time.Now().UTC().Unix()
secret := "fusen123"
a, err := GenerateJwtToken(&secret, 3600, now, 123, 1234)
if err != nil {
t.Error(err)
}
// log.Println(a)
claims, err := getJwtClaims(a, &secret)
if err != nil {
t.Error(err)
}
userinfo, err := GetUserInfoFormMapClaims(claims)
if err != nil {
t.Error(err)
}
if userinfo.UserId != 123 || userinfo.GuestId != 1234 {
t.Error(userinfo)
}
// log.Println(claims)
}
func TestGenBackendJwt(t *testing.T) {
now := time.Now().UTC().Unix()
secret := "fusen_backend_2023"
a, err := GenerateBackendJwtToken(&secret, 3600*24*7, now, 1, 1)
if err != nil {
t.Error(err)
}
log.Println(a)
claims, err := getJwtClaims(a, &secret)
if err != nil {
t.Error(err)
}
userinfo, err := GetBackendUserInfoFormMapClaims(claims)
if err != nil {
t.Error(err)
}
if userinfo.UserId != 1 || userinfo.DepartmentId != 1 {
t.Error(userinfo)
}
// log.Println(claims)
}
func TestCase1(t *testing.T) {
a := sha256.New()
a.Write([]byte("fusen_backend_3021"))
base64.RawURLEncoding.EncodeToString(a.Sum(nil))
as := fmt.Sprintf("%x", a.Sum(nil))
log.Println(as, len(as), base64.RawURLEncoding.EncodeToString(a.Sum(nil)))
// b := sha256.New().Sum([]byte("fusen_backend_2022"))
// bs := fmt.Sprintf("%x", b)
// log.Println(bs)
// log.Println(as == bs)
// log.Println(basic.CBCEncrypt("sdfsdfsadsasdasadas", "1232132131232132"))
// log.Println(basic.CBCDecrypt("8pq8ud33FfFZN2jUmBaNFfYbOeyrK1C/xVEtnbV2HfeG9KCGZfEcF6qrRwOHzWvT", "1232132131232132"))
}
func TestCheckValueRange(t *testing.T) {
v := 1
rv1 := []int{1, 3, 4}
if !CheckValueRange[int](v, rv1...) {
t.Error("1 in [1 3 4], but is false")
}
v = 2
if CheckValueRange(v, rv1...) {
t.Error("2 not in [1 3 4], but is true")
}
vstr := "funsen123"
rvstr := []string{"funsun123", "funsen123", "funsen23"}
if !CheckValueRange(vstr, rvstr...) {
t.Error("vstr in rvstr, but is false")
}
vstr = "funsen1234"
if CheckValueRange(vstr, rvstr...) {
t.Error("vstr not in rvstr, but is true")
}
}