9
9
"github.com/st2projects/ssh-sentinel-server/crypto"
10
10
"github.com/st2projects/ssh-sentinel-server/helper"
11
11
"github.com/st2projects/ssh-sentinel-server/sql"
12
- "io/ioutil "
12
+ "io"
13
13
"net/http"
14
14
"time"
15
15
)
@@ -18,41 +18,54 @@ func AuthenticationHandler(next http.Handler) http.Handler {
18
18
fn := func (w http.ResponseWriter , r * http.Request ) {
19
19
w .Header ().Set (contentTypeKey , jsonContentType )
20
20
21
- body , err := ioutil .ReadAll (r .Body )
21
+ body , err := io .ReadAll (r .Body )
22
22
23
23
if err != nil {
24
24
panic (helper .NewError ("Failed to marshall request %s" , err ))
25
25
}
26
26
27
27
signRequest , err := MarshallSigningRequest (bytes .NewReader (body ))
28
28
29
- r .Body = ioutil .NopCloser (bytes .NewBuffer (body ))
29
+ r .Body = io .NopCloser (bytes .NewBuffer (body ))
30
30
31
31
if err != nil {
32
32
panic (helper .NewError ("Failed to marshall request %s" , err ))
33
33
}
34
34
35
- user := sql .GetUserByUsername (signRequest .Username )
35
+ user , err := sql .GetUserByUsername (signRequest .Username )
36
+
37
+ if err != nil {
38
+ authorisationFailed (w , "No such user %s" , signRequest .Username )
39
+ }
36
40
37
41
hasValidAPIKey , err := crypto .Validate (signRequest .APIKey , user .APIKey .Key )
38
42
39
43
if ! hasValidAPIKey {
40
- w .WriteHeader (http .StatusUnauthorized )
41
- panic (helper .NewError ("Unauthorised key" ))
44
+ authorisationFailed (w , "Invalid API key for user %s" , signRequest .Username )
42
45
}
43
46
44
47
hasValidPrincipals := CheckPrincipals (user .Principals , signRequest .Principals )
45
48
46
49
if ! hasValidPrincipals {
47
- panic ( helper . NewError ( "One or more unauthorised principals requested %v" , signRequest .Principals ) )
50
+ authorisationFailed ( w , "One or more unauthorised principals requested %v" , signRequest .Principals )
48
51
}
49
52
53
+ log .Infof ("User %s is authenticated" , signRequest .Username )
54
+
50
55
next .ServeHTTP (w , r )
51
56
}
52
57
53
58
return http .HandlerFunc (fn )
54
59
}
55
60
61
+ func authorisationFailed (w http.ResponseWriter , msg string , args ... any ) {
62
+ w .WriteHeader (http .StatusUnauthorized )
63
+
64
+ log .Errorf (msg , args )
65
+
66
+ panic (helper .NewError ("Authentication failed" ))
67
+ }
68
+
56
69
func LoggingHandler (next http.Handler ) http.Handler {
57
70
fn := func (w http.ResponseWriter , r * http.Request ) {
58
71
t1 := time .Now ()
0 commit comments