ouath.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. package api
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. "github.com/lejianwen/rustdesk-api/v2/global"
  6. "github.com/lejianwen/rustdesk-api/v2/http/request/api"
  7. "github.com/lejianwen/rustdesk-api/v2/http/response"
  8. apiResp "github.com/lejianwen/rustdesk-api/v2/http/response/api"
  9. "github.com/lejianwen/rustdesk-api/v2/model"
  10. "github.com/lejianwen/rustdesk-api/v2/service"
  11. "github.com/lejianwen/rustdesk-api/v2/utils"
  12. "github.com/nicksnyder/go-i18n/v2/i18n"
  13. )
  14. type Oauth struct {
  15. }
  16. // OidcAuth
  17. // @Tags Oauth
  18. // @Summary OidcAuth
  19. // @Description OidcAuth
  20. // @Accept json
  21. // @Produce json
  22. // @Success 200 {object} apiResp.LoginRes
  23. // @Failure 500 {object} response.ErrorResponse
  24. // @Router /oidc/auth [post]
  25. func (o *Oauth) OidcAuth(c *gin.Context) {
  26. f := &api.OidcAuthRequest{}
  27. err := c.ShouldBindJSON(&f)
  28. if err != nil {
  29. response.Error(c, response.TranslateMsg(c, "ParamsError")+err.Error())
  30. return
  31. }
  32. oauthService := service.AllService.OauthService
  33. err, state, verifier, nonce, url := oauthService.BeginAuth(c, f.Op)
  34. if err != nil {
  35. response.Error(c, response.TranslateMsg(c, err.Error()))
  36. return
  37. }
  38. service.AllService.OauthService.SetOauthCache(state, &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. Verifier: verifier,
  47. Nonce: nonce,
  48. }, 5*60)
  49. //fmt.Println("code url", code, url)
  50. c.JSON(http.StatusOK, gin.H{
  51. "code": state,
  52. "url": url,
  53. })
  54. }
  55. func (o *Oauth) OidcAuthQueryPre(c *gin.Context) (*model.User, *model.UserToken) {
  56. var u *model.User
  57. var ut *model.UserToken
  58. q := &api.OidcAuthQuery{}
  59. // 解析查询参数并处理错误
  60. if err := c.ShouldBindQuery(q); err != nil {
  61. response.Error(c, response.TranslateMsg(c, "ParamsError")+": "+err.Error())
  62. return nil, nil
  63. }
  64. // 获取 OAuth 缓存
  65. v := service.AllService.OauthService.GetOauthCache(q.Code)
  66. if v == nil {
  67. response.Error(c, response.TranslateMsg(c, "OauthExpired"))
  68. return nil, nil
  69. }
  70. // 如果 UserId 为 0,说明还在授权中
  71. if v.UserId == 0 {
  72. c.JSON(http.StatusOK, gin.H{"message": "Authorization in progress, please login and bind"})
  73. return nil, nil
  74. }
  75. // 获取用户信息
  76. u = service.AllService.UserService.InfoById(v.UserId)
  77. if u == nil {
  78. response.Error(c, response.TranslateMsg(c, "UserNotFound"))
  79. return nil, nil
  80. }
  81. // 删除 OAuth 缓存
  82. service.AllService.OauthService.DeleteOauthCache(q.Code)
  83. // 创建登录日志并生成用户令牌
  84. ut = service.AllService.UserService.Login(u, &model.LoginLog{
  85. UserId: u.Id,
  86. Client: v.DeviceType,
  87. DeviceId: v.Id,
  88. Uuid: v.Uuid,
  89. Ip: c.ClientIP(),
  90. Type: model.LoginLogTypeOauth,
  91. Platform: v.DeviceOs,
  92. })
  93. if ut == nil {
  94. response.Error(c, response.TranslateMsg(c, "LoginFailed"))
  95. return nil, nil
  96. }
  97. // 返回用户令牌
  98. return u, ut
  99. }
  100. // OidcAuthQuery
  101. // @Tags Oauth
  102. // @Summary OidcAuthQuery
  103. // @Description OidcAuthQuery
  104. // @Accept json
  105. // @Produce json
  106. // @Success 200 {object} apiResp.LoginRes
  107. // @Failure 500 {object} response.ErrorResponse
  108. // @Router /oidc/auth-query [get]
  109. func (o *Oauth) OidcAuthQuery(c *gin.Context) {
  110. u, ut := o.OidcAuthQueryPre(c)
  111. if u == nil || ut == nil {
  112. return
  113. }
  114. c.JSON(http.StatusOK, apiResp.LoginRes{
  115. AccessToken: ut.Token,
  116. Type: "access_token",
  117. User: *(&apiResp.UserPayload{}).FromUser(u),
  118. })
  119. }
  120. // OauthCallback 回调
  121. // @Tags Oauth
  122. // @Summary OauthCallback
  123. // @Description OauthCallback
  124. // @Accept json
  125. // @Produce json
  126. // @Success 200 {object} apiResp.LoginRes
  127. // @Failure 500 {object} response.ErrorResponse
  128. // @Router /oauth/callback [get]
  129. func (o *Oauth) OauthCallback(c *gin.Context) {
  130. state := c.Query("state")
  131. if state == "" {
  132. c.HTML(http.StatusOK, "oauth_fail.html", gin.H{
  133. "message": "ParamIsEmpty",
  134. "sub_message": "state",
  135. })
  136. return
  137. }
  138. cacheKey := state
  139. oauthService := service.AllService.OauthService
  140. //从缓存中获取
  141. oauthCache := oauthService.GetOauthCache(cacheKey)
  142. if oauthCache == nil {
  143. c.HTML(http.StatusOK, "oauth_fail.html", gin.H{
  144. "message": "OauthExpired",
  145. })
  146. return
  147. }
  148. nonce := oauthCache.Nonce
  149. op := oauthCache.Op
  150. action := oauthCache.Action
  151. verifier := oauthCache.Verifier
  152. var user *model.User
  153. // 获取用户信息
  154. code := c.Query("code")
  155. err, oauthUser := oauthService.Callback(c, code, verifier, op, nonce)
  156. if err != nil {
  157. c.HTML(http.StatusOK, "oauth_fail.html", gin.H{
  158. "message": "OauthFailed",
  159. "sub_message": err.Error(),
  160. })
  161. return
  162. }
  163. userId := oauthCache.UserId
  164. openid := oauthUser.OpenId
  165. if action == service.OauthActionTypeBind {
  166. //fmt.Println("bind", ty, userData)
  167. // 检查此openid是否已经绑定过
  168. utr := oauthService.UserThirdInfo(op, openid)
  169. if utr.UserId > 0 {
  170. c.HTML(http.StatusOK, "oauth_fail.html", gin.H{
  171. "message": "OauthHasBindOtherUser",
  172. })
  173. return
  174. }
  175. //绑定
  176. user = service.AllService.UserService.InfoById(userId)
  177. if user == nil {
  178. c.HTML(http.StatusOK, "oauth_fail.html", gin.H{
  179. "message": "ItemNotFound",
  180. })
  181. return
  182. }
  183. //绑定
  184. err := oauthService.BindOauthUser(userId, oauthUser, op)
  185. if err != nil {
  186. c.HTML(http.StatusOK, "oauth_fail.html", gin.H{
  187. "message": "BindFail",
  188. })
  189. return
  190. }
  191. c.HTML(http.StatusOK, "oauth_success.html", gin.H{
  192. "message": "BindSuccess",
  193. })
  194. return
  195. } else if action == service.OauthActionTypeLogin {
  196. //登录
  197. if userId != 0 {
  198. c.HTML(http.StatusOK, "oauth_fail.html", gin.H{
  199. "message": "OauthHasBeenSuccess",
  200. })
  201. return
  202. }
  203. user = service.AllService.UserService.InfoByOauthId(op, openid)
  204. if user == nil {
  205. oauthConfig := oauthService.InfoByOp(op)
  206. if !*oauthConfig.AutoRegister {
  207. //c.String(http.StatusInternalServerError, "还未绑定用户,请先绑定")
  208. oauthCache.UpdateFromOauthUser(oauthUser)
  209. c.Redirect(http.StatusFound, "/_admin/#/oauth/bind/"+cacheKey)
  210. return
  211. }
  212. //自动注册
  213. err, user = service.AllService.UserService.RegisterByOauth(oauthUser, op)
  214. if err != nil {
  215. c.HTML(http.StatusOK, "oauth_fail.html", gin.H{
  216. "message": err.Error(),
  217. })
  218. return
  219. }
  220. }
  221. oauthCache.UserId = user.Id
  222. oauthService.SetOauthCache(cacheKey, oauthCache, 0)
  223. // 如果是webadmin,登录成功后跳转到webadmin
  224. if oauthCache.DeviceType == model.LoginLogClientWebAdmin {
  225. /*service.AllService.UserService.Login(u, &model.LoginLog{
  226. UserId: u.Id,
  227. Client: "webadmin",
  228. Uuid: "", //must be empty
  229. Ip: c.ClientIP(),
  230. Type: model.LoginLogTypeOauth,
  231. Platform: oauthService.DeviceOs,
  232. })*/
  233. c.Redirect(http.StatusFound, "/_admin/#/")
  234. return
  235. }
  236. c.HTML(http.StatusOK, "oauth_success.html", gin.H{
  237. "message": "OauthSuccess",
  238. })
  239. return
  240. } else {
  241. c.HTML(http.StatusOK, "oauth_fail.html", gin.H{
  242. "message": "ParamsError",
  243. })
  244. return
  245. }
  246. }
  247. type MessageParams struct {
  248. Lang string `json:"lang" form:"lang"`
  249. Title string `json:"title" form:"title"`
  250. Msg string `json:"msg" form:"msg"`
  251. }
  252. func (o *Oauth) Message(c *gin.Context) {
  253. mp := &MessageParams{}
  254. if err := c.ShouldBindQuery(mp); err != nil {
  255. return
  256. }
  257. localizer := global.Localizer(mp.Lang)
  258. res := ""
  259. if mp.Title != "" {
  260. title, err := localizer.LocalizeMessage(&i18n.Message{
  261. ID: mp.Title,
  262. })
  263. if err == nil {
  264. res = utils.StringConcat(";title='", title, "';")
  265. }
  266. }
  267. if mp.Msg != "" {
  268. msg, err := localizer.LocalizeMessage(&i18n.Message{
  269. ID: mp.Msg,
  270. })
  271. if err == nil {
  272. res = utils.StringConcat(res, "msg = '", msg, "';")
  273. }
  274. }
  275. //返回js内容
  276. c.Header("Content-Type", "application/javascript")
  277. c.String(http.StatusOK, res)
  278. }