oauth2.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. package oauth2
  2. import (
  3. "encoding/json"
  4. "log"
  5. "net/http"
  6. "strconv"
  7. "time"
  8. "golang.org/x/oauth2"
  9. auth "imuslab.com/arozos/mod/auth"
  10. syncdb "imuslab.com/arozos/mod/auth/oauth2/syncdb"
  11. reg "imuslab.com/arozos/mod/auth/register"
  12. db "imuslab.com/arozos/mod/database"
  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. coredb *db.Database
  22. config *Config
  23. }
  24. type Config struct {
  25. Enabled bool `json:"enabled"`
  26. IDP string `json:"idp"`
  27. RedirectURL string `json:"redirect_url"`
  28. ClientID string `json:"client_id"`
  29. ClientSecret string `json:"client_secret"`
  30. DefaultUserGroup string `json:"default_user_group"`
  31. }
  32. //NewOauthHandler xxx
  33. func NewOauthHandler(authAgent *auth.AuthAgent, register *reg.RegisterHandler, coreDb *db.Database) *OauthHandler {
  34. err := coreDb.NewTable("oauth")
  35. if err != nil {
  36. log.Println("Failed to create oauth database. Terminating.")
  37. panic(err)
  38. }
  39. NewlyCreatedOauthHandler := OauthHandler{
  40. googleOauthConfig: &oauth2.Config{
  41. RedirectURL: readSingleConfig("redirecturl", coreDb) + "/system/auth/oauth/authorize",
  42. ClientID: readSingleConfig("clientid", coreDb),
  43. ClientSecret: readSingleConfig("clientsecret", coreDb),
  44. Scopes: getScope(coreDb),
  45. Endpoint: getEndpoint(coreDb),
  46. },
  47. DefaultUserGroup: readSingleConfig("defaultusergroup", coreDb),
  48. ag: authAgent,
  49. syncDb: syncdb.NewSyncDB(),
  50. reg: register,
  51. coredb: coreDb,
  52. }
  53. return &NewlyCreatedOauthHandler
  54. }
  55. //HandleOauthLogin xxx
  56. func (oh *OauthHandler) HandleLogin(w http.ResponseWriter, r *http.Request) {
  57. //add cookies
  58. redirect, e := r.URL.Query()["redirect"]
  59. uuid := ""
  60. if !e || len(redirect[0]) < 1 {
  61. uuid = oh.syncDb.Store("/")
  62. } else {
  63. uuid = oh.syncDb.Store(redirect[0])
  64. }
  65. oh.addCookie(w, "uuid_login", uuid, 30*time.Minute)
  66. //handle redirect
  67. url := oh.googleOauthConfig.AuthCodeURL(uuid)
  68. http.Redirect(w, r, url, http.StatusTemporaryRedirect)
  69. }
  70. //OauthAuthorize xxx
  71. func (oh *OauthHandler) HandleAuthorize(w http.ResponseWriter, r *http.Request) {
  72. //read the uuid(aka the state parameter)
  73. uuid, err := r.Cookie("uuid_login")
  74. if err != nil {
  75. sendTextResponse(w, "Invalid redirect URI.")
  76. return
  77. }
  78. state := r.FormValue("state")
  79. if state != uuid.Value {
  80. sendTextResponse(w, "Invalid oauth state.")
  81. return
  82. }
  83. code := r.FormValue("code")
  84. token, err := oh.googleOauthConfig.Exchange(oauth2.NoContext, code)
  85. if err != nil {
  86. sendTextResponse(w, "Code exchange failed.")
  87. return
  88. }
  89. username, err := getUserInfo(token.AccessToken, oh.coredb)
  90. if err != nil {
  91. sendTextResponse(w, "Failed to obtain user info.")
  92. return
  93. }
  94. if !oh.ag.UserExists(username) {
  95. //register user if not already exists
  96. //random pwd to prevent ppl bypassing the OAuth handler
  97. if oh.reg.AllowRegistry {
  98. http.Redirect(w, r, "/public/register/register.system?user="+username, 302)
  99. } else {
  100. sendHTMLResponse(w, "You are not allowed to register in this system.&nbsp;<a href=\"/\">Back</a>")
  101. }
  102. } else {
  103. log.Println(username + " logged in via OAuth.")
  104. oh.ag.LoginUserByRequest(w, r, username, true)
  105. //clear the cooke
  106. oh.addCookie(w, "uuid_login", "-invaild-", -1)
  107. //read the value from db and delete it from db
  108. url := oh.syncDb.Read(uuid.Value)
  109. oh.syncDb.Delete(uuid.Value)
  110. //redirect to the desired page
  111. http.Redirect(w, r, url, 302)
  112. }
  113. }
  114. func (oh *OauthHandler) CheckOAuth(w http.ResponseWriter, r *http.Request) {
  115. enabled := oh.readSingleConfig("enabled")
  116. if enabled == "" {
  117. enabled = "false"
  118. }
  119. sendJSONResponse(w, enabled)
  120. }
  121. //https://golangcode.com/add-a-http-cookie/
  122. func (oh *OauthHandler) addCookie(w http.ResponseWriter, name, value string, ttl time.Duration) {
  123. expire := time.Now().Add(ttl)
  124. cookie := http.Cookie{
  125. Name: name,
  126. Value: value,
  127. Expires: expire,
  128. }
  129. http.SetCookie(w, &cookie)
  130. }
  131. func (oh *OauthHandler) ReadConfig(w http.ResponseWriter, r *http.Request) {
  132. enabled, _ := strconv.ParseBool(oh.readSingleConfig("enabled"))
  133. idp := oh.readSingleConfig("idp")
  134. redirecturl := oh.readSingleConfig("redirecturl")
  135. clientid := oh.readSingleConfig("clientid")
  136. clientsecret := oh.readSingleConfig("clientsecret")
  137. defaultusergroup := oh.readSingleConfig("defaultusergroup")
  138. config, err := json.Marshal(Config{
  139. Enabled: enabled,
  140. IDP: idp,
  141. RedirectURL: redirecturl,
  142. ClientID: clientid,
  143. ClientSecret: clientsecret,
  144. DefaultUserGroup: defaultusergroup,
  145. })
  146. if err != nil {
  147. empty, _ := json.Marshal(Config{})
  148. sendJSONResponse(w, string(empty))
  149. }
  150. sendJSONResponse(w, string(config))
  151. }
  152. func (oh *OauthHandler) WriteConfig(w http.ResponseWriter, r *http.Request) {
  153. enabled, err := mv(r, "enabled", true)
  154. if err != nil {
  155. sendErrorResponse(w, "enabled field can't be empty'")
  156. return
  157. }
  158. oh.coredb.Write("oauth", "enabled", enabled)
  159. if enabled != "true" {
  160. return
  161. }
  162. idp, err := mv(r, "idp", true)
  163. if err != nil {
  164. sendErrorResponse(w, "idp field can't be empty'")
  165. return
  166. }
  167. redirecturl, err := mv(r, "redirecturl", true)
  168. if err != nil {
  169. sendErrorResponse(w, "redirecturl field can't be empty'")
  170. return
  171. }
  172. clientid, err := mv(r, "clientid", true)
  173. if err != nil {
  174. sendErrorResponse(w, "clientid field can't be empty'")
  175. }
  176. clientsecret, err := mv(r, "clientsecret", true)
  177. if err != nil {
  178. sendErrorResponse(w, "clientsecret field can't be empty'")
  179. return
  180. }
  181. defaultusergroup, err := mv(r, "defaultusergroup", true)
  182. if err != nil {
  183. sendErrorResponse(w, "defaultusergroup field can't be empty'")
  184. return
  185. }
  186. oh.coredb.Write("oauth", "idp", idp)
  187. oh.coredb.Write("oauth", "redirecturl", redirecturl)
  188. oh.coredb.Write("oauth", "clientid", clientid)
  189. oh.coredb.Write("oauth", "clientsecret", clientsecret)
  190. oh.coredb.Write("oauth", "defaultusergroup", defaultusergroup)
  191. //update the information inside the oauth class
  192. oh.googleOauthConfig = &oauth2.Config{
  193. RedirectURL: oh.readSingleConfig("redirecturl") + "/system/auth/oauth/authorize",
  194. ClientID: oh.readSingleConfig("clientid"),
  195. ClientSecret: oh.readSingleConfig("clientsecret"),
  196. Scopes: getScope(oh.coredb),
  197. Endpoint: getEndpoint(oh.coredb),
  198. }
  199. sendOK(w)
  200. }
  201. func (oh *OauthHandler) readSingleConfig(key string) string {
  202. var value string
  203. err := oh.coredb.Read("oauth", key, &value)
  204. if err != nil {
  205. value = ""
  206. }
  207. return value
  208. }
  209. func readSingleConfig(key string, coredb *db.Database) string {
  210. var value string
  211. err := coredb.Read("oauth", key, &value)
  212. if err != nil {
  213. value = ""
  214. }
  215. return value
  216. }