package gpaste_test import ( "math/rand" "testing" "git.t-juice.club/torjus/gpaste" "git.t-juice.club/torjus/gpaste/users" ) 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} 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) } if _, err := as.ValidateToken(token); err != nil { t.Fatalf("Error validating token: %s", err) } 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) }