VIEWS - Dynamic select privileges - mysql-workbench

we're supposed to create dynamic SELECT privileges on a view for every user, using it's employee abbreviation (Mitarbeiterkuerzel).
But I'm not able to get it done.
In the end every user should be able to only select those values in all the columns where it's username euqals it's abbreviation.
USE IAF03_ByceDB;
DROP USER IF EXISTS 'heck.i'#'localhost';
DROP USER IF EXISTS 'brater.w'#'localhost';
DROP USER IF EXISTS 'budar.h'#'localhost';
DROP USER IF EXISTS 'baer.s'#'localhost';
DROP VIEW IF EXISTS V_Bestellungen;
CREATE USER 'heck.i'#'localhost' IDENTIFIED BY 'root';
CREATE USER 'brater.w'#'localhost' IDENTIFIED BY 'root';
CREATE USER 'budar.h'#'localhost' IDENTIFIED BY 'root';
CREATE USER 'baer.s'#'localhost' IDENTIFIED BY 'root';
CREATE VIEW V_Bestellungen AS
select k.KUN_NR, k.NACHNAME, k.VORNAME, A.TNR, A.BEZEICHNUNG, af.MENGE, at.BESTELLDATUM, a.VERKAUFSPREIS, af.MENGE * a.VERKAUFSPREIS AS 'Rechnungsbetrag', ANG_NR AS Sachbearbeiter, lower(concat(concat(concat(an.Nachname, '.'),substring(an.Vorname,1,1)), '#', 'localhost'))as MITARBEITERKUERZEL
FROM AUFTRAGSPOSITIONEN af
INNER JOIN AUFTRAEGE at USING (AUFTRAGSNR)
INNER JOIN ARTIKEL a USING (TNR)
INNER JOIN KUNDEN k USING (KUN_NR)
INNER JOIN ANGESTELLTE an USING (ANG_NR);
GRANT SELECT
ON iaf03_bycedb.V_Bestellungen
TO 'heck.i'#'localhost';

Just got one solution and it works.
USE IAF03_ByceDB;
DROP USER IF EXISTS 'heck.i'#'localhost';
DROP USER IF EXISTS 'brater.w'#'localhost';
DROP USER IF EXISTS 'budar.h'#'localhost';
DROP USER IF EXISTS 'baer.s'#'localhost';
DROP VIEW IF EXISTS V_Bestellungen;
CREATE USER 'heck.i'#'localhost' IDENTIFIED BY 'root';
CREATE USER 'brater.w'#'localhost' IDENTIFIED BY 'root';
CREATE USER 'budar.h'#'localhost' IDENTIFIED BY 'root';
CREATE USER 'baer.s'#'localhost' IDENTIFIED BY 'root';
CREATE VIEW V_Bestellungen AS
SELECT k.KUN_NR, k.NACHNAME, k.VORNAME, A.TNR, A.BEZEICHNUNG, af.MENGE, at.BESTELLDATUM, a.VERKAUFSPREIS, af.MENGE * a.VERKAUFSPREIS AS 'Rechnungsbetrag', ANG_NR AS Sachbearbeiter
FROM AUFTRAGSPOSITIONEN af
INNER JOIN AUFTRAEGE at USING (AUFTRAGSNR)
INNER JOIN ARTIKEL a USING (TNR)
INNER JOIN KUNDEN k USING (KUN_NR)
INNER JOIN ANGESTELLTE an USING (ANG_NR)
WHERE user() = lower(concat(concat(concat(an.Nachname, '.'),substring(an.Vorname,1,1)), '#', 'localhost'));
GRANT SELECT
ON iaf03_bycedb.V_Bestellungen
TO 'heck.i'#'localhost';
GRANT SELECT
ON iaf03_bycedb.V_Bestellungen
TO 'brater.w'#'localhost';
GRANT SELECT
ON iaf03_bycedb.V_Bestellungen
TO 'budar.h'#'localhost';
GRANT SELECT
ON iaf03_bycedb.V_Bestellungen
TO 'baer.s'#'localhost';
FLUSH PRIVILEGES;

Related

Is there a way to modify this query and make it more simple?

I am working on a MySQl data base and have several tables that I need to join based on a temporary table that I created (layer_2).
Each table that I join has the join key for the next table;
E.g. layer_2 joins with "colegios" table, then the result will have the join key for the next table "ciudades". and finally the result will have the Join key for the next table "departamentos".
from what I got it works but I want to know if there is a way to simplify this?
Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
tipo_institucion,
materia,
tematica,
area,
nombre_colegios,
direccion_colegios,
nombre_ciudades,
redsaber.departamentos.nombre as nombre_departamentos
From
(
Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
cuestionable_id,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
cole_ciud_id,
tipo_institucion,
materia,
tematica,
area,
combine_ciudad_id,
nombre_colegios,
direccion_colegios,
redsaber.ciudades.nombre as nombre_ciudades,
departamento_id
From
(Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
cuestionable_id,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
cole_ciud_id,
tipo_institucion,
materia,
tematica,
area,
ifnull(redsaber.colegios.ciudad_id,cole_ciud_id) as combine_ciudad_id,
redsaber.colegios.nombre as nombre_colegios,
redsaber.colegios.direccion as direccion_colegios
From layer_2
Left Join redsaber.colegios on layer_2.cole_ciud_id = redsaber.colegios.id
AND tipo_institucion = 'Colegio') as layer_3
Left Join redsaber.ciudades on combine_ciudad_id = redsaber.ciudades.id) as layer_4
Left Join redsaber.departamentos on departamento_id = redsaber.departamentos.id

How to read / list security labels on columns in postgreSQL

I've set up PostgreSQL Anonymizer on my database with security labels and everything works fine.
I'm trying to regularly ceck if there is missing security labels on the columns of my database to telle the developers to add them in the next release but I can't fin a way to read the security labels.
Can anyone know how to do this ?
EDIT on 10/11/2022
Thanks to #Shiva, I've end up doing this query :
select cl."oid", col.ordinal_position, col.table_schema, col.table_name, col.column_name
FROM information_schema.columns col
join pg_catalog.pg_class cl on cl.relname = col.table_name
WHERE col.table_schema = 'XXXX'
and not exists (select objoid FROM pg_seclabel where provider = 'anon' and objsubid = col.ordinal_position and objoid = cl."oid");
You have to query pg_seclabel catalog to get list of security labels.
SELECT objsubid, provider, label FROM pg_seclabel WHERE objoid::regclass = 'mytable'::regclass
objsubid is the column number whose corresponding column name can be found by querying information_schema.columns catalog.
SELECT column_name FROM information_schema.columns WHERE table_name = 'mytable' AND ordinal_position = <column_number>
You can combine the above two queries to find columns that do not have the required security labels.

T-SQL Question for Getting One Customer Type When There Can be More Than One Value

We have an organization that can have more than one customer type basically. However, what a user wants to see is either the partner or direct type (customer type is either Direct, Partner1, Partner2, or Partner3 but can be direct plus a partner value but only can be one of the partner values). So if a customer is both (ex: Direct and Partner1) they just want the type that is a partner (ex: Partner1). So I tried splitting out partners only into one temp table from a few tables joining together different org data. I have the same query without any limit pulling into a different temp table. Then I calculate count and put that into a temp table. Then I tried gathering data from all the temp tables. That is where I run into trouble and lose some of the customers where the type is direct (I have a image link below for a directcustomer and a customer who is both). I have been out of SQL for a bit so this one is throwing me...I figure the issue is the fact that I have a case statement referencing a table that a direct customer will not exist in (#WLPO). However I am not sure how to achieve pulling in these customers while also only selecting which partner type it is for a customer that has a partner and is also direct. FYI using MSSMS for querying.
If OBJECT_ID('tempdb..#WLPO') IS NOT NULL
DROP TABLE #WLPO
IF OBJECT_ID('tempdb..#org') IS NOT NULL
DROP TABLE #org
IF OBJECT_ID('tempdb..#OrgCount') IS NOT NULL
DROP TABLE #OrgCount
IF OBJECT_ID('tempdb..#cc') IS NOT NULL
DROP TABLE #cc
Select
o.OrganizationID,
o.OrganizationName,
os.WhiteLabelPartnerID,
s.StateName
INTO #WLPO
from [Org].[Organizations] o
join [Org].[OrganizationStates] os on o.OrganizationID=os.OrganizationID --and os.WhiteLabelPartnerID = 1
join [Lookup].[States] s on os.StateID = s.StateID
join [Org].[PaymentOnFile] pof on pof.OrganizationID=o.OrganizationID
where os.WhiteLabelPartnerID in (2,3,4)
and os.StateID in (1, 2, 3)
and o.OrganizationID = 7613
select * from #WLPO
Select
o.OrganizationID,
o.OrganizationName,
os.WhiteLabelPartnerID,
s.StateName
INTO #org
from [Org].[Organizations] o
join [Org].[OrganizationStates] os on o.OrganizationID=os.OrganizationID --and os.WhiteLabelPartnerID = 1
join [Lookup].[States] s on os.StateID = s.StateID
join [Org].[PaymentOnFile] pof on pof.OrganizationID=o.OrganizationID
where 1=1--os.WhiteLabelPartnerID = 1
and os.StateID in (1, 2, 3)
and o.OrganizationID = 7613
select * from #org
Select
OrganizationID,
count(OrganizationID) AS CountOrgTypes
INTO #OrgCount
from #org
where OrganizationID = 7613
group by OrganizationID
select * from #OrgCount
Select distinct
ct.OrganizationID,
ok.OrganizationName,
ct.CountOrgTypes,
case when ct.CountOrgTypes = 2 then wlp.WhiteLabelPartnerID
when ct.CountOrgTypes = 1 then ok.WhiteLabelPartnerID
END AS CustomerTypeCode,
case when ct.CountOrgTypes = 2 then wlp.StateName
when ct.CountOrgTypes = 1 then ok.StateName END As OrgState
INTO #cc
from #org ok
left join #WLPO wlp on wlp.OrganizationID=ok.OrganizationID
join #OrgCount ct on wlp.OrganizationID=ct.OrganizationID
select * from #cc
Select
OrganizationID,
OrganizationName,
CountOrgTypes,
case when CustomerTypeCode = 1 then 'Direct'
when CustomerTypeCode = 2 then 'Partner1'
when CustomerTypeCode = 3 then 'Partner2'
when CustomerTypeCode = 4 then 'Partner3' ELSE Null END AS CustomerType,
OrgState
from #cc
order by OrganizationName asc
DirectCustomer
CustomerwithBoth

SQL query for finding Foreign key constraints

I have one column , and i want to find in How many table that column used as foreign and also name of the table in which that column is used. I have PostgreSQL database . and i am using PG admin tool
select R.TABLE_NAME from INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE u
inner join INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS FK
on U.CONSTRAINT_CATALOG = FK.UNIQUE_CONSTRAINT_CATALOG
and U.CONSTRAINT_SCHEMA = FK.UNIQUE_CONSTRAINT_SCHEMA
and U.CONSTRAINT_NAME = FK.UNIQUE_CONSTRAINT_NAME inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE R
ON R.CONSTRAINT_CATALOG = FK.CONSTRAINT_CATALOG
AND R.CONSTRAINT_SCHEMA = FK.CONSTRAINT_SCHEMA
AND R.CONSTRAINT_NAME = FK.CONSTRAINT_NAME WHERE U.COLUMN_NAME='M_InLine_ID'
AND U.TABLE_NAME = 'M_InLine'
I tried above query but it snot given any output
Please help me out

Keycloak - Get all Users mapped to roles

I know keycloak has exposed below api,
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-services</artifactId>
<version>2.0.0.Final</version>
</dependency>
With complete documentation here. I cannot find the required api here to fetch all users with specific role mapped to them.
Problem Statement - I need to pick all users from keycloak server who have a specific role. I need to send email to all users with role mapped to them.
Based on the documentation it appears to be this API:
GET /{realm}/clients/{id}/roles/{role-name}/users
It is there for a while. In this older version however it was not possible to get more than 100 users this way. It was fixed later and pagination possibility was added.
There is an outstanding feature request asking for this function via the API.
In the meantime if your requirement is once-off you could obtain the user names (or email addresses) by interrogating the database joining KEYCLOAK_ROLE to USER_ROLE_MAPPING to USER_ENTITY
Something like:
SELECT username
FROM keycloak_role kr
JOIN user_role_mapping rm ON kr.id = rm.role_id
JOIN user_entity ue ON rm.user_id = ue.id
WHERE kr.name = 'your_role_name';
This should be now possible with the updated rest endpoint.
Set<UserRepresentation> usersOfRole = realmResource.roles().get(roleName).getRoleUserMembers();
Here is another interesting query, which would also display other useful fields.
SELECT kr_role.REALM_ID 'Realm', cl.CLIENT_ID 'Realm Client',
kr_role.NAME 'Role Name',
kr_role.DESCRIPTION 'Role Description',
user_ent.USERNAME 'Domain ID', user_ent.EMAIL 'Email'
FROM keycloak_role kr_role, user_role_mapping role_map,
user_entity user_ent, client cl
WHERE role_map.USER_ID = user_ent.ID
AND kr_role.ID = role_map.ROLE_ID
AND kr_role.CLIENT = cl.ID
AND cl.REALM_ID = '<realm_name>'
AND cl.CLIENT_ID = '<client_name>'
ORDER BY 1, 2, 3;
If anyone is still searching for a Postgres Query to find information regarding users/roles/groups in keycloak database, I came up with this one lately.
It uses two CTEs to have the groups and roles straight (recursing for groups in groups, because they can nest in arbitrary depth and fetching composite roles with their parents) and a simple UNION for group and direct assignments.
Please note the WHERE clause, where you can limit the realm and different aspects. You can search for
all roles from a specific user (just matching username)
all users, that have a particular role assigned (matching role_name)
everything coming from a specific group (I sometimes use it without the username column in the projection to just see, what roles a group has. Please note the prefix in the group column)
-- flat out GROUPS in GROUPS
WITH RECURSIVE groups AS (
SELECT
g.id,
g.id AS parent_group,
g.name,
g.name AS parent_name,
g.realm_id,
1 AS iter
FROM
keycloak_group g
UNION
SELECT
groups.id,
parents.parent_group,
groups.name,
parents.name,
groups.realm_id,
groups.iter + 1
FROM
groups
INNER JOIN keycloak_group parents ON groups.parent_group = parents.id
),
-- Collect roles and composite roles
roles AS (
SELECT
r.id,
r.name AS role_name,
null AS base_role,
c.client_id
FROM
keycloak_role r
LEFT JOIN client c ON r.client = c.id
UNION
SELECT
r.id,
r2.name,
r.name,
c.client_id
FROM
keycloak_role r
JOIN composite_role cr ON r.id = cr.composite
JOIN keycloak_role r2 ON r2.id = cr.child_role
LEFT JOIN client c ON r.client = c.id
)
SELECT DISTINCT
username,
role_name,
base_role, -- for composite roles
client_id,
source,
realm_name
FROM
(
-- Roles from Groups
SELECT
ue.username,
roles.role_name,
roles.base_role,
roles.client_id,
ue.realm_id,
'group ' || g.name AS source,
realm.name AS realm_name
FROM
user_entity ue
JOIN realm ON ue.realm_id = realm.id
JOIN user_group_membership ugm ON ue.id = ugm.user_id
JOIN groups g ON g.id = ugm.group_id
JOIN group_role_mapping grm ON g.parent_group = grm.group_id
JOIN roles roles ON roles.id = grm.role_id
UNION
-- direct role assignments on User
SELECT
ue.username,
roles.role_name,
roles.base_role,
roles.client_id,
ue.realm_id,
'direct',
realm.name
FROM
user_entity ue
JOIN realm ON ue.realm_id = realm.id
JOIN user_role_mapping urm ON ue.id = urm.user_id
JOIN roles roles ON roles.id = urm.role_id
) AS a
WHERE
realm_name = 'realm_name'
AND (
-- username = 'username'
role_name IN ('roleName')
-- source = 'group GROUPNAME'
)
ORDER BY
username,
role_name
;
This query works from keycloak 9 to 16.1.1 (the last jboss/keycloak version I got from docker hub).
SELECT username,
kr.NAME,
kr.REALM_ID
FROM KEYCLOAK_ROLE kr
JOIN USER_ROLE_MAPPING rm ON kr.id = rm.role_id
JOIN USER_ENTITY ue ON rm.user_id = ue.id
ORDER BY USERNAME,
NAME,
REALM_ID;