cookie.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. package auth
  10. import (
  11. "crypto/rand"
  12. "fmt"
  13. "io"
  14. "net/http"
  15. "net/url"
  16. "devt.de/krotik/common/datautil"
  17. "devt.de/krotik/common/errorutil"
  18. "devt.de/krotik/common/httputil/user"
  19. )
  20. /*
  21. cookieNameAuth defines the auth cookie name
  22. */
  23. const cookieNameAuth = "~aid"
  24. /*
  25. CookieMaxLifetime is the max life time of an auth cookie in seconds
  26. */
  27. var CookieMaxLifetime = 3600
  28. /*
  29. TestCookieAuthDisabled is a flag to disable cookie based authentication temporarily
  30. (should only be used by unit tests)
  31. */
  32. var TestCookieAuthDisabled = false
  33. /*
  34. CookieAuthHandleFuncWrapper datastructure. Wrapper for HandleFunc to add
  35. cookie authentication to all added endpoints.
  36. */
  37. type CookieAuthHandleFuncWrapper struct {
  38. origHandleFunc func(pattern string, handler func(http.ResponseWriter, *http.Request))
  39. authFunc func(user, pass string) bool
  40. accessFunc func(http.ResponseWriter, *http.Request, string) bool
  41. tokenMap *datautil.MapCache
  42. expiry int
  43. publicURL map[string]func(http.ResponseWriter, *http.Request)
  44. // Callbacks
  45. CallbackSessionExpired func(w http.ResponseWriter, r *http.Request)
  46. CallbackUnauthorized func(w http.ResponseWriter, r *http.Request)
  47. }
  48. /*
  49. NewCookieAuthHandleFuncWrapper creates a new HandleFunc wrapper.
  50. */
  51. func NewCookieAuthHandleFuncWrapper(origHandleFunc func(pattern string,
  52. handler func(http.ResponseWriter, *http.Request))) *CookieAuthHandleFuncWrapper {
  53. return &CookieAuthHandleFuncWrapper{
  54. origHandleFunc,
  55. nil,
  56. nil,
  57. datautil.NewMapCache(0, int64(CookieMaxLifetime)),
  58. CookieMaxLifetime,
  59. make(map[string]func(http.ResponseWriter, *http.Request)),
  60. // Session expired callback
  61. func(w http.ResponseWriter, r *http.Request) {
  62. w.WriteHeader(http.StatusUnauthorized)
  63. w.Write([]byte("Session expired\n"))
  64. },
  65. func(w http.ResponseWriter, r *http.Request) {
  66. w.WriteHeader(http.StatusUnauthorized)
  67. w.Write([]byte("Unauthorized\n"))
  68. },
  69. }
  70. }
  71. /*
  72. AddPublicPage adds a page which should be accessible without authentication.
  73. using a special handler.
  74. */
  75. func (cw *CookieAuthHandleFuncWrapper) AddPublicPage(url string, handler func(http.ResponseWriter, *http.Request)) {
  76. cw.publicURL[url] = handler
  77. }
  78. /*
  79. Expiry returns the current authentication expiry time in seconds.
  80. */
  81. func (cw *CookieAuthHandleFuncWrapper) Expiry() int {
  82. return cw.expiry
  83. }
  84. /*
  85. SetExpiry sets the authentication expiry time in seconds. All existing authentications
  86. are retracted during this function call.
  87. */
  88. func (cw *CookieAuthHandleFuncWrapper) SetExpiry(secs int) {
  89. cw.expiry = secs
  90. cw.tokenMap = datautil.NewMapCache(0, int64(secs))
  91. }
  92. /*
  93. SetAuthFunc sets an authentication function which can be used by the wrapper
  94. to authenticate users.
  95. */
  96. func (cw *CookieAuthHandleFuncWrapper) SetAuthFunc(authFunc func(user, pass string) bool) {
  97. cw.authFunc = authFunc
  98. }
  99. /*
  100. SetAccessFunc sets an access function which can be used by the wrapper to
  101. check the user access rights.
  102. */
  103. func (cw *CookieAuthHandleFuncWrapper) SetAccessFunc(accessFunc func(http.ResponseWriter, *http.Request, string) bool) {
  104. cw.accessFunc = accessFunc
  105. }
  106. /*
  107. AuthUser authenticates a user and creates an auth token unless testOnly is true.
  108. Returns an empty string if the authentication was not successful.
  109. */
  110. func (cw *CookieAuthHandleFuncWrapper) AuthUser(user, pass string, testOnly bool) string {
  111. if cw.authFunc != nil && cw.authFunc(user, pass) {
  112. if !testOnly {
  113. // Generate a valid auth token
  114. aid := cw.newAuthID()
  115. cw.tokenMap.Put(aid, user)
  116. return aid
  117. }
  118. return "ok"
  119. }
  120. return ""
  121. }
  122. /*
  123. CheckAuth checks the user authentication of an incomming request. Returns
  124. if the authentication is correct and the given username.
  125. */
  126. func (cw *CookieAuthHandleFuncWrapper) CheckAuth(r *http.Request) (string, bool) {
  127. var name string
  128. var ok bool
  129. cookie, _ := r.Cookie(cookieNameAuth)
  130. if cookie != nil && cookie.Value != "" {
  131. var user interface{}
  132. if user, ok = cw.tokenMap.Get(cookie.Value); ok {
  133. name = fmt.Sprint(user)
  134. }
  135. }
  136. return name, ok
  137. }
  138. /*
  139. SetAuthCookie sets the auth cookie in a given response object.
  140. */
  141. func (cw *CookieAuthHandleFuncWrapper) SetAuthCookie(yaid string, w http.ResponseWriter) {
  142. if yaid == "" {
  143. // Nothing to do if no auth id is given
  144. return
  145. }
  146. cookie := http.Cookie{
  147. Name: cookieNameAuth,
  148. Value: url.QueryEscape(yaid),
  149. Path: "/",
  150. HttpOnly: true,
  151. MaxAge: cw.expiry,
  152. }
  153. http.SetCookie(w, &cookie)
  154. }
  155. /*
  156. RemoveAuthCookie removes the auth cookie in a given response object and invalidates
  157. it.
  158. */
  159. func (cw *CookieAuthHandleFuncWrapper) RemoveAuthCookie(w http.ResponseWriter) {
  160. cookie := http.Cookie{
  161. Name: cookieNameAuth,
  162. Value: "",
  163. Path: "/",
  164. HttpOnly: true,
  165. MaxAge: -1,
  166. }
  167. http.SetCookie(w, &cookie)
  168. }
  169. /*
  170. InvalidateAuthCookie invalidates the authentication of an incomming request.
  171. */
  172. func (cw *CookieAuthHandleFuncWrapper) InvalidateAuthCookie(r *http.Request) {
  173. cookie, _ := r.Cookie(cookieNameAuth)
  174. if cookie != nil && cookie.Value != "" {
  175. cw.tokenMap.Remove(cookie.Value)
  176. }
  177. }
  178. /*
  179. newAuthID creates a new auth id.
  180. */
  181. func (cw *CookieAuthHandleFuncWrapper) newAuthID() string {
  182. b := make([]byte, 32)
  183. _, err := io.ReadFull(rand.Reader, b)
  184. errorutil.AssertOk(err)
  185. return fmt.Sprintf("A-%x", b)
  186. }
  187. /*
  188. HandleFunc is the new handle func which wraps an original handle functions to do an authentication check.
  189. */
  190. func (cw *CookieAuthHandleFuncWrapper) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
  191. cw.origHandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
  192. // Check if this is a public URL
  193. if chandler, ok := cw.publicURL[r.URL.Path]; ok {
  194. chandler(w, r)
  195. return
  196. }
  197. // Check if authentication is disabled
  198. if TestCookieAuthDisabled {
  199. handler(w, r)
  200. return
  201. }
  202. // Retrieve the cookie value
  203. cookie, _ := r.Cookie(cookieNameAuth)
  204. if cookie != nil && cookie.Value != "" {
  205. // Check in the token map if the user was authenticated
  206. if name, ok := cw.tokenMap.Get(cookie.Value); ok {
  207. nameString := fmt.Sprint(name)
  208. // Create or retrieve the user session (this call sets the session
  209. // cookie in the response) - a session is considered expired if
  210. // a session cookie is found in the request but no corresponding
  211. // session can be found by the UserSessionManager
  212. session, err := user.UserSessionManager.GetSession(nameString, w, r, true)
  213. if session != nil && err == nil && session.User() == nameString {
  214. // Set the auth cookie in the response
  215. cw.SetAuthCookie(cookie.Value, w)
  216. // Check authorization
  217. if cw.accessFunc == nil || cw.accessFunc(w, r, nameString) {
  218. // Handle the request
  219. handler(w, r)
  220. }
  221. return
  222. }
  223. // Remove auth token entry since the session has expired
  224. defer cw.tokenMap.Remove(cookie.Value)
  225. cw.CallbackSessionExpired(w, r)
  226. return
  227. }
  228. }
  229. cw.CallbackUnauthorized(w, r)
  230. })
  231. }