ouath.go 6.6 KB

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