oauth2.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. package oauth2
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "log"
  6. "net/http"
  7. "time"
  8. "golang.org/x/oauth2"
  9. "golang.org/x/oauth2/google"
  10. auth "imuslab.com/arozos/mod/auth"
  11. syncdb "imuslab.com/arozos/mod/auth/oauth2/syncdb"
  12. reg "imuslab.com/arozos/mod/auth/register"
  13. )
  14. type OauthHandler struct {
  15. googleOauthConfig *oauth2.Config
  16. syncDb *syncdb.SyncDB
  17. oauthStateString string
  18. DefaultUserGroup string
  19. ag *auth.AuthAgent
  20. reg *reg.RegisterHandler
  21. }
  22. type GoogleField struct {
  23. ID string `json:"id"`
  24. Email string `json:"email"`
  25. VerifiedEmail bool `json:"verified_email"`
  26. Name string `json:"name"`
  27. GivenName string `json:"given_name"`
  28. FamilyName string `json:"family_name"`
  29. Picture string `json:"picture"`
  30. Locale string `json:"locale"`
  31. }
  32. //NewOauthHandler xxx
  33. func NewOauthHandler(authAgent *auth.AuthAgent, register *reg.RegisterHandler) *OauthHandler {
  34. NewlyCreatedOauthHandler := OauthHandler{
  35. googleOauthConfig: &oauth2.Config{
  36. RedirectURL: "http://localhost:8080/system/auth/oauth/authorize",
  37. ClientID: "682431817920-nkmfn7m6uq0qbdo00hr2944m6r3hj8ua.apps.googleusercontent.com",
  38. ClientSecret: "Obdlr2S5n8rj_qwsPLhToD3h",
  39. Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile",
  40. "https://www.googleapis.com/auth/userinfo.email"},
  41. Endpoint: google.Endpoint,
  42. },
  43. // Some random string, random for each request
  44. DefaultUserGroup: "default",
  45. ag: authAgent,
  46. syncDb: syncdb.NewSyncDB(),
  47. reg: register,
  48. }
  49. return &NewlyCreatedOauthHandler
  50. }
  51. //HandleOauthLogin xxx
  52. func (oh *OauthHandler) HandleLogin(w http.ResponseWriter, r *http.Request) {
  53. //add cookies
  54. redirect, e := r.URL.Query()["redirect"]
  55. uuid := ""
  56. if !e || len(redirect[0]) < 1 {
  57. uuid = oh.syncDb.Store("/")
  58. } else {
  59. uuid = oh.syncDb.Store(redirect[0])
  60. }
  61. oh.addCookie(w, "uuid_login", uuid, 30*time.Minute)
  62. //handle redirect
  63. url := oh.googleOauthConfig.AuthCodeURL(uuid)
  64. http.Redirect(w, r, url, http.StatusTemporaryRedirect)
  65. }
  66. //OauthAuthorize xxx
  67. func (oh *OauthHandler) HandleAuthorize(w http.ResponseWriter, r *http.Request) {
  68. //read the uuid(aka the state parameter)
  69. uuid, err := r.Cookie("uuid_login")
  70. if err != nil {
  71. w.Header().Set("Content-Type", "text/html; charset=UTF-8")
  72. w.Write([]byte("Invalid redirect URI."))
  73. }
  74. state := r.FormValue("state")
  75. if state != uuid.Value {
  76. w.Header().Set("Content-Type", "text/html; charset=UTF-8")
  77. w.Write([]byte("Invalid oauth state."))
  78. return
  79. }
  80. code := r.FormValue("code")
  81. token, err := oh.googleOauthConfig.Exchange(oauth2.NoContext, code)
  82. if err != nil {
  83. w.Header().Set("Content-Type", "text/html; charset=UTF-8")
  84. w.Write([]byte("Code exchange failed."))
  85. return
  86. }
  87. response, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)
  88. defer response.Body.Close()
  89. contents, err := ioutil.ReadAll(response.Body)
  90. var data GoogleField
  91. json.Unmarshal([]byte(contents), &data)
  92. if !oh.ag.UserExists(data.Email) {
  93. //register user if not already exists
  94. //random pwd to prevent ppl bypassing the OAuth handler
  95. if oh.reg.AllowRegistry {
  96. http.Redirect(w, r, "/public/register/register.system?user="+data.Email, 302)
  97. } else {
  98. w.Header().Set("Content-Type", "text/html; charset=UTF-8")
  99. w.Write([]byte("You are not allowed to register in this system.&nbsp;<a href=\"/\">Back</a>"))
  100. }
  101. } else {
  102. log.Println(data.Email + " logged in via OAuth.")
  103. oh.ag.LoginUserByRequest(w, r, data.Email, true)
  104. //clear the cooke
  105. oh.addCookie(w, "uuid_login", "-invaild-", -1)
  106. //read the value from db and delete it from db
  107. url := oh.syncDb.Read(uuid.Value)
  108. oh.syncDb.Delete(uuid.Value)
  109. //redirect to the desired page
  110. http.Redirect(w, r, url, 302)
  111. }
  112. }
  113. func (oh *OauthHandler) CheckOAuth(w http.ResponseWriter, r *http.Request) {
  114. sendJSONResponse(w, "true")
  115. }
  116. //https://golangcode.com/add-a-http-cookie/
  117. func (oh *OauthHandler) addCookie(w http.ResponseWriter, name, value string, ttl time.Duration) {
  118. expire := time.Now().Add(ttl)
  119. cookie := http.Cookie{
  120. Name: name,
  121. Value: value,
  122. Expires: expire,
  123. }
  124. http.SetCookie(w, &cookie)
  125. }