options.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package auth
  2. import (
  3. "errors"
  4. "net/http"
  5. "time"
  6. "github.com/gorilla/sessions"
  7. )
  8. // Option is a function that changes a handler in a certain way during initialization
  9. type Option func(h *Handler) error
  10. // SetStore sets the gorilla session.Store impl that should be used
  11. func SetStore(s sessions.Store) Option {
  12. return func(h *Handler) error {
  13. if s == nil {
  14. return errors.New("sessions.Store can't be nil")
  15. }
  16. h.store = s
  17. return nil
  18. }
  19. }
  20. // SetSessionName sets the name to use for sessions (ie. cookie name)
  21. func SetSessionName(name string) Option {
  22. return func(h *Handler) error {
  23. if len(name) == 0 {
  24. return errors.New("SessionName can't be empty")
  25. }
  26. h.sessionName = name
  27. return nil
  28. }
  29. }
  30. // SetLanding sets the url to where a client is redirect to after login
  31. func SetLanding(l string) Option {
  32. return func(h *Handler) error {
  33. if l == "" {
  34. return errors.New("landing redirect can't be empty")
  35. }
  36. h.redirLanding = l
  37. return nil
  38. }
  39. }
  40. // SetLogout sets the url to where a client is redirect to after logout
  41. // uses Landing location by default
  42. func SetLogout(l string) Option {
  43. return func(h *Handler) error {
  44. if l == "" {
  45. return errors.New("logout redirect can't be empty")
  46. }
  47. h.redirLogout = l
  48. return nil
  49. }
  50. }
  51. // SetLifetime sets the duration of when a session expires after it is created
  52. func SetLifetime(d time.Duration) Option {
  53. return func(h *Handler) error {
  54. h.lifetime = d
  55. return nil
  56. }
  57. }
  58. // SetNotAuthorizedHandler re-routes the _not authorized_ response to a different http handler
  59. func SetNotAuthorizedHandler(nah http.Handler) Option {
  60. return func(h *Handler) error {
  61. h.notAuthorizedHandler = nah
  62. return nil
  63. }
  64. }
  65. // ErrorHandler is used to for the SetErrorHandler option.
  66. // It is a classical http.HandleFunc plus the error and response code the auth system determained.
  67. type ErrorHandler func(rw http.ResponseWriter, req *http.Request, err error, code int)
  68. // SetErrorHandler can be used to customize the look up error responses
  69. func SetErrorHandler(errh ErrorHandler) Option {
  70. return func(h *Handler) error {
  71. h.errorHandler = errh
  72. return nil
  73. }
  74. }