Extend CBI state handling
[project/luci.git] / libs / web / luasrc / sauth.lua
1 --[[
2
3 Session authentication
4 (c) 2008 Steven Barth <steven@midlink.org>
5
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
9
10         http://www.apache.org/licenses/LICENSE-2.0
11
12 $Id$
13
14 ]]--
15
16 --- LuCI session library.
17 module("luci.sauth", package.seeall)
18 require("luci.fs")
19 require("luci.util")
20 require("luci.sys")
21 require("luci.config")
22
23
24 luci.config.sauth = luci.config.sauth or {}
25 sessionpath = luci.config.sauth.sessionpath
26 sessiontime = tonumber(luci.config.sauth.sessiontime) or 15 * 60
27
28 --- Manually clean up expired sessions.
29 function clean()
30         local now   = os.time()
31         local files = luci.fs.dir(sessionpath)
32         
33         if not files then
34                 return nil
35         end
36         
37         for i, file in pairs(files) do
38                 local fname = sessionpath .. "/" .. file
39                 local stat = luci.fs.stat(fname)
40                 if stat and stat.type == "regular" and stat.atime + sessiontime < now then
41                         luci.fs.unlink(fname)
42                 end 
43         end
44 end
45
46 --- Prepare session storage by creating the session directory.
47 function prepare()
48         luci.fs.mkdir(sessionpath)
49         luci.fs.chmod(sessionpath, "a-rwx,u+rwx")
50          
51         if not sane() then
52                 error("Security Exception: Session path is not sane!")
53         end
54 end
55
56 --- Read a session and return its content.
57 -- @param id    Session identifier
58 -- @return              Session data
59 function read(id)
60         if not id then
61                 return
62         end
63         clean()
64         if not sane(sessionpath .. "/" .. id) then
65                 return
66         end
67         return luci.fs.readfile(sessionpath .. "/" .. id)
68 end
69
70
71 --- Check whether Session environment is sane.
72 -- @return Boolean status
73 function sane(file)
74         return luci.sys.process.info("uid")
75                         == luci.fs.stat(file or sessionpath, "uid")
76                 and luci.fs.stat(file or sessionpath, "mode")
77                         == (file and "rw-------" or "rwx------")
78 end
79
80
81 --- Write session data to a session file.
82 -- @param id    Session identifier
83 -- @param data  Session data
84 function write(id, data)
85         if not sane() then
86                 prepare()
87         end
88         luci.fs.writefile(sessionpath .. "/" .. id, data)
89         luci.fs.chmod(sessionpath .. "/" .. id, "a-rwx,u+rw")
90 end