auth.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. handleOauthNotConfigured(w)
  93. return
  94. }
  95. var functions = getCurrentAuthFunctions()
  96. if functions == nil {
  97. return
  98. }
  99. state, _ := getStateAndCode(r)
  100. _, err := netcache.Get(state) // if in netcache proceeed with node registration login
  101. if err == nil || len(state) == node_signin_length || errors.Is(err, netcache.ErrExpired) {
  102. logger.Log(0, "proceeding with node SSO callback")
  103. HandleNodeSSOCallback(w, r)
  104. } else { // handle normal login
  105. functions[handle_callback].(func(http.ResponseWriter, *http.Request))(w, r)
  106. }
  107. }
  108. // swagger:route GET /api/oauth/login nodes HandleAuthLogin
  109. //
  110. // Handles OAuth login.
  111. //
  112. // Schemes: https
  113. //
  114. // Security:
  115. // oauth
  116. func HandleAuthLogin(w http.ResponseWriter, r *http.Request) {
  117. if auth_provider == nil {
  118. var referer = r.Header.Get("referer")
  119. if referer != "" {
  120. http.Redirect(w, r, referer+"login?oauth=callback-error", http.StatusTemporaryRedirect)
  121. return
  122. }
  123. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  124. _, _ = fmt.Fprintln(w, oauthNotConfigured)
  125. return
  126. }
  127. var functions = getCurrentAuthFunctions()
  128. if functions == nil {
  129. return
  130. }
  131. functions[handle_login].(func(http.ResponseWriter, *http.Request))(w, r)
  132. }
  133. // IsOauthUser - returns
  134. func IsOauthUser(user *models.User) error {
  135. var currentValue, err = fetchPassValue("")
  136. if err != nil {
  137. return err
  138. }
  139. var bCryptErr = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(currentValue))
  140. return bCryptErr
  141. }
  142. // == private methods ==
  143. func addUser(email string) error {
  144. var hasAdmin, err = logic.HasAdmin()
  145. if err != nil {
  146. logger.Log(1, "error checking for existence of admin user during OAuth login for", email, "; user not added")
  147. return err
  148. } // generate random password to adapt to current model
  149. var newPass, fetchErr = fetchPassValue("")
  150. if fetchErr != nil {
  151. return fetchErr
  152. }
  153. var newUser = models.User{
  154. UserName: email,
  155. Password: newPass,
  156. }
  157. if !hasAdmin { // must be first attempt, create an admin
  158. if err = logic.CreateAdmin(&newUser); err != nil {
  159. logger.Log(1, "error creating admin from user,", email, "; user not added")
  160. } else {
  161. logger.Log(1, "admin created from user,", email, "; was first user added")
  162. }
  163. } else { // otherwise add to db as admin..?
  164. // TODO: add ability to add users with preemptive permissions
  165. newUser.IsAdmin = false
  166. if err = logic.CreateUser(&newUser); err != nil {
  167. logger.Log(1, "error creating user,", email, "; user not added")
  168. } else {
  169. logger.Log(0, "user created from ", email)
  170. }
  171. }
  172. return nil
  173. }
  174. func fetchPassValue(newValue string) (string, error) {
  175. type valueHolder struct {
  176. Value string `json:"value" bson:"value"`
  177. }
  178. var b64NewValue = base64.StdEncoding.EncodeToString([]byte(newValue))
  179. var newValueHolder = &valueHolder{
  180. Value: b64NewValue,
  181. }
  182. var data, marshalErr = json.Marshal(newValueHolder)
  183. if marshalErr != nil {
  184. return "", marshalErr
  185. }
  186. var currentValue, err = logic.FetchAuthSecret(auth_key, string(data))
  187. if err != nil {
  188. return "", err
  189. }
  190. var unmarshErr = json.Unmarshal([]byte(currentValue), newValueHolder)
  191. if unmarshErr != nil {
  192. return "", unmarshErr
  193. }
  194. var b64CurrentValue, b64Err = base64.StdEncoding.DecodeString(newValueHolder.Value)
  195. if b64Err != nil {
  196. logger.Log(0, "could not decode pass")
  197. return "", nil
  198. }
  199. return string(b64CurrentValue), nil
  200. }
  201. func getStateAndCode(r *http.Request) (string, string) {
  202. var state, code string
  203. if r.FormValue("state") != "" && r.FormValue("code") != "" {
  204. state = r.FormValue("state")
  205. code = r.FormValue("code")
  206. } else if r.URL.Query().Get("state") != "" && r.URL.Query().Get("code") != "" {
  207. state = r.URL.Query().Get("state")
  208. code = r.URL.Query().Get("code")
  209. }
  210. return state, code
  211. }
  212. func (user *OAuthUser) getUserName() string {
  213. var userName string
  214. if user.Email != "" {
  215. userName = user.Email
  216. } else if user.Login != "" {
  217. userName = user.Login
  218. } else if user.UserPrincipalName != "" {
  219. userName = user.UserPrincipalName
  220. } else if user.Name != "" {
  221. userName = user.Name
  222. }
  223. return userName
  224. }
  225. func isStateCached(state string) bool {
  226. _, err := netcache.Get(state)
  227. return err == nil || strings.Contains(err.Error(), "expired")
  228. }