auth.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. // HandleAuthCallback - handles oauth callback
  77. func HandleAuthCallback(w http.ResponseWriter, r *http.Request) {
  78. if auth_provider == nil {
  79. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  80. fmt.Fprintln(w, oauthNotConfigured)
  81. return
  82. }
  83. var functions = getCurrentAuthFunctions()
  84. if functions == nil {
  85. return
  86. }
  87. functions[handle_callback].(func(http.ResponseWriter, *http.Request))(w, r)
  88. }
  89. // HandleAuthLogin - handles oauth login
  90. func HandleAuthLogin(w http.ResponseWriter, r *http.Request) {
  91. if auth_provider == nil {
  92. var referer = r.Header.Get("referer")
  93. if referer != "" {
  94. http.Redirect(w, r, referer+"login?oauth=callback-error", http.StatusTemporaryRedirect)
  95. return
  96. }
  97. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  98. fmt.Fprintln(w, oauthNotConfigured)
  99. return
  100. }
  101. var functions = getCurrentAuthFunctions()
  102. if functions == nil {
  103. return
  104. }
  105. functions[handle_login].(func(http.ResponseWriter, *http.Request))(w, r)
  106. }
  107. // IsOauthUser - returns
  108. func IsOauthUser(user *models.User) error {
  109. var currentValue, err = fetchPassValue("")
  110. if err != nil {
  111. return err
  112. }
  113. var bCryptErr = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(currentValue))
  114. return bCryptErr
  115. }
  116. // == private methods ==
  117. func addUser(email string) error {
  118. var hasAdmin, err = logic.HasAdmin()
  119. if err != nil {
  120. logger.Log(1, "error checking for existence of admin user during OAuth login for", email, "; user not added")
  121. return err
  122. } // generate random password to adapt to current model
  123. var newPass, fetchErr = fetchPassValue("")
  124. if fetchErr != nil {
  125. return fetchErr
  126. }
  127. var newUser = models.User{
  128. UserName: email,
  129. Password: newPass,
  130. }
  131. if !hasAdmin { // must be first attempt, create an admin
  132. if newUser, err = logic.CreateAdmin(newUser); err != nil {
  133. logger.Log(1, "error creating admin from user,", email, "; user not added")
  134. } else {
  135. logger.Log(1, "admin created from user,", email, "; was first user added")
  136. }
  137. } else { // otherwise add to db as admin..?
  138. // TODO: add ability to add users with preemptive permissions
  139. newUser.IsAdmin = false
  140. if newUser, err = logic.CreateUser(newUser); err != nil {
  141. logger.Log(1, "error creating user,", email, "; user not added")
  142. } else {
  143. logger.Log(0, "user created from ", email)
  144. }
  145. }
  146. return nil
  147. }
  148. func fetchPassValue(newValue string) (string, error) {
  149. type valueHolder struct {
  150. Value string `json:"value" bson:"value"`
  151. }
  152. var b64NewValue = base64.StdEncoding.EncodeToString([]byte(newValue))
  153. var newValueHolder = &valueHolder{
  154. Value: b64NewValue,
  155. }
  156. var data, marshalErr = json.Marshal(newValueHolder)
  157. if marshalErr != nil {
  158. return "", marshalErr
  159. }
  160. var currentValue, err = logic.FetchAuthSecret(auth_key, string(data))
  161. if err != nil {
  162. return "", err
  163. }
  164. var unmarshErr = json.Unmarshal([]byte(currentValue), newValueHolder)
  165. if unmarshErr != nil {
  166. return "", unmarshErr
  167. }
  168. var b64CurrentValue, b64Err = base64.StdEncoding.DecodeString(newValueHolder.Value)
  169. if b64Err != nil {
  170. logger.Log(0, "could not decode pass")
  171. return "", nil
  172. }
  173. return string(b64CurrentValue), nil
  174. }