auth.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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/logic/pro/netcache"
  11. "github.com/gravitl/netmaker/models"
  12. "github.com/gravitl/netmaker/servercfg"
  13. "golang.org/x/crypto/bcrypt"
  14. "golang.org/x/oauth2"
  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 currentFrontendURL = servercfg.GetFrontendURL()
  68. if currentFrontendURL == "" {
  69. return ""
  70. }
  71. var authInfo = servercfg.GetAuthProviderInfo()
  72. var serverConn = servercfg.GetAPIHost()
  73. if strings.Contains(serverConn, "localhost") || strings.Contains(serverConn, "127.0.0.1") {
  74. serverConn = "http://" + serverConn
  75. logger.Log(1, "localhost OAuth detected, proceeding with insecure http redirect: (", serverConn, ")")
  76. } else {
  77. serverConn = "https://" + serverConn
  78. logger.Log(1, "external OAuth detected, proceeding with https redirect: ("+serverConn+")")
  79. }
  80. if authInfo[0] == "oidc" {
  81. functions[init_provider].(func(string, string, string, string))(serverConn+"/api/oauth/callback", authInfo[1], authInfo[2], authInfo[3])
  82. return authInfo[0]
  83. }
  84. functions[init_provider].(func(string, string, string))(serverConn+"/api/oauth/callback", authInfo[1], authInfo[2])
  85. return authInfo[0]
  86. }
  87. // Not included in API reference as part of the OAuth process itself.
  88. // HandleAuthCallback - handles oauth callback
  89. func HandleAuthCallback(w http.ResponseWriter, r *http.Request) {
  90. if auth_provider == nil {
  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. 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 || (err != nil && strings.Contains(err.Error(), "expired")) {
  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 newUser, 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 newUser, 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. }