auth.go 5.2 KB

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