login_oauth.go 6.0 KB

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