Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

375 rader
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. "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 SendEmailVerification(c *gin.Context) {
  211. email := c.Query("email")
  212. if err := common.Validate.Var(email, "required,email"); err != nil {
  213. c.JSON(http.StatusOK, gin.H{
  214. "success": false,
  215. "message": "无效的参数",
  216. })
  217. return
  218. }
  219. parts := strings.Split(email, "@")
  220. if len(parts) != 2 {
  221. c.JSON(http.StatusOK, gin.H{
  222. "success": false,
  223. "message": "无效的邮箱地址",
  224. })
  225. return
  226. }
  227. localPart := parts[0]
  228. domainPart := parts[1]
  229. if common.EmailDomainRestrictionEnabled {
  230. allowed := false
  231. for _, domain := range common.EmailDomainWhitelist {
  232. if domainPart == domain {
  233. allowed = true
  234. break
  235. }
  236. }
  237. if !allowed {
  238. c.JSON(http.StatusOK, gin.H{
  239. "success": false,
  240. "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.",
  241. })
  242. return
  243. }
  244. }
  245. if common.EmailAliasRestrictionEnabled {
  246. containsSpecialSymbols := strings.Contains(localPart, "+") || strings.Contains(localPart, ".")
  247. if containsSpecialSymbols {
  248. c.JSON(http.StatusOK, gin.H{
  249. "success": false,
  250. "message": "管理员已启用邮箱地址别名限制,您的邮箱地址由于包含特殊符号而被拒绝。",
  251. })
  252. return
  253. }
  254. }
  255. if model.IsEmailAlreadyTaken(email) {
  256. c.JSON(http.StatusOK, gin.H{
  257. "success": false,
  258. "message": "邮箱地址已被占用",
  259. })
  260. return
  261. }
  262. code := common.GenerateVerificationCode(6)
  263. common.RegisterVerificationCodeWithKey(email, code, common.EmailVerificationPurpose)
  264. subject := fmt.Sprintf("%s邮箱验证邮件", common.SystemName)
  265. content := fmt.Sprintf("<p>您好,你正在进行%s邮箱验证。</p>"+
  266. "<p>您的验证码为: <strong>%s</strong></p>"+
  267. "<p>验证码 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, code, common.VerificationValidMinutes)
  268. err := common.SendEmail(subject, email, content)
  269. if err != nil {
  270. common.ApiError(c, err)
  271. return
  272. }
  273. c.JSON(http.StatusOK, gin.H{
  274. "success": true,
  275. "message": "",
  276. })
  277. return
  278. }
  279. func SendPasswordResetEmail(c *gin.Context) {
  280. email := c.Query("email")
  281. if err := common.Validate.Var(email, "required,email"); err != nil {
  282. c.JSON(http.StatusOK, gin.H{
  283. "success": false,
  284. "message": "无效的参数",
  285. })
  286. return
  287. }
  288. if !model.IsEmailAlreadyTaken(email) {
  289. c.JSON(http.StatusOK, gin.H{
  290. "success": false,
  291. "message": "该邮箱地址未注册",
  292. })
  293. return
  294. }
  295. code := common.GenerateVerificationCode(0)
  296. common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
  297. link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, email, code)
  298. subject := fmt.Sprintf("%s密码重置", common.SystemName)
  299. content := fmt.Sprintf("<p>您好,你正在进行%s密码重置。</p>"+
  300. "<p>点击 <a href='%s'>此处</a> 进行密码重置。</p>"+
  301. "<p>如果链接无法点击,请尝试点击下面的链接或将其复制到浏览器中打开:<br> %s </p>"+
  302. "<p>重置链接 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, link, link, common.VerificationValidMinutes)
  303. err := common.SendEmail(subject, email, content)
  304. if err != nil {
  305. common.ApiError(c, err)
  306. return
  307. }
  308. c.JSON(http.StatusOK, gin.H{
  309. "success": true,
  310. "message": "",
  311. })
  312. return
  313. }
  314. type PasswordResetRequest struct {
  315. Email string `json:"email"`
  316. Token string `json:"token"`
  317. }
  318. func ResetPassword(c *gin.Context) {
  319. var req PasswordResetRequest
  320. err := json.NewDecoder(c.Request.Body).Decode(&req)
  321. if req.Email == "" || req.Token == "" {
  322. c.JSON(http.StatusOK, gin.H{
  323. "success": false,
  324. "message": "无效的参数",
  325. })
  326. return
  327. }
  328. if !common.VerifyCodeWithKey(req.Email, req.Token, common.PasswordResetPurpose) {
  329. c.JSON(http.StatusOK, gin.H{
  330. "success": false,
  331. "message": "重置链接非法或已过期",
  332. })
  333. return
  334. }
  335. password := common.GenerateVerificationCode(12)
  336. err = model.ResetUserPasswordByEmail(req.Email, password)
  337. if err != nil {
  338. common.ApiError(c, err)
  339. return
  340. }
  341. common.DeleteKey(req.Email, common.PasswordResetPurpose)
  342. c.JSON(http.StatusOK, gin.H{
  343. "success": true,
  344. "message": "",
  345. "data": password,
  346. })
  347. return
  348. }