MCPcopy
hub / github.com/dnote/dnote / TokenAuth

Function TokenAuth

pkg/server/middleware/auth.go:94–123  ·  view source on GitHub ↗

TokenAuth is an authentication middleware with token

(db *gorm.DB, next http.HandlerFunc, tokenType string, p *AuthParams)

Source from the content-addressed store, hash-verified

92
93// TokenAuth is an authentication middleware with token
94func TokenAuth(db *gorm.DB, next http.HandlerFunc, tokenType string, p *AuthParams) http.HandlerFunc {
95 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
96 user, token, ok, err := authWithToken(db, r, tokenType)
97 if err != nil {
98 // log the error and continue
99 log.ErrorWrap(err, "authenticating with token")
100 }
101
102 ctx := r.Context()
103
104 if ok {
105 ctx = context.WithToken(ctx, &token)
106 } else {
107 // If token-based auth fails, fall back to session-based auth
108 user, ok, err = AuthWithSession(db, r)
109 if err != nil {
110 DoError(w, "authenticating with session", err, http.StatusInternalServerError)
111 return
112 }
113
114 if !ok {
115 RespondUnauthorized(w)
116 return
117 }
118 }
119
120 ctx = context.WithUser(ctx, &user)
121 next.ServeHTTP(w, r.WithContext(ctx))
122 })
123}
124
125// AuthWithSession performs user authentication with session
126func AuthWithSession(db *gorm.DB, r *http.Request) (database.User, bool, error) {

Callers 1

TestTokenAuthFunction · 0.85

Calls 8

ErrorWrapFunction · 0.92
WithTokenFunction · 0.92
WithUserFunction · 0.92
authWithTokenFunction · 0.85
AuthWithSessionFunction · 0.85
DoErrorFunction · 0.85
RespondUnauthorizedFunction · 0.85
ServeHTTPMethod · 0.80

Tested by 1

TestTokenAuthFunction · 0.68