1
0

misc.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "one-api/common"
  7. "one-api/constant"
  8. "one-api/middleware"
  9. "one-api/model"
  10. "one-api/setting"
  11. "one-api/setting/console_setting"
  12. "one-api/setting/operation_setting"
  13. "one-api/setting/system_setting"
  14. "strings"
  15. "github.com/gin-gonic/gin"
  16. )
  17. func TestStatus(c *gin.Context) {
  18. err := model.PingDB()
  19. if err != nil {
  20. c.JSON(http.StatusServiceUnavailable, gin.H{
  21. "success": false,
  22. "message": "数据库连接失败",
  23. })
  24. return
  25. }
  26. // 获取HTTP统计信息
  27. httpStats := middleware.GetStats()
  28. c.JSON(http.StatusOK, gin.H{
  29. "success": true,
  30. "message": "Server is running",
  31. "http_stats": httpStats,
  32. })
  33. return
  34. }
  35. func GetStatus(c *gin.Context) {
  36. cs := console_setting.GetConsoleSetting()
  37. data := gin.H{
  38. "version": common.Version,
  39. "start_time": common.StartTime,
  40. "email_verification": common.EmailVerificationEnabled,
  41. "github_oauth": common.GitHubOAuthEnabled,
  42. "github_client_id": common.GitHubClientId,
  43. "linuxdo_oauth": common.LinuxDOOAuthEnabled,
  44. "linuxdo_client_id": common.LinuxDOClientId,
  45. "telegram_oauth": common.TelegramOAuthEnabled,
  46. "telegram_bot_name": common.TelegramBotName,
  47. "system_name": common.SystemName,
  48. "logo": common.Logo,
  49. "footer_html": common.Footer,
  50. "wechat_qrcode": common.WeChatAccountQRCodeImageURL,
  51. "wechat_login": common.WeChatAuthEnabled,
  52. "server_address": setting.ServerAddress,
  53. "price": setting.Price,
  54. "stripe_unit_price": setting.StripeUnitPrice,
  55. "min_topup": setting.MinTopUp,
  56. "stripe_min_topup": setting.StripeMinTopUp,
  57. "turnstile_check": common.TurnstileCheckEnabled,
  58. "turnstile_site_key": common.TurnstileSiteKey,
  59. "top_up_link": common.TopUpLink,
  60. "docs_link": operation_setting.GetGeneralSetting().DocsLink,
  61. "quota_per_unit": common.QuotaPerUnit,
  62. "display_in_currency": common.DisplayInCurrencyEnabled,
  63. "enable_batch_update": common.BatchUpdateEnabled,
  64. "enable_drawing": common.DrawingEnabled,
  65. "enable_task": common.TaskEnabled,
  66. "enable_data_export": common.DataExportEnabled,
  67. "data_export_default_time": common.DataExportDefaultTime,
  68. "default_collapse_sidebar": common.DefaultCollapseSidebar,
  69. "enable_online_topup": setting.PayAddress != "" && setting.EpayId != "" && setting.EpayKey != "",
  70. "enable_stripe_topup": setting.StripeApiSecret != "" && setting.StripeWebhookSecret != "" && setting.StripePriceId != "",
  71. "mj_notify_enabled": setting.MjNotifyEnabled,
  72. "chats": setting.Chats,
  73. "demo_site_enabled": operation_setting.DemoSiteEnabled,
  74. "self_use_mode_enabled": operation_setting.SelfUseModeEnabled,
  75. "default_use_auto_group": setting.DefaultUseAutoGroup,
  76. "pay_methods": setting.PayMethods,
  77. "usd_exchange_rate": setting.USDExchangeRate,
  78. // 面板启用开关
  79. "api_info_enabled": cs.ApiInfoEnabled,
  80. "uptime_kuma_enabled": cs.UptimeKumaEnabled,
  81. "announcements_enabled": cs.AnnouncementsEnabled,
  82. "faq_enabled": cs.FAQEnabled,
  83. "oidc_enabled": system_setting.GetOIDCSettings().Enabled,
  84. "oidc_client_id": system_setting.GetOIDCSettings().ClientId,
  85. "oidc_authorization_endpoint": system_setting.GetOIDCSettings().AuthorizationEndpoint,
  86. "setup": constant.Setup,
  87. }
  88. // 根据启用状态注入可选内容
  89. if cs.ApiInfoEnabled {
  90. data["api_info"] = console_setting.GetApiInfo()
  91. }
  92. if cs.AnnouncementsEnabled {
  93. data["announcements"] = console_setting.GetAnnouncements()
  94. }
  95. if cs.FAQEnabled {
  96. data["faq"] = console_setting.GetFAQ()
  97. }
  98. c.JSON(http.StatusOK, gin.H{
  99. "success": true,
  100. "message": "",
  101. "data": data,
  102. })
  103. return
  104. }
  105. func GetNotice(c *gin.Context) {
  106. common.OptionMapRWMutex.RLock()
  107. defer common.OptionMapRWMutex.RUnlock()
  108. c.JSON(http.StatusOK, gin.H{
  109. "success": true,
  110. "message": "",
  111. "data": common.OptionMap["Notice"],
  112. })
  113. return
  114. }
  115. func GetAbout(c *gin.Context) {
  116. common.OptionMapRWMutex.RLock()
  117. defer common.OptionMapRWMutex.RUnlock()
  118. c.JSON(http.StatusOK, gin.H{
  119. "success": true,
  120. "message": "",
  121. "data": common.OptionMap["About"],
  122. })
  123. return
  124. }
  125. func GetMidjourney(c *gin.Context) {
  126. common.OptionMapRWMutex.RLock()
  127. defer common.OptionMapRWMutex.RUnlock()
  128. c.JSON(http.StatusOK, gin.H{
  129. "success": true,
  130. "message": "",
  131. "data": common.OptionMap["Midjourney"],
  132. })
  133. return
  134. }
  135. func GetHomePageContent(c *gin.Context) {
  136. common.OptionMapRWMutex.RLock()
  137. defer common.OptionMapRWMutex.RUnlock()
  138. c.JSON(http.StatusOK, gin.H{
  139. "success": true,
  140. "message": "",
  141. "data": common.OptionMap["HomePageContent"],
  142. })
  143. return
  144. }
  145. func SendEmailVerification(c *gin.Context) {
  146. email := c.Query("email")
  147. if err := common.Validate.Var(email, "required,email"); err != nil {
  148. c.JSON(http.StatusOK, gin.H{
  149. "success": false,
  150. "message": "无效的参数",
  151. })
  152. return
  153. }
  154. parts := strings.Split(email, "@")
  155. if len(parts) != 2 {
  156. c.JSON(http.StatusOK, gin.H{
  157. "success": false,
  158. "message": "无效的邮箱地址",
  159. })
  160. return
  161. }
  162. localPart := parts[0]
  163. domainPart := parts[1]
  164. if common.EmailDomainRestrictionEnabled {
  165. allowed := false
  166. for _, domain := range common.EmailDomainWhitelist {
  167. if domainPart == domain {
  168. allowed = true
  169. break
  170. }
  171. }
  172. if !allowed {
  173. c.JSON(http.StatusOK, gin.H{
  174. "success": false,
  175. "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.",
  176. })
  177. return
  178. }
  179. }
  180. if common.EmailAliasRestrictionEnabled {
  181. containsSpecialSymbols := strings.Contains(localPart, "+") || strings.Contains(localPart, ".")
  182. if containsSpecialSymbols {
  183. c.JSON(http.StatusOK, gin.H{
  184. "success": false,
  185. "message": "管理员已启用邮箱地址别名限制,您的邮箱地址由于包含特殊符号而被拒绝。",
  186. })
  187. return
  188. }
  189. }
  190. if model.IsEmailAlreadyTaken(email) {
  191. c.JSON(http.StatusOK, gin.H{
  192. "success": false,
  193. "message": "邮箱地址已被占用",
  194. })
  195. return
  196. }
  197. code := common.GenerateVerificationCode(6)
  198. common.RegisterVerificationCodeWithKey(email, code, common.EmailVerificationPurpose)
  199. subject := fmt.Sprintf("%s邮箱验证邮件", common.SystemName)
  200. content := fmt.Sprintf("<p>您好,你正在进行%s邮箱验证。</p>"+
  201. "<p>您的验证码为: <strong>%s</strong></p>"+
  202. "<p>验证码 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, code, common.VerificationValidMinutes)
  203. err := common.SendEmail(subject, email, content)
  204. if err != nil {
  205. common.ApiError(c, err)
  206. return
  207. }
  208. c.JSON(http.StatusOK, gin.H{
  209. "success": true,
  210. "message": "",
  211. })
  212. return
  213. }
  214. func SendPasswordResetEmail(c *gin.Context) {
  215. email := c.Query("email")
  216. if err := common.Validate.Var(email, "required,email"); err != nil {
  217. c.JSON(http.StatusOK, gin.H{
  218. "success": false,
  219. "message": "无效的参数",
  220. })
  221. return
  222. }
  223. if !model.IsEmailAlreadyTaken(email) {
  224. c.JSON(http.StatusOK, gin.H{
  225. "success": false,
  226. "message": "该邮箱地址未注册",
  227. })
  228. return
  229. }
  230. code := common.GenerateVerificationCode(0)
  231. common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
  232. link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", setting.ServerAddress, email, code)
  233. subject := fmt.Sprintf("%s密码重置", common.SystemName)
  234. content := fmt.Sprintf("<p>您好,你正在进行%s密码重置。</p>"+
  235. "<p>点击 <a href='%s'>此处</a> 进行密码重置。</p>"+
  236. "<p>如果链接无法点击,请尝试点击下面的链接或将其复制到浏览器中打开:<br> %s </p>"+
  237. "<p>重置链接 %d 分钟内有效,如果不是本人操作,请忽略。</p>", common.SystemName, link, link, common.VerificationValidMinutes)
  238. err := common.SendEmail(subject, email, content)
  239. if err != nil {
  240. common.ApiError(c, err)
  241. return
  242. }
  243. c.JSON(http.StatusOK, gin.H{
  244. "success": true,
  245. "message": "",
  246. })
  247. return
  248. }
  249. type PasswordResetRequest struct {
  250. Email string `json:"email"`
  251. Token string `json:"token"`
  252. }
  253. func ResetPassword(c *gin.Context) {
  254. var req PasswordResetRequest
  255. err := json.NewDecoder(c.Request.Body).Decode(&req)
  256. if req.Email == "" || req.Token == "" {
  257. c.JSON(http.StatusOK, gin.H{
  258. "success": false,
  259. "message": "无效的参数",
  260. })
  261. return
  262. }
  263. if !common.VerifyCodeWithKey(req.Email, req.Token, common.PasswordResetPurpose) {
  264. c.JSON(http.StatusOK, gin.H{
  265. "success": false,
  266. "message": "重置链接非法或已过期",
  267. })
  268. return
  269. }
  270. password := common.GenerateVerificationCode(12)
  271. err = model.ResetUserPasswordByEmail(req.Email, password)
  272. if err != nil {
  273. common.ApiError(c, err)
  274. return
  275. }
  276. common.DeleteKey(req.Email, common.PasswordResetPurpose)
  277. c.JSON(http.StatusOK, gin.H{
  278. "success": true,
  279. "message": "",
  280. "data": password,
  281. })
  282. return
  283. }