session.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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. "sync"
  25. "time"
  26. "github.com/88250/gulu"
  27. "github.com/gin-gonic/gin"
  28. "github.com/gorilla/websocket"
  29. "github.com/siyuan-note/logging"
  30. "github.com/siyuan-note/siyuan/kernel/util"
  31. "github.com/steambap/captcha"
  32. )
  33. func LogoutAuth(c *gin.Context) {
  34. ret := gulu.Ret.NewResult()
  35. defer c.JSON(http.StatusOK, ret)
  36. if "" == Conf.AccessAuthCode {
  37. ret.Code = -1
  38. ret.Msg = Conf.Language(86)
  39. ret.Data = map[string]interface{}{"closeTimeout": 5000}
  40. return
  41. }
  42. session := util.GetSession(c)
  43. util.RemoveWorkspaceSession(session)
  44. if err := session.Save(c); nil != err {
  45. logging.LogErrorf("saves session failed: " + err.Error())
  46. ret.Code = -1
  47. ret.Msg = "save session failed"
  48. }
  49. }
  50. func LoginAuth(c *gin.Context) {
  51. ret := gulu.Ret.NewResult()
  52. defer c.JSON(http.StatusOK, ret)
  53. arg, ok := util.JsonArg(c, ret)
  54. if !ok {
  55. return
  56. }
  57. var inputCaptcha string
  58. session := util.GetSession(c)
  59. workspaceSession := util.GetWorkspaceSession(session)
  60. if util.NeedCaptcha() {
  61. captchaArg := arg["captcha"]
  62. if nil == captchaArg {
  63. ret.Code = 1
  64. ret.Msg = Conf.Language(21)
  65. logging.LogWarnf("invalid captcha")
  66. return
  67. }
  68. inputCaptcha = captchaArg.(string)
  69. if "" == inputCaptcha {
  70. ret.Code = 1
  71. ret.Msg = Conf.Language(21)
  72. logging.LogWarnf("invalid captcha")
  73. return
  74. }
  75. if strings.ToLower(workspaceSession.Captcha) != strings.ToLower(inputCaptcha) {
  76. ret.Code = 1
  77. ret.Msg = Conf.Language(22)
  78. logging.LogWarnf("invalid captcha")
  79. return
  80. }
  81. }
  82. authCode := arg["authCode"].(string)
  83. if Conf.AccessAuthCode != authCode {
  84. ret.Code = -1
  85. ret.Msg = Conf.Language(83)
  86. logging.LogWarnf("invalid auth code [ip=%s]", util.GetRemoteAddr(c.Request))
  87. util.WrongAuthCount++
  88. workspaceSession.Captcha = gulu.Rand.String(7)
  89. if util.NeedCaptcha() {
  90. ret.Code = 1 // 需要渲染验证码
  91. }
  92. if err := session.Save(c); nil != err {
  93. logging.LogErrorf("save session failed: " + err.Error())
  94. c.Status(http.StatusInternalServerError)
  95. return
  96. }
  97. return
  98. }
  99. workspaceSession.AccessAuthCode = authCode
  100. util.WrongAuthCount = 0
  101. workspaceSession.Captcha = gulu.Rand.String(7)
  102. logging.LogInfof("auth success [ip=%s]", util.GetRemoteAddr(c.Request))
  103. if err := session.Save(c); nil != err {
  104. logging.LogErrorf("save session failed: " + err.Error())
  105. c.Status(http.StatusInternalServerError)
  106. return
  107. }
  108. }
  109. func GetCaptcha(c *gin.Context) {
  110. img, err := captcha.New(100, 26, func(options *captcha.Options) {
  111. options.CharPreset = "ABCDEFGHKLMNPQRSTUVWXYZ23456789"
  112. options.Noise = 0.5
  113. options.CurveNumber = 0
  114. options.BackgroundColor = color.White
  115. })
  116. if nil != err {
  117. logging.LogErrorf("generates captcha failed: " + err.Error())
  118. c.Status(http.StatusInternalServerError)
  119. return
  120. }
  121. session := util.GetSession(c)
  122. workspaceSession := util.GetWorkspaceSession(session)
  123. workspaceSession.Captcha = img.Text
  124. if err = session.Save(c); nil != err {
  125. logging.LogErrorf("save session failed: " + err.Error())
  126. c.Status(http.StatusInternalServerError)
  127. return
  128. }
  129. if err = img.WriteImage(c.Writer); nil != err {
  130. logging.LogErrorf("writes captcha image failed: " + err.Error())
  131. c.Status(http.StatusInternalServerError)
  132. return
  133. }
  134. c.Status(http.StatusOK)
  135. }
  136. func CheckReadonly(c *gin.Context) {
  137. if util.ReadOnly {
  138. result := util.NewResult()
  139. result.Code = -1
  140. result.Msg = Conf.Language(34)
  141. result.Data = map[string]interface{}{"closeTimeout": 5000}
  142. c.JSON(http.StatusOK, result)
  143. c.Abort()
  144. return
  145. }
  146. }
  147. func CheckAuth(c *gin.Context) {
  148. // 已通过 JWT 认证
  149. if role := GetGinContextRole(c); IsValidRole(role, []Role{
  150. RoleAdministrator,
  151. RoleEditor,
  152. RoleReader,
  153. }) {
  154. c.Next()
  155. return
  156. }
  157. //logging.LogInfof("check auth for [%s]", c.Request.RequestURI)
  158. localhost := util.IsLocalHost(c.Request.RemoteAddr)
  159. // 未设置访问授权码
  160. if "" == Conf.AccessAuthCode {
  161. // Skip the empty access authorization code check https://github.com/siyuan-note/siyuan/issues/9709
  162. if util.SiyuanAccessAuthCodeBypass {
  163. c.Set(RoleContextKey, RoleAdministrator)
  164. c.Next()
  165. return
  166. }
  167. // Authenticate requests with the Origin header other than 127.0.0.1 https://github.com/siyuan-note/siyuan/issues/9180
  168. clientIP := c.ClientIP()
  169. host := c.GetHeader("Host")
  170. origin := c.GetHeader("Origin")
  171. forwardedHost := c.GetHeader("X-Forwarded-Host")
  172. if !localhost ||
  173. ("" != clientIP && !util.IsLocalHostname(clientIP)) ||
  174. ("" != host && !util.IsLocalHost(host)) ||
  175. ("" != origin && !util.IsLocalOrigin(origin) && !strings.HasPrefix(origin, "chrome-extension://")) ||
  176. ("" != forwardedHost && !util.IsLocalHost(forwardedHost)) {
  177. c.JSON(http.StatusUnauthorized, map[string]interface{}{"code": -1, "msg": "Auth failed: for security reasons, please set [Access authorization code] when using non-127.0.0.1 access\n\n为安全起见,使用非 127.0.0.1 访问时请设置 [访问授权码]"})
  178. c.Abort()
  179. return
  180. }
  181. c.Set(RoleContextKey, RoleAdministrator)
  182. c.Next()
  183. return
  184. }
  185. // 放过 /appearance/
  186. if strings.HasPrefix(c.Request.RequestURI, "/appearance/") ||
  187. strings.HasPrefix(c.Request.RequestURI, "/stage/build/export/") ||
  188. strings.HasPrefix(c.Request.RequestURI, "/stage/build/fonts/") ||
  189. strings.HasPrefix(c.Request.RequestURI, "/stage/protyle/") {
  190. c.Next()
  191. return
  192. }
  193. // 放过来自本机的某些请求
  194. if localhost {
  195. if strings.HasPrefix(c.Request.RequestURI, "/assets/") {
  196. c.Set(RoleContextKey, RoleAdministrator)
  197. c.Next()
  198. return
  199. }
  200. if strings.HasPrefix(c.Request.RequestURI, "/api/system/exit") {
  201. c.Set(RoleContextKey, RoleAdministrator)
  202. c.Next()
  203. return
  204. }
  205. if strings.HasPrefix(c.Request.RequestURI, "/api/system/getNetwork") {
  206. c.Set(RoleContextKey, RoleAdministrator)
  207. c.Next()
  208. return
  209. }
  210. if strings.HasPrefix(c.Request.RequestURI, "/api/sync/performSync") {
  211. if util.ContainerIOS == util.Container || util.ContainerAndroid == util.Container {
  212. c.Set(RoleContextKey, RoleAdministrator)
  213. c.Next()
  214. return
  215. }
  216. }
  217. }
  218. // 通过 Cookie
  219. session := util.GetSession(c)
  220. workspaceSession := util.GetWorkspaceSession(session)
  221. if workspaceSession.AccessAuthCode == Conf.AccessAuthCode {
  222. c.Set(RoleContextKey, RoleAdministrator)
  223. c.Next()
  224. return
  225. }
  226. // 通过 API token (header: Authorization)
  227. if authHeader := c.GetHeader("Authorization"); "" != authHeader {
  228. var token string
  229. if strings.HasPrefix(authHeader, "Token ") {
  230. token = strings.TrimPrefix(authHeader, "Token ")
  231. } else if strings.HasPrefix(authHeader, "token ") {
  232. token = strings.TrimPrefix(authHeader, "token ")
  233. } else if strings.HasPrefix(authHeader, "Bearer ") {
  234. token = strings.TrimPrefix(authHeader, "Bearer ")
  235. } else if strings.HasPrefix(authHeader, "bearer ") {
  236. token = strings.TrimPrefix(authHeader, "bearer ")
  237. }
  238. if "" != token {
  239. if Conf.Api.Token == token {
  240. c.Set(RoleContextKey, RoleAdministrator)
  241. c.Next()
  242. return
  243. }
  244. c.JSON(http.StatusUnauthorized, map[string]interface{}{"code": -1, "msg": "Auth failed [header: Authorization]"})
  245. c.Abort()
  246. return
  247. }
  248. }
  249. // 通过 API token (query-params: token)
  250. if token := c.Query("token"); "" != token {
  251. if Conf.Api.Token == token {
  252. c.Set(RoleContextKey, RoleAdministrator)
  253. c.Next()
  254. return
  255. }
  256. c.JSON(http.StatusUnauthorized, map[string]interface{}{"code": -1, "msg": "Auth failed [query: token]"})
  257. c.Abort()
  258. return
  259. }
  260. if "/check-auth" == c.Request.URL.Path { // 跳过访问授权页
  261. c.Next()
  262. return
  263. }
  264. if workspaceSession.AccessAuthCode != Conf.AccessAuthCode {
  265. userAgentHeader := c.GetHeader("User-Agent")
  266. if strings.HasPrefix(userAgentHeader, "SiYuan/") || strings.HasPrefix(userAgentHeader, "Mozilla/") {
  267. if "GET" != c.Request.Method || c.IsWebsocket() {
  268. c.JSON(http.StatusUnauthorized, map[string]interface{}{"code": -1, "msg": Conf.Language(156)})
  269. c.Abort()
  270. return
  271. }
  272. location := url.URL{}
  273. queryParams := url.Values{}
  274. queryParams.Set("to", c.Request.URL.String())
  275. location.RawQuery = queryParams.Encode()
  276. location.Path = "/check-auth"
  277. c.Redirect(http.StatusFound, location.String())
  278. c.Abort()
  279. return
  280. }
  281. c.JSON(http.StatusUnauthorized, map[string]interface{}{"code": -1, "msg": "Auth failed [session]"})
  282. c.Abort()
  283. return
  284. }
  285. c.Set(RoleContextKey, RoleAdministrator)
  286. c.Next()
  287. }
  288. func CheckAdminRole(c *gin.Context) {
  289. if IsValidRole(GetGinContextRole(c), []Role{
  290. RoleAdministrator,
  291. }) {
  292. c.Next()
  293. } else {
  294. c.AbortWithStatus(http.StatusForbidden)
  295. }
  296. }
  297. func CheckEditRole(c *gin.Context) {
  298. if IsValidRole(GetGinContextRole(c), []Role{
  299. RoleAdministrator,
  300. RoleEditor,
  301. }) {
  302. c.Next()
  303. } else {
  304. c.AbortWithStatus(http.StatusForbidden)
  305. }
  306. }
  307. func CheckReadRole(c *gin.Context) {
  308. if IsValidRole(GetGinContextRole(c), []Role{
  309. RoleAdministrator,
  310. RoleEditor,
  311. RoleReader,
  312. }) {
  313. c.Next()
  314. } else {
  315. c.AbortWithStatus(http.StatusForbidden)
  316. }
  317. }
  318. var timingAPIs = map[string]int{
  319. "/api/search/fullTextSearchBlock": 200, // Monitor the search performance and suggest solutions https://github.com/siyuan-note/siyuan/issues/7873
  320. }
  321. func Timing(c *gin.Context) {
  322. p := c.Request.URL.Path
  323. tip, ok := timingAPIs[p]
  324. if !ok {
  325. c.Next()
  326. return
  327. }
  328. timing := 15 * 1000
  329. if timingEnv := os.Getenv("SIYUAN_PERFORMANCE_TIMING"); "" != timingEnv {
  330. val, err := strconv.Atoi(timingEnv)
  331. if nil == err {
  332. timing = val
  333. }
  334. }
  335. now := time.Now().UnixMilli()
  336. c.Next()
  337. elapsed := int(time.Now().UnixMilli() - now)
  338. if timing < elapsed {
  339. logging.LogWarnf("[%s] elapsed [%dms]", c.Request.RequestURI, elapsed)
  340. util.PushMsg(Conf.Language(tip), 7000)
  341. }
  342. }
  343. func Recover(c *gin.Context) {
  344. defer func() {
  345. logging.Recover()
  346. c.Status(http.StatusInternalServerError)
  347. }()
  348. c.Next()
  349. }
  350. var (
  351. requestingLock = sync.Mutex{}
  352. requesting = map[string]*sync.Mutex{}
  353. )
  354. func ControlConcurrency(c *gin.Context) {
  355. if websocket.IsWebSocketUpgrade(c.Request) {
  356. c.Next()
  357. return
  358. }
  359. reqPath := c.Request.URL.Path
  360. // Improve the concurrency of the kernel data reading interfaces https://github.com/siyuan-note/siyuan/issues/10149
  361. if strings.HasPrefix(reqPath, "/stage/") || strings.HasPrefix(reqPath, "/assets/") || strings.HasPrefix(reqPath, "/appearance/") {
  362. c.Next()
  363. return
  364. }
  365. parts := strings.Split(reqPath, "/")
  366. function := parts[len(parts)-1]
  367. if strings.HasPrefix(function, "get") || strings.HasPrefix(function, "list") ||
  368. strings.HasPrefix(function, "search") || strings.HasPrefix(function, "render") || strings.HasPrefix(function, "ls") {
  369. c.Next()
  370. return
  371. }
  372. if strings.HasPrefix(function, "/api/query/") || strings.HasPrefix(function, "/api/search/") {
  373. c.Next()
  374. return
  375. }
  376. requestingLock.Lock()
  377. mutex := requesting[reqPath]
  378. if nil == mutex {
  379. mutex = &sync.Mutex{}
  380. requesting[reqPath] = mutex
  381. }
  382. requestingLock.Unlock()
  383. mutex.Lock()
  384. defer mutex.Unlock()
  385. c.Next()
  386. }