 /*
$Log: _authorization.sql,v $
Revision 1.32  2025/04/01 13:00:06  jmam
$send$ Odchudzone i z mode na select po autor.

Revision 1.31  2025/04/01 11:59:10  jmam
c.d. Usuwam _MODE LIKE '..Clear..'

Revision 1.30  2025/04/01 11:57:51  jmam
Usuwam _MODE LIKE '..Clear..'

Revision 1.29  2025/04/01 11:47:41  jmam
Tymcz. przed zgraniem

*/

DELIMITER $$

/* ************************************************************************************************************************************************************************
	narzędzia 
************************************************************************************************************************************************************************ */	

DROP PROCEDURE IF EXISTS `_authorization`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_authorization`(
	IN _MODE VARCHAR(250), 
	IN _IN_Session_GUID VARCHAR(255),
	IN _IN_Auth_Params TEXT,
	IN _Param_A VARCHAR(200),
	IN _Param_B VARCHAR(200),
	IN _Param_C VARCHAR(200),
	IN _Param_D VARCHAR(200),
	IN _Param_E VARCHAR(200)
)
/*
	CALL _authorization('', '', 0, '', '', '', '', '');
*/
S_authorization: BEGIN
	DECLARE _Need_Select BOOLEAN;
	DECLARE _UserGUID, _Md5_SESSION_GUID, _Md5_UserGUID, _Md5_Login, _Md5_Pswd, _Md5_log_DEV_ID, _Md5_log_APP_ID VARCHAR(150); 
	DECLARE _CONNECTION_ID INTEGER;
	
	DO _Birth_System(); -- było DO _TriggerDisabled();	--	aby miec @session.globals.INPUT_SALT_Hash
	
	SET @.NEW._sys_db_logons.DETAL = TRUE;	
	
	SET @.EMPTY_STR.Hash = _MD5_CHARSET('', @session.globals.INPUT_SALT_Hash, '', '', '', '');

	SET _Need_Select = (_Param_E LIKE '%<select%>%');	-- ten porcent % wew. <> jest ważny bo może być "..<select.sys_db_logons>.."
			SET @._Need_Select = _Need_Select;
	IF _Need_Select THEN
		SET 
			@.auth.SELECT.MODE = 
			IF(_Param_E LIKE '%<select>%',
				'SELECT.AUTH',
				IF (_Param_E LIKE '%<select._sys_db_logons_Tools>%',
					'SELECT.AUTH._sys_db_logons_Tools',
					IF (_Param_E LIKE '%<select._sys_authorization>%',
						'SELECT.AUTH._sys_authorization',
						IF (_Param_E LIKE '%<select._sys_connection_Tool>%',
							'SELECT.AUTH._sys_connection_Tool',
							'SELECT.AUTH'
						)
					)
				)
			)
		;
	END IF;
	SET _Param_E = REPLACE(_Param_E, '<select>', '');
	
	IF 
		_MODE LIKE 'LOG%' 
		OR
		_MODE LIKE 'AUTH%' 
	/******************************************************************************************************************************************
		LOGOWANIE / Autoryzacja
		Mamy wejścia typy
		LOG...:		- logowanie do sesji istniejącej lub takiej którą tu kreujemy (w zalezności od _IN_Session_GUID
		oraz
		AUTH...:	- autoryzacja bez logowania np. sprawdzenie dostepu do czegoś - spr. samego loginu i hasła
		
		LOG:#..
			LOG:#Login,#Pswd
			LOG:#UserGUID
			LOG:#SesjaZlecajaca
		LOG.BIO:#..
			LOG.BIO:#Login,#DEV_ID
			LOG.BIO:#UserGUID,#DEV_ID
		AUTH:#..
			AUTH:#Login,#Pswd					- autoryzacja bez logowania i nie wymagana sesja
			AUTH:#Login,#Pswd+ADD.BIO:DEV_ID	- dodawanie danych biometrycznych - podaje sie to samo co w AUTH.SESSION:#Login,#Pswd + to co w LOG.BIO:#UserGUID,#DEV_ID czyli  #UserGUID i #ID_Dev
		AUTH.SESSION:#..
			AUTH.SESSION:#Login,#Pswd		- tu konieczna jest sesja wejściowa do porównania czy w sesji siedzi weryfikowany 
		
		### ma nast. możliwości
		#Login,#Pswd
		#UserGUID
		UWAGA 
		#App_ID nie jest wymagane ale gdy poda się to jest sprawdzane czy istnieje moduł. 
		Jeśli nie istnieje przepuszczamy ale gdy istnieje to sprawdzamy dostęp!!!
	******************************************************************************************************************************************/
	THEN
	
		IF _IN_Auth_Params LIKE '%<prepare.by.@>%' THEN
		/*
			Logowanie na podst. zmiennych @.
			CALL _authorization('LOG:#Login,#Pswd', Session, '<prepare.by.@>', '', '', '', '', @.bypass.auth.MODE.SELECT);
		*/
		--	Parametry do sznurka	
			SET
				@.auth.we.Params = 
				CONCAT_WS('&',
					CONCAT('S.ID=', @.auth.we.S.ID),		-- jawna sesja gdy jest pieprzem (Pepper) w haszowaniu
					CONCAT('U.L#=', @.auth.we.U.L.5),
					CONCAT('U.P#=', @.auth.we.U.P.5),
					CONCAT('U.G#=', @.auth.we.U.G.5),		-- dla LOG:#UserGUID
					CONCAT('D.ID#=', @.auth.we.D.ID.5),
					CONCAT('A.ID#=', @.auth.we.A.ID.5),
					CONCAT('D.ID=', @.auth.we.D.ID),
					CONCAT('A.ID=', @.auth.we.A.ID),
					CONCAT('A.NAME=', @.auth.we.A.NAME),
					CONCAT('A.VER=', @.auth.we.A.VER),
					CONCAT('A.ACCESS=', @.auth.we.A.ACCESS),
					CONCAT('log_HOST=', @.auth.we.log_HOST), 
					CONCAT('log_HOST_NAME=', @.auth.we.log_HOST_NAME), 
					CONCAT('log_MACADDRESS=', @.auth.we.log_MACADDRESS)
				)
			;
			SET _IN_Auth_Params = @.auth.we.Params;
		END IF;
									--	Musi byc włączona @Session._sys_watch_time_Tools = TRUE
									-- 	CALL _sys_watch_time_Tools('start', '_authorization', '???', '', '', '');
		SET @._IN_Auth_Params = 
		--	Ważne Dodajemy do sznurka parametr IN_Session_GUID bo w proc. nie ma param wej.. IN_Session_GUID!!!
			CONCAT_WS('&',
				_IN_Auth_Params,
				CONCAT('IN_Session_GUID=', NULLIF(_IN_Session_GUID, ''))
			)
		;
						--	CALL _exproc_LOG('LOG', 'Test AUTH!!!', _IN_Auth_Params, _IN_Session_GUID, 'AUTH', @.log);
	--	UWAGA wstawka na razie!!!!!!!!!!!!!!!!!!!!!!!!!!
			IF 
				NULLIF(_Params2('_FetchParams', @._ModeParam, @._IN_Auth_Params, 'A.VER', ''), '') IS NULL
				AND IFNULL(_IN_Session_GUID, '') <> '' 
			THEN
				SET
					@.auth.A.VER = 
						(
						SELECT 
							sdl.log_APP_VER  -- sdl.Log_APP_ID 
						FROM `_sys_db_logons` sdl
						WHERE 
							sdl.GUID = _IN_Session_GUID
						LIMIT 1
						)
				;
				-- SET @._IN_Auth_Params = _Params2('Add', @._ModeParam, @._IN_Auth_Params, 'A.VER', @.auth.A.VER);
				-- SET @._IN_Auth_Params = _Params2('Delete', @._ModeParam, @._IN_Auth_Params, 'A.VER', '');
				SET @._IN_Auth_Params = 
				--	Ważne Dodajemy do sznurka parametr IN_Session_GUID bo w proc. nie ma param wej.. IN_Session_GUID!!!
					CONCAT_WS('&',
						@._IN_Auth_Params,
						CONCAT('A.VER=', NULLIF(@.auth.A.VER, ''))
					)
				;
			END IF;
			INSERT INTO `log` 
			(useridn, OsobaGUID, ip, info, Info_View, IDSession)
			SELECT
				IFNULL(sdl.log_USER, IFNULL(@SYSTEM.Client.Session.log_USER, IFNULL(@session.INFO.User_Login, @session.Registration.UserLogin))) AS useridn,
				IFNULL(sdl.log_USER_GUID , IFNULL(@SYSTEM.Client.Session.log_USER_GUID, IFNULL(@session.INFO.User_GUID, @session.Registration.UserGUID))) AS OsobaGUID,
				IF(sdl.GUID IS NOT NULL,
					CONCAT_WS(' - ', sdl.log_HOST_Name, CONCAT_WS(', ', CONCAT('IP: ', sdl.log_HOST), CONCAT('MCA: ', sdl.log_MACADDRESS))),
					IFNULL(@session.INFO.Host_IP, IFNULL(@session.Registration.IP, @session.CurrMyIPOnly))
				) AS IP,
				_IN_Auth_Params AS info,
				_IN_Auth_Params AS Info_View,
				sdl.GUID AS IDSession
			FROM `_sys_db_logons` sdl 
			WHERE
				TRUE 
				AND sdl.GUID = _IN_Session_GUID
			;
										SET @.x = '1;';
		/*
		
	--	Ponieważ w _MODE może być ADD.BIO:#UserGUID,#DEV_ID czyli rejestracja urz. + Id biometryczny to ...
		SET @.Orig._MODE = _MODE;
	--	i zmieniamy _MODE na autoryzacje (nie logowanie)
		SET _MODE = ADD.BIO
		*/
											-- CALL _sys_watch_time_Tools('start', 'CALL _user_accounts_inf', 'INSERT', '', '', '');
		CALL _user_accounts_inf(CONCAT('INSERT.', _MODE), '', '', @._IN_Auth_Params); 
											-- CALL _sys_watch_time_Tools('stop', 'CALL _user_accounts_inf', 'INSERT', '', '', '');
										SET @.x = '2;';
	--	Szukaj user wg...
											-- CALL _sys_watch_time_Tools('start', 'CALL _user_accounts_inf', 'Find.UserGUID', '', '', '');
		CALL _user_accounts_inf('Find.UserGUID', '', '', @._IN_Auth_Params); 
											-- CALL _sys_watch_time_Tools('stop', 'CALL _user_accounts_inf', 'Find.UserGUID', '', '', '');
			-- SELECT @.tuaiA.Oper_Mode;		
	--	Teraz ustaw param. konta o ile istnieje jesli nie istnieje to badzie tam nadal 'ERR.NO.USER'
		-- CALL _user_accounts_inf('<-_user_accounts', '', '', @._IN_Auth_Params); 
	--	Teraz pods. statusów
		-- CALL _user_accounts_inf('Summary', '', '', @._IN_Auth_Params); 
										SET @.x = '3;';

        
											-- CALL _sys_watch_time_Tools('start', 'CALL _user_accounts_inf', 'Check.Auth.PSWD', '', '', '');
		CALL _user_accounts_inf('Check.Auth.PSWD', '', '', @._IN_Auth_Params); 
											-- CALL _sys_watch_time_Tools('stop', 'CALL _user_accounts_inf', 'Check.Auth.PSWD', '', '', '');

		SET @.x = '4;';
		
											-- CALL _sys_watch_time_Tools('start', 'CALL _user_accounts_inf', 'Check.Modules', '', '', '');
		CALL _user_accounts_inf('Check.Modules', '', '', @._IN_Auth_Params); 
											-- CALL _sys_watch_time_Tools('stop', 'CALL _user_accounts_inf', 'Check.Modules', '', '', '');
										SET @.x = '5;';
											-- CALL _sys_watch_time_Tools('start', 'CALL _user_accounts_inf', 'Check.Limit.Log', '', '', '');
		CALL _user_accounts_inf('Check.Limit.Log', '', '', @._IN_Auth_Params); 
											-- CALL _sys_watch_time_Tools('stop', 'CALL _user_accounts_inf', 'Check.Limit.Log', '', '', '');
										SET @.x = '6;';
											-- CALL _sys_watch_time_Tools('start', 'CALL _user_accounts_inf', 'ADD.BIO.ID', '', '', '');
		CALL _user_accounts_inf('ADD.BIO.ID', '', '', @._IN_Auth_Params); 
											-- CALL _sys_watch_time_Tools('stop', 'CALL _user_accounts_inf', 'ADD.BIO.ID', '', '', '');
-- do dokonczenia ....

	/* ***************************************************************************************************************************
		Z sesjami jest tak że moga wystepowac jako Pepper ale nie musi to byc wejściowa 
		sesja czyli IN_Session_GUID (pepper dostajemy w sznurku jako sesje).
		Kiedy mamy juz sesje (stare db_logons) to podajemy ją i nie tworzymy tzn gdy robimy INSERT IGNORE to i tak nic nie zmieniamy
		Gdy mamy LOG... to logujemy sie do sesji która możemy miec podaną w IN_Session_GUID ale 
		nie musimy (kreujemy ja wtedy z nowym GUIDem)
		Inna sytacja to gdy chcemy zweryfikować usera na danej sesji (cos w stylu wygaszacza i autoryzacja do aktualnej sesji) 
		i wtedy podajemy ją i przy sprawdzaniu badamy zgodność usera w sesji z tym wyszukanym haszowo
		UWAGA gdy mamy doklejone wyrazenie ".Search.active.session" to szukamy niezamknietej sesji tego user dla urzadzebnia i aplikacji
		Zatem teraz pobierz sesje pasujaca
	****************************************************************************************************************************/
		
		SET @.SYSTEM.Search.Session.GUID = NULL;
		UPDATE `t_ua_inf` tuaiA
		SET 
			tuaiA.Session_GUID = 
				IF(tuaiA.IN_Mode LIKE '%.Search.active.session',
				--	1. SZUKAM SESJI tego uzytkownika i tego urzadzenia do tego programu
					IFNULL(@.SYSTEM.Search.Session.GUID := 
						(
							SELECT
								sdl.GUID
							FROM `_sys_db_logons` sdl
							WHERE
								sdl.log_USER_GUID = tuaiA.UserGUID
								AND
								_MD5_CHARSET('', tuaiA.SALT, tuaiA.PEPPER, sdl.log_DEV_ID, '', '') = tuaiA.In_DEV_ID_Hash
								AND
								_MD5_CHARSET('', tuaiA.SALT, tuaiA.PEPPER, sdl.log_APP_ID, '', '') = tuaiA.In_APP_ID_Hash
								AND
								NOT sdl.Inactive
								AND
								(NOT (tuaiA.Oper_Status LIKE 'ERR%'))	-- tylko dla pomyslnie znal. userów LUB !!!
							ORDER BY sdl.LOGGED_AT DESC
							LIMIT 1
						)
					, tuaiA.Session_GUID),
				--	2. ...	
					IF(tuaiA.IN_Mode LIKE '%LOG%:%',
					--	2.1 Logowanie do sesji - podanej lub domyslnej (nie wazne czy istnieje czy nie bo i tak potem robimy INSERT IGNORE
						IFNULL(tuaiA.IN_Session_GUID, Get_Var_Connection('Get.Session.GUID.or.New.If.NULL', '', @ParamWe123 := NULL, '')),	-- SPR.Get_Var_Connection !!!!!!
						-- IF(IFNULL(_Param_E, '') LIKE '%<Session.In.Hash>%',	--	uzyto sesji do Hash - ta sesja obowiązuje
						IF(tuaiA.IN_Mode LIKE '%AUTH.SESSION:%', 
						--	NIE POTRZEBNE!!!! Bez logowania - autoryzacja ale tu konieczna jest sesja wejściowa do porównania czy w sesji siedzi weryfikowany 
								NULLIF(tuaiA.IN_Session_GUID, ''), 	-- wymagamy nie pustego _ID gdy Mode ma CHECK.THIS.Session
								NULL
						)
					) 
				)
		WHERE
			TRUE
			-- AND (NOT (tar.Verify_Status LIKE 'ERR%'))	-- tylko dla pomyslnie znal. userów LUB !!!
		;			
	/* ***************************************************************************************************************************
		Na koniec ustaw _Verify_OK i ew. err_logon_count
		err_logon_count w `_user_accounts` !!!!!!
	****************************************************************************************************************************/
	
	--	MSG_LONG do zwrotu
	/* ***************************************************************************************************************************
		Zakładac sesję? A jeśli tak uwzgl. Errory etc.
		Najpierw wypełnij zmienne finalne
		@.auth.Final.xxxx
		Tak tak - nie wstawiamy insertem wszystko przez 
			CALL _sessions('rec.INSERT.for.UserGUID.from.@.auth.Final',...
		a że tam nie wolno uzywac temporarek to zlecamy to przez zmienne 
		I NIE OMIJAJ tego NIGDY!!!!
	****************************************************************************************************************************/
		SELECT
			tuaiA.IN_Mode,
			(tuaiA.IN_Mode LIKE '%LOG%:%') AS Need_INS_Session,
			tuaiA.Session_GUID,
			tuaiA.Oper_Status AS Verify_Status,
			tuaiA.Oper_Status LIKE 'OK%' AS Verify_OK, 
			tuaiA.UserGUID, tuaiA.UserGUID AS OsobaGUID, 
			tuaiA.APP_ID_GRP_Dost_Name, tuaiA.APP_ID, tuaiA.DEV_ID,
			tuaiA.Oper_Status_Msg AS Msg,
			-- tuaiA.MSG, 
			tuaiA.Msg_Log AS MSG_LONG
		INTO
			@.auth.Final.IN_Mode,
			@.auth.Final.Need_INS_Session,
			@.auth.Final.Session_GUID,
			@.auth.Final.Verify_Status,
			@.auth.Final.Verify_OK,
			@.auth.Final.USER_GUID,
			@.auth.Final.OsobaGUID,
			@.auth.Final.APP_ID_GRP_Dost_Name,
			@.auth.Final.APP_ID,
			-- @.auth.Final.APP_VER,
			@.auth.Final.DEV_ID,
			@.auth.Final.MSG,
			@.auth.Final.MSG_LONG
		FROM `t_ua_inf` tuaiA
		;
	--	Ewentualne wstawianie sesji ???
		IF @.auth.Final.Need_INS_Session THEN
			IF @.auth.Final.Verify_OK THEN
				CALL _sessions_APP('NEW.for.authorization+LOG.OK', NULLIF(@.auth.Final.Session_GUID, ''), '', '', '', '', '');
			ELSE
				CALL _sessions_APP('NEW.for.authorization+LOG.ERR', NULLIF(@.auth.Final.Session_GUID, ''), '', '', '', '', '');
			END IF;
		--	UWAGA ponieważ mogło nie byc sesji a powyżej (jeśli jej niebyło) załozono ją to...
		--		przepisz ja z @.sdl.GUID
			IF IFNULL(@.auth.Final.Session_GUID, '') = '' THEN
				UPDATE `t_ua_inf` tuaiA
				SET 
					tuaiA.Session_GUID = (@.auth.Final.Session_GUID := @.sdl.GUID)
				;
			END IF;
		--	Zapis w logu
			CALL _sessions_APP(IF(@.auth.Final.Verify_OK, 'LOG.session.LOG.OK', 'LOG.session.LOG.ERR'), @.auth.Final.Session_GUID, '', '', '', '', '');
		END IF;
		DO _counters_tools('INC', _MODE, '', '');		-- to tylko Licznik!!!!
	--	Ewentualny. SELECT (prawie zawsze tak)
		IF _Need_Select THEN
					SET @.x = CONCAT_WS('/', @.x, 'NeedSelect=1');
			-- 31 III 2025 CALL _sessions_APP(@.auth.SELECT.MODE, @.auth.Final.Session_GUID, '', '', '', '', '');
            -- 1 IV 2025 CALL _sessions_SEL(@.auth.SELECT.MODE, @.auth.Final.Session_GUID, '', '', '');
            CALL _authorization(@.auth.SELECT.MODE, @.auth.Final.Session_GUID,'','','','','','');
		END IF;
	--	Czyszczenie	
		IF NOT IFNULL(@session.Delfinek, FALSE) THEN
			CALL _user_accounts_inf('CLEAR', '', '', ''); 
		END IF;
		
											-- CALL _sys_watch_time_Tools('stop', '_authorization', '???', '', '', '');
	END IF;
	
    IF _MODE LIKE 'SELECT.%AUTH%' THEN
    /*  od IV 2025  - selecty zwiazane tylko z autoryzacją -
        - wziete z _sessions_SEL a tak na prawde to wiel lat w _sessions_App('Select...
    */
        IF _MODE LIKE 'SELECT.AUTH' THEN
            SELECT
                tsel.Session_GUID,
                tsel.Oper_Status AS Verify_Status, --  AS Inf_Status, 
                tsel.Oper_Status LIKE 'OK%' AS Verify_OK, --  AS Inf_Status_OK,  
                tsel.Oper_Status LIKE 'OK%' AS _Verify_OK,	-- kompatybilnośc z poprz. 
                -- tar.USER_GUID, -- tar.OsobaGUID,
                tsel.Oper_Status_Msg AS Msg,
                tsel.Oper_Status_Msg AS _MSG,	-- kompatybilnośc z poprz. 
                CONCAT_WS('\n',
                    NULLIF(tsel.Msg_Warn, ''),
                    tsel.Msg_Log
                ) AS MSG_LONG,
                tsel.Msg_Warn AS Msg_Warning,
                (IFNULL(tsel.Msg_Warn, '') <> '') AS IS_Warning,
                tsel.Status_N_Warn AS Verify_Status_All,
                -- tar.Add_MSG AS Inf_MsgEx,
                -- było ale zabrałem tsel.Verify_Access_available, --  AS Inf_Access_available,
                -- było ale zabrałem tsel.MSG_APP_ID_Err, -- tekst o braku dostepy
                -- było ale zabrałem tsel.MSG_APP_ID_OK,	 -- tekst o dostepach (dodatk.)
                IFNULL(u.err_logon_count, 0) AS err_logon_count,
                (@.auth.Max_User_Err_logon_count - IFNULL(u.err_logon_count, 0)) AS logon_tries, 
                sdl.GUID, 
                sdl.log_USER, 
                sdl.log_USER_GUID, 
                sdl.LAST_MSG, 
                /*
                IF(sdl.LAST_MSG LIKE 'ERR%' OR sdl.LAST_MSG LIKE '%.RODO.Need.Change.PSWD',
                    sdl.LAST_MSG,
                    ''
                ) AS VIEW_MSG,
                */
                sdl.STATUS, 
                CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, 
                u.User_account_Type,
                u.Administrator, 
                -- IF(sdl.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg,
                u.Ad_mail,
                IFNULL(
                    IFNULL(
                        (SELECT o.KontrGUID FROM `osoby` o WHERE o.GUID = sdl.log_USER_GUID)
                        ,
                        (SELECT hk.KontrGUID FROM `hr_kontrah_links` hk WHERE hk.osobaGUID = sdl.log_USER_GUID)
                    ),
                    ''
                ) AS KontrGUID,
                sdl.ext_flag LIKE '%<LOG:#Login,#Pswd:_FDatasSU>%' AS FDataSu
            FROM `t_ua_inf` tsel
            LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = tsel.Session_GUID
            -- LEFT JOIN `v_intnet_users` u ON u.GUID = sdl.log_USER_GUID
            -- LEFT JOIN `v_user_accounts` u ON u.GUID = sdl.log_USER_GUID
            LEFT JOIN `v_user_accounts_short` u ON u.GUID = sdl.log_USER_GUID
            WHERE 
                TRUE
                -- czy potrzebne??? AND tsel.Session_GUID = _IN_Session_GUID   -- dawne _GUID
            ;
        END IF;
        
        IF _MODE LIKE 'SELECT.old.AUTH' THEN
            SELECT
                Session_GUID,
                tar.Verify_Status, --  AS Inf_Status, 
                tar.Verify_OK, --  AS Inf_Status_OK,  
                -- tar.USER_GUID, -- tar.OsobaGUID,
                tar.MSG, --  AS Inf_Msg, 
                tar.MSG_LONG, --  AS Inf_Msg_Long,
                -- tar.Add_MSG AS Inf_MsgEx,
                tar.Verify_Access_available, --  AS Inf_Access_available,
                tar.MSG_APP_ID_Err,
                tar.MSG_APP_ID_OK,
                sdl.GUID, 
                sdl.log_USER, 
                sdl.log_USER_GUID, 
                sdl.LAST_MSG, 
                /*
                IF(sdl.LAST_MSG LIKE 'ERR%' OR sdl.LAST_MSG LIKE '%.RODO.Need.Change.PSWD',
                    sdl.LAST_MSG,
                    ''
                ) AS VIEW_MSG,
                */
                sdl.STATUS, 
                CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, 
                -- u.NazwiskoImie AS NazwiskoImiona,
                u.User_account_Type,
                u.Administrator, 
                -- IF(sdl.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg,
                IFNULL(
                    IFNULL(
                        (SELECT o.KontrGUID FROM `osoby` o WHERE o.GUID = sdl.log_USER_GUID)
                        ,
                        (SELECT hk.KontrGUID FROM `hr_kontrah_links` hk WHERE hk.osobaGUID = sdl.log_USER_GUID)
                    ),
                    ''
                ) AS KontrGUID
            FROM `t_auth_rec` tar
            LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = tar.Session_GUID
            LEFT JOIN `v_intnet_users` u ON u.GUID = sdl.log_USER_GUID
            WHERE 
                TRUE
                AND tar.Session_GUID = _IN_Session_GUID   -- dawne _GUID
            ;
        END IF;

        IF _MODE LIKE 'SELECT.AUTH._sys_db_logons_Tools' THEN
        --	_sys_db_logons_Tools
            SELECT 
                l.GUID, l.log_USER, l.log_USER_GUID, 
                -- l.LAST_MSG, 
                IFNULL(NULLIF(@.auth.Final.MSG, ''), @.auth.Final.Verify_Status) AS LAST_MSG,
                l.STATUS, u.Administrator, 
                CONCAT(u.Nazwisko, ' ', u.Imiona) AS NazwiskoImiona, u.User_account_Type, u.user_type,
                -- IF(l.LAST_MSG = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg
                IF(@.auth.Final.Verify_Status = 'OK.RODO.Need.Change.PSWD', 'Ze względu na przepisy RODO wymagana jest okresowa zmiana hasła.\nProszę podać nowe - zmienione - hasło!', '') AS Add_Msg
            FROM `_sys_db_logons` l
            LEFT JOIN `v_intnet_users` u ON u.GUID = l.log_USER_GUID
            WHERE 
                l.GUID = _IN_Session_GUID   -- dawne _GUID
            ;
        END IF;
        
        IF _MODE LIKE 'SELECT.AUTH._sys_authorization' THEN
        --	_sys_authorization
            SELECT
                -- tsel.*,
                sdl.GUID AS _Session_GUID, 
                tsel.IN_Mode AS L_Mode,
                tsel.UserGUID AS USER_GUID,
                    -- sdl.log_USER AS User_login,
                u.login AS User_login,
                tsel.Oper_Status LIKE 'OK%' AS _Verify_OK,
                tsel.Oper_Status AS _Verify_Status,
                tsel.Oper_Status_Msg AS _MSG,	-- kompatybilnośc z poprz. 
                u.User_account_Type AS User_type,
                u.Administrator AS admin, 
                u.Status,
                u.Ad_Mail,
                u.date_from,
                u.date_to,
                IFNULL(u.err_logon_count, 0) AS err_logon_count,
                u.GUID AS OsobaGUID,
                tsel.Owner,
                tsel.APP_ID,
                
                u.User_account_Type AS Typ,
                IF(@session.globals.RODO.Days = 0, '2100-01-01', DATE(DATE_ADD(u.Last_Change_Pswd, INTERVAL @session.globals.RODO.Days DAY))) AS USER_First_Day_to_Change_Pswd,
                u.Last_Change_Pswd AS USER_Last_Change_Pswd,
                tsel.Salt AS _INPUT_SALT_Hash,
                CONCAT_WS(' ', IFNULL(u.Nazwisko, 'Nie ustalony'), u.Imiona) AS USER_Str
            FROM `t_ua_inf` tsel
            LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = tsel.Session_GUID
            LEFT JOIN `v_user_accounts_short` u ON u.GUID = tsel.UserGUID -- sdl.log_USER_GUID
            WHERE 
                TRUE
                -- and tsel.Session_GUID = 'CON:20221214.084903:3111'
                -- tsel.Session_GUID = @.SYSTEM.Last_Insert.Session.GUID
            ;
        END IF;
        
        IF _MODE LIKE 'SELECT.AUTH._sys_connection_Tool' THEN
        --	_sys_connection_Tool
            SELECT tsel.Msg INTO @.tsel.Msg FROM `t_ua_inf` tsel;
            SELECT
                IF(sdl.Status LIKE '%ERR%', NULL, sdl.con_ID) AS Session_ID, 
                -- sdl.con_ID AS Session_ID, 
                IF(sdl.Status LIKE '%ERR%', NULL, sdl.GUID) AS Session_GUID, 
                -- sdl.GUID AS Session_GUID,
                IF(sdl.Status LIKE '%ERR%', NULL, sdl.log_USER_GUID) AS USER_GUID, 
                -- sdl.log_USER_GUID AS USER_GUID,
                IF(sdl.Status LIKE '%ERR%', @.tsel.Msg, 'Wersja zweryfikowana') AS Message
            FROM (
                SELECT
                    CONNECTION_ID() AS Session_ID, '' AS Session_GUID, '' AS USER_GUID
                ) n
            LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = _IN_Session_GUID   -- dawne _GUID
            ;
        END IF;
        
    
    --  Stara i nie wiem czy używana z t_auth_rec !!!!!    
        IF _MODE LIKE '%SELECT.from.`t_auth_rec`%' THEN
            SELECT 
                tar.*
            FROM `t_auth_rec` tar
            -- LEFT JOIN `kontrah` k ON k.
            ;
        END IF;
    END IF;
	
END$$


DELIMITER ;

/*
====================================================================================================================================================================================
	NOTATNIK
====================================================================================================================================================================================

Logowanie biometryczne
1. Aplikacja (tak było mniemam dotychczas pposiada:
- 	GUID USER oraz
-	ID urządzenia - ogólnie pojmowany ID np jakies IMEI/Mcaddress/etc.
Aby się zalogowac te dwa parametry musza byc przekazane analogicznie ja Login/hasło
w zwykłym logowaniu
Oczywiście teke parametyry musza byc posolone i popieprzone!!!
2. Parametry
W delfinku sznurek przygotowuje nastepujaco:
SET
	@._IN_Auth_Params = 
	CONCAT_WS('&',
		CONCAT('S.ID=', @.LOG.Input.Session),
		CONCAT('A.ID#=', @.LOG.Input.APP_ID.Hash),
		CONCAT('D.ID#=', @.LOG.Input.DEV_ID.Hash),	-- ID urzadzenia -> Sól/pieprz
		CONCAT('U.G#=', @.LOG.Input.USER_GUID.Hash),	-- UserGUID -> Sól/pieprz
		CONCAT('A.VER=', @.LOG.Input.APP_VER)		-- wersja app. (nieobow.!!!!!)
	)
;
czyli analogicznie jak logowanie tyler że 
3. Call - wołanie czyli procedura
CALL _authorization('LOG.BIO:#UserGUID,#DEV_ID', @.LOG.Input.Session, @._IN_Auth_Params, '', '', '', '', '<Select>');

Rejestracja BIO 
1. Rejestracja polega na autoryzacji i zarejestrowaniu ID urządzenia (chodzi o to samo ID co 
w p. 1.2.3 logowania BIO
Poniewaz jest tu także autoryzacja to sznurek musi posiadać za zatem user musi podać Login/hasło!!! a dodatkowo
oczywiście przekazywane jest ID
2. Parametry rej. BIO 
SET
	@._IN_Auth_Params =
	CONCAT_WS('&',
		CONCAT('S.ID=', @.LOG.Input.Session),
		CONCAT('U.L#=', @.LOG.Input.LOG_User.Hash),	-- login -> Sól/pieprz
		CONCAT('U.P#=', @.LOG.Input.LOG_PASS.Hash),	-- pswd -> Sól/pieprz
		CONCAT('D.ID=', @.LOG.Input.DEV_ID)			-- ID urzadzenia 
	)
;
3. Call rej. BIO
CALL _authorization('AUTH:#Login,#Pswd+ADD.BIO:DEV_ID', @.LOG.Input.Session, @._IN_Auth_Params, '', '', '', '', '<Select>');		

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*/
