alexandrevicenzi
7/28/2017 - 12:33 PM

Tus Server with Authentication

Tus Server with Authentication

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.")
	}
}