github.com/go-kivik/kivik/v4@v4.3.2/x/kivikd/cookies_test.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 // use this file except in compliance with the License. You may obtain a copy of 3 // the License at 4 // 5 // http://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 // License for the specific language governing permissions and limitations under 11 // the License. 12 13 //go:build !js 14 15 package kivikd 16 17 import ( 18 "testing" 19 20 "github.com/go-kivik/kivik/v4/x/kivikd/authdb" 21 ) 22 23 type validateTest struct { 24 Name string 25 Cookie string 26 User *authdb.UserContext 27 Valid bool 28 Err string 29 } 30 31 func TestValidateCookie(t *testing.T) { 32 s := &Service{} 33 if err := s.loadConf(); err != nil { 34 t.Fatal(err) 35 } 36 tests := []validateTest{ 37 { 38 Name: "Valid", Cookie: "YWRtaW46NThDNTQzN0Y6OnE2cBAuoQKvVBHF2l4PIqKHqDM", Valid: true, 39 User: &authdb.UserContext{Name: "admin", Salt: "foo bar baz"}, 40 }, 41 { 42 Name: "WrongSalt", Cookie: "YWRtaW46NThDNTQzN0Y697rnaWCa_rarAm25wbOg3Gm3mqc", Valid: false, 43 User: &authdb.UserContext{Name: "admin", Salt: "123"}, 44 }, 45 } 46 for _, test := range tests { 47 func(test validateTest) { 48 t.Run(test.Name, func(t *testing.T) { 49 valid, err := s.ValidateCookie(test.User, test.Cookie) 50 var errMsg string 51 if err != nil { 52 errMsg = err.Error() 53 } 54 if errMsg != test.Err { 55 t.Errorf("Unexpected error.\nExpected: %s\n Actual: %s\n", test.Err, errMsg) 56 } 57 if valid != test.Valid { 58 t.Errorf("Unexpected result. Expected %t, Actual %t", test.Valid, valid) 59 } 60 }) 61 }(test) 62 } 63 } 64 65 type tokenTest struct { 66 Name string 67 Salt string 68 Created int64 69 Expected string 70 Err string 71 } 72 73 func TestCreateAuthToken(t *testing.T) { 74 s := &Service{} 75 if err := s.loadConf(); err != nil { 76 t.Fatal(err) 77 } 78 tests := []tokenTest{ 79 {Name: "admin", Salt: "foo bar baz", Created: 1489322879, Expected: "YWRtaW46NThDNTQzN0Y6OnE2cBAuoQKvVBHF2l4PIqKHqDM"}, 80 {Name: "bob", Salt: "0123456789abc", Created: 1489322879, Expected: "Ym9iOjU4QzU0MzdGOihHwWRLS2vekOgsRrH1cEVrk6za"}, 81 } 82 83 for _, test := range tests { 84 func(test tokenTest) { 85 t.Run(test.Name, func(t *testing.T) { 86 result, err := s.CreateAuthToken(test.Name, test.Salt, test.Created) 87 var errMsg string 88 if err != nil { 89 errMsg = err.Error() 90 } 91 if errMsg != test.Err { 92 t.Errorf("Unexpected error. Expected '%s', got '%s'", test.Err, errMsg) 93 } 94 if result != test.Expected { 95 t.Errorf("Expected: %s\n Actual: %s\n", test.Expected, result) 96 } 97 }) 98 }(test) 99 } 100 }