Auth is an authentication middleware
(db *gorm.DB, next http.HandlerFunc, p *AuthParams)
| 64 | |
| 65 | // Auth is an authentication middleware |
| 66 | func Auth(db *gorm.DB, next http.HandlerFunc, p *AuthParams) http.HandlerFunc { |
| 67 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 68 | user, ok, err := AuthWithSession(db, r) |
| 69 | if !ok { |
| 70 | if p != nil && p.RedirectGuestsToLogin { |
| 71 | |
| 72 | q := url.Values{} |
| 73 | q.Set("referrer", r.URL.Path) |
| 74 | path := helpers.GetPath("/login", &q) |
| 75 | |
| 76 | http.Redirect(w, r, path, http.StatusFound) |
| 77 | return |
| 78 | } |
| 79 | |
| 80 | RespondUnauthorized(w) |
| 81 | return |
| 82 | } |
| 83 | if err != nil { |
| 84 | DoError(w, "authenticating with session", err, http.StatusInternalServerError) |
| 85 | return |
| 86 | } |
| 87 | |
| 88 | ctx := context.WithUser(r.Context(), &user) |
| 89 | next.ServeHTTP(w, r.WithContext(ctx)) |
| 90 | }) |
| 91 | } |
| 92 | |
| 93 | // TokenAuth is an authentication middleware with token |
| 94 | func TokenAuth(db *gorm.DB, next http.HandlerFunc, tokenType string, p *AuthParams) http.HandlerFunc { |