4 (c) 2008 Steven Barth <steven@midlink.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
16 --- LuCI session library.
17 module("luci.sauth", package.seeall)
20 require("luci.config")
21 local nixio = require "nixio", require "nixio.util"
22 local fs = require "nixio.fs"
25 luci.config.sauth = luci.config.sauth or {}
26 sessionpath = luci.config.sauth.sessionpath
27 sessiontime = tonumber(luci.config.sauth.sessiontime) or 15 * 60
29 --- Prepare session storage by creating the session directory.
31 fs.mkdir(sessionpath, 700)
33 error("Security Exception: Session path is not sane!")
37 local function _read(id)
38 local blob = fs.readfile(sessionpath .. "/" .. id)
42 local function _write(id, data)
43 local f = nixio.open(sessionpath .. "/" .. id, "w", 600)
48 local function _checkid(id)
49 return not not (id and #id == 32 and id:match("^[a-fA-F0-9]+$"))
52 --- Write session data to a session file.
53 -- @param id Session identifier
54 -- @param data Session data table
55 function write(id, data)
60 assert(_checkid(id), "Security Exception: Session ID is invalid!")
61 assert(type(data) == "table", "Security Exception: Session data invalid!")
63 data.atime = luci.sys.uptime()
65 _write(id, luci.util.get_bytecode(data))
68 --- Read a session and return its content.
69 -- @param id Session identifier
70 -- @return Session data table or nil if the given id is not found
72 if not id or #id == 0 then
76 assert(_checkid(id), "Security Exception: Session ID is invalid!")
78 if not sane(sessionpath .. "/" .. id) then
82 local blob = _read(id)
83 local func = loadstring(blob)
87 assert(type(sess) == "table", "Session data invalid!")
89 if sess.atime and sess.atime + sessiontime < luci.sys.uptime() then
94 -- refresh atime in session
100 --- Check whether Session environment is sane.
101 -- @return Boolean status
103 return luci.sys.process.info("uid")
104 == fs.stat(file or sessionpath, "uid")
105 and fs.stat(file or sessionpath, "modestr")
106 == (file and "rw-------" or "rwx------")
110 -- @param id Session identifier
112 assert(_checkid(id), "Security Exception: Session ID is invalid!")
113 fs.unlink(sessionpath .. "/" .. id)
116 --- Remove all expired session data files
120 for id in nixio.fs.dir(sessionpath) do
122 -- reading the session will kill it if it is expired