/* Example for sepgrsql support */
/* The sepgrsql module needs to be enabled before this script is run. */

/* fix labels */
\i /usr/share/postgresql/12/contrib/sepgsql.sql

CREATE DATABASE testdb;
\c testdb
\i /usr/share/postgresql/12/contrib/sepgsql.sql

/* local user */
CREATE ROLE test1 LOGIN;
GRANT ALL ON DATABASE testdb TO test1;

CREATE TABLE persons (
    id serial PRIMARY KEY,
    username VARCHAR(20) UNIQUE NOT NULL,
    email VARCHAR(200) NOT NULL,
    password VARCHAR (200) NOT NULL /* this is an example, don't save unhashed passwords _ever_ */
);

GRANT ALL ON TABLE persons TO test1;

/* A client needs at least c1 to read and at least c1.c3 to write */
SECURITY LABEL ON TABLE persons IS 'system.user:system.role:sepgsql.table.type:s0:c1-s0:c1.c3';

/* But needs c1.c4 to read the email */
SECURITY LABEL ON COLUMN persons.email IS 'system.user:system.role:sepgsql.column.type:s0:c1.c4';

/* Some example data */
INSERT INTO persons (username, email, password) VALUES ('fred', 'fred@example.com', '1234');
INSERT INTO persons (username, email, password) VALUES ('alex', 'mysecretemail@example.com', '0987654321');
INSERT INTO persons (username, email, password) VALUES ('john', 'john2@example.com', 'YES');
INSERT INTO persons (username, email, password) VALUES ('ariane', 'ariane@example.com', 'password2');
INSERT INTO persons (username, email, password) VALUES ('marie', 'marie@example.com', 'letmein');

/* example trusted procedure */
CREATE FUNCTION show_email(int) RETURNS text
AS 'SELECT regexp_replace(email, ''^.....'', ''____'', ''g'') FROM persons WHERE id = $1'
LANGUAGE sql;

/* but you need atleast c2 to execute it */
SECURITY LABEL ON FUNCTION show_email(int) IS 'system.user:system.role:sepgsql.proc.trusted.exec.type:s0:c2';
