-
-
Save mrtonyhuynh/610b3b1d2094dad2bc53628b323d71f5 to your computer and use it in GitHub Desktop.
Tus Server with Authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"github.com/tus/tusd" | |
"github.com/tus/tusd/filestore" | |
) | |
func UserIsAuthenticated(r *http.Request) { | |
// TODO: validate cookie or header. | |
return true | |
} | |
func main() { | |
store := filestore.FileStore{ | |
Path: "./uploads", | |
} | |
composer := tusd.NewStoreComposer() | |
composer.UseCore(store) | |
composer.UseGetReader(store) | |
composer.UseTerminater(store) | |
composer.UseFinisher(store) | |
composer.UseLocker(store) | |
tusHandler, err := tusd.NewHandler(tusd.Config{ | |
BasePath: "./uploads/", | |
StoreComposer: composer, | |
MaxSize: 0, | |
NotifyCompleteUploads: false, | |
NotifyTerminatedUploads: false, | |
RespectForwardedHeaders: true, | |
}) | |
if err != nil { | |
return nil, err | |
} | |
mux := http.NewServeMux() | |
mux.Handle("/uploads/", func(next http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
// OPTIONS is used to gather information about the Server's current configuration. | |
// It can't ask for authentication, otherwise it won't work with XHR requests. | |
if r.Method == "OPTIONS" { | |
next.ServeHTTP(w, r) | |
} else { | |
// check if user is authenticated. | |
if ok := UserIsAuthenticated(r); ok { | |
next.ServeHTTP(w, r) | |
} else { | |
w.WriteHeader(http.StatusUnauthorized) | |
} | |
} | |
}) | |
}(http.StripPrefix("/uploads/", tusHandler))) | |
// 127.0.0.1:8000/uploads | |
err = http.ListenAndServe("127.0.0.1:8000", mux) | |
if err != nil { | |
panic("unable to listen.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment