auth.go 5.4 KB

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