summaryrefslogtreecommitdiff
path: root/tex/context/base/mkiv/util-sql-logins.lua
blob: dcb48fb356aa1505cda33d219fccccf4791046ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
if not modules then modules = { } end modules ['util-sql-logins'] = {
    version   = 1.001,
    comment   = "companion to lmx-*",
    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
    copyright = "PRAGMA ADE / ConTeXt Development Team",
    license   = "see context related readme files"
}

if not utilities.sql then require("util-sql") end

local sql              = utilities.sql
local sqlexecute       = sql.execute
local sqlmakeconverter = sql.makeconverter

local format = string.format
local ostime = os.time
local formatter = string.formatter

local trace_logins  = true
local report_logins = logs.reporter("sql","logins")

local logins = sql.logins or { }
sql.logins   = logins

logins.maxnoflogins = logins.maxnoflogins or 10
logins.cooldowntime = logins.cooldowntime or 10 * 60
logins.purgetime    = logins.purgetime    or  1 * 60 * 60
logins.autopurge    = true

local function checkeddb(presets,datatable)
    return sql.usedatabase(presets,datatable or presets.datatable or "logins")
end

logins.usedb = checkeddb

local template = [[
    CREATE TABLE IF NOT EXISTS %basename% (
        `id`    int(11)     NOT NULL AUTO_INCREMENT,
        `name`  varchar(50) NOT NULL,
        `time`  int(11)     DEFAULT '0',
        `n`     int(11)     DEFAULT '0',
        `state` int(11)     DEFAULT '0',

        PRIMARY KEY                  (`id`),
        UNIQUE KEY `id_unique_index` (`id`),
        UNIQUE KEY `name_unique_key` (`name`)
    ) DEFAULT CHARSET = utf8 ;
]]

local sqlite_template = [[
    CREATE TABLE IF NOT EXISTS %basename% (
        `id`    INTEGER NOT NULL AUTO_INCREMENT,
        `name`  TEXT    NOT NULL,
        `time`  INTEGER DEFAULT '0',
        `n`     INTEGER DEFAULT '0',
        `state` INTEGER DEFAULT '0'
    ) ;
]]

function logins.createdb(presets,datatable)

    local db = checkeddb(presets,datatable)

    local data, keys = db.execute {
        template  = db.usedmethod == "sqlite" and sqlite_template or template,
        variables = {
            basename = db.basename,
        },
    }

    report_logins("datatable %a created in %a",db.name,db.base)

    return db

end

local template =[[
    DROP TABLE IF EXISTS %basename% ;
]]

function logins.deletedb(presets,datatable)

    local db = checkeddb(presets,datatable)

    local data, keys = db.execute {
        template  = template,
        variables = {
            basename = db.basename,
        },
    }

    report_logins("datatable %a removed in %a",db.name,db.base)

end

local states = {
    [0] = "unset",
    [1] = "known",
    [2] = "unknown",
}

local converter_fetch, fields_fetch = sqlmakeconverter {
    { name = "id",    type = "number" },
    { name = "name",  type = "string" },
    { name = "time",  type = "number" },
    { name = "n",     type = "number" },
    { name = "state", type = "number" }, -- faster than mapping
}

local template_fetch = format( [[
    SELECT
      %s
    FROM
        `logins`
    WHERE
        `name` = '%%[name]%%'
]], fields_fetch )

local template_insert = [[
    INSERT INTO `logins`
        ( `name`, `state`, `time`, `n`)
    VALUES
        ('%[name]%', %state%, %time%, %n%)
]]

local template_update = [[
    UPDATE
        `logins`
    SET
        `state` = %state%,
        `time` = %time%,
        `n` = %n%
    WHERE
        `name` = '%[name]%'
]]

local template_delete = [[
    DELETE FROM
        `logins`
    WHERE
        `name` = '%[name]%'
]]

local template_purge = [[
    DELETE FROM
        `logins`
    WHERE
        `time` < '%time%'
]]

-- todo: auto cleanup (when new attempt)

local cache = { } setmetatable(cache, { __mode = 'v' })

-- local function usercreate(presets)
--     sqlexecute {
--         template = template_create,
--         presets  = presets,
--     }
-- end

function logins.userunknown(db,name)
    local d = {
        name  = name,
        state = 2,
        time  = ostime(),
        n     = 0,
    }
    db.execute {
        template  = template_update,
        variables = d,
    }
    cache[name] = d
    report_logins("user %a is registered as unknown",name)
end

function logins.userknown(db,name)
    local d = {
        name  = name,
        state = 1,
        time  = ostime(),
        n     = 0,
    }
    db.execute {
        template  = template_update,
        variables = d,
    }
    cache[name] = d
    report_logins("user %a is registered as known",name)
end

function logins.userreset(db,name)
    db.execute {
        template  = template_delete,
    }
    cache[name] = nil
    report_logins("user %a is reset",name)
end

local function userpurge(db,delay)
    db.execute {
        template  = template_purge,
        variables = {
            time  = ostime() - (delay or logins.purgetime),
        }
    }
    cache = { }
    report_logins("users are purged")
end

logins.userpurge = userpurge

local function verdict(okay,...)
    if not trace_logins then
        -- no tracing
    elseif okay then
        report_logins("%s, granted",formatter(...))
    else
        report_logins("%s, blocked",formatter(...))
    end
    return okay
end

local lasttime  = 0

function logins.userpermitted(db,name)
    local currenttime = ostime()
    if logins.autopurge and (lasttime == 0 or (currenttime - lasttime > logins.purgetime)) then
        report_logins("automatic purge triggered")
        userpurge(db)
        lasttime = currenttime
    end
    local data = cache[name]
    if data then
        report_logins("user %a is cached",name)
    else
        report_logins("user %a is fetched",name)
        data = db.execute {
            template  = template_fetch,
            converter = converter_fetch,
            variables = {
                name = name,
            }
        }
    end
    if not data or not data.name then
        local d = {
            name  = name,
            state = 0,
            time  = currenttime,
            n     = 1,
        }
        db.execute {
            template  = template_insert,
            variables = d,
        }
        cache[name] = d
        return verdict(true,"creating new entry for %a",name)
    end
    cache[name] = data[1]
    local state = data.state
    if state == 2 then -- unknown
        return verdict(false,"user %a has state %a",name,states[state])
    end
    local n = data.n
    local m = logins.maxnoflogins
    if n > m then
        local deltatime = currenttime - data.time
        local cooldowntime = logins.cooldowntime
        if deltatime < cooldowntime then
            return verdict(false,"user %a is blocked for %s seconds out of %s",name,cooldowntime-deltatime,cooldowntime)
        else
            n = 0
        end
    end
    if n == 0 then
        local d = {
            name  = name,
            state = 0,
            time  = currenttime,
            n     = 1,
        }
        db.execute {
            template  = template_update,
            variables = d,
        }
        cache[name] = d
        return verdict(true,"user %a gets a first chance",name)
    else
        local d = {
            name  = name,
            state = 0,
            time  = currenttime,
            n     = n + 1,
        }
        db.execute {
            template  = template_update,
            variables = d,
        }
        cache[name] = d
        return verdict(true,"user %a gets a new chance, %s attempts out of %s done",name,n,m)
    end
end

return logins