all repos

onasty @ efd970430597e242aa15c24f868fc0e7103b45ac

a one-time notes service

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

Smirnov Oleksandr Smirnov Oleksandr
ss2316544@gmail.com
feat: add cors (#115)..., 1 year ago
1
package oauth
2
3
import (
4
	"context"
5
	"fmt"
6
	"io"
7
	"net/http"
8
	"net/url"
9
	"strings"
10
	"testing"
11
12
	"github.com/stretchr/testify/assert"
13
	"github.com/stretchr/testify/require"
14
	"golang.org/x/oauth2"
15
)
16
17
func TestGoogleProvider_GetAuthURL(t *testing.T) {
18
	provider := NewGoogleProvider("client.id", "secret", "http://localhost/callback")
19
	authURL := provider.GetAuthURL("test")
20
21
	assert.Contains(t, authURL, "client_id=client.id")
22
	assert.Contains(t, authURL, "state=test")
23
	assert.Contains(t, authURL, "scope="+
24
		url.QueryEscape("https://www.googleapis.com/auth/userinfo.email"))
25
}
26
27
func TestGoogleProvider_ExchangeCode(t *testing.T) {
28
	sub := "1234567890"
29
	email := "testemail@mail.com"
30
	resp := fmt.Sprintf(`{"sub":"%s", "email":"%s","email_verified":true}`, sub, email)
31
	client := &http.Client{
32
		Transport: mockClient(func(req *http.Request) (*http.Response, error) {
33
			if req.Method == http.MethodPost {
34
				return &http.Response{
35
					StatusCode: http.StatusOK,
36
					Header:     http.Header{"Content-Type": []string{"application/json"}},
37
					Body: io.NopCloser(
38
						strings.NewReader(`{"access_token":"fake",
39
							"token_type":"bearer",
40
							"expires_in":3600}`),
41
					),
42
				}, nil
43
			}
44
			return &http.Response{
45
				StatusCode: http.StatusOK,
46
				Header:     http.Header{"Content-Type": []string{"application/json"}},
47
				Body:       io.NopCloser(strings.NewReader(resp)),
48
			}, nil
49
		}),
50
	}
51
52
	provider := NewGoogleProvider("client.id", "secret", "http://localhost")
53
	ctx := context.WithValue(context.TODO(), oauth2.HTTPClient, client)
54
55
	info, err := provider.ExchangeCode(ctx, "")
56
	require.NoError(t, err)
57
	assert.Equal(t, "google", info.Provider)
58
	assert.Equal(t, sub, info.ProviderID)
59
	assert.Equal(t, email, info.Email)
60
	assert.True(t, info.EmailVerified)
61
}