You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

443 rivejä
14 KiB

  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "github.com/QuantumNous/new-api/common"
  8. "github.com/QuantumNous/new-api/constant"
  9. "github.com/QuantumNous/new-api/middleware"
  10. "github.com/QuantumNous/new-api/model"
  11. "github.com/QuantumNous/new-api/oauth"
  12. "github.com/QuantumNous/new-api/setting"
  13. "github.com/QuantumNous/new-api/setting/console_setting"
  14. "github.com/QuantumNous/new-api/setting/operation_setting"
  15. "github.com/QuantumNous/new-api/setting/system_setting"
  16. "github.com/gin-gonic/gin"
  17. )
  18. func TestStatus(c *gin.Context) {
  19. err := model.PingDB()
  20. if err != nil {
  21. c.JSON(http.StatusServiceUnavailable, gin.H{
  22. "success": false,
  23. "message": "数据库连接失败",
  24. })
  25. return
  26. }
  27. // 获取HTTP统计信息
  28. httpStats := middleware.GetStats()
  29. c.JSON(http.StatusOK, gin.H{
  30. "success": true,
  31. "message": "Server is running",
  32. "http_stats": httpStats,
  33. })
  34. return
  35. }
  36. func GetStatus(c *gin.Context) {
  37. cs := console_setting.GetConsoleSetting()
  38. common.OptionMapRWMutex.RLock()
  39. defer common.OptionMapRWMutex.RUnlock()
  40. passkeySetting := system_setting.GetPasskeySettings()
  41. legalSetting := system_setting.GetLegalSettings()
  42. data := gin.H{
  43. "version": common.Version,
  44. "start_time": common.StartTime,
  45. "email_verification": common.EmailVerificationEnabled,
  46. "github_oauth": common.GitHubOAuthEnabled,
  47. "github_client_id": common.GitHubClientId,
  48. "discord_oauth": system_setting.GetDiscordSettings().Enabled,
  49. "discord_client_id": system_setting.GetDiscordSettings().ClientId,
  50. "linuxdo_oauth": common.LinuxDOOAuthEnabled,
  51. "linuxdo_client_id": common.LinuxDOClientId,
  52. "linuxdo_minimum_trust_level": common.LinuxDOMinimumTrustLevel,
  53. "telegram_oauth": common.TelegramOAuthEnabled,
  54. "telegram_bot_name": common.TelegramBotName,
  55. "system_name": common.SystemName,
  56. "logo": common.GetEffectiveLogo(),
  57. "footer_html": common.Footer,
  58. "wechat_qrcode": common.WeChatAccountQRCodeImageURL,
  59. "wechat_login": common.WeChatAuthEnabled,
  60. "server_address": system_setting.ServerAddress,
  61. "turnstile_check": common.TurnstileCheckEnabled,
  62. "captcha_enabled": common.CaptchaEnabled,
  63. "turnstile_site_key": common.TurnstileSiteKey,
  64. "top_up_link": common.TopUpLink,
  65. "docs_link": operation_setting.GetGeneralSetting().DocsLink,
  66. "quota_per_unit": common.QuotaPerUnit,
  67. // 兼容旧前端:保留 display_in_currency,同时提供新的 quota_display_type
  68. "display_in_currency": operation_setting.IsCurrencyDisplay(),
  69. "quota_display_type": operation_setting.GetQuotaDisplayType(),
  70. "custom_currency_symbol": operation_setting.GetGeneralSetting().CustomCurrencySymbol,
  71. "custom_currency_exchange_rate": operation_setting.GetGeneralSetting().CustomCurrencyExchangeRate,
  72. "enable_batch_update": common.BatchUpdateEnabled,
  73. "enable_drawing": common.DrawingEnabled,
  74. "enable_task": common.TaskEnabled,
  75. "enable_data_export": common.DataExportEnabled,
  76. "data_export_default_time": common.DataExportDefaultTime,
  77. "default_collapse_sidebar": common.DefaultCollapseSidebar,
  78. "mj_notify_enabled": setting.MjNotifyEnabled,
  79. "chats": setting.Chats,
  80. "demo_site_enabled": operation_setting.DemoSiteEnabled,
  81. "self_use_mode_enabled": operation_setting.SelfUseModeEnabled,
  82. "default_use_auto_group": setting.DefaultUseAutoGroup,
  83. "default_language": common.DefaultLanguage,
  84. "usd_exchange_rate": operation_setting.USDExchangeRate,
  85. "price": operation_setting.Price,
  86. "stripe_unit_price": setting.StripeUnitPrice,
  87. // 面板启用开关
  88. "api_info_enabled": cs.ApiInfoEnabled,
  89. "uptime_kuma_enabled": cs.UptimeKumaEnabled,
  90. "announcements_enabled": cs.AnnouncementsEnabled,
  91. "faq_enabled": cs.FAQEnabled,
  92. // 模块管理配置
  93. "HeaderNavModules": common.OptionMap["HeaderNavModules"],
  94. "SidebarModulesAdmin": common.OptionMap["SidebarModulesAdmin"],
  95. "oidc_enabled": system_setting.GetOIDCSettings().Enabled,
  96. "oidc_client_id": system_setting.GetOIDCSettings().ClientId,
  97. "oidc_authorization_endpoint": system_setting.GetOIDCSettings().AuthorizationEndpoint,
  98. "passkey_login": passkeySetting.Enabled,
  99. "passkey_display_name": passkeySetting.RPDisplayName,
  100. "passkey_rp_id": passkeySetting.RPID,
  101. "passkey_origins": passkeySetting.Origins,
  102. "passkey_allow_insecure": passkeySetting.AllowInsecureOrigin,
  103. "passkey_user_verification": passkeySetting.UserVerification,
  104. "passkey_attachment": passkeySetting.AttachmentPreference,
  105. "setup": constant.Setup,
  106. "user_agreement_enabled": legalSetting.UserAgreementZh != "" || legalSetting.UserAgreementEn != "",
  107. "privacy_policy_enabled": legalSetting.PrivacyPolicyZh != "" || legalSetting.PrivacyPolicyEn != "",
  108. "terms_enabled": legalSetting.TermsOfServiceZh != "" || legalSetting.TermsOfServiceEn != "",
  109. "usage_policy_enabled": legalSetting.UsagePolicyZh != "" || legalSetting.UsagePolicyEn != "",
  110. "checkin_enabled": operation_setting.GetCheckinSetting().Enabled,
  111. "_qn": "new-api",
  112. }
  113. // 根据启用状态注入可选内容
  114. if cs.ApiInfoEnabled {
  115. data["api_info"] = console_setting.GetApiInfo()
  116. }
  117. if cs.AnnouncementsEnabled {
  118. data["announcements"] = console_setting.GetAnnouncements()
  119. }
  120. if cs.FAQEnabled {
  121. data["faq"] = console_setting.GetFAQ()
  122. }
  123. // Add enabled custom OAuth providers
  124. customProviders := oauth.GetEnabledCustomProviders()
  125. if len(customProviders) > 0 {
  126. type CustomOAuthInfo struct {
  127. Id int `json:"id"`
  128. Name string `json:"name"`
  129. Slug string `json:"slug"`
  130. Icon string `json:"icon"`
  131. ClientId string `json:"client_id"`
  132. AuthorizationEndpoint string `json:"authorization_endpoint"`
  133. Scopes string `json:"scopes"`
  134. }
  135. providersInfo := make([]CustomOAuthInfo, 0, len(customProviders))
  136. for _, p := range customProviders {
  137. config := p.GetConfig()
  138. providersInfo = append(providersInfo, CustomOAuthInfo{
  139. Id: config.Id,
  140. Name: config.Name,
  141. Slug: config.Slug,
  142. Icon: config.Icon,
  143. ClientId: config.ClientId,
  144. AuthorizationEndpoint: config.AuthorizationEndpoint,
  145. Scopes: config.Scopes,
  146. })
  147. }
  148. data["custom_oauth_providers"] = providersInfo
  149. }
  150. c.JSON(http.StatusOK, gin.H{
  151. "success": true,
  152. "message": "",
  153. "data": data,
  154. })
  155. return
  156. }
  157. func GetNotice(c *gin.Context) {
  158. common.OptionMapRWMutex.RLock()
  159. defer common.OptionMapRWMutex.RUnlock()
  160. c.JSON(http.StatusOK, gin.H{
  161. "success": true,
  162. "message": "",
  163. "data": common.OptionMap["Notice"],
  164. })
  165. return
  166. }
  167. func GetAbout(c *gin.Context) {
  168. common.OptionMapRWMutex.RLock()
  169. defer common.OptionMapRWMutex.RUnlock()
  170. c.JSON(http.StatusOK, gin.H{
  171. "success": true,
  172. "message": "",
  173. "data": common.OptionMap["About"],
  174. })
  175. return
  176. }
  177. func getLegalContent(zh, en string, lang string) string {
  178. if lang == "en" {
  179. return en
  180. }
  181. return zh
  182. }
  183. func GetUserAgreement(c *gin.Context) {
  184. ls := system_setting.GetLegalSettings()
  185. lang := c.Query("lang")
  186. c.JSON(http.StatusOK, gin.H{
  187. "success": true,
  188. "message": "",
  189. "data": getLegalContent(ls.UserAgreementZh, ls.UserAgreementEn, lang),
  190. })
  191. return
  192. }
  193. func GetPrivacyPolicy(c *gin.Context) {
  194. ls := system_setting.GetLegalSettings()
  195. lang := c.Query("lang")
  196. c.JSON(http.StatusOK, gin.H{
  197. "success": true,
  198. "message": "",
  199. "data": getLegalContent(ls.PrivacyPolicyZh, ls.PrivacyPolicyEn, lang),
  200. })
  201. return
  202. }
  203. func GetTermsOfService(c *gin.Context) {
  204. ls := system_setting.GetLegalSettings()
  205. lang := c.Query("lang")
  206. c.JSON(http.StatusOK, gin.H{
  207. "success": true,
  208. "message": "",
  209. "data": getLegalContent(ls.TermsOfServiceZh, ls.TermsOfServiceEn, lang),
  210. })
  211. return
  212. }
  213. func GetUsagePolicy(c *gin.Context) {
  214. ls := system_setting.GetLegalSettings()
  215. lang := c.Query("lang")
  216. c.JSON(http.StatusOK, gin.H{
  217. "success": true,
  218. "message": "",
  219. "data": getLegalContent(ls.UsagePolicyZh, ls.UsagePolicyEn, lang),
  220. })
  221. return
  222. }
  223. func GetMidjourney(c *gin.Context) {
  224. common.OptionMapRWMutex.RLock()
  225. defer common.OptionMapRWMutex.RUnlock()
  226. c.JSON(http.StatusOK, gin.H{
  227. "success": true,
  228. "message": "",
  229. "data": common.OptionMap["Midjourney"],
  230. })
  231. return
  232. }
  233. func GetHomePageContent(c *gin.Context) {
  234. common.OptionMapRWMutex.RLock()
  235. defer common.OptionMapRWMutex.RUnlock()
  236. c.JSON(http.StatusOK, gin.H{
  237. "success": true,
  238. "message": "",
  239. "data": common.OptionMap["HomePageContent"],
  240. })
  241. return
  242. }
  243. func GetCaptcha(c *gin.Context) {
  244. if !common.CaptchaEnabled {
  245. c.JSON(http.StatusOK, gin.H{
  246. "success": false,
  247. "message": "验证码功能未启用",
  248. })
  249. return
  250. }
  251. id, b64s, err := common.GenerateCaptcha()
  252. if err != nil {
  253. common.ApiErrorMsg(c, "生成验证码失败")
  254. return
  255. }
  256. common.ApiSuccess(c, gin.H{
  257. "id": id,
  258. "captcha_image": b64s,
  259. })
  260. }
  261. func SendEmailVerification(c *gin.Context) {
  262. if common.CaptchaEnabled {
  263. captchaId := c.Query("captcha_id")
  264. captchaCode := c.Query("captcha_code")
  265. if captchaId == "" || captchaCode == "" {
  266. common.ApiErrorMsg(c, "请先完成图片验证码")
  267. return
  268. }
  269. if !common.VerifyCaptcha(captchaId, captchaCode) {
  270. common.ApiErrorMsg(c, "图片验证码错误或已过期")
  271. return
  272. }
  273. }
  274. email := c.Query("email")
  275. if err := common.Validate.Var(email, "required,email"); err != nil {
  276. c.JSON(http.StatusOK, gin.H{
  277. "success": false,
  278. "message": "无效的参数",
  279. })
  280. return
  281. }
  282. parts := strings.Split(email, "@")
  283. if len(parts) != 2 {
  284. c.JSON(http.StatusOK, gin.H{
  285. "success": false,
  286. "message": "无效的邮箱地址",
  287. })
  288. return
  289. }
  290. localPart := parts[0]
  291. domainPart := parts[1]
  292. if common.EmailDomainRestrictionEnabled {
  293. allowed := false
  294. for _, domain := range common.EmailDomainWhitelist {
  295. if domainPart == domain {
  296. allowed = true
  297. break
  298. }
  299. }
  300. if !allowed {
  301. c.JSON(http.StatusOK, gin.H{
  302. "success": false,
  303. "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.",
  304. })
  305. return
  306. }
  307. }
  308. if common.EmailAliasRestrictionEnabled {
  309. containsSpecialSymbols := strings.Contains(localPart, "+") || strings.Contains(localPart, ".")
  310. if containsSpecialSymbols {
  311. c.JSON(http.StatusOK, gin.H{
  312. "success": false,
  313. "message": "管理员已启用邮箱地址别名限制,您的邮箱地址由于包含特殊符号而被拒绝。",
  314. })
  315. return
  316. }
  317. }
  318. if model.IsEmailAlreadyTaken(email) {
  319. c.JSON(http.StatusOK, gin.H{
  320. "success": false,
  321. "message": "邮箱地址已被占用",
  322. })
  323. return
  324. }
  325. code := common.GenerateVerificationCode(6)
  326. common.RegisterVerificationCodeWithKey(email, code, common.EmailVerificationPurpose)
  327. subject := fmt.Sprintf("%s邮箱验证邮件", common.SystemName)
  328. content := fmt.Sprintf("<p>您好,你正在进行%s邮箱验证。</p>"+
  329. "<p>您的验证码为: <strong>%s</strong></p>"+
  330. "<p>验证码 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, code, common.VerificationValidMinutes)
  331. err := common.SendEmail(subject, email, content)
  332. if err != nil {
  333. common.ApiError(c, err)
  334. return
  335. }
  336. c.JSON(http.StatusOK, gin.H{
  337. "success": true,
  338. "message": "",
  339. })
  340. return
  341. }
  342. func SendPasswordResetEmail(c *gin.Context) {
  343. email := c.Query("email")
  344. if err := common.Validate.Var(email, "required,email"); err != nil {
  345. c.JSON(http.StatusOK, gin.H{
  346. "success": false,
  347. "message": "无效的参数",
  348. })
  349. return
  350. }
  351. if !model.IsEmailAlreadyTaken(email) {
  352. c.JSON(http.StatusOK, gin.H{
  353. "success": false,
  354. "message": "该邮箱地址未注册",
  355. })
  356. return
  357. }
  358. code := common.GenerateVerificationCode(0)
  359. common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
  360. link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, email, code)
  361. subject := fmt.Sprintf("%s密码重置", common.SystemName)
  362. content := fmt.Sprintf("<p>您好,你正在进行%s密码重置。</p>"+
  363. "<p>点击 <a href='%s'>此处</a> 进行密码重置。</p>"+
  364. "<p>如果链接无法点击,请尝试点击下面的链接或将其复制到浏览器中打开:<br> %s </p>"+
  365. "<p>重置链接 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, link, link, common.VerificationValidMinutes)
  366. err := common.SendEmail(subject, email, content)
  367. if err != nil {
  368. common.ApiError(c, err)
  369. return
  370. }
  371. c.JSON(http.StatusOK, gin.H{
  372. "success": true,
  373. "message": "",
  374. })
  375. return
  376. }
  377. type PasswordResetRequest struct {
  378. Email string `json:"email"`
  379. Token string `json:"token"`
  380. }
  381. func ResetPassword(c *gin.Context) {
  382. var req PasswordResetRequest
  383. err := json.NewDecoder(c.Request.Body).Decode(&req)
  384. if req.Email == "" || req.Token == "" {
  385. c.JSON(http.StatusOK, gin.H{
  386. "success": false,
  387. "message": "无效的参数",
  388. })
  389. return
  390. }
  391. if !common.VerifyCodeWithKey(req.Email, req.Token, common.PasswordResetPurpose) {
  392. c.JSON(http.StatusOK, gin.H{
  393. "success": false,
  394. "message": "重置链接非法或已过期",
  395. })
  396. return
  397. }
  398. password := common.GenerateVerificationCode(12)
  399. err = model.ResetUserPasswordByEmail(req.Email, password)
  400. if err != nil {
  401. common.ApiError(c, err)
  402. return
  403. }
  404. common.DeleteKey(req.Email, common.PasswordResetPurpose)
  405. c.JSON(http.StatusOK, gin.H{
  406. "success": true,
  407. "message": "",
  408. "data": password,
  409. })
  410. return
  411. }