TokenAuth is an authentication middleware with token
(db *gorm.DB, next http.HandlerFunc, tokenType string, p *AuthParams)
| 92 | |
| 93 | // TokenAuth is an authentication middleware with token |
| 94 | func 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 |
| 126 | func AuthWithSession(db *gorm.DB, r *http.Request) (database.User, bool, error) { |