gpaste/auth_test.go

57 lines
1.6 KiB
Go

package gpaste_test
import (
"math/rand"
"testing"
"git.t-juice.club/torjus/gpaste"
"git.t-juice.club/torjus/gpaste/users"
"github.com/google/go-cmp/cmp"
)
func TestAuth(t *testing.T) {
t.Run("Token", func(t *testing.T) {
us := users.NewMemoryUserStore()
secret := []byte(randomString(16))
as := gpaste.NewAuthService(us, secret)
username := randomString(8)
password := randomString(16)
user := &users.User{Username: username, Role: users.RoleAdmin}
if err := user.SetPassword(password); err != nil {
t.Fatalf("error setting user password: %s", err)
}
if err := us.Store(user); err != nil {
t.Fatalf("Error storing user: %s", err)
}
token, err := as.Login(username, password)
if err != nil {
t.Fatalf("Error creating token: %s", err)
}
claims, err := as.ValidateToken(token)
if err != nil {
t.Fatalf("Error validating token: %s", err)
}
if claims.Role != user.Role {
t.Fatalf("Token role is not correct: %s", cmp.Diff(claims.Role, user.Role))
}
invalidToken := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDMyMjk3NjMsImp0aSI6ImUzNDk5NWI1LThiZmMtNDQyNy1iZDgxLWFmNmQ3OTRiYzM0YiIsImlhdCI6MTY0MjYyNDk2MywibmJmIjoxNjQyNjI0OTYzLCJzdWIiOiJYdE5Hemt5ZSJ9.VM6dkwSLaBv8cStkWRVVv9ADjdUrHGHrlB7GB7Ly7n8`
if _, err := as.ValidateToken(invalidToken); err == nil {
t.Fatalf("Invalid token passed validation")
}
})
}
func randomString(length int) string {
const charset = "abcdefghijklmnopqrstabcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, length)
for i := range b {
b[i] = charset[rand.Intn(len(charset))]
}
return string(b)
}