github.com/grafviktor/keep-my-secret@v0.9.10-0.20230908165355-19f35cce90e5/internal/api/web/middleware/authenticate.go (about) 1 package middleware 2 3 import ( 4 "context" 5 "log" 6 "net/http" 7 8 "github.com/grafviktor/keep-my-secret/internal/api" 9 "github.com/grafviktor/keep-my-secret/internal/api/utils" 10 "github.com/grafviktor/keep-my-secret/internal/constant" 11 ) 12 13 // AuthRequired middleware for checking if user is authenticated 14 // If user is not authenticated, it will return unauthorized response (401) 15 // If user is authenticated, it will add user login to context 16 func (m *middleware) AuthRequired(next http.Handler) http.Handler { 17 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 18 _, claims, err := m.authVerifier.VerifyAuthHeader(m.config, w, r) 19 if err != nil { 20 log.Printf("auth: %v", err.Error()) 21 22 _ = utils.WriteJSON(w, http.StatusUnauthorized, api.Response{ 23 Status: constant.APIStatusFail, 24 Message: "unauthorized", 25 Data: nil, 26 }) 27 28 return 29 } 30 31 r = r.WithContext(context.WithValue(r.Context(), api.ContextUserLogin, claims.Subject)) 32 33 next.ServeHTTP(w, r) 34 }) 35 }