ouath.go 7.6 KB

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