auth.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package auth
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "net/http"
  7. "strings"
  8. "golang.org/x/crypto/bcrypt"
  9. "golang.org/x/oauth2"
  10. "github.com/gravitl/netmaker/logger"
  11. "github.com/gravitl/netmaker/logic"
  12. "github.com/gravitl/netmaker/logic/pro/netcache"
  13. "github.com/gravitl/netmaker/models"
  14. "github.com/gravitl/netmaker/servercfg"
  15. )
  16. // == consts ==
  17. const (
  18. init_provider = "initprovider"
  19. get_user_info = "getuserinfo"
  20. handle_callback = "handlecallback"
  21. handle_login = "handlelogin"
  22. google_provider_name = "google"
  23. azure_ad_provider_name = "azure-ad"
  24. github_provider_name = "github"
  25. oidc_provider_name = "oidc"
  26. verify_user = "verifyuser"
  27. auth_key = "netmaker_auth"
  28. user_signin_length = 16
  29. node_signin_length = 64
  30. )
  31. // OAuthUser - generic OAuth strategy user
  32. type OAuthUser struct {
  33. Name string `json:"name" bson:"name"`
  34. Email string `json:"email" bson:"email"`
  35. Login string `json:"login" bson:"login"`
  36. UserPrincipalName string `json:"userPrincipalName" bson:"userPrincipalName"`
  37. AccessToken string `json:"accesstoken" bson:"accesstoken"`
  38. }
  39. var auth_provider *oauth2.Config
  40. func getCurrentAuthFunctions() map[string]interface{} {
  41. var authInfo = servercfg.GetAuthProviderInfo()
  42. var authProvider = authInfo[0]
  43. switch authProvider {
  44. case google_provider_name:
  45. return google_functions
  46. case azure_ad_provider_name:
  47. return azure_ad_functions
  48. case github_provider_name:
  49. return github_functions
  50. case oidc_provider_name:
  51. return oidc_functions
  52. default:
  53. return nil
  54. }
  55. }
  56. // InitializeAuthProvider - initializes the auth provider if any is present
  57. func InitializeAuthProvider() string {
  58. var functions = getCurrentAuthFunctions()
  59. if functions == nil {
  60. return ""
  61. }
  62. var _, err = fetchPassValue(logic.RandomString(64))
  63. if err != nil {
  64. logger.Log(0, err.Error())
  65. return ""
  66. }
  67. var authInfo = servercfg.GetAuthProviderInfo()
  68. var serverConn = servercfg.GetAPIHost()
  69. if strings.Contains(serverConn, "localhost") || strings.Contains(serverConn, "127.0.0.1") {
  70. serverConn = "http://" + serverConn
  71. logger.Log(1, "localhost OAuth detected, proceeding with insecure http redirect: (", serverConn, ")")
  72. } else {
  73. serverConn = "https://" + serverConn
  74. logger.Log(1, "external OAuth detected, proceeding with https redirect: ("+serverConn+")")
  75. }
  76. if authInfo[0] == "oidc" {
  77. functions[init_provider].(func(string, string, string, string))(serverConn+"/api/oauth/callback", authInfo[1], authInfo[2], authInfo[3])
  78. return authInfo[0]
  79. }
  80. functions[init_provider].(func(string, string, string))(serverConn+"/api/oauth/callback", authInfo[1], authInfo[2])
  81. return authInfo[0]
  82. }
  83. // HandleAuthCallback - handles oauth callback
  84. // Note: not included in API reference as part of the OAuth process itself.
  85. func HandleAuthCallback(w http.ResponseWriter, r *http.Request) {
  86. if auth_provider == nil {
  87. handleOauthNotConfigured(w)
  88. return
  89. }
  90. var functions = getCurrentAuthFunctions()
  91. if functions == nil {
  92. return
  93. }
  94. state, _ := getStateAndCode(r)
  95. _, err := netcache.Get(state) // if in netcache proceeed with node registration login
  96. if err == nil || len(state) == node_signin_length || errors.Is(err, netcache.ErrExpired) {
  97. logger.Log(0, "proceeding with node SSO callback")
  98. HandleNodeSSOCallback(w, r)
  99. } else { // handle normal login
  100. functions[handle_callback].(func(http.ResponseWriter, *http.Request))(w, r)
  101. }
  102. }
  103. // swagger:route GET /api/oauth/login nodes HandleAuthLogin
  104. //
  105. // Handles OAuth login.
  106. //
  107. // Schemes: https
  108. //
  109. // Security:
  110. // oauth
  111. func HandleAuthLogin(w http.ResponseWriter, r *http.Request) {
  112. if auth_provider == nil {
  113. handleOauthNotConfigured(w)
  114. return
  115. }
  116. var functions = getCurrentAuthFunctions()
  117. if functions == nil {
  118. return
  119. }
  120. if servercfg.GetFrontendURL() == "" {
  121. handleOauthNotConfigured(w)
  122. return
  123. }
  124. functions[handle_login].(func(http.ResponseWriter, *http.Request))(w, r)
  125. }
  126. // IsOauthUser - returns
  127. func IsOauthUser(user *models.User) error {
  128. var currentValue, err = fetchPassValue("")
  129. if err != nil {
  130. return err
  131. }
  132. var bCryptErr = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(currentValue))
  133. return bCryptErr
  134. }
  135. // == private methods ==
  136. func addUser(email string) error {
  137. var hasAdmin, err = logic.HasAdmin()
  138. if err != nil {
  139. logger.Log(1, "error checking for existence of admin user during OAuth login for", email, "; user not added")
  140. return err
  141. } // generate random password to adapt to current model
  142. var newPass, fetchErr = fetchPassValue("")
  143. if fetchErr != nil {
  144. return fetchErr
  145. }
  146. var newUser = models.User{
  147. UserName: email,
  148. Password: newPass,
  149. }
  150. if !hasAdmin { // must be first attempt, create an admin
  151. if err = logic.CreateAdmin(&newUser); err != nil {
  152. logger.Log(1, "error creating admin from user,", email, "; user not added")
  153. } else {
  154. logger.Log(1, "admin created from user,", email, "; was first user added")
  155. }
  156. } else { // otherwise add to db as admin..?
  157. // TODO: add ability to add users with preemptive permissions
  158. newUser.IsAdmin = false
  159. if err = logic.CreateUser(&newUser); err != nil {
  160. logger.Log(1, "error creating user,", email, "; user not added")
  161. } else {
  162. logger.Log(0, "user created from ", email)
  163. }
  164. }
  165. return nil
  166. }
  167. func fetchPassValue(newValue string) (string, error) {
  168. type valueHolder struct {
  169. Value string `json:"value" bson:"value"`
  170. }
  171. var b64NewValue = base64.StdEncoding.EncodeToString([]byte(newValue))
  172. var newValueHolder = &valueHolder{
  173. Value: b64NewValue,
  174. }
  175. var data, marshalErr = json.Marshal(newValueHolder)
  176. if marshalErr != nil {
  177. return "", marshalErr
  178. }
  179. var currentValue, err = logic.FetchAuthSecret(auth_key, string(data))
  180. if err != nil {
  181. return "", err
  182. }
  183. var unmarshErr = json.Unmarshal([]byte(currentValue), newValueHolder)
  184. if unmarshErr != nil {
  185. return "", unmarshErr
  186. }
  187. var b64CurrentValue, b64Err = base64.StdEncoding.DecodeString(newValueHolder.Value)
  188. if b64Err != nil {
  189. logger.Log(0, "could not decode pass")
  190. return "", nil
  191. }
  192. return string(b64CurrentValue), nil
  193. }
  194. func getStateAndCode(r *http.Request) (string, string) {
  195. var state, code string
  196. if r.FormValue("state") != "" && r.FormValue("code") != "" {
  197. state = r.FormValue("state")
  198. code = r.FormValue("code")
  199. } else if r.URL.Query().Get("state") != "" && r.URL.Query().Get("code") != "" {
  200. state = r.URL.Query().Get("state")
  201. code = r.URL.Query().Get("code")
  202. }
  203. return state, code
  204. }
  205. func (user *OAuthUser) getUserName() string {
  206. var userName string
  207. if user.Email != "" {
  208. userName = user.Email
  209. } else if user.Login != "" {
  210. userName = user.Login
  211. } else if user.UserPrincipalName != "" {
  212. userName = user.UserPrincipalName
  213. } else if user.Name != "" {
  214. userName = user.Name
  215. }
  216. return userName
  217. }
  218. func isStateCached(state string) bool {
  219. _, err := netcache.Get(state)
  220. return err == nil || strings.Contains(err.Error(), "expired")
  221. }