misc.go 8.8 KB

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