auth.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 auth_provider *oauth2.Config
  29. func getCurrentAuthFunctions() map[string]interface{} {
  30. var authInfo = servercfg.GetAuthProviderInfo()
  31. var authProvider = authInfo[0]
  32. switch authProvider {
  33. case google_provider_name:
  34. return google_functions
  35. case azure_ad_provider_name:
  36. return azure_ad_functions
  37. case github_provider_name:
  38. return github_functions
  39. case oidc_provider_name:
  40. return oidc_functions
  41. default:
  42. return nil
  43. }
  44. }
  45. // InitializeAuthProvider - initializes the auth provider if any is present
  46. func InitializeAuthProvider() string {
  47. var functions = getCurrentAuthFunctions()
  48. if functions == nil {
  49. return ""
  50. }
  51. var _, err = fetchPassValue(logic.RandomString(64))
  52. if err != nil {
  53. logger.Log(0, err.Error())
  54. return ""
  55. }
  56. var currentFrontendURL = servercfg.GetFrontendURL()
  57. if currentFrontendURL == "" {
  58. return ""
  59. }
  60. var authInfo = servercfg.GetAuthProviderInfo()
  61. var serverConn = servercfg.GetAPIHost()
  62. if strings.Contains(serverConn, "localhost") || strings.Contains(serverConn, "127.0.0.1") {
  63. serverConn = "http://" + serverConn
  64. logger.Log(1, "localhost OAuth detected, proceeding with insecure http redirect: (", serverConn, ")")
  65. } else {
  66. serverConn = "https://" + serverConn
  67. logger.Log(1, "external OAuth detected, proceeding with https redirect: ("+serverConn+")")
  68. }
  69. if authInfo[0] == "oidc" {
  70. functions[init_provider].(func(string, string, string, string))(serverConn+"/api/oauth/callback", authInfo[1], authInfo[2], authInfo[3])
  71. return authInfo[0]
  72. }
  73. functions[init_provider].(func(string, string, string))(serverConn+"/api/oauth/callback", authInfo[1], authInfo[2])
  74. return authInfo[0]
  75. }
  76. // Not included in API reference as part of the OAuth process itself.
  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. // swagger:route GET /api/oauth/login nodes HandleAuthLogin
  91. //
  92. // Handles OAuth login.
  93. //
  94. // Schemes: https
  95. //
  96. // Security:
  97. // oauth
  98. func HandleAuthLogin(w http.ResponseWriter, r *http.Request) {
  99. if auth_provider == nil {
  100. var referer = r.Header.Get("referer")
  101. if referer != "" {
  102. http.Redirect(w, r, referer+"login?oauth=callback-error", http.StatusTemporaryRedirect)
  103. return
  104. }
  105. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  106. fmt.Fprintln(w, oauthNotConfigured)
  107. return
  108. }
  109. var functions = getCurrentAuthFunctions()
  110. if functions == nil {
  111. return
  112. }
  113. functions[handle_login].(func(http.ResponseWriter, *http.Request))(w, r)
  114. }
  115. // IsOauthUser - returns
  116. func IsOauthUser(user *models.User) error {
  117. var currentValue, err = fetchPassValue("")
  118. if err != nil {
  119. return err
  120. }
  121. var bCryptErr = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(currentValue))
  122. return bCryptErr
  123. }
  124. // == private methods ==
  125. func addUser(email string) error {
  126. var hasAdmin, err = logic.HasAdmin()
  127. if err != nil {
  128. logger.Log(1, "error checking for existence of admin user during OAuth login for", email, "; user not added")
  129. return err
  130. } // generate random password to adapt to current model
  131. var newPass, fetchErr = fetchPassValue("")
  132. if fetchErr != nil {
  133. return fetchErr
  134. }
  135. var newUser = models.User{
  136. UserName: email,
  137. Password: newPass,
  138. }
  139. if !hasAdmin { // must be first attempt, create an admin
  140. if newUser, err = logic.CreateAdmin(newUser); err != nil {
  141. logger.Log(1, "error creating admin from user,", email, "; user not added")
  142. } else {
  143. logger.Log(1, "admin created from user,", email, "; was first user added")
  144. }
  145. } else { // otherwise add to db as admin..?
  146. // TODO: add ability to add users with preemptive permissions
  147. newUser.IsAdmin = false
  148. if newUser, err = logic.CreateUser(newUser); err != nil {
  149. logger.Log(1, "error creating user,", email, "; user not added")
  150. } else {
  151. logger.Log(0, "user created from ", email)
  152. }
  153. }
  154. return nil
  155. }
  156. func fetchPassValue(newValue string) (string, error) {
  157. type valueHolder struct {
  158. Value string `json:"value" bson:"value"`
  159. }
  160. var b64NewValue = base64.StdEncoding.EncodeToString([]byte(newValue))
  161. var newValueHolder = &valueHolder{
  162. Value: b64NewValue,
  163. }
  164. var data, marshalErr = json.Marshal(newValueHolder)
  165. if marshalErr != nil {
  166. return "", marshalErr
  167. }
  168. var currentValue, err = logic.FetchAuthSecret(auth_key, string(data))
  169. if err != nil {
  170. return "", err
  171. }
  172. var unmarshErr = json.Unmarshal([]byte(currentValue), newValueHolder)
  173. if unmarshErr != nil {
  174. return "", unmarshErr
  175. }
  176. var b64CurrentValue, b64Err = base64.StdEncoding.DecodeString(newValueHolder.Value)
  177. if b64Err != nil {
  178. logger.Log(0, "could not decode pass")
  179. return "", nil
  180. }
  181. return string(b64CurrentValue), nil
  182. }