google.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package auth
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "github.com/gravitl/netmaker/logic"
  8. "github.com/gravitl/netmaker/models"
  9. "github.com/gravitl/netmaker/servercfg"
  10. "golang.org/x/oauth2"
  11. "golang.org/x/oauth2/google"
  12. )
  13. var google_functions = map[string]interface{}{
  14. init_provider: initGoogle,
  15. get_user_info: getUserInfo,
  16. handle_callback: handleGoogleCallback,
  17. handle_login: handleGoogleLogin,
  18. verify_user: verifyGoogleUser,
  19. }
  20. // == handle google authentication here ==
  21. func initGoogle(redirectURL string, clientID string, clientSecret string) {
  22. auth_provider = &oauth2.Config{
  23. RedirectURL: redirectURL,
  24. ClientID: clientID,
  25. ClientSecret: clientSecret,
  26. Scopes: []string{"https://www.googleapis.com/auth/userinfo.email"},
  27. Endpoint: google.Endpoint,
  28. }
  29. }
  30. func handleGoogleLogin(w http.ResponseWriter, r *http.Request) {
  31. oauth_state_string = logic.RandomString(16)
  32. if auth_provider == nil && servercfg.GetFrontendURL() != "" {
  33. http.Redirect(w, r, servercfg.GetFrontendURL()+"?oauth=callback-error", http.StatusTemporaryRedirect)
  34. } else if auth_provider == nil {
  35. fmt.Fprintf(w, "%s", []byte("no frontend URL was provided and an OAuth login was attempted\nplease reconfigure server to use OAuth or use basic credentials"))
  36. return
  37. }
  38. var url = auth_provider.AuthCodeURL(oauth_state_string)
  39. http.Redirect(w, r, url, http.StatusTemporaryRedirect)
  40. }
  41. func handleGoogleCallback(w http.ResponseWriter, r *http.Request) {
  42. var content, err = getUserInfo(r.FormValue("state"), r.FormValue("code"))
  43. if err != nil {
  44. fmt.Println(err.Error())
  45. http.Redirect(w, r, servercfg.GetFrontendURL()+"?oauth=callback-error", http.StatusTemporaryRedirect)
  46. return
  47. }
  48. _, err = logic.GetUser(content.Email)
  49. if err != nil { // user must not exists, so try to make one
  50. if err = addUser(content.Email); err != nil {
  51. return
  52. }
  53. }
  54. var newPass, fetchErr = fetchPassValue("")
  55. if fetchErr != nil {
  56. return
  57. }
  58. // send a netmaker jwt token
  59. var authRequest = models.UserAuthParams{
  60. UserName: content.Email,
  61. Password: newPass,
  62. }
  63. var jwt, jwtErr = logic.VerifyAuthRequest(authRequest)
  64. if jwtErr != nil {
  65. logic.Log("could not parse jwt for user "+authRequest.UserName, 1)
  66. return
  67. }
  68. logic.Log("completed google oauth sigin in for "+content.Email, 0)
  69. http.Redirect(w, r, servercfg.GetFrontendURL()+"?login="+jwt+"&email="+content.Email, http.StatusPermanentRedirect)
  70. }
  71. func getUserInfo(state string, code string) (*OauthUser, error) {
  72. if state != oauth_state_string {
  73. return nil, fmt.Errorf("invalid oauth state")
  74. }
  75. var token, err = auth_provider.Exchange(oauth2.NoContext, code)
  76. if err != nil {
  77. return nil, fmt.Errorf("code exchange failed: %s", err.Error())
  78. }
  79. var data []byte
  80. data, err = json.Marshal(token)
  81. if err != nil {
  82. return nil, fmt.Errorf("failed to convert token to json: %s", err.Error())
  83. }
  84. response, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)
  85. if err != nil {
  86. return nil, fmt.Errorf("failed getting user info: %s", err.Error())
  87. }
  88. defer response.Body.Close()
  89. contents, err := ioutil.ReadAll(response.Body)
  90. if err != nil {
  91. return nil, fmt.Errorf("failed reading response body: %s", err.Error())
  92. }
  93. var userInfo = &OauthUser{}
  94. if err = json.Unmarshal(contents, userInfo); err != nil {
  95. return nil, fmt.Errorf("failed parsing email from response data: %s", err.Error())
  96. }
  97. userInfo.AccessToken = string(data)
  98. return userInfo, nil
  99. }
  100. func verifyGoogleUser(token *oauth2.Token) bool {
  101. return token.Valid()
  102. }