Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

407 řádky
13 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.Logo,
  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. "usd_exchange_rate": operation_setting.USDExchangeRate,
  84. "price": operation_setting.Price,
  85. "stripe_unit_price": setting.StripeUnitPrice,
  86. // 面板启用开关
  87. "api_info_enabled": cs.ApiInfoEnabled,
  88. "uptime_kuma_enabled": cs.UptimeKumaEnabled,
  89. "announcements_enabled": cs.AnnouncementsEnabled,
  90. "faq_enabled": cs.FAQEnabled,
  91. // 模块管理配置
  92. "HeaderNavModules": common.OptionMap["HeaderNavModules"],
  93. "SidebarModulesAdmin": common.OptionMap["SidebarModulesAdmin"],
  94. "oidc_enabled": system_setting.GetOIDCSettings().Enabled,
  95. "oidc_client_id": system_setting.GetOIDCSettings().ClientId,
  96. "oidc_authorization_endpoint": system_setting.GetOIDCSettings().AuthorizationEndpoint,
  97. "passkey_login": passkeySetting.Enabled,
  98. "passkey_display_name": passkeySetting.RPDisplayName,
  99. "passkey_rp_id": passkeySetting.RPID,
  100. "passkey_origins": passkeySetting.Origins,
  101. "passkey_allow_insecure": passkeySetting.AllowInsecureOrigin,
  102. "passkey_user_verification": passkeySetting.UserVerification,
  103. "passkey_attachment": passkeySetting.AttachmentPreference,
  104. "setup": constant.Setup,
  105. "user_agreement_enabled": legalSetting.UserAgreement != "",
  106. "privacy_policy_enabled": legalSetting.PrivacyPolicy != "",
  107. "checkin_enabled": operation_setting.GetCheckinSetting().Enabled,
  108. "_qn": "new-api",
  109. }
  110. // 根据启用状态注入可选内容
  111. if cs.ApiInfoEnabled {
  112. data["api_info"] = console_setting.GetApiInfo()
  113. }
  114. if cs.AnnouncementsEnabled {
  115. data["announcements"] = console_setting.GetAnnouncements()
  116. }
  117. if cs.FAQEnabled {
  118. data["faq"] = console_setting.GetFAQ()
  119. }
  120. // Add enabled custom OAuth providers
  121. customProviders := oauth.GetEnabledCustomProviders()
  122. if len(customProviders) > 0 {
  123. type CustomOAuthInfo struct {
  124. Id int `json:"id"`
  125. Name string `json:"name"`
  126. Slug string `json:"slug"`
  127. Icon string `json:"icon"`
  128. ClientId string `json:"client_id"`
  129. AuthorizationEndpoint string `json:"authorization_endpoint"`
  130. Scopes string `json:"scopes"`
  131. }
  132. providersInfo := make([]CustomOAuthInfo, 0, len(customProviders))
  133. for _, p := range customProviders {
  134. config := p.GetConfig()
  135. providersInfo = append(providersInfo, CustomOAuthInfo{
  136. Id: config.Id,
  137. Name: config.Name,
  138. Slug: config.Slug,
  139. Icon: config.Icon,
  140. ClientId: config.ClientId,
  141. AuthorizationEndpoint: config.AuthorizationEndpoint,
  142. Scopes: config.Scopes,
  143. })
  144. }
  145. data["custom_oauth_providers"] = providersInfo
  146. }
  147. c.JSON(http.StatusOK, gin.H{
  148. "success": true,
  149. "message": "",
  150. "data": data,
  151. })
  152. return
  153. }
  154. func GetNotice(c *gin.Context) {
  155. common.OptionMapRWMutex.RLock()
  156. defer common.OptionMapRWMutex.RUnlock()
  157. c.JSON(http.StatusOK, gin.H{
  158. "success": true,
  159. "message": "",
  160. "data": common.OptionMap["Notice"],
  161. })
  162. return
  163. }
  164. func GetAbout(c *gin.Context) {
  165. common.OptionMapRWMutex.RLock()
  166. defer common.OptionMapRWMutex.RUnlock()
  167. c.JSON(http.StatusOK, gin.H{
  168. "success": true,
  169. "message": "",
  170. "data": common.OptionMap["About"],
  171. })
  172. return
  173. }
  174. func GetUserAgreement(c *gin.Context) {
  175. c.JSON(http.StatusOK, gin.H{
  176. "success": true,
  177. "message": "",
  178. "data": system_setting.GetLegalSettings().UserAgreement,
  179. })
  180. return
  181. }
  182. func GetPrivacyPolicy(c *gin.Context) {
  183. c.JSON(http.StatusOK, gin.H{
  184. "success": true,
  185. "message": "",
  186. "data": system_setting.GetLegalSettings().PrivacyPolicy,
  187. })
  188. return
  189. }
  190. func GetMidjourney(c *gin.Context) {
  191. common.OptionMapRWMutex.RLock()
  192. defer common.OptionMapRWMutex.RUnlock()
  193. c.JSON(http.StatusOK, gin.H{
  194. "success": true,
  195. "message": "",
  196. "data": common.OptionMap["Midjourney"],
  197. })
  198. return
  199. }
  200. func GetHomePageContent(c *gin.Context) {
  201. common.OptionMapRWMutex.RLock()
  202. defer common.OptionMapRWMutex.RUnlock()
  203. c.JSON(http.StatusOK, gin.H{
  204. "success": true,
  205. "message": "",
  206. "data": common.OptionMap["HomePageContent"],
  207. })
  208. return
  209. }
  210. func GetCaptcha(c *gin.Context) {
  211. if !common.CaptchaEnabled {
  212. c.JSON(http.StatusOK, gin.H{
  213. "success": false,
  214. "message": "验证码功能未启用",
  215. })
  216. return
  217. }
  218. id, b64s, err := common.GenerateCaptcha()
  219. if err != nil {
  220. common.ApiErrorMsg(c, "生成验证码失败")
  221. return
  222. }
  223. common.ApiSuccess(c, gin.H{
  224. "id": id,
  225. "captcha_image": b64s,
  226. })
  227. }
  228. func SendEmailVerification(c *gin.Context) {
  229. if common.CaptchaEnabled {
  230. captchaId := c.Query("captcha_id")
  231. captchaCode := c.Query("captcha_code")
  232. if captchaId == "" || captchaCode == "" {
  233. common.ApiErrorMsg(c, "请先完成图片验证码")
  234. return
  235. }
  236. if !common.VerifyCaptcha(captchaId, captchaCode) {
  237. common.ApiErrorMsg(c, "图片验证码错误或已过期")
  238. return
  239. }
  240. }
  241. email := c.Query("email")
  242. if err := common.Validate.Var(email, "required,email"); err != nil {
  243. c.JSON(http.StatusOK, gin.H{
  244. "success": false,
  245. "message": "无效的参数",
  246. })
  247. return
  248. }
  249. parts := strings.Split(email, "@")
  250. if len(parts) != 2 {
  251. c.JSON(http.StatusOK, gin.H{
  252. "success": false,
  253. "message": "无效的邮箱地址",
  254. })
  255. return
  256. }
  257. localPart := parts[0]
  258. domainPart := parts[1]
  259. if common.EmailDomainRestrictionEnabled {
  260. allowed := false
  261. for _, domain := range common.EmailDomainWhitelist {
  262. if domainPart == domain {
  263. allowed = true
  264. break
  265. }
  266. }
  267. if !allowed {
  268. c.JSON(http.StatusOK, gin.H{
  269. "success": false,
  270. "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.",
  271. })
  272. return
  273. }
  274. }
  275. if common.EmailAliasRestrictionEnabled {
  276. containsSpecialSymbols := strings.Contains(localPart, "+") || strings.Contains(localPart, ".")
  277. if containsSpecialSymbols {
  278. c.JSON(http.StatusOK, gin.H{
  279. "success": false,
  280. "message": "管理员已启用邮箱地址别名限制,您的邮箱地址由于包含特殊符号而被拒绝。",
  281. })
  282. return
  283. }
  284. }
  285. if model.IsEmailAlreadyTaken(email) {
  286. c.JSON(http.StatusOK, gin.H{
  287. "success": false,
  288. "message": "邮箱地址已被占用",
  289. })
  290. return
  291. }
  292. code := common.GenerateVerificationCode(6)
  293. common.RegisterVerificationCodeWithKey(email, code, common.EmailVerificationPurpose)
  294. subject := fmt.Sprintf("%s邮箱验证邮件", common.SystemName)
  295. content := fmt.Sprintf("<p>您好,你正在进行%s邮箱验证。</p>"+
  296. "<p>您的验证码为: <strong>%s</strong></p>"+
  297. "<p>验证码 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, code, common.VerificationValidMinutes)
  298. err := common.SendEmail(subject, email, content)
  299. if err != nil {
  300. common.ApiError(c, err)
  301. return
  302. }
  303. c.JSON(http.StatusOK, gin.H{
  304. "success": true,
  305. "message": "",
  306. })
  307. return
  308. }
  309. func SendPasswordResetEmail(c *gin.Context) {
  310. email := c.Query("email")
  311. if err := common.Validate.Var(email, "required,email"); err != nil {
  312. c.JSON(http.StatusOK, gin.H{
  313. "success": false,
  314. "message": "无效的参数",
  315. })
  316. return
  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(0)
  326. common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
  327. link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, email, code)
  328. subject := fmt.Sprintf("%s密码重置", common.SystemName)
  329. content := fmt.Sprintf("<p>您好,你正在进行%s密码重置。</p>"+
  330. "<p>点击 <a href='%s'>此处</a> 进行密码重置。</p>"+
  331. "<p>如果链接无法点击,请尝试点击下面的链接或将其复制到浏览器中打开:<br> %s </p>"+
  332. "<p>重置链接 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, link, link, common.VerificationValidMinutes)
  333. err := common.SendEmail(subject, email, content)
  334. if err != nil {
  335. common.ApiError(c, err)
  336. return
  337. }
  338. c.JSON(http.StatusOK, gin.H{
  339. "success": true,
  340. "message": "",
  341. })
  342. return
  343. }
  344. type PasswordResetRequest struct {
  345. Email string `json:"email"`
  346. Token string `json:"token"`
  347. }
  348. func ResetPassword(c *gin.Context) {
  349. var req PasswordResetRequest
  350. err := json.NewDecoder(c.Request.Body).Decode(&req)
  351. if req.Email == "" || req.Token == "" {
  352. c.JSON(http.StatusOK, gin.H{
  353. "success": false,
  354. "message": "无效的参数",
  355. })
  356. return
  357. }
  358. if !common.VerifyCodeWithKey(req.Email, req.Token, common.PasswordResetPurpose) {
  359. c.JSON(http.StatusOK, gin.H{
  360. "success": false,
  361. "message": "重置链接非法或已过期",
  362. })
  363. return
  364. }
  365. password := common.GenerateVerificationCode(12)
  366. err = model.ResetUserPasswordByEmail(req.Email, password)
  367. if err != nil {
  368. common.ApiError(c, err)
  369. return
  370. }
  371. common.DeleteKey(req.Email, common.PasswordResetPurpose)
  372. c.JSON(http.StatusOK, gin.H{
  373. "success": true,
  374. "message": "",
  375. "data": password,
  376. })
  377. return
  378. }