d25f287c5a030095a43a73171eb5c0ba7d387e5b
[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.config")
21
22
23 luci.config.sauth = luci.config.sauth or {}
24 sessionpath = luci.config.sauth.sessionpath
25 sessiontime = tonumber(luci.config.sauth.sessiontime)
26
27 --- Manually clean up expired sessions.
28 function clean()
29         local now   = os.time()
30         local files = luci.fs.dir(sessionpath)
31         
32         if not files then
33                 return nil
34         end
35         
36         for i, file in pairs(files) do
37                 local fname = sessionpath .. "/" .. file
38                 local stat = luci.fs.stat(fname)
39                 if stat and stat.type == "regular" and stat.atime + sessiontime < now then
40                         luci.fs.unlink(fname)
41                 end 
42         end
43 end
44
45 --- Prepare session storage by creating the session directory.
46 function prepare()
47         luci.fs.mkdir(sessionpath)
48         luci.fs.chmod(sessionpath, "a-rwx,u+rwx")
49 end
50
51 --- Read a session and return its content.
52 -- @param id    Session identifier
53 -- @return              Session data
54 function read(id)
55         if not id then
56                 return
57         end
58         clean()
59         return luci.fs.readfile(sessionpath .. "/" .. id)
60 end
61
62
63 --- Write session data to a session file.
64 -- @param id    Session identifier
65 -- @param data  Session data
66 function write(id, data)
67         if not luci.fs.stat(sessionpath) then
68                 prepare()
69         end
70         luci.fs.writefile(sessionpath .. "/" .. id, data)
71         luci.fs.chmod(sessionpath .. "/" .. id, "a-rwx,u+rw")
72 end