#!/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(token) -- add token to the database local env = luasql.postgres() local con = env:connect(config.db) 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 ttrd = config.ttrd + math.floor(math.random() * config.ruttl) local ruttl = math.floor((math.random()+0.5) * 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+"..ttrd.." from tokens where ttl<"..now..";" local clean = "delete from tokens where ttl<"..now..";" local dig = "delete from graveyard where ttrd<"..now..";" assert(con:execute(gravedigger .. clean .. dig .. update .. insert .. update .. insert)) con:close() env:close() end function check_token(token) -- checks if the token is valid if not is_base64(token) then return false end local env = luasql.postgres() local con = env:connect(config.db) 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 con:close() env:close() 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