Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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