Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

395 lignes
12 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. "turnstile_site_key": common.TurnstileSiteKey,
  63. "top_up_link": common.TopUpLink,
  64. "docs_link": operation_setting.GetGeneralSetting().DocsLink,
  65. "quota_per_unit": common.QuotaPerUnit,
  66. // 兼容旧前端:保留 display_in_currency,同时提供新的 quota_display_type
  67. "display_in_currency": operation_setting.IsCurrencyDisplay(),
  68. "quota_display_type": operation_setting.GetQuotaDisplayType(),
  69. "custom_currency_symbol": operation_setting.GetGeneralSetting().CustomCurrencySymbol,
  70. "custom_currency_exchange_rate": operation_setting.GetGeneralSetting().CustomCurrencyExchangeRate,
  71. "enable_batch_update": common.BatchUpdateEnabled,
  72. "enable_drawing": common.DrawingEnabled,
  73. "enable_task": common.TaskEnabled,
  74. "enable_data_export": common.DataExportEnabled,
  75. "data_export_default_time": common.DataExportDefaultTime,
  76. "default_collapse_sidebar": common.DefaultCollapseSidebar,
  77. "mj_notify_enabled": setting.MjNotifyEnabled,
  78. "chats": setting.Chats,
  79. "demo_site_enabled": operation_setting.DemoSiteEnabled,
  80. "self_use_mode_enabled": operation_setting.SelfUseModeEnabled,
  81. "default_use_auto_group": setting.DefaultUseAutoGroup,
  82. "default_language": common.DefaultLanguage,
  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. "terms_enabled": legalSetting.TermsOfService != "",
  108. "usage_policy_enabled": legalSetting.UsagePolicy != "",
  109. "checkin_enabled": operation_setting.GetCheckinSetting().Enabled,
  110. "_qn": "new-api",
  111. }
  112. // 根据启用状态注入可选内容
  113. if cs.ApiInfoEnabled {
  114. data["api_info"] = console_setting.GetApiInfo()
  115. }
  116. if cs.AnnouncementsEnabled {
  117. data["announcements"] = console_setting.GetAnnouncements()
  118. }
  119. if cs.FAQEnabled {
  120. data["faq"] = console_setting.GetFAQ()
  121. }
  122. // Add enabled custom OAuth providers
  123. customProviders := oauth.GetEnabledCustomProviders()
  124. if len(customProviders) > 0 {
  125. type CustomOAuthInfo struct {
  126. Id int `json:"id"`
  127. Name string `json:"name"`
  128. Slug string `json:"slug"`
  129. Icon string `json:"icon"`
  130. ClientId string `json:"client_id"`
  131. AuthorizationEndpoint string `json:"authorization_endpoint"`
  132. Scopes string `json:"scopes"`
  133. }
  134. providersInfo := make([]CustomOAuthInfo, 0, len(customProviders))
  135. for _, p := range customProviders {
  136. config := p.GetConfig()
  137. providersInfo = append(providersInfo, CustomOAuthInfo{
  138. Id: config.Id,
  139. Name: config.Name,
  140. Slug: config.Slug,
  141. Icon: config.Icon,
  142. ClientId: config.ClientId,
  143. AuthorizationEndpoint: config.AuthorizationEndpoint,
  144. Scopes: config.Scopes,
  145. })
  146. }
  147. data["custom_oauth_providers"] = providersInfo
  148. }
  149. c.JSON(http.StatusOK, gin.H{
  150. "success": true,
  151. "message": "",
  152. "data": data,
  153. })
  154. return
  155. }
  156. func GetNotice(c *gin.Context) {
  157. common.OptionMapRWMutex.RLock()
  158. defer common.OptionMapRWMutex.RUnlock()
  159. c.JSON(http.StatusOK, gin.H{
  160. "success": true,
  161. "message": "",
  162. "data": common.OptionMap["Notice"],
  163. })
  164. return
  165. }
  166. func GetAbout(c *gin.Context) {
  167. common.OptionMapRWMutex.RLock()
  168. defer common.OptionMapRWMutex.RUnlock()
  169. c.JSON(http.StatusOK, gin.H{
  170. "success": true,
  171. "message": "",
  172. "data": common.OptionMap["About"],
  173. })
  174. return
  175. }
  176. func GetUserAgreement(c *gin.Context) {
  177. c.JSON(http.StatusOK, gin.H{
  178. "success": true,
  179. "message": "",
  180. "data": system_setting.GetLegalSettings().UserAgreement,
  181. })
  182. return
  183. }
  184. func GetPrivacyPolicy(c *gin.Context) {
  185. c.JSON(http.StatusOK, gin.H{
  186. "success": true,
  187. "message": "",
  188. "data": system_setting.GetLegalSettings().PrivacyPolicy,
  189. })
  190. return
  191. }
  192. func GetTermsOfService(c *gin.Context) {
  193. c.JSON(http.StatusOK, gin.H{
  194. "success": true,
  195. "message": "",
  196. "data": system_setting.GetLegalSettings().TermsOfService,
  197. })
  198. return
  199. }
  200. func GetUsagePolicy(c *gin.Context) {
  201. c.JSON(http.StatusOK, gin.H{
  202. "success": true,
  203. "message": "",
  204. "data": system_setting.GetLegalSettings().UsagePolicy,
  205. })
  206. return
  207. }
  208. func GetMidjourney(c *gin.Context) {
  209. common.OptionMapRWMutex.RLock()
  210. defer common.OptionMapRWMutex.RUnlock()
  211. c.JSON(http.StatusOK, gin.H{
  212. "success": true,
  213. "message": "",
  214. "data": common.OptionMap["Midjourney"],
  215. })
  216. return
  217. }
  218. func GetHomePageContent(c *gin.Context) {
  219. common.OptionMapRWMutex.RLock()
  220. defer common.OptionMapRWMutex.RUnlock()
  221. c.JSON(http.StatusOK, gin.H{
  222. "success": true,
  223. "message": "",
  224. "data": common.OptionMap["HomePageContent"],
  225. })
  226. return
  227. }
  228. func SendEmailVerification(c *gin.Context) {
  229. email := c.Query("email")
  230. if err := common.Validate.Var(email, "required,email"); err != nil {
  231. c.JSON(http.StatusOK, gin.H{
  232. "success": false,
  233. "message": "无效的参数",
  234. })
  235. return
  236. }
  237. parts := strings.Split(email, "@")
  238. if len(parts) != 2 {
  239. c.JSON(http.StatusOK, gin.H{
  240. "success": false,
  241. "message": "无效的邮箱地址",
  242. })
  243. return
  244. }
  245. localPart := parts[0]
  246. domainPart := parts[1]
  247. if common.EmailDomainRestrictionEnabled {
  248. allowed := false
  249. for _, domain := range common.EmailDomainWhitelist {
  250. if domainPart == domain {
  251. allowed = true
  252. break
  253. }
  254. }
  255. if !allowed {
  256. c.JSON(http.StatusOK, gin.H{
  257. "success": false,
  258. "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.",
  259. })
  260. return
  261. }
  262. }
  263. if common.EmailAliasRestrictionEnabled {
  264. containsSpecialSymbols := strings.Contains(localPart, "+") || strings.Contains(localPart, ".")
  265. if containsSpecialSymbols {
  266. c.JSON(http.StatusOK, gin.H{
  267. "success": false,
  268. "message": "管理员已启用邮箱地址别名限制,您的邮箱地址由于包含特殊符号而被拒绝。",
  269. })
  270. return
  271. }
  272. }
  273. if model.IsEmailAlreadyTaken(email) {
  274. c.JSON(http.StatusOK, gin.H{
  275. "success": false,
  276. "message": "邮箱地址已被占用",
  277. })
  278. return
  279. }
  280. code := common.GenerateVerificationCode(6)
  281. common.RegisterVerificationCodeWithKey(email, code, common.EmailVerificationPurpose)
  282. subject := fmt.Sprintf("%s邮箱验证邮件", common.SystemName)
  283. content := fmt.Sprintf("<p>您好,你正在进行%s邮箱验证。</p>"+
  284. "<p>您的验证码为: <strong>%s</strong></p>"+
  285. "<p>验证码 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, code, common.VerificationValidMinutes)
  286. err := common.SendEmail(subject, email, content)
  287. if err != nil {
  288. common.ApiError(c, err)
  289. return
  290. }
  291. c.JSON(http.StatusOK, gin.H{
  292. "success": true,
  293. "message": "",
  294. })
  295. return
  296. }
  297. func SendPasswordResetEmail(c *gin.Context) {
  298. email := c.Query("email")
  299. if err := common.Validate.Var(email, "required,email"); err != nil {
  300. c.JSON(http.StatusOK, gin.H{
  301. "success": false,
  302. "message": "无效的参数",
  303. })
  304. return
  305. }
  306. if !model.IsEmailAlreadyTaken(email) {
  307. c.JSON(http.StatusOK, gin.H{
  308. "success": false,
  309. "message": "该邮箱地址未注册",
  310. })
  311. return
  312. }
  313. code := common.GenerateVerificationCode(0)
  314. common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
  315. link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, email, code)
  316. subject := fmt.Sprintf("%s密码重置", common.SystemName)
  317. content := fmt.Sprintf("<p>您好,你正在进行%s密码重置。</p>"+
  318. "<p>点击 <a href='%s'>此处</a> 进行密码重置。</p>"+
  319. "<p>如果链接无法点击,请尝试点击下面的链接或将其复制到浏览器中打开:<br> %s </p>"+
  320. "<p>重置链接 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, link, link, common.VerificationValidMinutes)
  321. err := common.SendEmail(subject, email, content)
  322. if err != nil {
  323. common.ApiError(c, err)
  324. return
  325. }
  326. c.JSON(http.StatusOK, gin.H{
  327. "success": true,
  328. "message": "",
  329. })
  330. return
  331. }
  332. type PasswordResetRequest struct {
  333. Email string `json:"email"`
  334. Token string `json:"token"`
  335. }
  336. func ResetPassword(c *gin.Context) {
  337. var req PasswordResetRequest
  338. err := json.NewDecoder(c.Request.Body).Decode(&req)
  339. if req.Email == "" || req.Token == "" {
  340. c.JSON(http.StatusOK, gin.H{
  341. "success": false,
  342. "message": "无效的参数",
  343. })
  344. return
  345. }
  346. if !common.VerifyCodeWithKey(req.Email, req.Token, common.PasswordResetPurpose) {
  347. c.JSON(http.StatusOK, gin.H{
  348. "success": false,
  349. "message": "重置链接非法或已过期",
  350. })
  351. return
  352. }
  353. password := common.GenerateVerificationCode(12)
  354. err = model.ResetUserPasswordByEmail(req.Email, password)
  355. if err != nil {
  356. common.ApiError(c, err)
  357. return
  358. }
  359. common.DeleteKey(req.Email, common.PasswordResetPurpose)
  360. c.JSON(http.StatusOK, gin.H{
  361. "success": true,
  362. "message": "",
  363. "data": password,
  364. })
  365. return
  366. }