gitea源码

source_callout.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package oauth2
  4. import (
  5. "net/http"
  6. "github.com/markbates/goth"
  7. "github.com/markbates/goth/gothic"
  8. )
  9. // Callout redirects request/response pair to authenticate against the provider
  10. func (source *Source) Callout(request *http.Request, response http.ResponseWriter) error {
  11. // not sure if goth is thread safe (?) when using multiple providers
  12. request.Header.Set(ProviderHeaderKey, source.AuthSource.Name)
  13. // don't use the default gothic begin handler to prevent issues when some error occurs
  14. // normally the gothic library will write some custom stuff to the response instead of our own nice error page
  15. // gothic.BeginAuthHandler(response, request)
  16. gothRWMutex.RLock()
  17. defer gothRWMutex.RUnlock()
  18. url, err := gothic.GetAuthURL(response, request)
  19. if err == nil {
  20. http.Redirect(response, request, url, http.StatusTemporaryRedirect)
  21. }
  22. return err
  23. }
  24. // Callback handles OAuth callback, resolve to a goth user and send back to original url
  25. // this will trigger a new authentication request, but because we save it in the session we can use that
  26. func (source *Source) Callback(request *http.Request, response http.ResponseWriter) (goth.User, error) {
  27. // not sure if goth is thread safe (?) when using multiple providers
  28. request.Header.Set(ProviderHeaderKey, source.AuthSource.Name)
  29. gothRWMutex.RLock()
  30. defer gothRWMutex.RUnlock()
  31. user, err := gothic.CompleteUserAuth(response, request)
  32. if err != nil {
  33. return user, err
  34. }
  35. return user, nil
  36. }