gpaste/auth_test.go

52 lines
1.4 KiB
Go
Raw Permalink Normal View History

2022-01-19 20:45:53 +00:00
package gpaste_test
import (
2022-01-20 02:35:55 +00:00
"math/rand"
2022-01-19 20:45:53 +00:00
"testing"
"git.t-juice.club/torjus/gpaste"
2022-01-20 02:35:55 +00:00
"git.t-juice.club/torjus/gpaste/users"
2022-01-19 20:45:53 +00:00
)
func TestAuth(t *testing.T) {
t.Run("Token", func(t *testing.T) {
2022-01-20 02:35:55 +00:00
us := users.NewMemoryUserStore()
2022-01-19 20:45:53 +00:00
secret := []byte(randomString(16))
as := gpaste.NewAuthService(us, secret)
username := randomString(8)
password := randomString(16)
2022-01-20 02:35:55 +00:00
user := &users.User{Username: username}
2022-01-19 20:45:53 +00:00
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)
}
2022-01-20 00:04:44 +00:00
if _, err := as.ValidateToken(token); err != nil {
2022-01-19 20:45:53 +00:00
t.Fatalf("Error validating token: %s", err)
}
invalidToken := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDMyMjk3NjMsImp0aSI6ImUzNDk5NWI1LThiZmMtNDQyNy1iZDgxLWFmNmQ3OTRiYzM0YiIsImlhdCI6MTY0MjYyNDk2MywibmJmIjoxNjQyNjI0OTYzLCJzdWIiOiJYdE5Hemt5ZSJ9.VM6dkwSLaBv8cStkWRVVv9ADjdUrHGHrlB7GB7Ly7n8`
2022-01-20 00:04:44 +00:00
if _, err := as.ValidateToken(invalidToken); err == nil {
2022-01-19 20:45:53 +00:00
t.Fatalf("Invalid token passed validation")
}
})
}
2022-01-20 02:35:55 +00:00
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)
}