auth.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. package auth
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "github.com/gravitl/netmaker/logic"
  9. "github.com/gravitl/netmaker/models"
  10. "github.com/gravitl/netmaker/servercfg"
  11. "golang.org/x/crypto/bcrypt"
  12. "golang.org/x/oauth2"
  13. )
  14. // == consts ==
  15. const (
  16. init_provider = "initprovider"
  17. get_user_info = "getuserinfo"
  18. handle_callback = "handlecallback"
  19. handle_login = "handlelogin"
  20. google_provider_name = "google"
  21. azure_ad_provider_name = "azure-ad"
  22. github_provider_name = "github"
  23. verify_user = "verifyuser"
  24. auth_key = "netmaker_auth"
  25. )
  26. var oauth_state_string = "netmaker-oauth-state" // should be set randomly each provider login
  27. var auth_provider *oauth2.Config
  28. func getCurrentAuthFunctions() map[string]interface{} {
  29. var authInfo = servercfg.GetAuthProviderInfo()
  30. var authProvider = authInfo[0]
  31. switch authProvider {
  32. case google_provider_name:
  33. return google_functions
  34. case azure_ad_provider_name:
  35. return azure_ad_functions
  36. case github_provider_name:
  37. return github_functions
  38. default:
  39. return nil
  40. }
  41. }
  42. // InitializeAuthProvider - initializes the auth provider if any is present
  43. func InitializeAuthProvider() string {
  44. var functions = getCurrentAuthFunctions()
  45. if functions == nil {
  46. return ""
  47. }
  48. var _, err = fetchPassValue(logic.RandomString(64))
  49. if err != nil {
  50. logic.Log(err.Error(), 0)
  51. return ""
  52. }
  53. var currentFrontendURL = servercfg.GetFrontendURL()
  54. if currentFrontendURL == "" {
  55. return ""
  56. }
  57. var authInfo = servercfg.GetAuthProviderInfo()
  58. var serverConn = servercfg.GetAPIHost()
  59. if strings.Contains(serverConn, "localhost") || strings.Contains(serverConn, "127.0.0.1") {
  60. logic.Log("localhost OAuth detected, proceeding with insecure http redirect", 1)
  61. serverConn = "http://" + serverConn
  62. } else {
  63. logic.Log("external OAuth detected, proceeding with https redirect", 1)
  64. serverConn = "https://" + serverConn
  65. }
  66. functions[init_provider].(func(string, string, string))(serverConn+"/api/oauth/callback", authInfo[1], authInfo[2])
  67. return authInfo[0]
  68. }
  69. // HandleAuthCallback - handles oauth callback
  70. func HandleAuthCallback(w http.ResponseWriter, r *http.Request) {
  71. if auth_provider == nil {
  72. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  73. fmt.Fprintln(w, oauthNotConfigured)
  74. return
  75. }
  76. var functions = getCurrentAuthFunctions()
  77. if functions == nil {
  78. return
  79. }
  80. functions[handle_callback].(func(http.ResponseWriter, *http.Request))(w, r)
  81. }
  82. // HandleAuthLogin - handles oauth login
  83. func HandleAuthLogin(w http.ResponseWriter, r *http.Request) {
  84. if auth_provider == nil {
  85. var referer = r.Header.Get("referer")
  86. if referer != "" {
  87. http.Redirect(w, r, referer+"?oauth=callback-error", http.StatusTemporaryRedirect)
  88. return
  89. }
  90. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  91. fmt.Fprintln(w, oauthNotConfigured)
  92. return
  93. }
  94. var functions = getCurrentAuthFunctions()
  95. if functions == nil {
  96. return
  97. }
  98. functions[handle_login].(func(http.ResponseWriter, *http.Request))(w, r)
  99. }
  100. // IsOauthUser - returns
  101. func IsOauthUser(user *models.User) error {
  102. var currentValue, err = fetchPassValue("")
  103. if err != nil {
  104. return err
  105. }
  106. var bCryptErr = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(currentValue))
  107. return bCryptErr
  108. }
  109. // == private methods ==
  110. func addUser(email string) error {
  111. var hasAdmin, err = logic.HasAdmin()
  112. if err != nil {
  113. logic.Log("error checking for existence of admin user during OAuth login for "+email+", user not added", 1)
  114. return err
  115. } // generate random password to adapt to current model
  116. var newPass, fetchErr = fetchPassValue("")
  117. if fetchErr != nil {
  118. return fetchErr
  119. }
  120. var newUser = models.User{
  121. UserName: email,
  122. Password: newPass,
  123. }
  124. if !hasAdmin { // must be first attempt, create an admin
  125. if newUser, err = logic.CreateAdmin(newUser); err != nil {
  126. logic.Log("error creating admin from user, "+email+", user not added", 1)
  127. } else {
  128. logic.Log("admin created from user, "+email+", was first user added", 0)
  129. }
  130. } else { // otherwise add to db as admin..?
  131. // TODO: add ability to add users with preemptive permissions
  132. newUser.IsAdmin = false
  133. if newUser, err = logic.CreateUser(newUser); err != nil {
  134. logic.Log("error creating user, "+email+", user not added", 1)
  135. } else {
  136. logic.Log("user created from, "+email+"", 0)
  137. }
  138. }
  139. return nil
  140. }
  141. func fetchPassValue(newValue string) (string, error) {
  142. type valueHolder struct {
  143. Value string `json:"value" bson:"value"`
  144. }
  145. var b64NewValue = base64.StdEncoding.EncodeToString([]byte(newValue))
  146. var newValueHolder = &valueHolder{
  147. Value: b64NewValue,
  148. }
  149. var data, marshalErr = json.Marshal(newValueHolder)
  150. if marshalErr != nil {
  151. return "", marshalErr
  152. }
  153. var currentValue, err = logic.FetchAuthSecret(auth_key, string(data))
  154. if err != nil {
  155. return "", err
  156. }
  157. var unmarshErr = json.Unmarshal([]byte(currentValue), newValueHolder)
  158. if unmarshErr != nil {
  159. return "", unmarshErr
  160. }
  161. var b64CurrentValue, b64Err = base64.StdEncoding.DecodeString(newValueHolder.Value)
  162. if b64Err != nil {
  163. logic.Log("could not decode pass", 0)
  164. return "", nil
  165. }
  166. return string(b64CurrentValue), nil
  167. }