Browse Source

allow multiple account for email

Piotr Labudda 4 years ago
parent
commit
8eeeb3511d
4 changed files with 231 additions and 47 deletions
  1. 153 22
      auth.php
  2. 29 0
      theme/panel_biall_net.php
  3. 46 0
      tools/ChangeUser.php
  4. 3 25
      tools/RemindPasswd.php

+ 153 - 22
auth.php

@@ -26,26 +26,34 @@ class Theme_Auth_panel_biall_net { // TODO: implements AuthBaseInterface {
 
 		if (empty($login) || empty($pass)) throw new Exception("Proszę podać login i hasło!");
 
-		// { // TODO: TEST
-		// 	$login = "krzys.dworski@gmail.com"; // COMPANIES.user_mail_contact
-		// 	$pass = "76022801989"; // COMPANIES.P_PESEL or COMPANIES.PASSWD varchar(100) --- table PANEL_KLIENTA_BN_AUTH
+		// $item = self::fetchUser($login);
+		// if (empty($item['PASSWD']) || 32 != strlen($item['PASSWD'])) {
+		// 	throw new Exception("Proszę użyć funkcji przypomnienia hasła");
 		// }
 
-		$item = self::fetchUser($login);
-		if (empty($item['PASSWD']) || 32 != strlen($item['PASSWD'])) {
-			throw new Exception("Proszę użyć funkcji przypomnienia hasła");
-		}
+		// if (md5($pass) !== $item['PASSWD']) {
+		// 	throw new Exception("Proszę podać poprawny login i hasło!");
+		// }
 
-		if (md5($pass) !== $item['PASSWD']) {
-			throw new Exception("Proszę podać poprawny login i hasło!");
+		$userInfo = null;
+		$activeUsers = self::makeActiveUsers($login);
+		foreach ($activeUsers as $item) {
+			if (empty($item['PASSWD']) || 32 != strlen($item['PASSWD'])) {
+				continue; // throw new Exception("Proszę użyć funkcji przypomnienia hasła");
+			}
+			if (md5($pass) === $item['PASSWD']) {
+				$userInfo = $item;
+				break;
+			}
 		}
+		if (!$userInfo) throw new Exception("Proszę podać poprawny login i hasło!");
 
 		return (object)[
-			'ID' => $item['ID'],
-			'ADM_ACCOUNT' => $item['LOGIN'], // AUTHORIZE_USER, ADM_ACCOUNT
-			'ADM_NAME' => implode(" ", [ $item['P_NAME'], $item['P_NAME_SECOND'] ]), // ADM_NAME
+			'ID' => $userInfo['ID'],
+			'ADM_ACCOUNT' => $userInfo['LOGIN'], // AUTHORIZE_USER, ADM_ACCOUNT
+			'ADM_NAME' => implode(" ", [ $userInfo['P_NAME'], $userInfo['P_NAME_SECOND'] ]), // ADM_NAME
 			'ADM_TECH_WORKER' => "", // ADM_TECH_WORKER
-			'ADM_COMPANY' => $item['BILLING_OWNER'], // ADM_COMPANY
+			'ADM_COMPANY' => $userInfo['BILLING_OWNER'], // ADM_COMPANY
 			'ADM_ADMIN_LEVEL' => 5, // ADM_ADMIN_LEVEL // > 5 will show msg for Kandydat
 			'ADM_PHONE' => "", // ADM_PHONE
 			'ADM_ADMIN_EXPIRE' => "", // ADM_ADMIN_EXPIRE
@@ -53,6 +61,104 @@ class Theme_Auth_panel_biall_net { // TODO: implements AuthBaseInterface {
 			'EMPLOYEE_TYPE' => "Klient", // EMPLOYEE_TYPE // [ 'Pracownik','Kandydat','Partner','Anonymous','Kontakt','Skrypt' ]
 		];
 	}
+	static function testAuth($login, $pass) {
+		$userInfo = null;
+		$activeUsers = self::makeActiveUsers($login);
+		foreach ($activeUsers as $item) {
+			if (empty($item['PASSWD']) || 32 != strlen($item['PASSWD'])) {
+				continue; // throw new Exception("Proszę użyć funkcji przypomnienia hasła");
+			}
+			if (md5($pass) === $item['PASSWD']) {
+				$userInfo = $item;
+				break;
+			}
+		}
+
+		if (!$userInfo) throw new Exception("Proszę podać poprawny login i hasło!");
+		return $userInfo;
+	}
+
+	// after auth set additional session variables
+	static function authorizedTrigger($login, $pass = '') {
+		$fetchAllUsers = self::fetchActiveUsers($login);
+		$_SESSION['PANEL_BN_USERS'] = (count($fetchAllUsers) > 1) ? array_map(function ($item) {
+			return [
+				'ID' => $item['ID'],
+				'LOGIN' => $item['LOGIN'],
+				'P_NAME' => $item['P_NAME'],
+				'P_NAME_SECOND' => $item['P_NAME_SECOND'],
+				'BILLING_OWNER' => $item['BILLING_OWNER'],
+			];
+		}, $fetchAllUsers) : [];
+	}
+
+	static function test_fetchAllUsers($login) {
+		$sqlTest = "
+			select c.ID
+				, c.user_mail_contact
+				, c.P_NAME, c.P_NAME_SECOND
+				, c.P_PESEL, c.P_NIP
+				, c.A_STATUS, c.STATUS
+				, c.A_CLASSIFIED, c.A_ADM_COMPANY
+				, c.BILLING_OWNER -- 1 BN, 3 NETDAY
+			from COMPANIES c
+			where c.user_mail_contact = :email
+		";
+		return DB::getPDO()->tryHandleException([ __CLASS__, 'preparePanelBNAuthTables' ], 'fetchAll', [
+			$sqlTest, [ ':email' => $login ]
+		]);
+	}
+
+	static function makeActiveUsers($login) {
+		$activeUsers = self::fetchActiveUsers($login);
+
+		foreach ($activeUsers as $idx => $item) {
+			if (!$item['ID_AUTH']) {
+				$activeUsers[$idx]['P_PESEL'] = trim(str_replace(' ', '', $item['P_PESEL']));
+				$activeUsers[$idx]['P_NIP'] = trim(str_replace([' ', '-'], '', $item['P_NIP']));
+				$passwd = (!empty($activeUsers[$idx]['P_PESEL'])) ? $activeUsers[$idx]['P_PESEL'] : $activeUsers[$idx]['P_NIP'];
+				$hashPass = ($passwd) ? md5($passwd) : null;
+				DB::getPDO()->insert('PANEL_KLIENTA_BN_AUTH', [
+					'ID_BILLING_USERS' => $activeUsers[$idx]['ID'],
+					'LOGIN' => $activeUsers[$idx]['user_mail_contact'],
+					'PASSWD' => $hashPass,
+					'A_RECORD_CREATE_DATE' => "NOW()",
+				]);
+				$activeUsers[$idx]['ID_BILLING_USERS'] = $activeUsers[$idx]['ID'];
+				$activeUsers[$idx]['LOGIN'] = $activeUsers[$idx]['user_mail_contact'];
+				$activeUsers[$idx]['PASSWD'] = $hashPass;
+			}
+		}
+
+		return $activeUsers;
+	}
+
+	static function fetchActiveUsers($login) {
+		// TODO: filtr BN / NETDAY ?
+		// TODO: filtr ZGODA_NA mail/fv ?
+		$sql = "
+			select c.ID
+				, c.user_mail_contact
+				, c.P_NAME, c.P_NAME_SECOND
+				, c.P_PESEL, c.P_NIP
+				, c.A_STATUS, c.STATUS
+				, c.A_CLASSIFIED, c.A_ADM_COMPANY
+				, c.BILLING_OWNER -- 1 BN, 3 NETDAY
+				, p.ID as ID_AUTH
+				, p.LOGIN
+				, p.PASSWD
+				, p.REMIND_PASS_KEY
+				, p.REMIND_PASS_VALID_TILL
+			from COMPANIES c
+				left join PANEL_KLIENTA_BN_AUTH p on ( p.ID_BILLING_USERS = c.ID and p.LOGIN = c.user_mail_contact )
+			where c.user_mail_contact = :email
+				and c.A_CLASSIFIED = :acl
+				and c.A_ADM_COMPANY = :acl
+		";
+		return DB::getPDO()->tryHandleException([ __CLASS__, 'preparePanelBNAuthTables' ], 'fetchAll', [
+			$sql, [ ':email' => $login, ':acl' => '27_BIALL-NET' ]
+		]);
+	}
 
 	static function fetchUser($login) {
 		$item = DB::getPDO()->tryHandleException([ __CLASS__, 'preparePanelBNAuthTables' ], 'fetchFirst', [
@@ -97,20 +203,44 @@ class Theme_Auth_panel_biall_net { // TODO: implements AuthBaseInterface {
 		return $item;
 	}
 
+	static function sendRemindPasswd($email, $resetLink, $recipient) {
+		$recipient = "piotrl86+bn-test-remind@gmail.com"; // TODO: ($recipient) ? $recipient : $email
+
+		$headers = "MIME-Version: 1.0\n";
+		$headers .= "Content-Type: text/plain; charset=\"utf-8\"\n";
+		$headers .= 'From: Panel klienta BIALL-NET <noreply@biall-net.pl>' . "\r\n";
+		// $headers .= 'Bcc: piotrl86@gmail.com' . "\r\n";
+
+		$subject = "Panel BIALL-NET: Ustawianie nowego hasła";
+
+		$body = implode("\r\n\r\n", [
+			"Ktoś poprosił o wygenerowanie nowego hasła dla następującego konta:",
+			"Nazwa witryny: Panel klienta BIALL-NET",
+			"Nazwa użytkownika: {$email}",
+			"Jeśli to pomyłka po prostu zignoruj tego maila i nic się nie stanie.",
+			"Aby zresetować hasło, przejdź tutaj:",
+			"{$resetLink}",
+		]);
+
+		mail($recipient, $subject, $body, $headers);
+	}
+
 	static function generateRemindKey($email) {
 		$remindKey = substr(md5($email . "" . date("Y-m-d H:i:s")), 0, 16);
 		$remindTill = date("Y-m-d", mktime(0,0,0, date("m"), date("d") + 2, date("Y")));
-		$userInfo = self::fetchUser($email);
+		// $userInfo = self::fetchUser($email);
+		self::makeActiveUsers($email); // creates PANEL_KLIENTA_BN_AUTH if missing
 		DB::getPDO()->execSql("
 			update PANEL_KLIENTA_BN_AUTH
 			set REMIND_PASS_KEY = :remind_key
 				, REMIND_PASS_VALID_TILL = :remind_till
 				, A_RECORD_UPDATE_DATE = NOW()
-			where ID_BILLING_USERS = :id_user
-				and LOGIN = :login
+			where LOGIN = :login
+		--		and ID_BILLING_USERS = :id_user
 		", [
-			':id_user' => $userInfo['ID'],
-			':login' => $userInfo['LOGIN'],
+			// ':id_user' => $userInfo['ID'],
+			// ':login' => $userInfo['LOGIN'],
+			':login' => $email,
 			':remind_key' => $remindKey,
 			':remind_till' => $remindTill,
 		]);
@@ -148,11 +278,12 @@ class Theme_Auth_panel_biall_net { // TODO: implements AuthBaseInterface {
 				, REMIND_PASS_VALID_TILL = '0000-00-00'
 				, PASSWD = :hash_passwd
 				, A_RECORD_UPDATE_DATE = NOW()
-			where ID_BILLING_USERS = :id_user
-				and LOGIN = :login
+			where LOGIN = :login
+		--		and ID_BILLING_USERS = :id_user
 		", [
-			':id_user' => $userInfo['ID'],
-			':login' => $userInfo['LOGIN'],
+			// ':id_user' => $userInfo['ID'],
+			// ':login' => $userInfo['LOGIN'],
+			':login' => $email,
 			':hash_passwd' => md5($newPasswd),
 		]);
 	}

+ 29 - 0
theme/panel_biall_net.php

@@ -64,6 +64,7 @@ class Theme_panel_biall_net extends ThemeDefault {
 	}
 
 	function home($data) { // TODO: home page view
+		// trigger_error(date("Y-m-d H:i:s") . "\t" . "panel_bn/home uid(".User::getID().") ses: { ID: {$_SESSION['ID']}, ADM_NAME: {$_SESSION['ADM_NAME']} }", E_USER_NOTICE);
 		if (is_array($data) && !empty($data)) {
 			extract($data);
 		}
@@ -116,6 +117,34 @@ class Theme_panel_biall_net extends ThemeDefault {
 		$saldo = $billDocs->get_saldo();
 		$nr_konta = Windykacja_FunkcjeL1::bankowy_make_nrach($company['NR_RACH_MASS_PAY'], User::getID(), 0);
 
+		if (!empty($_SESSION['PANEL_BN_USERS'])) {
+			$idUser = User::getID();
+			// echo UI::h('pre', [], var_export($_SESSION['PANEL_BN_USERS'], true));
+			echo UI::h('form', [ 'method' => "POST" ], [
+				UI::h('div', [ 'class' => "row" ], [
+					UI::h('div', [ 'class' => "col-md-offset-3 col-md-6" ], [
+						UI::h('div', [ 'class' => "form-group" ], [
+							UI::h('label', [ 'class' => "label-control" ], "Klient"),
+							UI::h('select', [ 'name' => "id", 'class' => "form-control", 'onChange' => "this.form.submit()" ], array_map(function ($item) use ($idUser) {
+								// 'ID' => '13684',
+								// 'LOGIN' => 'paulina.kinowska@wp.pl',
+								// 'P_NAME' => 'Paulina',
+								// 'P_NAME_SECOND' => 'Kinowska',
+								// 'BILLING_OWNER' => '3',
+								return UI::h('option', array_merge(
+									[ 'value' => $item['ID'] ],
+									($idUser == $item['ID']) ? [ 'selected' => "selected" ] : []
+								), $item['P_NAME'] . " " . $item['P_NAME_SECOND']);
+							}, $_SESSION['PANEL_BN_USERS'])),
+							UI::h('input', [ 'type' => "hidden", 'name' => "_route", 'value' => "UrlAction_ChangeUser" ]),
+							UI::h('input', [ 'type' => "hidden", 'name' => "_postTask", 'value' => "_changeUser" ]),
+						]),
+					]),
+				]),
+			]);
+
+		}
+
 		include dirname(__FILE__) . '/view/home.php';
 	}
 

+ 46 - 0
tools/ChangeUser.php

@@ -0,0 +1,46 @@
+<?php
+
+Lib::loadClass('RouteToolBase');
+Lib::loadClass('UI');
+Lib::loadClass('Response');
+Lib::loadClass('Theme');
+
+require_once dirname(__FILE__) . '/../auth.php'; // Theme_Auth_panel_biall_net
+
+// class name must have the same name as file
+// index.php?_route=UrlAction_ChangeUser  - uruchamia defaultAction
+class RouteTool_ChangeUser extends RouteToolBase {
+
+	function handleAuth() {
+		$id = V::get('id', '', $_POST);
+		$authIds = (!empty($_SESSION['PANEL_BN_USERS'])) ? array_map(V::makePick('ID'), $_SESSION['PANEL_BN_USERS']) : [];
+		// trigger_error(date("Y-m-d H:i:s") . "\t" . "panel_bn/RouteTool_ChangeUser to({$id}) ids:[".implode(",", $authIds)."]", E_USER_NOTICE);
+		if (!$id || !in_array($id, $authIds)) {
+			return Response::sendRedirect( "index.php" );
+		}
+
+		foreach ($_SESSION['PANEL_BN_USERS'] as $item) {
+			if ($id != $item['ID']) continue;
+
+			// trigger_error(date("Y-m-d H:i:s") . "\t" . "panel_bn/RouteTool_ChangeUser changed to({$id})", E_USER_NOTICE);
+			@session_start();
+			$_SESSION['ADM_ID'] = $item['ID'];
+			// 'ADM_ACCOUNT' => $item['LOGIN'], // AUTHORIZE_USER, ADM_ACCOUNT
+			$_SESSION['ADM_NAME'] = implode(" ", [ $item['P_NAME'], $item['P_NAME_SECOND'] ]); // ADM_NAME
+			$_SESSION['ADM_COMPANY'] = $item['BILLING_OWNER']; // ADM_COMPANY
+			session_write_close();
+			sleep(1);
+			// trigger_error(date("Y-m-d H:i:s") . "\t" . "panel_bn/RouteTool_ChangeUser ses: { ID: {$_SESSION['ID']}, ADM_NAME: {$_SESSION['ADM_NAME']} }", E_USER_NOTICE);
+		}
+
+		Response::sendRedirect( "index.php" );
+		exit;
+	}
+
+	function defaultAction() {
+		UI::gora();
+		echo '<h1>ChangeUser Tool</h1>';
+		UI::dol();
+	}
+
+}

+ 3 - 25
tools/RemindPasswd.php

@@ -42,32 +42,10 @@ class RouteTool_RemindPasswd extends RouteToolBase {
 
 		// BŁĄD: Brak zarejestrowanego użytkownika o wprowadzonym adresie email.
 
-		$item = Theme_Auth_panel_biall_net::fetchUser($email);
+		Theme_Auth_panel_biall_net::fetchUser($email);
 		$remindKey = Theme_Auth_panel_biall_net::generateRemindKey($email);
-		{
-			$resetLink = $this->getLink('rp', [ 'login' => $email, 'key' => $remindKey ]);
-
-			$recipient = "piotrl86+bn-test-remind@gmail.com"; // TODO: $email
-
-			$headers = "MIME-Version: 1.0\n";
-			$headers .= "Content-Type: text/plain; charset=\"utf-8\"\n";
-			//$headers .= 'Bcc: pawel.ratajczak@biall.com.pl' . "\r\n";
-			$headers .= 'From: Panel klienta BIALL-NET <noreply@biall-net.pl>' . "\r\n";
-			$headers .= 'Bcc: piotrl86@gmail.com' . "\r\n";
-	
-			$subject = "Panel BIALL-NET: Ustawianie nowego hasła";
-
-			$body = implode("\r\n\r\n", [
-				"Ktoś poprosił o wygenerowanie nowego hasła dla następującego konta:",
-				"Nazwa witryny: Panel klienta BIALL-NET",
-				"Nazwa użytkownika: {$email}",
-				"Jeśli to pomyłka po prostu zignoruj tego maila i nic się nie stanie.",
-				"Aby zresetować hasło, przejdź tutaj:",
-				"{$resetLink}",
-			]);
-
-			mail($recipient, $subject, $body, $headers);
-		}
+		$resetLink = $this->getLink('rp', [ 'login' => $email, 'key' => $remindKey ]);
+		Theme_Auth_panel_biall_net::sendRemindPasswd($email, $resetLink);
 	}
 
 	function rpAction() {