session.go 12 KB

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