fc4942b97e8d969e2f9faa7784b9967732224742
[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 module("luci.sauth", package.seeall)
16 require("luci.fs")
17 require("luci.util")
18 require("luci.config")
19
20
21 luci.config.sauth = luci.config.sauth or {}
22 sessionpath = luci.config.sauth.sessionpath
23 sessiontime = tonumber(luci.config.sauth.sessiontime)
24
25
26 function clean()
27         local now   = os.time()
28         local files = luci.fs.dir(sessionpath)
29         
30         if not files then
31                 return nil
32         end
33         
34         for i, file in pairs(files) do
35                 local fname = sessionpath .. "/" .. file
36                 local stat = luci.fs.stat(fname)
37                 if stat and stat.type == "regular" and stat.atime + sessiontime < now then
38                         luci.fs.unlink(fname)
39                 end 
40         end
41 end
42
43 function prepare()
44         luci.fs.mkdir(sessionpath)
45         luci.fs.chmod(sessionpath, "a-rwx,u+rwx")
46 end
47
48 function read(id)
49         if not id then
50                 return
51         end
52         clean()
53         return luci.fs.readfile(sessionpath .. "/" .. id)
54 end
55
56 function write(id, data)
57         if not luci.fs.stat(sessionpath) then
58                 prepare()
59         end
60         luci.fs.writefile(sessionpath .. "/" .. id, data)
61         luci.fs.chmod(sessionpath .. "/" .. id, "a-rwx,u+rw")
62 end