42 lines
1.6 KiB
Lua
42 lines
1.6 KiB
Lua
#!/usr/bin/env lua
|
|
|
|
require 'luasql.postgres'
|
|
require 'config'
|
|
require 'base64'
|
|
local base64 = enc
|
|
|
|
function generate_token() -- generates a new token (the next)
|
|
local len = config.key_len / 8 * 6
|
|
local f = io.open("/dev/urandom","r")
|
|
local r = f:read(len)
|
|
return base64(r)
|
|
end
|
|
|
|
function add_token(con, token) -- add token to the database
|
|
local now = os.time()
|
|
math.randomseed(now)
|
|
local prefix = token:sub(1, config.prefix_len)
|
|
local ttl = now + config.ttl + math.floor(math.random() * config.ruttl)
|
|
local update = "delete from tokens where prefix='"..prefix.."';"
|
|
local insert = "insert into tokens (prefix, token, ttl) values ('"..prefix.."', '"..token.."', "..ttl..");"
|
|
local gravedigger = "insert into graveyard (prefix, token, ttrd) select prefix, token, ttl+"..config.ttrd.." from tokens where ttl<"..now..";"
|
|
local clean = "delete from tokens where ttl<"..now..";"
|
|
local dig = "delete from graveyard where ttrd<"..now..";"
|
|
con:execute(gravedigger .. clean .. dig .. update .. insert .. update .. insert)
|
|
end
|
|
|
|
function check_token(con, token) -- checks if the token is valid
|
|
if not is_base64(token) then return false end
|
|
local result = true
|
|
local ttl = con:execute("select ttl from tokens where token='"..token.."';"):fetch()
|
|
if ttl == nil then result = false end
|
|
if type(ttl) == "number" then if tonumber(ttl) < os.time() then result = false end end
|
|
return result
|
|
end
|
|
|
|
function set_prefix(old, new) -- sets the prefix from the old token on the new token
|
|
local prefix = old:sub(1, config.prefix_len)
|
|
return prefix .. new:sub(config.prefix_len+1)
|
|
end
|
|
|