misc.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/constant"
  8. "one-api/middleware"
  9. "one-api/model"
  10. "one-api/setting"
  11. "one-api/setting/console_setting"
  12. "one-api/setting/operation_setting"
  13. "one-api/setting/system_setting"
  14. "strings"
  15. "github.com/gin-gonic/gin"
  16. )
  17. func TestStatus(c *gin.Context) {
  18. err := model.PingDB()
  19. if err != nil {
  20. c.JSON(http.StatusServiceUnavailable, gin.H{
  21. "success": false,
  22. "message": "数据库连接失败",
  23. })
  24. return
  25. }
  26. // 获取HTTP统计信息
  27. httpStats := middleware.GetStats()
  28. c.JSON(http.StatusOK, gin.H{
  29. "success": true,
  30. "message": "Server is running",
  31. "http_stats": httpStats,
  32. })
  33. return
  34. }
  35. func GetStatus(c *gin.Context) {
  36. cs := console_setting.GetConsoleSetting()
  37. common.OptionMapRWMutex.RLock()
  38. defer common.OptionMapRWMutex.RUnlock()
  39. data := gin.H{
  40. "version": common.Version,
  41. "start_time": common.StartTime,
  42. "email_verification": common.EmailVerificationEnabled,
  43. "github_oauth": common.GitHubOAuthEnabled,
  44. "github_client_id": common.GitHubClientId,
  45. "linuxdo_oauth": common.LinuxDOOAuthEnabled,
  46. "linuxdo_client_id": common.LinuxDOClientId,
  47. "linuxdo_minimum_trust_level": common.LinuxDOMinimumTrustLevel,
  48. "telegram_oauth": common.TelegramOAuthEnabled,
  49. "telegram_bot_name": common.TelegramBotName,
  50. "system_name": common.SystemName,
  51. "logo": common.Logo,
  52. "footer_html": common.Footer,
  53. "wechat_qrcode": common.WeChatAccountQRCodeImageURL,
  54. "wechat_login": common.WeChatAuthEnabled,
  55. "server_address": system_setting.ServerAddress,
  56. "turnstile_check": common.TurnstileCheckEnabled,
  57. "turnstile_site_key": common.TurnstileSiteKey,
  58. "top_up_link": common.TopUpLink,
  59. "docs_link": operation_setting.GetGeneralSetting().DocsLink,
  60. "quota_per_unit": common.QuotaPerUnit,
  61. "display_in_currency": common.DisplayInCurrencyEnabled,
  62. "enable_batch_update": common.BatchUpdateEnabled,
  63. "enable_drawing": common.DrawingEnabled,
  64. "enable_task": common.TaskEnabled,
  65. "enable_data_export": common.DataExportEnabled,
  66. "data_export_default_time": common.DataExportDefaultTime,
  67. "default_collapse_sidebar": common.DefaultCollapseSidebar,
  68. "mj_notify_enabled": setting.MjNotifyEnabled,
  69. "chats": setting.Chats,
  70. "demo_site_enabled": operation_setting.DemoSiteEnabled,
  71. "self_use_mode_enabled": operation_setting.SelfUseModeEnabled,
  72. "default_use_auto_group": setting.DefaultUseAutoGroup,
  73. "usd_exchange_rate": operation_setting.USDExchangeRate,
  74. "price": operation_setting.Price,
  75. "stripe_unit_price": setting.StripeUnitPrice,
  76. // 面板启用开关
  77. "api_info_enabled": cs.ApiInfoEnabled,
  78. "uptime_kuma_enabled": cs.UptimeKumaEnabled,
  79. "announcements_enabled": cs.AnnouncementsEnabled,
  80. "faq_enabled": cs.FAQEnabled,
  81. // 模块管理配置
  82. "HeaderNavModules": common.OptionMap["HeaderNavModules"],
  83. "SidebarModulesAdmin": common.OptionMap["SidebarModulesAdmin"],
  84. "oidc_enabled": system_setting.GetOIDCSettings().Enabled,
  85. "oidc_client_id": system_setting.GetOIDCSettings().ClientId,
  86. "oidc_authorization_endpoint": system_setting.GetOIDCSettings().AuthorizationEndpoint,
  87. "setup": constant.Setup,
  88. }
  89. // 根据启用状态注入可选内容
  90. if cs.ApiInfoEnabled {
  91. data["api_info"] = console_setting.GetApiInfo()
  92. }
  93. if cs.AnnouncementsEnabled {
  94. data["announcements"] = console_setting.GetAnnouncements()
  95. }
  96. if cs.FAQEnabled {
  97. data["faq"] = console_setting.GetFAQ()
  98. }
  99. c.JSON(http.StatusOK, gin.H{
  100. "success": true,
  101. "message": "",
  102. "data": data,
  103. })
  104. return
  105. }
  106. func GetNotice(c *gin.Context) {
  107. common.OptionMapRWMutex.RLock()
  108. defer common.OptionMapRWMutex.RUnlock()
  109. c.JSON(http.StatusOK, gin.H{
  110. "success": true,
  111. "message": "",
  112. "data": common.OptionMap["Notice"],
  113. })
  114. return
  115. }
  116. func GetAbout(c *gin.Context) {
  117. common.OptionMapRWMutex.RLock()
  118. defer common.OptionMapRWMutex.RUnlock()
  119. c.JSON(http.StatusOK, gin.H{
  120. "success": true,
  121. "message": "",
  122. "data": common.OptionMap["About"],
  123. })
  124. return
  125. }
  126. func GetMidjourney(c *gin.Context) {
  127. common.OptionMapRWMutex.RLock()
  128. defer common.OptionMapRWMutex.RUnlock()
  129. c.JSON(http.StatusOK, gin.H{
  130. "success": true,
  131. "message": "",
  132. "data": common.OptionMap["Midjourney"],
  133. })
  134. return
  135. }
  136. func GetHomePageContent(c *gin.Context) {
  137. common.OptionMapRWMutex.RLock()
  138. defer common.OptionMapRWMutex.RUnlock()
  139. c.JSON(http.StatusOK, gin.H{
  140. "success": true,
  141. "message": "",
  142. "data": common.OptionMap["HomePageContent"],
  143. })
  144. return
  145. }
  146. func SendEmailVerification(c *gin.Context) {
  147. email := c.Query("email")
  148. if err := common.Validate.Var(email, "required,email"); err != nil {
  149. c.JSON(http.StatusOK, gin.H{
  150. "success": false,
  151. "message": "无效的参数",
  152. })
  153. return
  154. }
  155. parts := strings.Split(email, "@")
  156. if len(parts) != 2 {
  157. c.JSON(http.StatusOK, gin.H{
  158. "success": false,
  159. "message": "无效的邮箱地址",
  160. })
  161. return
  162. }
  163. localPart := parts[0]
  164. domainPart := parts[1]
  165. if common.EmailDomainRestrictionEnabled {
  166. allowed := false
  167. for _, domain := range common.EmailDomainWhitelist {
  168. if domainPart == domain {
  169. allowed = true
  170. break
  171. }
  172. }
  173. if !allowed {
  174. c.JSON(http.StatusOK, gin.H{
  175. "success": false,
  176. "message": "The administrator has enabled the email domain name whitelist, and your email address is not allowed due to special symbols or it's not in the whitelist.",
  177. })
  178. return
  179. }
  180. }
  181. if common.EmailAliasRestrictionEnabled {
  182. containsSpecialSymbols := strings.Contains(localPart, "+") || strings.Contains(localPart, ".")
  183. if containsSpecialSymbols {
  184. c.JSON(http.StatusOK, gin.H{
  185. "success": false,
  186. "message": "管理员已启用邮箱地址别名限制,您的邮箱地址由于包含特殊符号而被拒绝。",
  187. })
  188. return
  189. }
  190. }
  191. if model.IsEmailAlreadyTaken(email) {
  192. c.JSON(http.StatusOK, gin.H{
  193. "success": false,
  194. "message": "邮箱地址已被占用",
  195. })
  196. return
  197. }
  198. code := common.GenerateVerificationCode(6)
  199. common.RegisterVerificationCodeWithKey(email, code, common.EmailVerificationPurpose)
  200. subject := fmt.Sprintf("%s邮箱验证邮件", common.SystemName)
  201. content := fmt.Sprintf("<p>您好,你正在进行%s邮箱验证。</p>"+
  202. "<p>您的验证码为: <strong>%s</strong></p>"+
  203. "<p>验证码 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, code, common.VerificationValidMinutes)
  204. err := common.SendEmail(subject, email, content)
  205. if err != nil {
  206. common.ApiError(c, err)
  207. return
  208. }
  209. c.JSON(http.StatusOK, gin.H{
  210. "success": true,
  211. "message": "",
  212. })
  213. return
  214. }
  215. func SendPasswordResetEmail(c *gin.Context) {
  216. email := c.Query("email")
  217. if err := common.Validate.Var(email, "required,email"); err != nil {
  218. c.JSON(http.StatusOK, gin.H{
  219. "success": false,
  220. "message": "无效的参数",
  221. })
  222. return
  223. }
  224. if !model.IsEmailAlreadyTaken(email) {
  225. c.JSON(http.StatusOK, gin.H{
  226. "success": false,
  227. "message": "该邮箱地址未注册",
  228. })
  229. return
  230. }
  231. code := common.GenerateVerificationCode(0)
  232. common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
  233. link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, email, code)
  234. subject := fmt.Sprintf("%s密码重置", common.SystemName)
  235. content := fmt.Sprintf("<p>您好,你正在进行%s密码重置。</p>"+
  236. "<p>点击 <a href='%s'>此处</a> 进行密码重置。</p>"+
  237. "<p>如果链接无法点击,请尝试点击下面的链接或将其复制到浏览器中打开:<br> %s </p>"+
  238. "<p>重置链接 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, link, link, common.VerificationValidMinutes)
  239. err := common.SendEmail(subject, email, content)
  240. if err != nil {
  241. common.ApiError(c, err)
  242. return
  243. }
  244. c.JSON(http.StatusOK, gin.H{
  245. "success": true,
  246. "message": "",
  247. })
  248. return
  249. }
  250. type PasswordResetRequest struct {
  251. Email string `json:"email"`
  252. Token string `json:"token"`
  253. }
  254. func ResetPassword(c *gin.Context) {
  255. var req PasswordResetRequest
  256. err := json.NewDecoder(c.Request.Body).Decode(&req)
  257. if req.Email == "" || req.Token == "" {
  258. c.JSON(http.StatusOK, gin.H{
  259. "success": false,
  260. "message": "无效的参数",
  261. })
  262. return
  263. }
  264. if !common.VerifyCodeWithKey(req.Email, req.Token, common.PasswordResetPurpose) {
  265. c.JSON(http.StatusOK, gin.H{
  266. "success": false,
  267. "message": "重置链接非法或已过期",
  268. })
  269. return
  270. }
  271. password := common.GenerateVerificationCode(12)
  272. err = model.ResetUserPasswordByEmail(req.Email, password)
  273. if err != nil {
  274. common.ApiError(c, err)
  275. return
  276. }
  277. common.DeleteKey(req.Email, common.PasswordResetPurpose)
  278. c.JSON(http.StatusOK, gin.H{
  279. "success": true,
  280. "message": "",
  281. "data": password,
  282. })
  283. return
  284. }