go-firebase icon indicating copy to clipboard operation
go-firebase copied to clipboard

Custom ServeMux usage

Open yasarix opened this issue 8 years ago • 2 comments

auth.Server() method is creating a new ServeMux and setting the handlers for generate and verify handlers. This is useful when you are using http.Handler or http.HadleFunc with default ServeMux. However, this is making auth.Server() unusable with something like gorilla/mux.

This pull request allows user to pass the default or any custom ServeMux into auth.Server(), so it can be used along with gorilla/mux or any similar packages.

Example:

serveMux := http.DefaultServeMux

router := mux.NewRouter()
router.Handle("/auth", auth.Server(customClaims,
	firebase.ServerServeMux(serveMux),
	firebase.ServerGenerateURI("/auth/token"),
	firebase.ServerVerifyURI("/auth/verify")))

apiRouter := router.PathPrefix("/api").Subrouter()

// but we need to add it for the API endpoint
c := cors.New(cors.Options{
	AllowedOrigins: []string{"*"},
	AllowedHeaders: []string{"Authorization"},
})

// API Handlers
apiRouter.Handle("/account/create", c.Handler(auth.AnyRole(http.HandlerFunc(createAccount),"user")))

http.Handle("/", router)

auth.Server() creates a new ServeMux if nothing is passed.

yasarix avatar Feb 06 '17 06:02 yasarix

I'm a big fan of packages working against the default handler interfaces when possible. It may be that if something doesn't work with those then it might be better to just re-implement the handlers which aren't really that large but let me have a look at it and a think.

I only added the server to this package because I ended up with almost the same code in the example as well as a couple of projects I was using it with so wanted to be lazy and avoid some repetition.

CaptainCodeman avatar Feb 08 '17 20:02 CaptainCodeman

If someone is using something like gorilla/mux and also wants to use the Server to generate the token, then he/she will have to pass the DefaultServeMux into Server or, re-implement token generation which will cause repetition.

I think the better solution would be converting verifyHandler() and generateHandler() to public functions, and allow package users to use them in their applications with default or custom handlers packages.

yasarix avatar Feb 08 '17 21:02 yasarix