...
1
2
3
4
5
6
7
8
9
10
11
12
13 package couchauth
14
15 import (
16 "context"
17 "net/http"
18 "testing"
19
20 "github.com/go-kivik/kivik/v4"
21 _ "github.com/go-kivik/kivik/v4/couchdb"
22 "github.com/go-kivik/kivik/v4/kiviktest/kt"
23 )
24
25 type tuser struct {
26 ID string `json:"_id"`
27 Name string `json:"name"`
28 Type string `json:"type"`
29 Roles []string `json:"roles"`
30 Password string `json:"password"`
31 }
32
33 func TestBadDSN(t *testing.T) {
34 if _, err := New("http://foo.com:port with spaces/"); err == nil {
35 t.Errorf("Expected error for invalid URL.")
36 }
37 if _, err := New("http://foo:bar@foo.com/"); err == nil {
38 t.Error("Expected error for DSN with credentials.")
39 }
40 }
41
42 func TestCouchAuth(t *testing.T) {
43 t.Skip("Reconfigure test not to require Docker")
44 client := kt.GetClient(t)
45 db := client.DB("_users")
46 if e := db.Err(); e != nil {
47 t.Fatalf("Failed to connect to db: %s", e)
48 }
49 name := kt.TestDBName(t)
50 user := &tuser{
51 ID: kivik.UserPrefix + name,
52 Name: name,
53 Type: "user",
54 Roles: []string{"coolguy"},
55 Password: "abc123",
56 }
57 rev, e := db.Put(context.Background(), user.ID, user)
58 if e != nil {
59 t.Fatalf("Failed to create user: %s", e)
60 }
61 defer db.Delete(context.Background(), user.ID, rev)
62 auth, e := New(kt.NoAuthDSN(t))
63 if e != nil {
64 t.Fatalf("Failed to connect to remote server: %s", e)
65 }
66 t.Run("sync", func(t *testing.T) {
67 t.Run("Validate", func(t *testing.T) {
68 t.Parallel()
69 t.Run("ValidUser", func(t *testing.T) {
70 t.Parallel()
71 uCtx, err := auth.Validate(context.Background(), user.Name, "abc123")
72 if err != nil {
73 t.Errorf("Validation failure for good password: %s", err)
74 }
75 if uCtx == nil {
76 t.Errorf("User should have been validated")
77 }
78 })
79 t.Run("WrongPassword", func(t *testing.T) {
80 t.Parallel()
81 uCtx, err := auth.Validate(context.Background(), user.Name, "foobar")
82 if kivik.HTTPStatus(err) != http.StatusUnauthorized {
83 t.Errorf("Expected Unauthorized for bad password, got %s", err)
84 }
85 if uCtx != nil {
86 t.Errorf("User should not have been validated with wrong password")
87 }
88 })
89 t.Run("MissingUser", func(t *testing.T) {
90 t.Parallel()
91 uCtx, err := auth.Validate(context.Background(), "nobody", "foo")
92 if kivik.HTTPStatus(err) != http.StatusUnauthorized {
93 t.Errorf("Expected Unauthorized for bad username, got %s", err)
94 }
95 if uCtx != nil {
96 t.Errorf("User should not have been validated with wrong username")
97 }
98 })
99 })
100 })
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117 }
118
View as plain text