misc.go 12 KB

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