You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

241 lines
6.3 KiB

Oauth2 consumer (#679) * initial stuff for oauth2 login, fails on: * login button on the signIn page to start the OAuth2 flow and a callback for each provider Only GitHub is implemented for now * show login button only when the OAuth2 consumer is configured (and activated) * create macaron group for oauth2 urls * prevent net/http in modules (other then oauth2) * use a new data sessions oauth2 folder for storing the oauth2 session data * add missing 2FA when this is enabled on the user * add password option for OAuth2 user , for use with git over http and login to the GUI * add tip for registering a GitHub OAuth application * at startup of Gitea register all configured providers and also on adding/deleting of new providers * custom handling of errors in oauth2 request init + show better tip * add ExternalLoginUser model and migration script to add it to database * link a external account to an existing account (still need to handle wrong login and signup) and remove if user is removed * remove the linked external account from the user his settings * if user is unknown we allow him to register a new account or link it to some existing account * sign up with button on signin page (als change OAuth2Provider structure so we can store basic stuff about providers) * from gorilla/sessions docs: "Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory!" (we're using gorilla/sessions for storing oauth2 sessions) * use updated goth lib that now supports getting the OAuth2 user if the AccessToken is still valid instead of re-authenticating (prevent flooding the OAuth2 provider)
7 years ago
  1. // Copyright 2012 The Gorilla Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package sessions
  5. import (
  6. "encoding/gob"
  7. "fmt"
  8. "net/http"
  9. "time"
  10. "github.com/gorilla/context"
  11. )
  12. // Default flashes key.
  13. const flashesKey = "_flash"
  14. // Options --------------------------------------------------------------------
  15. // Options stores configuration for a session or session store.
  16. //
  17. // Fields are a subset of http.Cookie fields.
  18. type Options struct {
  19. Path string
  20. Domain string
  21. // MaxAge=0 means no 'Max-Age' attribute specified.
  22. // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'.
  23. // MaxAge>0 means Max-Age attribute present and given in seconds.
  24. MaxAge int
  25. Secure bool
  26. HttpOnly bool
  27. }
  28. // Session --------------------------------------------------------------------
  29. // NewSession is called by session stores to create a new session instance.
  30. func NewSession(store Store, name string) *Session {
  31. return &Session{
  32. Values: make(map[interface{}]interface{}),
  33. store: store,
  34. name: name,
  35. }
  36. }
  37. // Session stores the values and optional configuration for a session.
  38. type Session struct {
  39. // The ID of the session, generated by stores. It should not be used for
  40. // user data.
  41. ID string
  42. // Values contains the user-data for the session.
  43. Values map[interface{}]interface{}
  44. Options *Options
  45. IsNew bool
  46. store Store
  47. name string
  48. }
  49. // Flashes returns a slice of flash messages from the session.
  50. //
  51. // A single variadic argument is accepted, and it is optional: it defines
  52. // the flash key. If not defined "_flash" is used by default.
  53. func (s *Session) Flashes(vars ...string) []interface{} {
  54. var flashes []interface{}
  55. key := flashesKey
  56. if len(vars) > 0 {
  57. key = vars[0]
  58. }
  59. if v, ok := s.Values[key]; ok {
  60. // Drop the flashes and return it.
  61. delete(s.Values, key)
  62. flashes = v.([]interface{})
  63. }
  64. return flashes
  65. }
  66. // AddFlash adds a flash message to the session.
  67. //
  68. // A single variadic argument is accepted, and it is optional: it defines
  69. // the flash key. If not defined "_flash" is used by default.
  70. func (s *Session) AddFlash(value interface{}, vars ...string) {
  71. key := flashesKey
  72. if len(vars) > 0 {
  73. key = vars[0]
  74. }
  75. var flashes []interface{}
  76. if v, ok := s.Values[key]; ok {
  77. flashes = v.([]interface{})
  78. }
  79. s.Values[key] = append(flashes, value)
  80. }
  81. // Save is a convenience method to save this session. It is the same as calling
  82. // store.Save(request, response, session). You should call Save before writing to
  83. // the response or returning from the handler.
  84. func (s *Session) Save(r *http.Request, w http.ResponseWriter) error {
  85. return s.store.Save(r, w, s)
  86. }
  87. // Name returns the name used to register the session.
  88. func (s *Session) Name() string {
  89. return s.name
  90. }
  91. // Store returns the session store used to register the session.
  92. func (s *Session) Store() Store {
  93. return s.store
  94. }
  95. // Registry -------------------------------------------------------------------
  96. // sessionInfo stores a session tracked by the registry.
  97. type sessionInfo struct {
  98. s *Session
  99. e error
  100. }
  101. // contextKey is the type used to store the registry in the context.
  102. type contextKey int
  103. // registryKey is the key used to store the registry in the context.
  104. const registryKey contextKey = 0
  105. // GetRegistry returns a registry instance for the current request.
  106. func GetRegistry(r *http.Request) *Registry {
  107. registry := context.Get(r, registryKey)
  108. if registry != nil {
  109. return registry.(*Registry)
  110. }
  111. newRegistry := &Registry{
  112. request: r,
  113. sessions: make(map[string]sessionInfo),
  114. }
  115. context.Set(r, registryKey, newRegistry)
  116. return newRegistry
  117. }
  118. // Registry stores sessions used during a request.
  119. type Registry struct {
  120. request *http.Request
  121. sessions map[string]sessionInfo
  122. }
  123. // Get registers and returns a session for the given name and session store.
  124. //
  125. // It returns a new session if there are no sessions registered for the name.
  126. func (s *Registry) Get(store Store, name string) (session *Session, err error) {
  127. if !isCookieNameValid(name) {
  128. return nil, fmt.Errorf("sessions: invalid character in cookie name: %s", name)
  129. }
  130. if info, ok := s.sessions[name]; ok {
  131. session, err = info.s, info.e
  132. } else {
  133. session, err = store.New(s.request, name)
  134. session.name = name
  135. s.sessions[name] = sessionInfo{s: session, e: err}
  136. }
  137. session.store = store
  138. return
  139. }
  140. // Save saves all sessions registered for the current request.
  141. func (s *Registry) Save(w http.ResponseWriter) error {
  142. var errMulti MultiError
  143. for name, info := range s.sessions {
  144. session := info.s
  145. if session.store == nil {
  146. errMulti = append(errMulti, fmt.Errorf(
  147. "sessions: missing store for session %q", name))
  148. } else if err := session.store.Save(s.request, w, session); err != nil {
  149. errMulti = append(errMulti, fmt.Errorf(
  150. "sessions: error saving session %q -- %v", name, err))
  151. }
  152. }
  153. if errMulti != nil {
  154. return errMulti
  155. }
  156. return nil
  157. }
  158. // Helpers --------------------------------------------------------------------
  159. func init() {
  160. gob.Register([]interface{}{})
  161. }
  162. // Save saves all sessions used during the current request.
  163. func Save(r *http.Request, w http.ResponseWriter) error {
  164. return GetRegistry(r).Save(w)
  165. }
  166. // NewCookie returns an http.Cookie with the options set. It also sets
  167. // the Expires field calculated based on the MaxAge value, for Internet
  168. // Explorer compatibility.
  169. func NewCookie(name, value string, options *Options) *http.Cookie {
  170. cookie := &http.Cookie{
  171. Name: name,
  172. Value: value,
  173. Path: options.Path,
  174. Domain: options.Domain,
  175. MaxAge: options.MaxAge,
  176. Secure: options.Secure,
  177. HttpOnly: options.HttpOnly,
  178. }
  179. if options.MaxAge > 0 {
  180. d := time.Duration(options.MaxAge) * time.Second
  181. cookie.Expires = time.Now().Add(d)
  182. } else if options.MaxAge < 0 {
  183. // Set it to the past to expire now.
  184. cookie.Expires = time.Unix(1, 0)
  185. }
  186. return cookie
  187. }
  188. // Error ----------------------------------------------------------------------
  189. // MultiError stores multiple errors.
  190. //
  191. // Borrowed from the App Engine SDK.
  192. type MultiError []error
  193. func (m MultiError) Error() string {
  194. s, n := "", 0
  195. for _, e := range m {
  196. if e != nil {
  197. if n == 0 {
  198. s = e.Error()
  199. }
  200. n++
  201. }
  202. }
  203. switch n {
  204. case 0:
  205. return "(0 errors)"
  206. case 1:
  207. return s
  208. case 2:
  209. return s + " (and 1 other error)"
  210. }
  211. return fmt.Sprintf("%s (and %d other errors)", s, n-1)
  212. }