auth.go 7.2 KB

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