tokenUtil.lua 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. local crypt = require "crypt"
  2. local DES_SECRET = "8RD8SxJx"
  3. local root = {}
  4. function root.create(uid, password)
  5. local timestamp = os.time()
  6. local s = string.format("%s:%s:%s", uid, timestamp, password)
  7. s = crypt.base64encode(crypt.desencode(DES_SECRET, s))
  8. return s:gsub("[+/]", function (c)
  9. if c == '+' then
  10. return '-'
  11. else
  12. return '_'
  13. end
  14. end)
  15. end
  16. local function parseToken(token)
  17. token = token:gsub("[-_]", function (c)
  18. if c == '-' then
  19. return '+'
  20. else
  21. return '/'
  22. end
  23. end)
  24. local s = crypt.desdecode(DES_SECRET, crypt.base64decode(token))
  25. return s:match("([^:]+):([^:]+):(.+)")
  26. end
  27. function root.auth(uid, password, token)
  28. if not uid or not token then
  29. return false, "function:token_auth args illedge!"
  30. end
  31. local tuid, time, password = parseToken(token)
  32. if not tuid or not time or not password then
  33. return false, "token parse fail!"
  34. end
  35. tuid = tonumber(tuid) or 0
  36. if tuid ~= uid then
  37. return false, string.format("uid not same, %d, %d", uid, tuid)
  38. end
  39. --检验时间
  40. local now = os.time()
  41. local time = tonumber(time) or 0
  42. if time + 86400 < now then
  43. return false, string.format("time expire, val %d", time)
  44. end
  45. return true
  46. end
  47. return root