session.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. // SiYuan - Refactor your thinking
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package model
  17. import (
  18. "image/color"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "github.com/88250/gulu"
  26. "github.com/gin-gonic/gin"
  27. "github.com/siyuan-note/logging"
  28. "github.com/siyuan-note/siyuan/kernel/util"
  29. "github.com/steambap/captcha"
  30. )
  31. func LogoutAuth(c *gin.Context) {
  32. ret := gulu.Ret.NewResult()
  33. defer c.JSON(http.StatusOK, ret)
  34. if "" == Conf.AccessAuthCode {
  35. ret.Code = -1
  36. ret.Msg = Conf.Language(86)
  37. ret.Data = map[string]interface{}{"closeTimeout": 5000}
  38. return
  39. }
  40. session := util.GetSession(c)
  41. util.RemoveWorkspaceSession(session)
  42. if err := session.Save(c); nil != err {
  43. logging.LogErrorf("saves session failed: " + err.Error())
  44. ret.Code = -1
  45. ret.Msg = "save session failed"
  46. }
  47. }
  48. func LoginAuth(c *gin.Context) {
  49. ret := gulu.Ret.NewResult()
  50. defer c.JSON(http.StatusOK, ret)
  51. arg, ok := util.JsonArg(c, ret)
  52. if !ok {
  53. return
  54. }
  55. var inputCaptcha string
  56. session := util.GetSession(c)
  57. workspaceSession := util.GetWorkspaceSession(session)
  58. if util.NeedCaptcha() {
  59. captchaArg := arg["captcha"]
  60. if nil == captchaArg {
  61. ret.Code = 1
  62. ret.Msg = Conf.Language(21)
  63. return
  64. }
  65. inputCaptcha = captchaArg.(string)
  66. if "" == inputCaptcha {
  67. ret.Code = 1
  68. ret.Msg = Conf.Language(21)
  69. return
  70. }
  71. if strings.ToLower(workspaceSession.Captcha) != strings.ToLower(inputCaptcha) {
  72. ret.Code = 1
  73. ret.Msg = Conf.Language(22)
  74. return
  75. }
  76. }
  77. authCode := arg["authCode"].(string)
  78. if Conf.AccessAuthCode != authCode {
  79. ret.Code = -1
  80. ret.Msg = Conf.Language(83)
  81. util.WrongAuthCount++
  82. workspaceSession.Captcha = gulu.Rand.String(7)
  83. if util.NeedCaptcha() {
  84. ret.Code = 1 // 需要渲染验证码
  85. }
  86. if err := session.Save(c); nil != err {
  87. logging.LogErrorf("save session failed: " + err.Error())
  88. c.Status(500)
  89. return
  90. }
  91. return
  92. }
  93. workspaceSession.AccessAuthCode = authCode
  94. util.WrongAuthCount = 0
  95. workspaceSession.Captcha = gulu.Rand.String(7)
  96. if err := session.Save(c); nil != err {
  97. logging.LogErrorf("save session failed: " + err.Error())
  98. c.Status(500)
  99. return
  100. }
  101. }
  102. func GetCaptcha(c *gin.Context) {
  103. img, err := captcha.New(100, 26, func(options *captcha.Options) {
  104. options.CharPreset = "ABCDEFGHKLMNPQRSTUVWXYZ23456789"
  105. options.Noise = 0.5
  106. options.CurveNumber = 0
  107. options.BackgroundColor = color.White
  108. })
  109. if nil != err {
  110. logging.LogErrorf("generates captcha failed: " + err.Error())
  111. c.Status(500)
  112. return
  113. }
  114. session := util.GetSession(c)
  115. workspaceSession := util.GetWorkspaceSession(session)
  116. workspaceSession.Captcha = img.Text
  117. if err = session.Save(c); nil != err {
  118. logging.LogErrorf("save session failed: " + err.Error())
  119. c.Status(500)
  120. return
  121. }
  122. if err = img.WriteImage(c.Writer); nil != err {
  123. logging.LogErrorf("writes captcha image failed: " + err.Error())
  124. c.Status(500)
  125. return
  126. }
  127. c.Status(200)
  128. }
  129. func CheckReadonly(c *gin.Context) {
  130. if util.ReadOnly {
  131. result := util.NewResult()
  132. result.Code = -1
  133. result.Msg = Conf.Language(34)
  134. result.Data = map[string]interface{}{"closeTimeout": 5000}
  135. c.JSON(200, result)
  136. c.Abort()
  137. return
  138. }
  139. }
  140. func CheckAuth(c *gin.Context) {
  141. //logging.LogInfof("check auth for [%s]", c.Request.RequestURI)
  142. if "" == Conf.AccessAuthCode {
  143. c.Next()
  144. return
  145. }
  146. // 放过 /appearance/
  147. if strings.HasPrefix(c.Request.RequestURI, "/appearance/") ||
  148. strings.HasPrefix(c.Request.RequestURI, "/stage/build/export/") ||
  149. strings.HasPrefix(c.Request.RequestURI, "/stage/build/fonts/") ||
  150. strings.HasPrefix(c.Request.RequestURI, "/stage/protyle/") {
  151. c.Next()
  152. return
  153. }
  154. // 放过来自本机的某些请求
  155. if strings.HasPrefix(c.Request.RemoteAddr, util.LocalHost) ||
  156. strings.HasPrefix(c.Request.RemoteAddr, "127.0.0.1") ||
  157. strings.HasPrefix(c.Request.RemoteAddr, "[::1]") {
  158. if strings.HasPrefix(c.Request.RequestURI, "/assets/") {
  159. c.Next()
  160. return
  161. }
  162. if strings.HasPrefix(c.Request.RequestURI, "/api/system/exit") {
  163. c.Next()
  164. return
  165. }
  166. }
  167. // 通过 Cookie
  168. session := util.GetSession(c)
  169. workspaceSession := util.GetWorkspaceSession(session)
  170. if workspaceSession.AccessAuthCode == Conf.AccessAuthCode {
  171. c.Next()
  172. return
  173. }
  174. // 通过 API token (header: Authorization)
  175. if authHeader := c.GetHeader("Authorization"); "" != authHeader {
  176. if strings.HasPrefix(authHeader, "Token ") {
  177. token := strings.TrimPrefix(authHeader, "Token ")
  178. if Conf.Api.Token == token {
  179. c.Next()
  180. return
  181. }
  182. c.JSON(401, map[string]interface{}{"code": -1, "msg": "Auth failed"})
  183. c.Abort()
  184. return
  185. }
  186. }
  187. // 通过 API token (query-params: token)
  188. if token := c.Query("token"); "" != token {
  189. if Conf.Api.Token == token {
  190. c.Next()
  191. return
  192. }
  193. c.JSON(401, map[string]interface{}{"code": -1, "msg": "Auth failed"})
  194. c.Abort()
  195. return
  196. }
  197. if "/check-auth" == c.Request.URL.Path { // 跳过访问授权页
  198. c.Next()
  199. return
  200. }
  201. if workspaceSession.AccessAuthCode != Conf.AccessAuthCode {
  202. userAgentHeader := c.GetHeader("User-Agent")
  203. if strings.HasPrefix(userAgentHeader, "SiYuan/") || strings.HasPrefix(userAgentHeader, "Mozilla/") {
  204. if "GET" != c.Request.Method {
  205. c.JSON(401, map[string]interface{}{"code": -1, "msg": Conf.Language(156)})
  206. c.Abort()
  207. return
  208. }
  209. location := url.URL{}
  210. queryParams := url.Values{}
  211. queryParams.Set("to", c.Request.URL.String())
  212. location.RawQuery = queryParams.Encode()
  213. location.Path = "/check-auth"
  214. c.Redirect(302, location.String())
  215. c.Abort()
  216. return
  217. }
  218. c.JSON(401, map[string]interface{}{"code": -1, "msg": "Auth failed"})
  219. c.Abort()
  220. return
  221. }
  222. c.Next()
  223. }
  224. var timingAPIs = map[string]int{
  225. "/api/search/fullTextSearchBlock": 200, // Monitor the search performance and suggest solutions https://github.com/siyuan-note/siyuan/issues/7873
  226. }
  227. func Timing(c *gin.Context) {
  228. p := c.Request.URL.Path
  229. tip, ok := timingAPIs[p]
  230. if !ok {
  231. c.Next()
  232. return
  233. }
  234. timing := 15 * 1000
  235. if timingEnv := os.Getenv("SIYUAN_PERFORMANCE_TIMING"); "" != timingEnv {
  236. val, err := strconv.Atoi(timingEnv)
  237. if nil == err {
  238. timing = val
  239. }
  240. }
  241. now := time.Now().UnixMilli()
  242. c.Next()
  243. elapsed := int(time.Now().UnixMilli() - now)
  244. if timing < elapsed {
  245. logging.LogWarnf("[%s] elapsed [%dms]", c.Request.RequestURI, elapsed)
  246. util.PushMsg(Conf.Language(tip), 7000)
  247. }
  248. }
  249. func Recover(c *gin.Context) {
  250. defer func() {
  251. logging.Recover()
  252. c.Status(500)
  253. }()
  254. c.Next()
  255. }