misc.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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/logger"
  10. "github.com/QuantumNous/new-api/middleware"
  11. "github.com/QuantumNous/new-api/model"
  12. "github.com/QuantumNous/new-api/oauth"
  13. "github.com/QuantumNous/new-api/setting"
  14. "github.com/QuantumNous/new-api/setting/console_setting"
  15. "github.com/QuantumNous/new-api/setting/operation_setting"
  16. "github.com/QuantumNous/new-api/setting/system_setting"
  17. "github.com/gin-gonic/gin"
  18. )
  19. func TestStatus(c *gin.Context) {
  20. err := model.PingDB()
  21. if err != nil {
  22. c.JSON(http.StatusServiceUnavailable, gin.H{
  23. "success": false,
  24. "message": "数据库连接失败",
  25. })
  26. return
  27. }
  28. // 获取HTTP统计信息
  29. httpStats := middleware.GetStats()
  30. c.JSON(http.StatusOK, gin.H{
  31. "success": true,
  32. "message": "Server is running",
  33. "http_stats": httpStats,
  34. })
  35. return
  36. }
  37. func GetStatus(c *gin.Context) {
  38. cs := console_setting.GetConsoleSetting()
  39. common.OptionMapRWMutex.RLock()
  40. defer common.OptionMapRWMutex.RUnlock()
  41. passkeySetting := system_setting.GetPasskeySettings()
  42. legalSetting := system_setting.GetLegalSettings()
  43. data := gin.H{
  44. "version": common.Version,
  45. "start_time": common.StartTime,
  46. "email_verification": common.EmailVerificationEnabled,
  47. "github_oauth": common.GitHubOAuthEnabled,
  48. "github_client_id": common.GitHubClientId,
  49. "discord_oauth": system_setting.GetDiscordSettings().Enabled,
  50. "discord_client_id": system_setting.GetDiscordSettings().ClientId,
  51. "linuxdo_oauth": common.LinuxDOOAuthEnabled,
  52. "linuxdo_client_id": common.LinuxDOClientId,
  53. "linuxdo_minimum_trust_level": common.LinuxDOMinimumTrustLevel,
  54. "telegram_oauth": common.TelegramOAuthEnabled,
  55. "telegram_bot_name": common.TelegramBotName,
  56. "theme": system_setting.GetThemeSettings().Frontend,
  57. "system_name": common.SystemName,
  58. "logo": common.Logo,
  59. "footer_html": common.Footer,
  60. "wechat_qrcode": common.WeChatAccountQRCodeImageURL,
  61. "wechat_login": common.WeChatAuthEnabled,
  62. "server_address": system_setting.ServerAddress,
  63. "turnstile_check": common.TurnstileCheckEnabled,
  64. "turnstile_site_key": common.TurnstileSiteKey,
  65. "top_up_link": common.TopUpLink,
  66. "docs_link": operation_setting.GetGeneralSetting().DocsLink,
  67. "quota_per_unit": common.QuotaPerUnit,
  68. // 兼容旧前端:保留 display_in_currency,同时提供新的 quota_display_type
  69. "display_in_currency": operation_setting.IsCurrencyDisplay(),
  70. "quota_display_type": operation_setting.GetQuotaDisplayType(),
  71. "custom_currency_symbol": operation_setting.GetGeneralSetting().CustomCurrencySymbol,
  72. "custom_currency_exchange_rate": operation_setting.GetGeneralSetting().CustomCurrencyExchangeRate,
  73. "enable_batch_update": common.BatchUpdateEnabled,
  74. "enable_drawing": common.DrawingEnabled,
  75. "enable_task": common.TaskEnabled,
  76. "enable_data_export": common.DataExportEnabled,
  77. "data_export_default_time": common.DataExportDefaultTime,
  78. "default_collapse_sidebar": common.DefaultCollapseSidebar,
  79. "mj_notify_enabled": setting.MjNotifyEnabled,
  80. "chats": setting.Chats,
  81. "demo_site_enabled": operation_setting.DemoSiteEnabled,
  82. "self_use_mode_enabled": operation_setting.SelfUseModeEnabled,
  83. "default_use_auto_group": setting.DefaultUseAutoGroup,
  84. "usd_exchange_rate": operation_setting.USDExchangeRate,
  85. "price": operation_setting.Price,
  86. "stripe_unit_price": setting.StripeUnitPrice,
  87. // 面板启用开关
  88. "api_info_enabled": cs.ApiInfoEnabled,
  89. "uptime_kuma_enabled": cs.UptimeKumaEnabled,
  90. "announcements_enabled": cs.AnnouncementsEnabled,
  91. "faq_enabled": cs.FAQEnabled,
  92. // 模块管理配置
  93. "HeaderNavModules": common.OptionMap["HeaderNavModules"],
  94. "SidebarModulesAdmin": common.OptionMap["SidebarModulesAdmin"],
  95. "oidc_enabled": system_setting.GetOIDCSettings().Enabled,
  96. "oidc_client_id": system_setting.GetOIDCSettings().ClientId,
  97. "oidc_authorization_endpoint": system_setting.GetOIDCSettings().AuthorizationEndpoint,
  98. "passkey_login": passkeySetting.Enabled,
  99. "passkey_display_name": passkeySetting.RPDisplayName,
  100. "passkey_rp_id": passkeySetting.RPID,
  101. "passkey_origins": passkeySetting.Origins,
  102. "passkey_allow_insecure": passkeySetting.AllowInsecureOrigin,
  103. "passkey_user_verification": passkeySetting.UserVerification,
  104. "passkey_attachment": passkeySetting.AttachmentPreference,
  105. "setup": constant.Setup,
  106. "user_agreement_enabled": legalSetting.UserAgreement != "",
  107. "privacy_policy_enabled": legalSetting.PrivacyPolicy != "",
  108. "checkin_enabled": operation_setting.GetCheckinSetting().Enabled,
  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. code := common.GenerateVerificationCode(0)
  290. common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
  291. link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, email, code)
  292. subject := fmt.Sprintf("%s密码重置", common.SystemName)
  293. content := fmt.Sprintf("<p>您好,你正在进行%s密码重置。</p>"+
  294. "<p>点击 <a href='%s'>此处</a> 进行密码重置。</p>"+
  295. "<p>如果链接无法点击,请尝试点击下面的链接或将其复制到浏览器中打开:<br> %s </p>"+
  296. "<p>重置链接 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, link, link, common.VerificationValidMinutes)
  297. err := common.SendEmail(subject, email, content)
  298. if err != nil {
  299. logger.LogError(c.Request.Context(), fmt.Sprintf("failed to send password reset email to %s: %s", email, err.Error()))
  300. }
  301. }
  302. c.JSON(http.StatusOK, gin.H{
  303. "success": true,
  304. "message": "",
  305. })
  306. }
  307. type PasswordResetRequest struct {
  308. Email string `json:"email"`
  309. Token string `json:"token"`
  310. }
  311. func ResetPassword(c *gin.Context) {
  312. var req PasswordResetRequest
  313. err := json.NewDecoder(c.Request.Body).Decode(&req)
  314. if req.Email == "" || req.Token == "" {
  315. c.JSON(http.StatusOK, gin.H{
  316. "success": false,
  317. "message": "无效的参数",
  318. })
  319. return
  320. }
  321. if !common.VerifyCodeWithKey(req.Email, req.Token, common.PasswordResetPurpose) {
  322. c.JSON(http.StatusOK, gin.H{
  323. "success": false,
  324. "message": "重置链接非法或已过期",
  325. })
  326. return
  327. }
  328. password := common.GenerateVerificationCode(12)
  329. err = model.ResetUserPasswordByEmail(req.Email, password)
  330. if err != nil {
  331. common.ApiError(c, err)
  332. return
  333. }
  334. common.DeleteKey(req.Email, common.PasswordResetPurpose)
  335. c.JSON(http.StatusOK, gin.H{
  336. "success": true,
  337. "message": "",
  338. "data": password,
  339. })
  340. return
  341. }