summaryrefslogtreecommitdiff
path: root/sql/modules/Session.sql
blob: 8b8b65c6cc807f13de772dda72a771254c2c3669 (plain)
  1. CREATE OR REPLACE FUNCTION session_check(in_session_id int, in_token text)
  2. RETURNS session AS
  3. $$
  4. DECLARE out_row session%ROWTYPE;
  5. BEGIN
  6. UPDATE session
  7. SET last_used = now()
  8. WHERE session_id = in_session_id
  9. AND token = in_token
  10. AND last_used > now() - (SELECT value FROM defaults
  11. WHERE setting_key = 'timeout')::interval
  12. AND users_id = (select id from users
  13. where username = SESSION_USER);
  14. IF FOUND THEN
  15. SELECT * INTO out_row WHERE session_id = in_session_id;
  16. ELSE
  17. DELETE FROM SESSION
  18. WHERE users_id IN (select id from users
  19. where username = SESSION_USER);
  20. -- the above query also releases all discretionary locks by the
  21. -- session
  22. IF NOT FOUND THEN
  23. PERFORM id FROM users WHERE username = SESSION_USER;
  24. IF NOT FOUND THEN
  25. RAISE EXCEPTION 'User Not Known';
  26. END IF;
  27. END IF;
  28. INSERT INTO session(users_id, token, last_used, transaction_id)
  29. SELECT id, md5(random()::text), now(), 0
  30. FROM users WHERE username = SESSION_USER;
  31. -- TODO-- remove transaction_id field from session table
  32. SELECT * INTO out_row FROM session
  33. WHERE session_id = currval('session_session_id_seq');
  34. END IF;
  35. RETURN out_row;
  36. END;
  37. $$ LANGUAGE PLPGSQL;
  38. COMMENT ON FUNCTION session_check(int, text) IS
  39. $$ Return code is 0 for failure, 1 for success. $$;