all repos

onasty @ 7dbb390c92161e9e45ec8715bbc8071061f9d85a

a one-time notes service

onasty/internal/oauth/google_test.go(view raw)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package oauth

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"golang.org/x/oauth2"
)

func TestGoogleProvider_GetAuthURL(t *testing.T) {
	provider := NewGoogleProvider("client.id", "secret", "http://localhost/callback")
	authURL := provider.GetAuthURL("test")

	assert.Contains(t, authURL, "client_id=client.id")
	assert.Contains(t, authURL, "state=test")
	assert.Contains(t, authURL, "scope="+
		url.QueryEscape("https://www.googleapis.com/auth/userinfo.email"))
}

func TestGoogleProvider_ExchangeCode(t *testing.T) {
	sub := "1234567890"
	email := "testemail@mail.com"
	resp := fmt.Sprintf(`{"sub":"%s", "email":"%s","email_verified":true}`, sub, email)
	client := &http.Client{
		Transport: mockClient(func(req *http.Request) (*http.Response, error) {
			if req.Method == http.MethodPost {
				return &http.Response{
					StatusCode: http.StatusOK,
					Header:     http.Header{"Content-Type": []string{"application/json"}},
					Body: io.NopCloser(
						strings.NewReader(`{"access_token":"fake",
							"token_type":"bearer",
							"expires_in":3600}`),
					),
				}, nil
			}
			return &http.Response{
				StatusCode: http.StatusOK,
				Header:     http.Header{"Content-Type": []string{"application/json"}},
				Body:       io.NopCloser(strings.NewReader(resp)),
			}, nil
		}),
	}

	provider := NewGoogleProvider("client.id", "secret", "http://localhost")
	ctx := context.WithValue(context.TODO(), oauth2.HTTPClient, client)

	info, err := provider.ExchangeCode(ctx, "")
	require.NoError(t, err)
	assert.Equal(t, "google", info.Provider)
	assert.Equal(t, sub, info.ProviderID)
	assert.Equal(t, email, info.Email)
	assert.True(t, info.EmailVerified)
}