github.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. package auth
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "strings"
  10. "github.com/gravitl/netmaker/database"
  11. "github.com/gravitl/netmaker/logger"
  12. "github.com/gravitl/netmaker/logic"
  13. "github.com/gravitl/netmaker/models"
  14. proLogic "github.com/gravitl/netmaker/pro/logic"
  15. "github.com/gravitl/netmaker/servercfg"
  16. "golang.org/x/oauth2"
  17. "golang.org/x/oauth2/github"
  18. )
  19. var github_functions = map[string]interface{}{
  20. init_provider: initGithub,
  21. get_user_info: getGithubUserInfo,
  22. handle_callback: handleGithubCallback,
  23. handle_login: handleGithubLogin,
  24. verify_user: verifyGithubUser,
  25. }
  26. // == handle github authentication here ==
  27. func initGithub(redirectURL string, clientID string, clientSecret string) {
  28. auth_provider = &oauth2.Config{
  29. RedirectURL: redirectURL,
  30. ClientID: clientID,
  31. ClientSecret: clientSecret,
  32. Scopes: []string{"read:user", "user:email"},
  33. Endpoint: github.Endpoint,
  34. }
  35. }
  36. func handleGithubLogin(w http.ResponseWriter, r *http.Request) {
  37. appName := r.Header.Get("X-Application-Name")
  38. if appName == "" {
  39. appName = logic.NetmakerDesktopApp
  40. }
  41. var oauth_state_string = logic.RandomString(user_signin_length)
  42. if auth_provider == nil {
  43. handleOauthNotConfigured(w)
  44. return
  45. }
  46. if err := logic.SetState(appName, oauth_state_string); err != nil {
  47. handleOauthNotConfigured(w)
  48. return
  49. }
  50. var url = auth_provider.AuthCodeURL(oauth_state_string)
  51. http.Redirect(w, r, url, http.StatusTemporaryRedirect)
  52. }
  53. func handleGithubCallback(w http.ResponseWriter, r *http.Request) {
  54. var rState, rCode = getStateAndCode(r)
  55. state, err := logic.GetState(rState)
  56. if err != nil {
  57. handleOauthNotValid(w)
  58. return
  59. }
  60. content, err := getGithubUserInfo(rState, rCode)
  61. if err != nil {
  62. logger.Log(1, "error when getting user info from github:", err.Error())
  63. if strings.Contains(err.Error(), "invalid oauth state") || strings.Contains(err.Error(), "failed to fetch user email from SSO state") {
  64. handleOauthNotValid(w)
  65. return
  66. }
  67. handleOauthNotConfigured(w)
  68. return
  69. }
  70. var inviteExists bool
  71. // check if invite exists for User
  72. in, err := logic.GetUserInvite(content.Email)
  73. if err == nil {
  74. inviteExists = true
  75. }
  76. // check if user approval is already pending
  77. if !inviteExists && logic.IsPendingUser(content.Email) {
  78. handleOauthUserSignUpApprovalPending(w)
  79. return
  80. }
  81. // if user exists with provider ID, convert them into email ID
  82. user, err := logic.GetUser(content.Login)
  83. if err == nil {
  84. // if user exists, then ensure user's auth type is
  85. // oauth before proceeding.
  86. if user.AuthType == models.BasicAuth {
  87. logger.Log(0, "invalid auth type: basic_auth")
  88. handleAuthTypeMismatch(w)
  89. return
  90. }
  91. // checks if user exists with email
  92. _, err := logic.GetUser(content.Email)
  93. if err != nil {
  94. user.UserName = content.Email
  95. user.ExternalIdentityProviderID = content.Login
  96. database.DeleteRecord(database.USERS_TABLE_NAME, content.Login)
  97. d, _ := json.Marshal(user)
  98. database.Insert(user.UserName, string(d), database.USERS_TABLE_NAME)
  99. }
  100. }
  101. _, err = logic.GetUser(content.Email)
  102. if err != nil {
  103. if database.IsEmptyRecord(err) { // user must not exist, so try to make one
  104. if inviteExists {
  105. // create user
  106. user, err := proLogic.PrepareOauthUserFromInvite(in)
  107. if err != nil {
  108. logic.ReturnErrorResponse(w, r, logic.FormatError(err, "internal"))
  109. return
  110. }
  111. user.ExternalIdentityProviderID = string(content.ID)
  112. if err = logic.CreateUser(&user); err != nil {
  113. handleSomethingWentWrong(w)
  114. return
  115. }
  116. logic.DeleteUserInvite(content.Email)
  117. logic.DeletePendingUser(content.Email)
  118. } else {
  119. if !isEmailAllowed(content.Email) {
  120. handleOauthUserNotAllowedToSignUp(w)
  121. return
  122. }
  123. err = logic.InsertPendingUser(&models.User{
  124. UserName: content.Email,
  125. ExternalIdentityProviderID: string(content.ID),
  126. AuthType: models.OAuth,
  127. })
  128. if err != nil {
  129. handleSomethingWentWrong(w)
  130. return
  131. }
  132. handleFirstTimeOauthUserSignUp(w)
  133. return
  134. }
  135. } else {
  136. handleSomethingWentWrong(w)
  137. return
  138. }
  139. }
  140. user, err = logic.GetUser(content.Email)
  141. if err != nil {
  142. handleOauthUserNotFound(w)
  143. return
  144. }
  145. if user.AccountDisabled {
  146. handleUserAccountDisabled(w)
  147. return
  148. }
  149. userRole, err := logic.GetRole(user.PlatformRoleID)
  150. if err != nil {
  151. handleSomethingWentWrong(w)
  152. return
  153. }
  154. if userRole.DenyDashboardAccess {
  155. handleOauthUserNotAllowed(w)
  156. return
  157. }
  158. var newPass, fetchErr = logic.FetchPassValue("")
  159. if fetchErr != nil {
  160. return
  161. }
  162. // send a netmaker jwt token
  163. var authRequest = models.UserAuthParams{
  164. UserName: content.Email,
  165. Password: newPass,
  166. }
  167. var jwt, jwtErr = logic.VerifyAuthRequest(authRequest, state.AppName)
  168. if jwtErr != nil {
  169. logger.Log(1, "could not parse jwt for user", authRequest.UserName)
  170. return
  171. }
  172. logic.LogEvent(&models.Event{
  173. Action: models.Login,
  174. Source: models.Subject{
  175. ID: user.UserName,
  176. Name: user.UserName,
  177. Type: models.UserSub,
  178. },
  179. TriggeredBy: user.UserName,
  180. Target: models.Subject{
  181. ID: models.DashboardSub.String(),
  182. Name: models.DashboardSub.String(),
  183. Type: models.DashboardSub,
  184. Info: user,
  185. },
  186. Origin: models.Dashboard,
  187. })
  188. logger.Log(1, "completed github OAuth sigin in for", content.Email)
  189. http.Redirect(w, r, servercfg.GetFrontendURL()+"/login?login="+jwt+"&user="+content.Email, http.StatusPermanentRedirect)
  190. }
  191. func getGithubUserInfo(state, code string) (*OAuthUser, error) {
  192. oauth_state_string, isValid := logic.IsStateValid(state)
  193. if (!isValid || state != oauth_state_string) && !isStateCached(state) {
  194. return nil, fmt.Errorf("invalid oauth state")
  195. }
  196. var token, err = auth_provider.Exchange(context.Background(), code, oauth2.SetAuthURLParam("prompt", "login"))
  197. if err != nil {
  198. return nil, fmt.Errorf("code exchange failed: %s", err.Error())
  199. }
  200. if !token.Valid() {
  201. return nil, fmt.Errorf("GitHub code exchange yielded invalid token")
  202. }
  203. var data []byte
  204. data, err = json.Marshal(token)
  205. if err != nil {
  206. return nil, fmt.Errorf("failed to convert token to json: %s", err.Error())
  207. }
  208. var httpClient = &http.Client{}
  209. var httpReq, reqErr = http.NewRequest("GET", "https://api.github.com/user", nil)
  210. if reqErr != nil {
  211. return nil, fmt.Errorf("failed to create request to GitHub")
  212. }
  213. httpReq.Header.Set("Authorization", "token "+token.AccessToken)
  214. response, err := httpClient.Do(httpReq)
  215. if err != nil {
  216. return nil, fmt.Errorf("failed getting user info: %s", err.Error())
  217. }
  218. defer response.Body.Close()
  219. contents, err := io.ReadAll(response.Body)
  220. if err != nil {
  221. return nil, fmt.Errorf("failed reading response body: %s", err.Error())
  222. }
  223. var userInfo = &OAuthUser{}
  224. if err = json.Unmarshal(contents, userInfo); err != nil {
  225. return nil, fmt.Errorf("failed parsing email from response data: %s", err.Error())
  226. }
  227. userInfo.AccessToken = string(data)
  228. if userInfo.Email == "" {
  229. // if user's email is not made public, get the info from the github emails api
  230. logger.Log(2, "fetching user email from github api")
  231. userInfo.Email, err = getGithubEmailsInfo(token.AccessToken)
  232. if err != nil {
  233. logger.Log(0, "failed to fetch user's email from github: ", err.Error())
  234. }
  235. }
  236. if userInfo.Email == "" {
  237. err = errors.New("failed to fetch user email from SSO state")
  238. return userInfo, err
  239. }
  240. return userInfo, nil
  241. }
  242. func verifyGithubUser(token *oauth2.Token) bool {
  243. return token.Valid()
  244. }
  245. func getGithubEmailsInfo(accessToken string) (string, error) {
  246. var httpClient = &http.Client{}
  247. var httpReq, reqErr = http.NewRequest("GET", "https://api.github.com/user/emails", nil)
  248. if reqErr != nil {
  249. return "", fmt.Errorf("failed to create request to GitHub")
  250. }
  251. httpReq.Header.Add("Accept", "application/vnd.github.v3+json")
  252. httpReq.Header.Set("Authorization", "token "+accessToken)
  253. response, err := httpClient.Do(httpReq)
  254. if err != nil {
  255. return "", fmt.Errorf("failed getting user info: %s", err.Error())
  256. }
  257. defer response.Body.Close()
  258. contents, err := io.ReadAll(response.Body)
  259. if err != nil {
  260. return "", fmt.Errorf("failed reading response body: %s", err.Error())
  261. }
  262. emailsInfo := []interface{}{}
  263. err = json.Unmarshal(contents, &emailsInfo)
  264. if err != nil {
  265. return "", err
  266. }
  267. for _, info := range emailsInfo {
  268. emailInfoMap := info.(map[string]interface{})
  269. if emailInfoMap["primary"].(bool) {
  270. return emailInfoMap["email"].(string), nil
  271. }
  272. }
  273. return "", errors.New("email not found")
  274. }