1// go:build unit
2
3package service
4
5import (
6 "testing"
7)
8
9func TestCheck(t *testing.T) {
10 testCases := []struct {
11 name string
12 passphrase []byte
13 username string
14 password string
15 wantError bool
16 }{
17 {
18 name: "generated",
19 passphrase: nil,
20 username: "gabrielgio",
21 password: "adminadmin",
22 wantError: false,
23 },
24 {
25 name: "static",
26 passphrase: []byte("$2a$14$W2yT0E6Zm8nTecqipHUQGOLC6PvNjIQqpQTW/MZmD5oqDfaBJnBV6"),
27 username: "gabrielgio",
28 password: "adminadmin",
29 wantError: false,
30 },
31 {
32 name: "error",
33 passphrase: []byte("This is not a valid hash"),
34 username: "gabrielgio",
35 password: "adminadmin",
36 wantError: true,
37 },
38 }
39
40 for _, tc := range testCases {
41 t.Run(tc.name, func(t *testing.T) {
42 mock := &mockAuthRepository{
43 username: tc.username,
44 password: tc.password,
45 passphrase: tc.passphrase,
46 }
47
48 service := AuthService{authRepository: mock}
49
50 if service.CheckAuth(tc.username, tc.password) == tc.wantError {
51 t.Errorf("Invalid result, wanted %t got %t", tc.wantError, !tc.wantError)
52 }
53 })
54 }
55}
56
57func TestValidate(t *testing.T) {
58 testCases := []struct {
59 name string
60 aesKey []byte
61 }{
62 {
63 name: "generated",
64 aesKey: nil,
65 },
66 {
67 name: "static",
68 aesKey: []byte("RTGkmunKmi5agh7jaqENunG2zI/godnkqhHaHyX/AVg="),
69 },
70 }
71
72 for _, tc := range testCases {
73 t.Run(tc.name, func(t *testing.T) {
74 mock := &mockAuthRepository{
75 aesKey: tc.aesKey,
76 }
77
78 service := AuthService{authRepository: mock}
79
80 token, err := service.IssueToken()
81 if err != nil {
82 t.Fatalf("Error issuing token: %s", err.Error())
83 }
84
85 v, err := service.ValidateToken(token)
86 if err != nil {
87 t.Fatalf("Error validating token: %s", err.Error())
88 }
89
90 if !v {
91 t.Error("Invalid token generated")
92 }
93 })
94 }
95}
96
97type mockAuthRepository struct {
98 username string
99 password string
100 passphrase []byte
101
102 aesKey []byte
103}
104
105func (m *mockAuthRepository) GetPassphrase() []byte {
106 if m.passphrase == nil {
107 hash, _ := GenerateHash(m.username, m.password)
108 m.passphrase = []byte(hash)
109 }
110 return m.passphrase
111}
112
113func (m *mockAuthRepository) GetBase64AesKey() []byte {
114 if m.aesKey == nil {
115 key, _ := GenerateAesKey()
116 m.aesKey = []byte(key)
117 }
118 return m.aesKey
119}