ouath.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. package api
  2. import (
  3. "Gwen/global"
  4. "Gwen/http/request/api"
  5. "Gwen/http/response"
  6. apiResp "Gwen/http/response/api"
  7. "Gwen/model"
  8. "Gwen/service"
  9. "github.com/gin-gonic/gin"
  10. "net/http"
  11. )
  12. type Oauth struct {
  13. }
  14. // OidcAuth
  15. // @Tags Oauth
  16. // @Summary OidcAuth
  17. // @Description OidcAuth
  18. // @Accept json
  19. // @Produce json
  20. // @Success 200 {object} apiResp.LoginRes
  21. // @Failure 500 {object} response.ErrorResponse
  22. // @Router /oidc/auth [post]
  23. func (o *Oauth) OidcAuth(c *gin.Context) {
  24. f := &api.OidcAuthRequest{}
  25. err := c.ShouldBindJSON(&f)
  26. if err != nil {
  27. response.Error(c, response.TranslateMsg(c, "ParamsError")+err.Error())
  28. return
  29. }
  30. oauthService := service.AllService.OauthService
  31. var code string
  32. var url string
  33. err, code, url = oauthService.BeginAuth(f.Op)
  34. if err != nil {
  35. response.Error(c, response.TranslateMsg(c, err.Error()))
  36. return
  37. }
  38. service.AllService.OauthService.SetOauthCache(code, &service.OauthCacheItem{
  39. Action: service.OauthActionTypeLogin,
  40. Id: f.Id,
  41. Op: f.Op,
  42. Uuid: f.Uuid,
  43. DeviceName: f.DeviceInfo.Name,
  44. DeviceOs: f.DeviceInfo.Os,
  45. DeviceType: f.DeviceInfo.Type,
  46. }, 5*60)
  47. //fmt.Println("code url", code, url)
  48. c.JSON(http.StatusOK, gin.H{
  49. "code": code,
  50. "url": url,
  51. })
  52. }
  53. func (o *Oauth) OidcAuthQueryPre(c *gin.Context) (*model.User, *model.UserToken) {
  54. var u *model.User
  55. var ut *model.UserToken
  56. q := &api.OidcAuthQuery{}
  57. // 解析查询参数并处理错误
  58. if err := c.ShouldBindQuery(q); err != nil {
  59. response.Error(c, response.TranslateMsg(c, "ParamsError")+": "+err.Error())
  60. return nil, nil
  61. }
  62. // 获取 OAuth 缓存
  63. v := service.AllService.OauthService.GetOauthCache(q.Code)
  64. if v == nil {
  65. response.Error(c, response.TranslateMsg(c, "OauthExpired"))
  66. return nil, nil
  67. }
  68. // 如果 UserId 为 0,说明还在授权中
  69. if v.UserId == 0 {
  70. c.JSON(http.StatusOK, gin.H{"message": "Authorization in progress, please login and bind"})
  71. return nil, nil
  72. }
  73. // 获取用户信息
  74. u = service.AllService.UserService.InfoById(v.UserId)
  75. if u == nil {
  76. response.Error(c, response.TranslateMsg(c, "UserNotFound"))
  77. return nil, nil
  78. }
  79. // 删除 OAuth 缓存
  80. service.AllService.OauthService.DeleteOauthCache(q.Code)
  81. // 创建登录日志并生成用户令牌
  82. ut = service.AllService.UserService.Login(u, &model.LoginLog{
  83. UserId: u.Id,
  84. Client: v.DeviceType,
  85. Uuid: v.Uuid,
  86. Ip: c.ClientIP(),
  87. Type: model.LoginLogTypeOauth,
  88. Platform: v.DeviceOs,
  89. })
  90. if ut == nil {
  91. response.Error(c, response.TranslateMsg(c, "LoginFailed"))
  92. return nil, nil
  93. }
  94. // 返回用户令牌
  95. return u, ut
  96. }
  97. // OidcAuthQuery
  98. // @Tags Oauth
  99. // @Summary OidcAuthQuery
  100. // @Description OidcAuthQuery
  101. // @Accept json
  102. // @Produce json
  103. // @Success 200 {object} apiResp.LoginRes
  104. // @Failure 500 {object} response.ErrorResponse
  105. // @Router /oidc/auth-query [get]
  106. func (o *Oauth) OidcAuthQuery(c *gin.Context) {
  107. u, ut := o.OidcAuthQueryPre(c)
  108. if u == nil || ut == nil {
  109. return
  110. }
  111. c.JSON(http.StatusOK, apiResp.LoginRes{
  112. AccessToken: ut.Token,
  113. Type: "access_token",
  114. User: *(&apiResp.UserPayload{}).FromUser(u),
  115. })
  116. }
  117. // OauthCallback 回调
  118. // @Tags Oauth
  119. // @Summary OauthCallback
  120. // @Description OauthCallback
  121. // @Accept json
  122. // @Produce json
  123. // @Success 200 {object} apiResp.LoginRes
  124. // @Failure 500 {object} response.ErrorResponse
  125. // @Router /oauth/callback [get]
  126. func (o *Oauth) OauthCallback(c *gin.Context) {
  127. state := c.Query("state")
  128. if state == "" {
  129. c.String(http.StatusInternalServerError, response.TranslateParamMsg(c, "ParamIsEmpty", "state"))
  130. return
  131. }
  132. cacheKey := state
  133. oauthService := service.AllService.OauthService
  134. //从缓存中获取
  135. oauthCache := oauthService.GetOauthCache(cacheKey)
  136. if oauthCache == nil {
  137. c.String(http.StatusInternalServerError, response.TranslateMsg(c, "OauthExpired"))
  138. return
  139. }
  140. op := oauthCache.Op
  141. action := oauthCache.Action
  142. var user *model.User
  143. // 获取用户信息
  144. code := c.Query("code")
  145. err, oauthUser := oauthService.Callback(code, op)
  146. if err != nil {
  147. c.String(http.StatusInternalServerError, response.TranslateMsg(c, "OauthFailed")+response.TranslateMsg(c, err.Error()))
  148. return
  149. }
  150. userId := oauthCache.UserId
  151. openid := oauthUser.OpenId
  152. if action == service.OauthActionTypeBind {
  153. //fmt.Println("bind", ty, userData)
  154. // 检查此openid是否已经绑定过
  155. utr := oauthService.UserThirdInfo(op, openid)
  156. if utr.UserId > 0 {
  157. c.String(http.StatusInternalServerError, response.TranslateMsg(c, "OauthHasBindOtherUser"))
  158. return
  159. }
  160. //绑定
  161. user = service.AllService.UserService.InfoById(userId)
  162. if user == nil {
  163. c.String(http.StatusInternalServerError, response.TranslateMsg(c, "ItemNotFound"))
  164. return
  165. }
  166. //绑定
  167. err := oauthService.BindOauthUser(userId, oauthUser, op)
  168. if err != nil {
  169. c.String(http.StatusInternalServerError, response.TranslateMsg(c, "BindFail"))
  170. return
  171. }
  172. c.String(http.StatusOK, response.TranslateMsg(c, "BindSuccess"))
  173. return
  174. } else if action == service.OauthActionTypeLogin {
  175. //登录
  176. if userId != 0 {
  177. c.String(http.StatusInternalServerError, response.TranslateMsg(c, "OauthHasBeenSuccess"))
  178. return
  179. }
  180. user = service.AllService.UserService.InfoByOauthId(op, openid)
  181. if user == nil {
  182. oauthConfig := oauthService.InfoByOp(op)
  183. if !*oauthConfig.AutoRegister {
  184. //c.String(http.StatusInternalServerError, "还未绑定用户,请先绑定")
  185. oauthCache.UpdateFromOauthUser(oauthUser)
  186. url := global.Config.Rustdesk.ApiServer + "/_admin/#/oauth/bind/" + cacheKey
  187. c.Redirect(http.StatusFound, url)
  188. return
  189. }
  190. //自动注册
  191. user = service.AllService.UserService.RegisterByOauth(oauthUser, op)
  192. if user.Id == 0 {
  193. c.String(http.StatusInternalServerError, response.TranslateMsg(c, "OauthRegisterFailed"))
  194. return
  195. }
  196. }
  197. oauthCache.UserId = user.Id
  198. oauthService.SetOauthCache(cacheKey, oauthCache, 0)
  199. // 如果是webadmin,登录成功后跳转到webadmin
  200. if oauthCache.DeviceType == "webadmin" {
  201. /*service.AllService.UserService.Login(u, &model.LoginLog{
  202. UserId: u.Id,
  203. Client: "webadmin",
  204. Uuid: "", //must be empty
  205. Ip: c.ClientIP(),
  206. Type: model.LoginLogTypeOauth,
  207. Platform: oauthService.DeviceOs,
  208. })*/
  209. url := global.Config.Rustdesk.ApiServer + "/_admin/#/"
  210. c.Redirect(http.StatusFound, url)
  211. return
  212. }
  213. c.String(http.StatusOK, response.TranslateMsg(c, "OauthSuccess"))
  214. return
  215. } else {
  216. c.String(http.StatusInternalServerError, response.TranslateMsg(c, "ParamsError"))
  217. return
  218. }
  219. }