user.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "one-api/common"
  8. "one-api/dto"
  9. "one-api/logger"
  10. "one-api/model"
  11. "one-api/setting"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "one-api/constant"
  16. "github.com/gin-contrib/sessions"
  17. "github.com/gin-gonic/gin"
  18. )
  19. type LoginRequest struct {
  20. Username string `json:"username"`
  21. Password string `json:"password"`
  22. }
  23. func Login(c *gin.Context) {
  24. if !common.PasswordLoginEnabled {
  25. c.JSON(http.StatusOK, gin.H{
  26. "message": "管理员关闭了密码登录",
  27. "success": false,
  28. })
  29. return
  30. }
  31. var loginRequest LoginRequest
  32. err := json.NewDecoder(c.Request.Body).Decode(&loginRequest)
  33. if err != nil {
  34. c.JSON(http.StatusOK, gin.H{
  35. "message": "无效的参数",
  36. "success": false,
  37. })
  38. return
  39. }
  40. username := loginRequest.Username
  41. password := loginRequest.Password
  42. if username == "" || password == "" {
  43. c.JSON(http.StatusOK, gin.H{
  44. "message": "无效的参数",
  45. "success": false,
  46. })
  47. return
  48. }
  49. user := model.User{
  50. Username: username,
  51. Password: password,
  52. }
  53. err = user.ValidateAndFill()
  54. if err != nil {
  55. c.JSON(http.StatusOK, gin.H{
  56. "message": err.Error(),
  57. "success": false,
  58. })
  59. return
  60. }
  61. // 检查是否启用2FA
  62. if model.IsTwoFAEnabled(user.Id) {
  63. // 设置pending session,等待2FA验证
  64. session := sessions.Default(c)
  65. session.Set("pending_username", user.Username)
  66. session.Set("pending_user_id", user.Id)
  67. err := session.Save()
  68. if err != nil {
  69. c.JSON(http.StatusOK, gin.H{
  70. "message": "无法保存会话信息,请重试",
  71. "success": false,
  72. })
  73. return
  74. }
  75. c.JSON(http.StatusOK, gin.H{
  76. "message": "请输入两步验证码",
  77. "success": true,
  78. "data": map[string]interface{}{
  79. "require_2fa": true,
  80. },
  81. })
  82. return
  83. }
  84. setupLogin(&user, c)
  85. }
  86. // setup session & cookies and then return user info
  87. func setupLogin(user *model.User, c *gin.Context) {
  88. session := sessions.Default(c)
  89. session.Set("id", user.Id)
  90. session.Set("username", user.Username)
  91. session.Set("role", user.Role)
  92. session.Set("status", user.Status)
  93. session.Set("group", user.Group)
  94. err := session.Save()
  95. if err != nil {
  96. c.JSON(http.StatusOK, gin.H{
  97. "message": "无法保存会话信息,请重试",
  98. "success": false,
  99. })
  100. return
  101. }
  102. cleanUser := model.User{
  103. Id: user.Id,
  104. Username: user.Username,
  105. DisplayName: user.DisplayName,
  106. Role: user.Role,
  107. Status: user.Status,
  108. Group: user.Group,
  109. }
  110. c.JSON(http.StatusOK, gin.H{
  111. "message": "",
  112. "success": true,
  113. "data": cleanUser,
  114. })
  115. }
  116. func Logout(c *gin.Context) {
  117. session := sessions.Default(c)
  118. session.Clear()
  119. err := session.Save()
  120. if err != nil {
  121. c.JSON(http.StatusOK, gin.H{
  122. "message": err.Error(),
  123. "success": false,
  124. })
  125. return
  126. }
  127. c.JSON(http.StatusOK, gin.H{
  128. "message": "",
  129. "success": true,
  130. })
  131. }
  132. func Register(c *gin.Context) {
  133. if !common.RegisterEnabled {
  134. c.JSON(http.StatusOK, gin.H{
  135. "message": "管理员关闭了新用户注册",
  136. "success": false,
  137. })
  138. return
  139. }
  140. if !common.PasswordRegisterEnabled {
  141. c.JSON(http.StatusOK, gin.H{
  142. "message": "管理员关闭了通过密码进行注册,请使用第三方账户验证的形式进行注册",
  143. "success": false,
  144. })
  145. return
  146. }
  147. var user model.User
  148. err := json.NewDecoder(c.Request.Body).Decode(&user)
  149. if err != nil {
  150. c.JSON(http.StatusOK, gin.H{
  151. "success": false,
  152. "message": "无效的参数",
  153. })
  154. return
  155. }
  156. if err := common.Validate.Struct(&user); err != nil {
  157. c.JSON(http.StatusOK, gin.H{
  158. "success": false,
  159. "message": "输入不合法 " + err.Error(),
  160. })
  161. return
  162. }
  163. if common.EmailVerificationEnabled {
  164. if user.Email == "" || user.VerificationCode == "" {
  165. c.JSON(http.StatusOK, gin.H{
  166. "success": false,
  167. "message": "管理员开启了邮箱验证,请输入邮箱地址和验证码",
  168. })
  169. return
  170. }
  171. if !common.VerifyCodeWithKey(user.Email, user.VerificationCode, common.EmailVerificationPurpose) {
  172. c.JSON(http.StatusOK, gin.H{
  173. "success": false,
  174. "message": "验证码错误或已过期",
  175. })
  176. return
  177. }
  178. }
  179. exist, err := model.CheckUserExistOrDeleted(user.Username, user.Email)
  180. if err != nil {
  181. c.JSON(http.StatusOK, gin.H{
  182. "success": false,
  183. "message": "数据库错误,请稍后重试",
  184. })
  185. common.SysLog(fmt.Sprintf("CheckUserExistOrDeleted error: %v", err))
  186. return
  187. }
  188. if exist {
  189. c.JSON(http.StatusOK, gin.H{
  190. "success": false,
  191. "message": "用户名已存在,或已注销",
  192. })
  193. return
  194. }
  195. affCode := user.AffCode // this code is the inviter's code, not the user's own code
  196. inviterId, _ := model.GetUserIdByAffCode(affCode)
  197. cleanUser := model.User{
  198. Username: user.Username,
  199. Password: user.Password,
  200. DisplayName: user.Username,
  201. InviterId: inviterId,
  202. Role: common.RoleCommonUser, // 明确设置角色为普通用户
  203. }
  204. if common.EmailVerificationEnabled {
  205. cleanUser.Email = user.Email
  206. }
  207. if err := cleanUser.Insert(inviterId); err != nil {
  208. common.ApiError(c, err)
  209. return
  210. }
  211. // 获取插入后的用户ID
  212. var insertedUser model.User
  213. if err := model.DB.Where("username = ?", cleanUser.Username).First(&insertedUser).Error; err != nil {
  214. c.JSON(http.StatusOK, gin.H{
  215. "success": false,
  216. "message": "用户注册失败或用户ID获取失败",
  217. })
  218. return
  219. }
  220. // 生成默认令牌
  221. if constant.GenerateDefaultToken {
  222. key, err := common.GenerateKey()
  223. if err != nil {
  224. c.JSON(http.StatusOK, gin.H{
  225. "success": false,
  226. "message": "生成默认令牌失败",
  227. })
  228. common.SysLog("failed to generate token key: " + err.Error())
  229. return
  230. }
  231. // 生成默认令牌
  232. token := model.Token{
  233. UserId: insertedUser.Id, // 使用插入后的用户ID
  234. Name: cleanUser.Username + "的初始令牌",
  235. Key: key,
  236. CreatedTime: common.GetTimestamp(),
  237. AccessedTime: common.GetTimestamp(),
  238. ExpiredTime: -1, // 永不过期
  239. RemainQuota: 500000, // 示例额度
  240. UnlimitedQuota: true,
  241. ModelLimitsEnabled: false,
  242. }
  243. if setting.DefaultUseAutoGroup {
  244. token.Group = "auto"
  245. }
  246. if err := token.Insert(); err != nil {
  247. c.JSON(http.StatusOK, gin.H{
  248. "success": false,
  249. "message": "创建默认令牌失败",
  250. })
  251. return
  252. }
  253. }
  254. c.JSON(http.StatusOK, gin.H{
  255. "success": true,
  256. "message": "",
  257. })
  258. return
  259. }
  260. func GetAllUsers(c *gin.Context) {
  261. pageInfo := common.GetPageQuery(c)
  262. users, total, err := model.GetAllUsers(pageInfo)
  263. if err != nil {
  264. common.ApiError(c, err)
  265. return
  266. }
  267. pageInfo.SetTotal(int(total))
  268. pageInfo.SetItems(users)
  269. common.ApiSuccess(c, pageInfo)
  270. return
  271. }
  272. func SearchUsers(c *gin.Context) {
  273. keyword := c.Query("keyword")
  274. group := c.Query("group")
  275. pageInfo := common.GetPageQuery(c)
  276. users, total, err := model.SearchUsers(keyword, group, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
  277. if err != nil {
  278. common.ApiError(c, err)
  279. return
  280. }
  281. pageInfo.SetTotal(int(total))
  282. pageInfo.SetItems(users)
  283. common.ApiSuccess(c, pageInfo)
  284. return
  285. }
  286. func GetUser(c *gin.Context) {
  287. id, err := strconv.Atoi(c.Param("id"))
  288. if err != nil {
  289. common.ApiError(c, err)
  290. return
  291. }
  292. user, err := model.GetUserById(id, false)
  293. if err != nil {
  294. common.ApiError(c, err)
  295. return
  296. }
  297. myRole := c.GetInt("role")
  298. if myRole <= user.Role && myRole != common.RoleRootUser {
  299. c.JSON(http.StatusOK, gin.H{
  300. "success": false,
  301. "message": "无权获取同级或更高等级用户的信息",
  302. })
  303. return
  304. }
  305. c.JSON(http.StatusOK, gin.H{
  306. "success": true,
  307. "message": "",
  308. "data": user,
  309. })
  310. return
  311. }
  312. func GenerateAccessToken(c *gin.Context) {
  313. id := c.GetInt("id")
  314. user, err := model.GetUserById(id, true)
  315. if err != nil {
  316. common.ApiError(c, err)
  317. return
  318. }
  319. // get rand int 28-32
  320. randI := common.GetRandomInt(4)
  321. key, err := common.GenerateRandomKey(29 + randI)
  322. if err != nil {
  323. c.JSON(http.StatusOK, gin.H{
  324. "success": false,
  325. "message": "生成失败",
  326. })
  327. common.SysLog("failed to generate key: " + err.Error())
  328. return
  329. }
  330. user.SetAccessToken(key)
  331. if model.DB.Where("access_token = ?", user.AccessToken).First(user).RowsAffected != 0 {
  332. c.JSON(http.StatusOK, gin.H{
  333. "success": false,
  334. "message": "请重试,系统生成的 UUID 竟然重复了!",
  335. })
  336. return
  337. }
  338. if err := user.Update(false); err != nil {
  339. common.ApiError(c, err)
  340. return
  341. }
  342. c.JSON(http.StatusOK, gin.H{
  343. "success": true,
  344. "message": "",
  345. "data": user.AccessToken,
  346. })
  347. return
  348. }
  349. type TransferAffQuotaRequest struct {
  350. Quota int `json:"quota" binding:"required"`
  351. }
  352. func TransferAffQuota(c *gin.Context) {
  353. id := c.GetInt("id")
  354. user, err := model.GetUserById(id, true)
  355. if err != nil {
  356. common.ApiError(c, err)
  357. return
  358. }
  359. tran := TransferAffQuotaRequest{}
  360. if err := c.ShouldBindJSON(&tran); err != nil {
  361. common.ApiError(c, err)
  362. return
  363. }
  364. err = user.TransferAffQuotaToQuota(tran.Quota)
  365. if err != nil {
  366. c.JSON(http.StatusOK, gin.H{
  367. "success": false,
  368. "message": "划转失败 " + err.Error(),
  369. })
  370. return
  371. }
  372. c.JSON(http.StatusOK, gin.H{
  373. "success": true,
  374. "message": "划转成功",
  375. })
  376. }
  377. func GetAffCode(c *gin.Context) {
  378. id := c.GetInt("id")
  379. user, err := model.GetUserById(id, true)
  380. if err != nil {
  381. common.ApiError(c, err)
  382. return
  383. }
  384. if user.AffCode == "" {
  385. user.AffCode = common.GetRandomString(4)
  386. if err := user.Update(false); err != nil {
  387. c.JSON(http.StatusOK, gin.H{
  388. "success": false,
  389. "message": err.Error(),
  390. })
  391. return
  392. }
  393. }
  394. c.JSON(http.StatusOK, gin.H{
  395. "success": true,
  396. "message": "",
  397. "data": user.AffCode,
  398. })
  399. return
  400. }
  401. func GetSelf(c *gin.Context) {
  402. id := c.GetInt("id")
  403. userRole := c.GetInt("role")
  404. user, err := model.GetUserById(id, false)
  405. if err != nil {
  406. common.ApiError(c, err)
  407. return
  408. }
  409. // Hide admin remarks: set to empty to trigger omitempty tag, ensuring the remark field is not included in JSON returned to regular users
  410. user.Remark = ""
  411. // 计算用户权限信息
  412. permissions := calculateUserPermissions(userRole)
  413. // 获取用户设置并提取sidebar_modules
  414. userSetting := user.GetSetting()
  415. // 构建响应数据,包含用户信息和权限
  416. responseData := map[string]interface{}{
  417. "id": user.Id,
  418. "username": user.Username,
  419. "display_name": user.DisplayName,
  420. "role": user.Role,
  421. "status": user.Status,
  422. "email": user.Email,
  423. "group": user.Group,
  424. "quota": user.Quota,
  425. "used_quota": user.UsedQuota,
  426. "request_count": user.RequestCount,
  427. "aff_code": user.AffCode,
  428. "aff_count": user.AffCount,
  429. "aff_quota": user.AffQuota,
  430. "aff_history_quota": user.AffHistoryQuota,
  431. "inviter_id": user.InviterId,
  432. "linux_do_id": user.LinuxDOId,
  433. "setting": user.Setting,
  434. "stripe_customer": user.StripeCustomer,
  435. "sidebar_modules": userSetting.SidebarModules, // 正确提取sidebar_modules字段
  436. "permissions": permissions, // 新增权限字段
  437. }
  438. c.JSON(http.StatusOK, gin.H{
  439. "success": true,
  440. "message": "",
  441. "data": responseData,
  442. })
  443. return
  444. }
  445. // 计算用户权限的辅助函数
  446. func calculateUserPermissions(userRole int) map[string]interface{} {
  447. permissions := map[string]interface{}{}
  448. // 根据用户角色计算权限
  449. if userRole == common.RoleRootUser {
  450. // 超级管理员不需要边栏设置功能
  451. permissions["sidebar_settings"] = false
  452. permissions["sidebar_modules"] = map[string]interface{}{}
  453. } else if userRole == common.RoleAdminUser {
  454. // 管理员可以设置边栏,但不包含系统设置功能
  455. permissions["sidebar_settings"] = true
  456. permissions["sidebar_modules"] = map[string]interface{}{
  457. "admin": map[string]interface{}{
  458. "setting": false, // 管理员不能访问系统设置
  459. },
  460. }
  461. } else {
  462. // 普通用户只能设置个人功能,不包含管理员区域
  463. permissions["sidebar_settings"] = true
  464. permissions["sidebar_modules"] = map[string]interface{}{
  465. "admin": false, // 普通用户不能访问管理员区域
  466. }
  467. }
  468. return permissions
  469. }
  470. // 根据用户角色生成默认的边栏配置
  471. func generateDefaultSidebarConfig(userRole int) string {
  472. defaultConfig := map[string]interface{}{}
  473. // 聊天区域 - 所有用户都可以访问
  474. defaultConfig["chat"] = map[string]interface{}{
  475. "enabled": true,
  476. "playground": true,
  477. "chat": true,
  478. }
  479. // 控制台区域 - 所有用户都可以访问
  480. defaultConfig["console"] = map[string]interface{}{
  481. "enabled": true,
  482. "detail": true,
  483. "token": true,
  484. "log": true,
  485. "midjourney": true,
  486. "task": true,
  487. }
  488. // 个人中心区域 - 所有用户都可以访问
  489. defaultConfig["personal"] = map[string]interface{}{
  490. "enabled": true,
  491. "topup": true,
  492. "personal": true,
  493. }
  494. // 管理员区域 - 根据角色决定
  495. if userRole == common.RoleAdminUser {
  496. // 管理员可以访问管理员区域,但不能访问系统设置
  497. defaultConfig["admin"] = map[string]interface{}{
  498. "enabled": true,
  499. "channel": true,
  500. "models": true,
  501. "redemption": true,
  502. "user": true,
  503. "setting": false, // 管理员不能访问系统设置
  504. }
  505. } else if userRole == common.RoleRootUser {
  506. // 超级管理员可以访问所有功能
  507. defaultConfig["admin"] = map[string]interface{}{
  508. "enabled": true,
  509. "channel": true,
  510. "models": true,
  511. "redemption": true,
  512. "user": true,
  513. "setting": true,
  514. }
  515. }
  516. // 普通用户不包含admin区域
  517. // 转换为JSON字符串
  518. configBytes, err := json.Marshal(defaultConfig)
  519. if err != nil {
  520. common.SysLog("生成默认边栏配置失败: " + err.Error())
  521. return ""
  522. }
  523. return string(configBytes)
  524. }
  525. func GetUserModels(c *gin.Context) {
  526. id, err := strconv.Atoi(c.Param("id"))
  527. if err != nil {
  528. id = c.GetInt("id")
  529. }
  530. user, err := model.GetUserCache(id)
  531. if err != nil {
  532. common.ApiError(c, err)
  533. return
  534. }
  535. groups := setting.GetUserUsableGroups(user.Group)
  536. var models []string
  537. for group := range groups {
  538. for _, g := range model.GetGroupEnabledModels(group) {
  539. if !common.StringsContains(models, g) {
  540. models = append(models, g)
  541. }
  542. }
  543. }
  544. c.JSON(http.StatusOK, gin.H{
  545. "success": true,
  546. "message": "",
  547. "data": models,
  548. })
  549. return
  550. }
  551. func UpdateUser(c *gin.Context) {
  552. var updatedUser model.User
  553. err := json.NewDecoder(c.Request.Body).Decode(&updatedUser)
  554. if err != nil || updatedUser.Id == 0 {
  555. c.JSON(http.StatusOK, gin.H{
  556. "success": false,
  557. "message": "无效的参数",
  558. })
  559. return
  560. }
  561. if updatedUser.Password == "" {
  562. updatedUser.Password = "$I_LOVE_U" // make Validator happy :)
  563. }
  564. if err := common.Validate.Struct(&updatedUser); err != nil {
  565. c.JSON(http.StatusOK, gin.H{
  566. "success": false,
  567. "message": "输入不合法 " + err.Error(),
  568. })
  569. return
  570. }
  571. originUser, err := model.GetUserById(updatedUser.Id, false)
  572. if err != nil {
  573. common.ApiError(c, err)
  574. return
  575. }
  576. myRole := c.GetInt("role")
  577. if myRole <= originUser.Role && myRole != common.RoleRootUser {
  578. c.JSON(http.StatusOK, gin.H{
  579. "success": false,
  580. "message": "无权更新同权限等级或更高权限等级的用户信息",
  581. })
  582. return
  583. }
  584. if myRole <= updatedUser.Role && myRole != common.RoleRootUser {
  585. c.JSON(http.StatusOK, gin.H{
  586. "success": false,
  587. "message": "无权将其他用户权限等级提升到大于等于自己的权限等级",
  588. })
  589. return
  590. }
  591. if updatedUser.Password == "$I_LOVE_U" {
  592. updatedUser.Password = "" // rollback to what it should be
  593. }
  594. updatePassword := updatedUser.Password != ""
  595. if err := updatedUser.Edit(updatePassword); err != nil {
  596. common.ApiError(c, err)
  597. return
  598. }
  599. if originUser.Quota != updatedUser.Quota {
  600. model.RecordLog(originUser.Id, model.LogTypeManage, fmt.Sprintf("管理员将用户额度从 %s修改为 %s", logger.LogQuota(originUser.Quota), logger.LogQuota(updatedUser.Quota)))
  601. }
  602. c.JSON(http.StatusOK, gin.H{
  603. "success": true,
  604. "message": "",
  605. })
  606. return
  607. }
  608. func UpdateSelf(c *gin.Context) {
  609. var requestData map[string]interface{}
  610. err := json.NewDecoder(c.Request.Body).Decode(&requestData)
  611. if err != nil {
  612. c.JSON(http.StatusOK, gin.H{
  613. "success": false,
  614. "message": "无效的参数",
  615. })
  616. return
  617. }
  618. // 检查是否是sidebar_modules更新请求
  619. if sidebarModules, exists := requestData["sidebar_modules"]; exists {
  620. userId := c.GetInt("id")
  621. user, err := model.GetUserById(userId, false)
  622. if err != nil {
  623. common.ApiError(c, err)
  624. return
  625. }
  626. // 获取当前用户设置
  627. currentSetting := user.GetSetting()
  628. // 更新sidebar_modules字段
  629. if sidebarModulesStr, ok := sidebarModules.(string); ok {
  630. currentSetting.SidebarModules = sidebarModulesStr
  631. }
  632. // 保存更新后的设置
  633. user.SetSetting(currentSetting)
  634. if err := user.Update(false); err != nil {
  635. c.JSON(http.StatusOK, gin.H{
  636. "success": false,
  637. "message": "更新设置失败: " + err.Error(),
  638. })
  639. return
  640. }
  641. c.JSON(http.StatusOK, gin.H{
  642. "success": true,
  643. "message": "设置更新成功",
  644. })
  645. return
  646. }
  647. // 原有的用户信息更新逻辑
  648. var user model.User
  649. requestDataBytes, err := json.Marshal(requestData)
  650. if err != nil {
  651. c.JSON(http.StatusOK, gin.H{
  652. "success": false,
  653. "message": "无效的参数",
  654. })
  655. return
  656. }
  657. err = json.Unmarshal(requestDataBytes, &user)
  658. if err != nil {
  659. c.JSON(http.StatusOK, gin.H{
  660. "success": false,
  661. "message": "无效的参数",
  662. })
  663. return
  664. }
  665. if user.Password == "" {
  666. user.Password = "$I_LOVE_U" // make Validator happy :)
  667. }
  668. if err := common.Validate.Struct(&user); err != nil {
  669. c.JSON(http.StatusOK, gin.H{
  670. "success": false,
  671. "message": "输入不合法 " + err.Error(),
  672. })
  673. return
  674. }
  675. cleanUser := model.User{
  676. Id: c.GetInt("id"),
  677. Username: user.Username,
  678. Password: user.Password,
  679. DisplayName: user.DisplayName,
  680. }
  681. if user.Password == "$I_LOVE_U" {
  682. user.Password = "" // rollback to what it should be
  683. cleanUser.Password = ""
  684. }
  685. updatePassword, err := checkUpdatePassword(user.OriginalPassword, user.Password, cleanUser.Id)
  686. if err != nil {
  687. common.ApiError(c, err)
  688. return
  689. }
  690. if err := cleanUser.Update(updatePassword); err != nil {
  691. common.ApiError(c, err)
  692. return
  693. }
  694. c.JSON(http.StatusOK, gin.H{
  695. "success": true,
  696. "message": "",
  697. })
  698. return
  699. }
  700. func checkUpdatePassword(originalPassword string, newPassword string, userId int) (updatePassword bool, err error) {
  701. var currentUser *model.User
  702. currentUser, err = model.GetUserById(userId, true)
  703. if err != nil {
  704. return
  705. }
  706. if !common.ValidatePasswordAndHash(originalPassword, currentUser.Password) {
  707. err = fmt.Errorf("原密码错误")
  708. return
  709. }
  710. if newPassword == "" {
  711. return
  712. }
  713. updatePassword = true
  714. return
  715. }
  716. func DeleteUser(c *gin.Context) {
  717. id, err := strconv.Atoi(c.Param("id"))
  718. if err != nil {
  719. common.ApiError(c, err)
  720. return
  721. }
  722. originUser, err := model.GetUserById(id, false)
  723. if err != nil {
  724. common.ApiError(c, err)
  725. return
  726. }
  727. myRole := c.GetInt("role")
  728. if myRole <= originUser.Role {
  729. c.JSON(http.StatusOK, gin.H{
  730. "success": false,
  731. "message": "无权删除同权限等级或更高权限等级的用户",
  732. })
  733. return
  734. }
  735. err = model.HardDeleteUserById(id)
  736. if err != nil {
  737. c.JSON(http.StatusOK, gin.H{
  738. "success": true,
  739. "message": "",
  740. })
  741. return
  742. }
  743. }
  744. func DeleteSelf(c *gin.Context) {
  745. id := c.GetInt("id")
  746. user, _ := model.GetUserById(id, false)
  747. if user.Role == common.RoleRootUser {
  748. c.JSON(http.StatusOK, gin.H{
  749. "success": false,
  750. "message": "不能删除超级管理员账户",
  751. })
  752. return
  753. }
  754. err := model.DeleteUserById(id)
  755. if err != nil {
  756. common.ApiError(c, err)
  757. return
  758. }
  759. c.JSON(http.StatusOK, gin.H{
  760. "success": true,
  761. "message": "",
  762. })
  763. return
  764. }
  765. func CreateUser(c *gin.Context) {
  766. var user model.User
  767. err := json.NewDecoder(c.Request.Body).Decode(&user)
  768. user.Username = strings.TrimSpace(user.Username)
  769. if err != nil || user.Username == "" || user.Password == "" {
  770. c.JSON(http.StatusOK, gin.H{
  771. "success": false,
  772. "message": "无效的参数",
  773. })
  774. return
  775. }
  776. if err := common.Validate.Struct(&user); err != nil {
  777. c.JSON(http.StatusOK, gin.H{
  778. "success": false,
  779. "message": "输入不合法 " + err.Error(),
  780. })
  781. return
  782. }
  783. if user.DisplayName == "" {
  784. user.DisplayName = user.Username
  785. }
  786. myRole := c.GetInt("role")
  787. if user.Role >= myRole {
  788. c.JSON(http.StatusOK, gin.H{
  789. "success": false,
  790. "message": "无法创建权限大于等于自己的用户",
  791. })
  792. return
  793. }
  794. // Even for admin users, we cannot fully trust them!
  795. cleanUser := model.User{
  796. Username: user.Username,
  797. Password: user.Password,
  798. DisplayName: user.DisplayName,
  799. Role: user.Role, // 保持管理员设置的角色
  800. }
  801. if err := cleanUser.Insert(0); err != nil {
  802. common.ApiError(c, err)
  803. return
  804. }
  805. c.JSON(http.StatusOK, gin.H{
  806. "success": true,
  807. "message": "",
  808. })
  809. return
  810. }
  811. type ManageRequest struct {
  812. Id int `json:"id"`
  813. Action string `json:"action"`
  814. }
  815. // ManageUser Only admin user can do this
  816. func ManageUser(c *gin.Context) {
  817. var req ManageRequest
  818. err := json.NewDecoder(c.Request.Body).Decode(&req)
  819. if err != nil {
  820. c.JSON(http.StatusOK, gin.H{
  821. "success": false,
  822. "message": "无效的参数",
  823. })
  824. return
  825. }
  826. user := model.User{
  827. Id: req.Id,
  828. }
  829. // Fill attributes
  830. model.DB.Unscoped().Where(&user).First(&user)
  831. if user.Id == 0 {
  832. c.JSON(http.StatusOK, gin.H{
  833. "success": false,
  834. "message": "用户不存在",
  835. })
  836. return
  837. }
  838. myRole := c.GetInt("role")
  839. if myRole <= user.Role && myRole != common.RoleRootUser {
  840. c.JSON(http.StatusOK, gin.H{
  841. "success": false,
  842. "message": "无权更新同权限等级或更高权限等级的用户信息",
  843. })
  844. return
  845. }
  846. switch req.Action {
  847. case "disable":
  848. user.Status = common.UserStatusDisabled
  849. if user.Role == common.RoleRootUser {
  850. c.JSON(http.StatusOK, gin.H{
  851. "success": false,
  852. "message": "无法禁用超级管理员用户",
  853. })
  854. return
  855. }
  856. case "enable":
  857. user.Status = common.UserStatusEnabled
  858. case "delete":
  859. if user.Role == common.RoleRootUser {
  860. c.JSON(http.StatusOK, gin.H{
  861. "success": false,
  862. "message": "无法删除超级管理员用户",
  863. })
  864. return
  865. }
  866. if err := user.Delete(); err != nil {
  867. c.JSON(http.StatusOK, gin.H{
  868. "success": false,
  869. "message": err.Error(),
  870. })
  871. return
  872. }
  873. case "promote":
  874. if myRole != common.RoleRootUser {
  875. c.JSON(http.StatusOK, gin.H{
  876. "success": false,
  877. "message": "普通管理员用户无法提升其他用户为管理员",
  878. })
  879. return
  880. }
  881. if user.Role >= common.RoleAdminUser {
  882. c.JSON(http.StatusOK, gin.H{
  883. "success": false,
  884. "message": "该用户已经是管理员",
  885. })
  886. return
  887. }
  888. user.Role = common.RoleAdminUser
  889. case "demote":
  890. if user.Role == common.RoleRootUser {
  891. c.JSON(http.StatusOK, gin.H{
  892. "success": false,
  893. "message": "无法降级超级管理员用户",
  894. })
  895. return
  896. }
  897. if user.Role == common.RoleCommonUser {
  898. c.JSON(http.StatusOK, gin.H{
  899. "success": false,
  900. "message": "该用户已经是普通用户",
  901. })
  902. return
  903. }
  904. user.Role = common.RoleCommonUser
  905. }
  906. if err := user.Update(false); err != nil {
  907. common.ApiError(c, err)
  908. return
  909. }
  910. clearUser := model.User{
  911. Role: user.Role,
  912. Status: user.Status,
  913. }
  914. c.JSON(http.StatusOK, gin.H{
  915. "success": true,
  916. "message": "",
  917. "data": clearUser,
  918. })
  919. return
  920. }
  921. func EmailBind(c *gin.Context) {
  922. email := c.Query("email")
  923. code := c.Query("code")
  924. if !common.VerifyCodeWithKey(email, code, common.EmailVerificationPurpose) {
  925. c.JSON(http.StatusOK, gin.H{
  926. "success": false,
  927. "message": "验证码错误或已过期",
  928. })
  929. return
  930. }
  931. session := sessions.Default(c)
  932. id := session.Get("id")
  933. user := model.User{
  934. Id: id.(int),
  935. }
  936. err := user.FillUserById()
  937. if err != nil {
  938. common.ApiError(c, err)
  939. return
  940. }
  941. user.Email = email
  942. // no need to check if this email already taken, because we have used verification code to check it
  943. err = user.Update(false)
  944. if err != nil {
  945. common.ApiError(c, err)
  946. return
  947. }
  948. c.JSON(http.StatusOK, gin.H{
  949. "success": true,
  950. "message": "",
  951. })
  952. return
  953. }
  954. type topUpRequest struct {
  955. Key string `json:"key"`
  956. }
  957. var topUpLocks sync.Map
  958. var topUpCreateLock sync.Mutex
  959. type topUpTryLock struct {
  960. ch chan struct{}
  961. }
  962. func newTopUpTryLock() *topUpTryLock {
  963. return &topUpTryLock{ch: make(chan struct{}, 1)}
  964. }
  965. func (l *topUpTryLock) TryLock() bool {
  966. select {
  967. case l.ch <- struct{}{}:
  968. return true
  969. default:
  970. return false
  971. }
  972. }
  973. func (l *topUpTryLock) Unlock() {
  974. select {
  975. case <-l.ch:
  976. default:
  977. }
  978. }
  979. func getTopUpLock(userID int) *topUpTryLock {
  980. if v, ok := topUpLocks.Load(userID); ok {
  981. return v.(*topUpTryLock)
  982. }
  983. topUpCreateLock.Lock()
  984. defer topUpCreateLock.Unlock()
  985. if v, ok := topUpLocks.Load(userID); ok {
  986. return v.(*topUpTryLock)
  987. }
  988. l := newTopUpTryLock()
  989. topUpLocks.Store(userID, l)
  990. return l
  991. }
  992. func TopUp(c *gin.Context) {
  993. id := c.GetInt("id")
  994. lock := getTopUpLock(id)
  995. if !lock.TryLock() {
  996. c.JSON(http.StatusOK, gin.H{
  997. "success": false,
  998. "message": "充值处理中,请稍后重试",
  999. })
  1000. return
  1001. }
  1002. defer lock.Unlock()
  1003. req := topUpRequest{}
  1004. err := c.ShouldBindJSON(&req)
  1005. if err != nil {
  1006. common.ApiError(c, err)
  1007. return
  1008. }
  1009. quota, err := model.Redeem(req.Key, id)
  1010. if err != nil {
  1011. common.ApiError(c, err)
  1012. return
  1013. }
  1014. c.JSON(http.StatusOK, gin.H{
  1015. "success": true,
  1016. "message": "",
  1017. "data": quota,
  1018. })
  1019. }
  1020. type UpdateUserSettingRequest struct {
  1021. QuotaWarningType string `json:"notify_type"`
  1022. QuotaWarningThreshold float64 `json:"quota_warning_threshold"`
  1023. WebhookUrl string `json:"webhook_url,omitempty"`
  1024. WebhookSecret string `json:"webhook_secret,omitempty"`
  1025. NotificationEmail string `json:"notification_email,omitempty"`
  1026. BarkUrl string `json:"bark_url,omitempty"`
  1027. AcceptUnsetModelRatioModel bool `json:"accept_unset_model_ratio_model"`
  1028. RecordIpLog bool `json:"record_ip_log"`
  1029. }
  1030. func UpdateUserSetting(c *gin.Context) {
  1031. var req UpdateUserSettingRequest
  1032. if err := c.ShouldBindJSON(&req); err != nil {
  1033. c.JSON(http.StatusOK, gin.H{
  1034. "success": false,
  1035. "message": "无效的参数",
  1036. })
  1037. return
  1038. }
  1039. // 验证预警类型
  1040. if req.QuotaWarningType != dto.NotifyTypeEmail && req.QuotaWarningType != dto.NotifyTypeWebhook && req.QuotaWarningType != dto.NotifyTypeBark {
  1041. c.JSON(http.StatusOK, gin.H{
  1042. "success": false,
  1043. "message": "无效的预警类型",
  1044. })
  1045. return
  1046. }
  1047. // 验证预警阈值
  1048. if req.QuotaWarningThreshold <= 0 {
  1049. c.JSON(http.StatusOK, gin.H{
  1050. "success": false,
  1051. "message": "预警阈值必须大于0",
  1052. })
  1053. return
  1054. }
  1055. // 如果是webhook类型,验证webhook地址
  1056. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1057. if req.WebhookUrl == "" {
  1058. c.JSON(http.StatusOK, gin.H{
  1059. "success": false,
  1060. "message": "Webhook地址不能为空",
  1061. })
  1062. return
  1063. }
  1064. // 验证URL格式
  1065. if _, err := url.ParseRequestURI(req.WebhookUrl); err != nil {
  1066. c.JSON(http.StatusOK, gin.H{
  1067. "success": false,
  1068. "message": "无效的Webhook地址",
  1069. })
  1070. return
  1071. }
  1072. }
  1073. // 如果是邮件类型,验证邮箱地址
  1074. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1075. // 验证邮箱格式
  1076. if !strings.Contains(req.NotificationEmail, "@") {
  1077. c.JSON(http.StatusOK, gin.H{
  1078. "success": false,
  1079. "message": "无效的邮箱地址",
  1080. })
  1081. return
  1082. }
  1083. }
  1084. // 如果是Bark类型,验证Bark URL
  1085. if req.QuotaWarningType == dto.NotifyTypeBark {
  1086. if req.BarkUrl == "" {
  1087. c.JSON(http.StatusOK, gin.H{
  1088. "success": false,
  1089. "message": "Bark推送URL不能为空",
  1090. })
  1091. return
  1092. }
  1093. // 验证URL格式
  1094. if _, err := url.ParseRequestURI(req.BarkUrl); err != nil {
  1095. c.JSON(http.StatusOK, gin.H{
  1096. "success": false,
  1097. "message": "无效的Bark推送URL",
  1098. })
  1099. return
  1100. }
  1101. // 检查是否是HTTP或HTTPS
  1102. if !strings.HasPrefix(req.BarkUrl, "https://") && !strings.HasPrefix(req.BarkUrl, "http://") {
  1103. c.JSON(http.StatusOK, gin.H{
  1104. "success": false,
  1105. "message": "Bark推送URL必须以http://或https://开头",
  1106. })
  1107. return
  1108. }
  1109. }
  1110. userId := c.GetInt("id")
  1111. user, err := model.GetUserById(userId, true)
  1112. if err != nil {
  1113. common.ApiError(c, err)
  1114. return
  1115. }
  1116. // 构建设置
  1117. settings := dto.UserSetting{
  1118. NotifyType: req.QuotaWarningType,
  1119. QuotaWarningThreshold: req.QuotaWarningThreshold,
  1120. AcceptUnsetRatioModel: req.AcceptUnsetModelRatioModel,
  1121. RecordIpLog: req.RecordIpLog,
  1122. }
  1123. // 如果是webhook类型,添加webhook相关设置
  1124. if req.QuotaWarningType == dto.NotifyTypeWebhook {
  1125. settings.WebhookUrl = req.WebhookUrl
  1126. if req.WebhookSecret != "" {
  1127. settings.WebhookSecret = req.WebhookSecret
  1128. }
  1129. }
  1130. // 如果提供了通知邮箱,添加到设置中
  1131. if req.QuotaWarningType == dto.NotifyTypeEmail && req.NotificationEmail != "" {
  1132. settings.NotificationEmail = req.NotificationEmail
  1133. }
  1134. // 如果是Bark类型,添加Bark URL到设置中
  1135. if req.QuotaWarningType == dto.NotifyTypeBark {
  1136. settings.BarkUrl = req.BarkUrl
  1137. }
  1138. // 更新用户设置
  1139. user.SetSetting(settings)
  1140. if err := user.Update(false); err != nil {
  1141. c.JSON(http.StatusOK, gin.H{
  1142. "success": false,
  1143. "message": "更新设置失败: " + err.Error(),
  1144. })
  1145. return
  1146. }
  1147. c.JSON(http.StatusOK, gin.H{
  1148. "success": true,
  1149. "message": "设置已更新",
  1150. })
  1151. }