login_oauth.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package api
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "encoding/base64"
  8. "errors"
  9. "fmt"
  10. "io/ioutil"
  11. "net/http"
  12. "net/url"
  13. "golang.org/x/oauth2"
  14. "github.com/grafana/grafana/pkg/bus"
  15. "github.com/grafana/grafana/pkg/log"
  16. "github.com/grafana/grafana/pkg/metrics"
  17. "github.com/grafana/grafana/pkg/middleware"
  18. m "github.com/grafana/grafana/pkg/models"
  19. "github.com/grafana/grafana/pkg/services/session"
  20. "github.com/grafana/grafana/pkg/setting"
  21. "github.com/grafana/grafana/pkg/social"
  22. )
  23. var (
  24. ErrProviderDeniedRequest = errors.New("Login provider denied login request")
  25. ErrEmailNotAllowed = errors.New("Required email domain not fulfilled")
  26. ErrSignUpNotAllowed = errors.New("Signup is not allowed for this adapter")
  27. ErrUsersQuotaReached = errors.New("Users quota reached")
  28. ErrNoEmail = errors.New("Login provider didn't return an email address")
  29. oauthLogger = log.New("oauth")
  30. )
  31. func GenStateString() string {
  32. rnd := make([]byte, 32)
  33. rand.Read(rnd)
  34. return base64.URLEncoding.EncodeToString(rnd)
  35. }
  36. func OAuthLogin(ctx *m.Context) {
  37. if setting.OAuthService == nil {
  38. ctx.Handle(404, "OAuth not enabled", nil)
  39. return
  40. }
  41. name := ctx.Params(":name")
  42. connect, ok := social.SocialMap[name]
  43. if !ok {
  44. ctx.Handle(404, fmt.Sprintf("No OAuth with name %s configured", name), nil)
  45. return
  46. }
  47. errorParam := ctx.Query("error")
  48. if errorParam != "" {
  49. errorDesc := ctx.Query("error_description")
  50. oauthLogger.Error("failed to login ", "error", errorParam, "errorDesc", errorDesc)
  51. redirectWithError(ctx, ErrProviderDeniedRequest, "error", errorParam, "errorDesc", errorDesc)
  52. return
  53. }
  54. code := ctx.Query("code")
  55. if code == "" {
  56. state := GenStateString()
  57. ctx.Session.Set(session.SESS_KEY_OAUTH_STATE, state)
  58. if setting.OAuthService.OAuthInfos[name].HostedDomain == "" {
  59. ctx.Redirect(connect.AuthCodeURL(state, oauth2.AccessTypeOnline))
  60. } else {
  61. ctx.Redirect(connect.AuthCodeURL(state, oauth2.SetAuthURLParam("hd", setting.OAuthService.OAuthInfos[name].HostedDomain), oauth2.AccessTypeOnline))
  62. }
  63. return
  64. }
  65. savedState, ok := ctx.Session.Get(session.SESS_KEY_OAUTH_STATE).(string)
  66. if !ok {
  67. ctx.Handle(500, "login.OAuthLogin(missing saved state)", nil)
  68. return
  69. }
  70. queryState := ctx.Query("state")
  71. if savedState != queryState {
  72. ctx.Handle(500, "login.OAuthLogin(state mismatch)", nil)
  73. return
  74. }
  75. // handle call back
  76. tr := &http.Transport{
  77. TLSClientConfig: &tls.Config{
  78. InsecureSkipVerify: setting.OAuthService.OAuthInfos[name].TlsSkipVerify,
  79. },
  80. }
  81. oauthClient := &http.Client{
  82. Transport: tr,
  83. }
  84. if setting.OAuthService.OAuthInfos[name].TlsClientCert != "" || setting.OAuthService.OAuthInfos[name].TlsClientKey != "" {
  85. cert, err := tls.LoadX509KeyPair(setting.OAuthService.OAuthInfos[name].TlsClientCert, setting.OAuthService.OAuthInfos[name].TlsClientKey)
  86. if err != nil {
  87. ctx.Logger.Error("Failed to setup TlsClientCert", "oauth", name, "error", err)
  88. ctx.Handle(500, "login.OAuthLogin(Failed to setup TlsClientCert)", nil)
  89. return
  90. }
  91. tr.TLSClientConfig.Certificates = append(tr.TLSClientConfig.Certificates, cert)
  92. }
  93. if setting.OAuthService.OAuthInfos[name].TlsClientCa != "" {
  94. caCert, err := ioutil.ReadFile(setting.OAuthService.OAuthInfos[name].TlsClientCa)
  95. if err != nil {
  96. ctx.Logger.Error("Failed to setup TlsClientCa", "oauth", name, "error", err)
  97. ctx.Handle(500, "login.OAuthLogin(Failed to setup TlsClientCa)", nil)
  98. return
  99. }
  100. caCertPool := x509.NewCertPool()
  101. caCertPool.AppendCertsFromPEM(caCert)
  102. tr.TLSClientConfig.RootCAs = caCertPool
  103. }
  104. oauthCtx := context.WithValue(context.Background(), oauth2.HTTPClient, oauthClient)
  105. // get token from provider
  106. token, err := connect.Exchange(oauthCtx, code)
  107. if err != nil {
  108. ctx.Handle(500, "login.OAuthLogin(NewTransportWithCode)", err)
  109. return
  110. }
  111. // token.TokenType was defaulting to "bearer", which is out of spec, so we explicitly set to "Bearer"
  112. token.TokenType = "Bearer"
  113. oauthLogger.Debug("OAuthLogin Got token", "token", token)
  114. // set up oauth2 client
  115. client := connect.Client(oauthCtx, token)
  116. // get user info
  117. userInfo, err := connect.UserInfo(client, token)
  118. if err != nil {
  119. if sErr, ok := err.(*social.Error); ok {
  120. redirectWithError(ctx, sErr)
  121. } else {
  122. ctx.Handle(500, fmt.Sprintf("login.OAuthLogin(get info from %s)", name), err)
  123. }
  124. return
  125. }
  126. oauthLogger.Debug("OAuthLogin got user info", "userInfo", userInfo)
  127. // validate that we got at least an email address
  128. if userInfo.Email == "" {
  129. redirectWithError(ctx, ErrNoEmail)
  130. return
  131. }
  132. // validate that the email is allowed to login to grafana
  133. if !connect.IsEmailAllowed(userInfo.Email) {
  134. redirectWithError(ctx, ErrEmailNotAllowed)
  135. return
  136. }
  137. userQuery := m.GetUserByEmailQuery{Email: userInfo.Email}
  138. err = bus.Dispatch(&userQuery)
  139. // create account if missing
  140. if err == m.ErrUserNotFound {
  141. if !connect.IsSignupAllowed() {
  142. redirectWithError(ctx, ErrSignUpNotAllowed)
  143. return
  144. }
  145. limitReached, err := middleware.QuotaReached(ctx, "user")
  146. if err != nil {
  147. ctx.Handle(500, "Failed to get user quota", err)
  148. return
  149. }
  150. if limitReached {
  151. redirectWithError(ctx, ErrUsersQuotaReached)
  152. return
  153. }
  154. cmd := m.CreateUserCommand{
  155. Login: userInfo.Login,
  156. Email: userInfo.Email,
  157. Name: userInfo.Name,
  158. Company: userInfo.Company,
  159. DefaultOrgRole: userInfo.Role,
  160. }
  161. if err = bus.Dispatch(&cmd); err != nil {
  162. ctx.Handle(500, "Failed to create account", err)
  163. return
  164. }
  165. userQuery.Result = &cmd.Result
  166. } else if err != nil {
  167. ctx.Handle(500, "Unexpected error", err)
  168. }
  169. // login
  170. loginUserWithUser(userQuery.Result, ctx)
  171. metrics.M_Api_Login_OAuth.Inc()
  172. if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
  173. ctx.SetCookie("redirect_to", "", -1, setting.AppSubUrl+"/")
  174. ctx.Redirect(redirectTo)
  175. return
  176. }
  177. ctx.Redirect(setting.AppSubUrl + "/")
  178. }
  179. func redirectWithError(ctx *m.Context, err error, v ...interface{}) {
  180. ctx.Logger.Error(err.Error(), v...)
  181. ctx.Session.Set("loginError", err.Error())
  182. ctx.Redirect(setting.AppSubUrl + "/login")
  183. }