azure-ad.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. package auth
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "github.com/gravitl/netmaker/database"
  9. "github.com/gravitl/netmaker/logger"
  10. "github.com/gravitl/netmaker/logic"
  11. "github.com/gravitl/netmaker/models"
  12. "github.com/gravitl/netmaker/servercfg"
  13. "golang.org/x/oauth2"
  14. "golang.org/x/oauth2/microsoft"
  15. )
  16. var azure_ad_functions = map[string]interface{}{
  17. init_provider: initAzureAD,
  18. get_user_info: getAzureUserInfo,
  19. handle_callback: handleAzureCallback,
  20. handle_login: handleAzureLogin,
  21. verify_user: verifyAzureUser,
  22. }
  23. // == handle azure ad authentication here ==
  24. func initAzureAD(redirectURL string, clientID string, clientSecret string) {
  25. auth_provider = &oauth2.Config{
  26. RedirectURL: redirectURL,
  27. ClientID: clientID,
  28. ClientSecret: clientSecret,
  29. Scopes: []string{"User.Read"},
  30. Endpoint: microsoft.AzureADEndpoint(servercfg.GetAzureTenant()),
  31. }
  32. }
  33. func handleAzureLogin(w http.ResponseWriter, r *http.Request) {
  34. var oauth_state_string = logic.RandomString(user_signin_length)
  35. if auth_provider == nil {
  36. handleOauthNotConfigured(w)
  37. return
  38. }
  39. if err := logic.SetState(oauth_state_string); err != nil {
  40. handleOauthNotConfigured(w)
  41. return
  42. }
  43. var url = auth_provider.AuthCodeURL(oauth_state_string)
  44. http.Redirect(w, r, url, http.StatusTemporaryRedirect)
  45. }
  46. func handleAzureCallback(w http.ResponseWriter, r *http.Request) {
  47. var rState, rCode = getStateAndCode(r)
  48. var content, err = getAzureUserInfo(rState, rCode)
  49. if err != nil {
  50. logger.Log(1, "error when getting user info from azure:", err.Error())
  51. handleOauthNotConfigured(w)
  52. return
  53. }
  54. if !isEmailAllowed(content.UserPrincipalName) {
  55. handleOauthUserNotAllowedToSignUp(w)
  56. return
  57. }
  58. // check if user approval is already pending
  59. if logic.IsPendingUser(content.UserPrincipalName) {
  60. handleOauthUserNotAllowed(w)
  61. return
  62. }
  63. _, err = logic.GetUser(content.UserPrincipalName)
  64. if err != nil {
  65. if database.IsEmptyRecord(err) { // user must not exist, so try to make one
  66. err = logic.InsertPendingUser(&models.User{
  67. UserName: content.UserPrincipalName,
  68. })
  69. if err != nil {
  70. handleSomethingWentWrong(w)
  71. return
  72. }
  73. handleOauthUserNotAllowed(w)
  74. return
  75. } else {
  76. handleSomethingWentWrong(w)
  77. return
  78. }
  79. }
  80. user, err := logic.GetUser(content.UserPrincipalName)
  81. if err != nil {
  82. handleOauthUserNotFound(w)
  83. return
  84. }
  85. if !(user.IsSuperAdmin || user.IsAdmin) {
  86. handleOauthUserNotAllowed(w)
  87. return
  88. }
  89. var newPass, fetchErr = FetchPassValue("")
  90. if fetchErr != nil {
  91. return
  92. }
  93. // send a netmaker jwt token
  94. var authRequest = models.UserAuthParams{
  95. UserName: content.UserPrincipalName,
  96. Password: newPass,
  97. }
  98. var jwt, jwtErr = logic.VerifyAuthRequest(authRequest)
  99. if jwtErr != nil {
  100. logger.Log(1, "could not parse jwt for user", authRequest.UserName)
  101. return
  102. }
  103. logger.Log(1, "completed azure OAuth sigin in for", content.UserPrincipalName)
  104. http.Redirect(w, r, servercfg.GetFrontendURL()+"/login?login="+jwt+"&user="+content.UserPrincipalName, http.StatusPermanentRedirect)
  105. }
  106. func getAzureUserInfo(state string, code string) (*OAuthUser, error) {
  107. oauth_state_string, isValid := logic.IsStateValid(state)
  108. if (!isValid || state != oauth_state_string) && !isStateCached(state) {
  109. return nil, fmt.Errorf("invalid oauth state")
  110. }
  111. var token, err = auth_provider.Exchange(context.Background(), code)
  112. if err != nil {
  113. return nil, fmt.Errorf("code exchange failed: %s", err.Error())
  114. }
  115. var data []byte
  116. data, err = json.Marshal(token)
  117. if err != nil {
  118. return nil, fmt.Errorf("failed to convert token to json: %s", err.Error())
  119. }
  120. var httpReq, reqErr = http.NewRequest("GET", "https://graph.microsoft.com/v1.0/me", nil)
  121. if reqErr != nil {
  122. return nil, fmt.Errorf("failed to create request to GitHub")
  123. }
  124. httpReq.Header.Set("Authorization", "Bearer "+token.AccessToken)
  125. response, err := http.DefaultClient.Do(httpReq)
  126. if err != nil {
  127. return nil, fmt.Errorf("failed getting user info: %s", err.Error())
  128. }
  129. defer response.Body.Close()
  130. contents, err := io.ReadAll(response.Body)
  131. if err != nil {
  132. return nil, fmt.Errorf("failed reading response body: %s", err.Error())
  133. }
  134. var userInfo = &OAuthUser{}
  135. if err = json.Unmarshal(contents, userInfo); err != nil {
  136. return nil, fmt.Errorf("failed parsing email from response data: %s", err.Error())
  137. }
  138. userInfo.AccessToken = string(data)
  139. return userInfo, nil
  140. }
  141. func verifyAzureUser(token *oauth2.Token) bool {
  142. return token.Valid()
  143. }