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