Skip to content

Commit

Permalink
Add token sign in convenience methods, and more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kwoodhouse93 committed Nov 4, 2022
1 parent 4c90b33 commit b90ea5d
Show file tree
Hide file tree
Showing 10 changed files with 178 additions and 94 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ down:
@docker compose -f docker-compose.yaml down 2>/dev/null && echo "${GREEN}Removed${NC}"

test: up
-go test -count=1 -v ./...
-go test -v ./...
@make down

test_ci:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ Required for V1 release:
- Test infrastructure
- [X] Postgres container with GoTrue config
- [X] GoTrue container - signup enabled, autoconfirm off
- [ ] GoTrue container - signup enabled, autoconfirm on
- [X] GoTrue container - signup enabled, autoconfirm on
- [ ] GoTrue container - signup disabled
- [ ] Mail server
- [ ] Support for Captcha tokens
Expand Down
39 changes: 0 additions & 39 deletions _token_test.go

This file was deleted.

13 changes: 7 additions & 6 deletions admingeneratelink_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"testing"
"time"

"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand All @@ -15,11 +16,11 @@ func TestAdminGenerateLink(t *testing.T) {
assert := assert.New(t)
require := require.New(t)

c := client.WithToken(adminToken())
admin := withAdmin(client)

// Testing signup link
email := randomEmail()
resp, err := c.AdminGenerateLink(gotrue.AdminGenerateLinkRequest{
resp, err := admin.AdminGenerateLink(gotrue.AdminGenerateLinkRequest{
Type: "signup",
Email: email,
Password: "password",
Expand All @@ -36,7 +37,7 @@ func TestAdminGenerateLink(t *testing.T) {
assert.Equal("http://localhost:3000", resp.RedirectTo)
assert.Contains(resp.ActionLink, resp.HashedToken)

assert.Regexp(uuidRegex, resp.ID)
assert.NotEqual(uuid.UUID{}, resp.ID)
assert.Equal(resp.Email, email)
assert.InDelta(time.Now().Unix(), resp.ConfirmationSentAt.Unix(), float64(time.Second))
assert.InDelta(time.Now().Unix(), resp.CreatedAt.Unix(), float64(time.Second))
Expand Down Expand Up @@ -130,15 +131,15 @@ func TestAdminGenerateLink(t *testing.T) {
}
for name, data := range tests {
t.Run(name, func(t *testing.T) {
_, err := c.AdminGenerateLink(data)
_, err := admin.AdminGenerateLink(data)
assert.Error(err)
assert.ErrorContains(err, "request is invalid")
})
}

// Testing email change links
newEmail := randomEmail()
resp, err = c.AdminGenerateLink(gotrue.AdminGenerateLinkRequest{
resp, err = admin.AdminGenerateLink(gotrue.AdminGenerateLinkRequest{
Type: "email_change_current",
Email: email,
NewEmail: newEmail,
Expand All @@ -153,7 +154,7 @@ func TestAdminGenerateLink(t *testing.T) {
assert.NotEmpty(resp.EmailOTP)
assert.Contains(resp.ActionLink, resp.HashedToken)

assert.Regexp(uuidRegex, resp.ID)
assert.NotEqual(uuid.UUID{}, resp.ID)
assert.Equal(resp.Email, email)
assert.Equal(resp.EmailChange, newEmail)
assert.InDelta(time.Now().Unix(), resp.ConfirmationSentAt.Unix(), float64(time.Second))
Expand Down
13 changes: 7 additions & 6 deletions adminusers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gotrue_test
import (
"testing"

"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand All @@ -13,7 +14,7 @@ func TestAdminCreateUser(t *testing.T) {
assert := assert.New(t)
require := require.New(t)

c := client.WithToken(adminToken())
admin := withAdmin(client)

pass := "password"
email := randomEmail()
Expand All @@ -22,7 +23,7 @@ func TestAdminCreateUser(t *testing.T) {
Role: "admin",
Password: &pass,
}
resp, err := c.AdminCreateUser(req)
resp, err := admin.AdminCreateUser(req)
require.NoError(err)
require.Regexp(uuidRegex, resp.ID)
assert.Equal(resp.Email, email)
Expand All @@ -33,7 +34,7 @@ func TestAdminListUsers(t *testing.T) {
assert := assert.New(t)
require := require.New(t)

c := client.WithToken(adminToken())
admin := withAdmin(client)

// Create a user that we know should be returned
pass := "password"
Expand All @@ -43,16 +44,16 @@ func TestAdminListUsers(t *testing.T) {
Role: "test",
Password: &pass,
}
createResp, err := c.AdminCreateUser(req)
createResp, err := admin.AdminCreateUser(req)
require.NoError(err)
require.Regexp(uuidRegex, createResp.ID)

// Then list and look up the user we just created
resp, err := c.AdminListUsers()
resp, err := admin.AdminListUsers()
require.NoError(err)
assert.NotEmpty(resp)
for _, u := range resp.Users {
assert.Regexp(uuidRegex, u.ID)
assert.NotEqual(uuid.UUID{}, u.ID)
if u.ID == createResp.ID {
assert.Equal(u.Email, createResp.Email)
}
Expand Down
66 changes: 31 additions & 35 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ const (
)

var (
// Global client is used for all tests in this package.
client *gotrue.Client
// Global clients are used for all tests in this package.
client *gotrue.Client
autoconfirmClient *gotrue.Client

// Used to validate UUIDs.
uuidRegex = regexp.MustCompile(`^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$`)
)

// Utility function to generate some random chars
func randomString(n int) string {
// Using all lower case because email addresses are lowercased by GoTrue.
letterBytes := "abcdefghijklmnopqrstuvwxyz"
Expand All @@ -39,11 +39,23 @@ func randomString(n int) string {
return string(b)
}

// Utility function to generate a random email address.
func randomEmail() string {
return fmt.Sprintf("%s@test.com", randomString(10))
}

func randomNumberString(n int) string {
numberBytes := "0123456789"
b := make([]byte, n)
for i := range b {
b[i] = numberBytes[rand.Intn(len(numberBytes))]
}
return string(b)
}

func randomPhoneNumber() string {
return fmt.Sprintf("+1%s", randomNumberString(10))
}

func adminToken() string {
t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"aud": "admin",
Expand All @@ -58,8 +70,15 @@ func adminToken() string {
return token
}

func withAdmin(c *gotrue.Client) *gotrue.Client {
return c.WithToken(adminToken())
}

func TestMain(m *testing.M) {
// Please refer to docker-compose.yaml and /testing/README.md for more info
// on this test set up.
client = gotrue.New(projectReference, apiKey).WithCustomGoTrueURL("http://localhost:9999")
autoconfirmClient = gotrue.New(projectReference, apiKey).WithCustomGoTrueURL("http://localhost:9998")

// Ensure the server is ready before running tests.
err := backoff.Retry(
Expand All @@ -71,6 +90,14 @@ func TestMain(m *testing.M) {
if health.Name != "GoTrue" {
return fmt.Errorf("health check - unexpected server name: %s", health.Name)
}

health, err = autoconfirmClient.HealthCheck()
if err != nil {
return err
}
if health.Name != "GoTrue" {
return fmt.Errorf("health check - unexpected server name: %s", health.Name)
}
return nil
},
backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 10),
Expand All @@ -82,34 +109,3 @@ func TestMain(m *testing.M) {
code := m.Run()
os.Exit(code)
}

// // Disabled as not working, and not needed now
// // pass := "test"
// // err = c.AdminCreateUser(gotrue.AdminCreateUserRequest{
// // UserID: uuid.NewString(),
// // Role: "anon",
// // Email: "test@example.com",
// // EmailConfirm: true,
// // Password: &pass,
// // })
// // if err != nil {
// // log.Fatal(err)
// // }

// // signupResp, err := c.Signup(gotrue.SignupRequest{
// // Email: "test@example.com",
// // Password: "test me",
// // })
// // if err != nil {
// // log.Fatal(err)
// // }
// // log.Printf("%+v", signupResp)

// // inviteResp, err := c.Invite(gotrue.InviteRequest{
// // Email: "test@example.com",
// // })
// // if err != nil {
// // log.Fatal(err)
// // }
// // log.Printf("%+v", inviteResp)
// }
32 changes: 30 additions & 2 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
version: "3.9"
services:
gotrue:
# Signups enabled, auto-confirm off
container_name: gotrue
depends_on:
- postgres
image: supabase/gotrue:v2.25.1
restart: always
restart: on-failure
ports:
- '9999:9999'
- '9100:9100'
environment:
GOTRUE_JWT_SECRET: "secret"
GOTRUE_DB_DRIVER: "postgres"
Expand All @@ -23,6 +23,34 @@ services:
GOTRUE_RATE_LIMIT_TOKEN_REFRESH: "1000000"
GOTRUE_MFA_RATE_LIMIT_CHALLENGE_AND_VERIFY: "1000000"
GOTRUE_SMTP_MAX_FREQUENCY: "1ns"

gotrue_autoconfirm:
# Signups enabled, auto-confirm on
container_name: gotrue_autoconfirm
depends_on:
- postgres
image: supabase/gotrue:v2.25.1
restart: on-failure
ports:
- '9998:9998'
environment:
GOTRUE_JWT_SECRET: "secret"
GOTRUE_DB_DRIVER: "postgres"
NAMESPACE: "auth"
DATABASE_URL: "postgres://supabase_auth_admin:root@postgres:5432/postgres"
API_EXTERNAL_URL: "http://localhost:9998"
GOTRUE_API_HOST: "0.0.0.0"
PORT: "9998"
GOTRUE_SITE_URL: "http://localhost:3000"
GOTRUE_RATE_LIMIT_EMAIL_SENT: "1000000"
GOTRUE_RATE_LIMIT_VERIFY: "1000000"
GOTRUE_RATE_LIMIT_TOKEN_REFRESH: "1000000"
GOTRUE_MFA_RATE_LIMIT_CHALLENGE_AND_VERIFY: "1000000"
GOTRUE_SMTP_MAX_FREQUENCY: "1ns"
GOTRUE_MAILER_AUTOCONFIRM: 'true'
GOTRUE_SMS_AUTOCONFIRM: 'true'
GOTRUE_EXTERNAL_PHONE_ENABLED: 'true'

postgres:
build:
context: ./testing
Expand Down
5 changes: 3 additions & 2 deletions signup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"testing"
"time"

"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand All @@ -21,7 +22,7 @@ func TestSignup(t *testing.T) {
Password: "password",
})
require.NoError(err)
assert.Regexp(uuidRegex, userResp.ID)
assert.NotEqual(uuid.UUID{}, userResp.ID)
assert.Equal(userResp.Email, email)
assert.InDelta(time.Now().Unix(), userResp.ConfirmationSentAt.Unix(), float64(time.Second))
assert.InDelta(time.Now().Unix(), userResp.CreatedAt.Unix(), float64(time.Second))
Expand All @@ -33,7 +34,7 @@ func TestSignup(t *testing.T) {
Password: "password",
})
require.NoError(err)
assert.Regexp(uuidRegex, dupeUserResp.ID)
assert.NotEqual(uuid.UUID{}, dupeUserResp.ID)
assert.Equal(dupeUserResp.Email, email)
assert.InDelta(time.Now().Unix(), dupeUserResp.ConfirmationSentAt.Unix(), float64(time.Second))
assert.InDelta(time.Now().Unix(), dupeUserResp.CreatedAt.Unix(), float64(time.Second))
Expand Down
Loading

0 comments on commit b90ea5d

Please sign in to comment.