auth.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. <?php
  2. // rename file to: `config.php`
  3. // @used by User class to login
  4. // - [ ] use to fetch user groups for acl
  5. /**
  6. * User object:
  7. * - ID // ADM_ID
  8. * - ADM_ACCOUNT // AUTHORIZE_USER, ADM_ACCOUNT
  9. * - ADM_NAME // ADM_NAME
  10. * - ADM_TECH_WORKER // ADM_TECH_WORKER
  11. * - ADM_COMPANY // ADM_COMPANY
  12. * - ADM_ADMIN_LEVEL // ADM_ADMIN_LEVEL
  13. * - ADM_PHONE // ADM_PHONE
  14. * - ADM_ADMIN_EXPIRE // ADM_ADMIN_EXPIRE
  15. * - ADM_ADMIN_DESC // ADM_ADMIN_DESC
  16. * - EMPLOYEE_TYPE // EMPLOYEE_TYPE
  17. * - EMAIL_IMAP_IMPORT_HOST // EMAIL_IMAP_IMPORT_HOST
  18. * - EMAIL_IMAP_IMPORT_USERNAME // EMAIL_IMAP_IMPORT_USERNAME
  19. */
  20. class Theme_Auth_panel_biall_net { // TODO: implements AuthBaseInterface {
  21. static function login($login, $pass) { // @return User object or null
  22. if (empty($login) || empty($pass)) throw new Exception("Proszę podać login i hasło!");
  23. // $item = self::fetchUser($login);
  24. // if (empty($item['PASSWD']) || 32 != strlen($item['PASSWD'])) {
  25. // throw new Exception("Proszę użyć funkcji przypomnienia hasła");
  26. // }
  27. // if (md5($pass) !== $item['PASSWD']) {
  28. // throw new Exception("Proszę podać poprawny login i hasło!");
  29. // }
  30. $userInfo = null;
  31. $activeUsers = self::makeActiveUsers($login);
  32. foreach ($activeUsers as $item) {
  33. if (empty($item['PASSWD']) || 32 != strlen($item['PASSWD'])) {
  34. continue; // throw new Exception("Proszę użyć funkcji przypomnienia hasła");
  35. }
  36. if (md5($pass) === $item['PASSWD']) {
  37. $userInfo = $item;
  38. break;
  39. }
  40. }
  41. if (!$userInfo) throw new Exception("Proszę podać poprawny login i hasło!");
  42. return (object)[
  43. 'ID' => $userInfo['ID'],
  44. 'ADM_ACCOUNT' => $userInfo['LOGIN'], // AUTHORIZE_USER, ADM_ACCOUNT
  45. 'ADM_NAME' => implode(" ", [ $userInfo['P_NAME'], $userInfo['P_NAME_SECOND'] ]), // ADM_NAME
  46. 'ADM_TECH_WORKER' => "", // ADM_TECH_WORKER
  47. 'ADM_COMPANY' => $userInfo['BILLING_OWNER'], // ADM_COMPANY
  48. 'ADM_ADMIN_LEVEL' => 5, // ADM_ADMIN_LEVEL // > 5 will show msg for Kandydat
  49. 'ADM_PHONE' => "", // ADM_PHONE
  50. 'ADM_ADMIN_EXPIRE' => "", // ADM_ADMIN_EXPIRE
  51. 'ADM_ADMIN_DESC' => "", // ADM_ADMIN_DESC
  52. 'EMPLOYEE_TYPE' => "Klient", // EMPLOYEE_TYPE // [ 'Pracownik','Kandydat','Partner','Anonymous','Kontakt','Skrypt' ]
  53. ];
  54. }
  55. static function testAuth($login, $pass) {
  56. $userInfo = null;
  57. $activeUsers = self::makeActiveUsers($login);
  58. foreach ($activeUsers as $item) {
  59. if (empty($item['PASSWD']) || 32 != strlen($item['PASSWD'])) {
  60. continue; // throw new Exception("Proszę użyć funkcji przypomnienia hasła");
  61. }
  62. if (md5($pass) === $item['PASSWD']) {
  63. $userInfo = $item;
  64. break;
  65. }
  66. }
  67. if (!$userInfo) throw new Exception("Proszę podać poprawny login i hasło!");
  68. return $userInfo;
  69. }
  70. static function getUserID() { // User::getID() => Theme_Auth_panel_biall_net::getUserID()
  71. if (User::isAdmin() && !empty($_SESSION['PANEL_BN_USER_SELECTED']) && !empty($_SESSION['PANEL_BN_USERS'])) {
  72. return $_SESSION['PANEL_BN_USER_SELECTED'];
  73. } else return User::getID();
  74. }
  75. // after auth set additional session variables
  76. static function authorizedTrigger($login, $pass = '') {
  77. $fetchAllUsers = self::fetchActiveUsers($login);
  78. $_SESSION['PANEL_BN_USERS'] = (count($fetchAllUsers) > 1) ? array_map(function ($item) {
  79. return [
  80. 'ID' => $item['ID'],
  81. 'LOGIN' => $item['LOGIN'],
  82. 'P_NAME' => $item['P_NAME'],
  83. 'P_NAME_SECOND' => $item['P_NAME_SECOND'],
  84. 'BILLING_OWNER' => $item['BILLING_OWNER'],
  85. ];
  86. }, $fetchAllUsers) : [];
  87. }
  88. static function test_fetchAllUsers($login) {
  89. $sqlTest = "
  90. select c.ID
  91. , c.user_mail_contact
  92. , c.P_NAME, c.P_NAME_SECOND
  93. , c.P_PESEL, c.P_NIP
  94. , c.A_STATUS, c.STATUS
  95. , c.A_CLASSIFIED, c.A_ADM_COMPANY
  96. , c.BILLING_OWNER -- 1 BN, 3 NETDAY
  97. from COMPANIES c
  98. where c.user_mail_contact = :email
  99. ";
  100. return DB::getPDO()->tryHandleException([ __CLASS__, 'preparePanelBNAuthTables' ], 'fetchAll', [
  101. $sqlTest, [ ':email' => $login ]
  102. ]);
  103. }
  104. static function makeActiveUsers($login) {
  105. $activeUsers = self::fetchActiveUsers($login);
  106. foreach ($activeUsers as $idx => $item) {
  107. if (!$item['ID_AUTH']) {
  108. $activeUsers[$idx]['P_PESEL'] = trim(str_replace(' ', '', $item['P_PESEL']));
  109. $activeUsers[$idx]['P_NIP'] = trim(str_replace([' ', '-'], '', $item['P_NIP']));
  110. $passwd = (!empty($activeUsers[$idx]['P_PESEL'])) ? $activeUsers[$idx]['P_PESEL'] : $activeUsers[$idx]['P_NIP'];
  111. $hashPass = ($passwd) ? md5($passwd) : null;
  112. DB::getPDO()->insert('PANEL_KLIENTA_BN_AUTH', [
  113. 'ID_BILLING_USERS' => $activeUsers[$idx]['ID'],
  114. 'LOGIN' => $activeUsers[$idx]['user_mail_contact'],
  115. 'PASSWD' => $hashPass,
  116. 'A_RECORD_CREATE_DATE' => "NOW()",
  117. ]);
  118. $activeUsers[$idx]['ID_BILLING_USERS'] = $activeUsers[$idx]['ID'];
  119. $activeUsers[$idx]['LOGIN'] = $activeUsers[$idx]['user_mail_contact'];
  120. $activeUsers[$idx]['PASSWD'] = $hashPass;
  121. }
  122. }
  123. return $activeUsers;
  124. }
  125. static function fetchActiveUsers($login) {
  126. // TODO: filtr BN / NETDAY ?
  127. // TODO: filtr ZGODA_NA mail/fv ?
  128. $sql = "
  129. select c.ID
  130. , c.user_mail_contact
  131. , c.P_NAME, c.P_NAME_SECOND
  132. , c.P_PESEL, c.P_NIP
  133. , c.A_STATUS, c.STATUS
  134. , c.A_CLASSIFIED, c.A_ADM_COMPANY
  135. , c.BILLING_OWNER -- 1 BN, 3 NETDAY
  136. , p.ID as ID_AUTH
  137. , p.LOGIN
  138. , p.PASSWD
  139. , p.REMIND_PASS_KEY
  140. , p.REMIND_PASS_VALID_TILL
  141. from COMPANIES c
  142. left join PANEL_KLIENTA_BN_AUTH p on ( p.ID_BILLING_USERS = c.ID and p.LOGIN = c.user_mail_contact )
  143. where c.user_mail_contact = :email
  144. and c.A_CLASSIFIED = :acl
  145. and c.A_ADM_COMPANY = :acl
  146. ";
  147. return DB::getPDO()->tryHandleException([ __CLASS__, 'preparePanelBNAuthTables' ], 'fetchAll', [
  148. $sql, [ ':email' => $login, ':acl' => '27_BIALL-NET' ]
  149. ]);
  150. }
  151. static function fetchUser($login) {
  152. $item = DB::getPDO()->tryHandleException([ __CLASS__, 'preparePanelBNAuthTables' ], 'fetchFirst', [
  153. "
  154. select c.ID, c.user_mail_contact, c.P_PESEL
  155. -- , c.PASSWD
  156. , c.P_NAME, c.P_NAME_SECOND
  157. , c.BILLING_OWNER -- 1 BN, 3 NETDAY
  158. , c.is_firma
  159. , c.P_NIP
  160. , p.ID as ID_AUTH
  161. , p.LOGIN
  162. , p.PASSWD
  163. , p.REMIND_PASS_KEY
  164. , p.REMIND_PASS_VALID_TILL
  165. from COMPANIES c
  166. left join PANEL_KLIENTA_BN_AUTH p on ( p.ID_BILLING_USERS = c.ID and p.LOGIN = c.user_mail_contact )
  167. where c.user_mail_contact like :email
  168. ",
  169. [
  170. ':email' => $login,
  171. ]
  172. ]);
  173. if (!$item) throw new Exception("BŁĄD: Brak zarejestrowanego użytkownika o wprowadzonym adresie email.");
  174. if (!$item['ID_AUTH']) {
  175. $item['P_PESEL'] = trim(str_replace(' ', '', $item['P_PESEL']));
  176. $item['P_NIP'] = trim(str_replace([' ', '-'], '', $item['P_NIP']));
  177. $passwd = (!empty($item['P_PESEL'])) ? $item['P_PESEL'] : $item['P_NIP'];
  178. $hashPass = ($passwd) ? md5($passwd) : null;
  179. DB::getPDO()->insert('PANEL_KLIENTA_BN_AUTH', [
  180. 'ID_BILLING_USERS' => $item['ID'],
  181. 'LOGIN' => $item['user_mail_contact'],
  182. 'PASSWD' => $hashPass,
  183. 'A_RECORD_CREATE_DATE' => "NOW()",
  184. ]);
  185. $item['ID_BILLING_USERS'] = $item['ID'];
  186. $item['LOGIN'] = $item['user_mail_contact'];
  187. $item['PASSWD'] = $hashPass;
  188. }
  189. return $item;
  190. }
  191. static function sendRemindPasswd($email, $resetLink, $recipient) {
  192. $recipient = "piotrl86+bn-test-remind@gmail.com"; // TODO: ($recipient) ? $recipient : $email
  193. $headers = "MIME-Version: 1.0\n";
  194. $headers .= "Content-Type: text/plain; charset=\"utf-8\"\n";
  195. $headers .= 'From: Panel klienta BIALL-NET <noreply@biall-net.pl>' . "\r\n";
  196. // $headers .= 'Bcc: piotrl86@gmail.com' . "\r\n";
  197. $subject = "Panel BIALL-NET: Ustawianie nowego hasła";
  198. $body = implode("\r\n\r\n", [
  199. "Ktoś poprosił o wygenerowanie nowego hasła dla następującego konta:",
  200. "Nazwa witryny: Panel klienta BIALL-NET",
  201. "Nazwa użytkownika: {$email}",
  202. "Jeśli to pomyłka po prostu zignoruj tego maila i nic się nie stanie.",
  203. "Aby zresetować hasło, przejdź tutaj:",
  204. "{$resetLink}",
  205. ]);
  206. mail($recipient, $subject, $body, $headers);
  207. }
  208. static function generateRemindKey($email) {
  209. $remindKey = substr(md5($email . "" . date("Y-m-d H:i:s")), 0, 16);
  210. $remindTill = date("Y-m-d", mktime(0,0,0, date("m"), date("d") + 2, date("Y")));
  211. // $userInfo = self::fetchUser($email);
  212. self::makeActiveUsers($email); // creates PANEL_KLIENTA_BN_AUTH if missing
  213. DB::getPDO()->execSql("
  214. update PANEL_KLIENTA_BN_AUTH
  215. set REMIND_PASS_KEY = :remind_key
  216. , REMIND_PASS_VALID_TILL = :remind_till
  217. , A_RECORD_UPDATE_DATE = NOW()
  218. where LOGIN = :login
  219. -- and ID_BILLING_USERS = :id_user
  220. ", [
  221. // ':id_user' => $userInfo['ID'],
  222. // ':login' => $userInfo['LOGIN'],
  223. ':login' => $email,
  224. ':remind_key' => $remindKey,
  225. ':remind_till' => $remindTill,
  226. ]);
  227. return $remindKey;
  228. }
  229. static function setPasswd($email, $newPasswd, $remindKey) {
  230. if (empty($email)) throw new Exception("Missing login!");
  231. if (empty($newPasswd)) throw new Exception("Missing password!");
  232. if (empty($remindKey)) throw new Exception("Missing remindKey!");
  233. // TODO: validate password!
  234. if (strlen($newPasswd) < 8) throw new Exception("Hasło musi się składać z co najmniej 8 znaków");
  235. $userInfo = self::fetchUser($email);
  236. // DBG::nicePrint([
  237. // 'c1' => empty($userInfo['REMIND_PASS_KEY']),
  238. // 'c2' => $userInfo['REMIND_PASS_KEY'] !== $remindKey,
  239. // 'c2.L' => $userInfo['REMIND_PASS_KEY'],
  240. // 'c2.R' => $remindKey,
  241. // 'c3' => date("Y-m-d") > $userInfo['REMIND_PASS_VALID_TILL'],
  242. // 'c3.L' => date("Y-m-d"),
  243. // 'c3.R' => $userInfo['REMIND_PASS_VALID_TILL'],
  244. // 'user' => $userInfo,
  245. // ], 'DBG');
  246. if (empty($userInfo['REMIND_PASS_KEY'])
  247. || $userInfo['REMIND_PASS_KEY'] !== $remindKey
  248. || date("Y-m-d") > $userInfo['REMIND_PASS_VALID_TILL']
  249. ) throw new Exception("Odnośnik do resetowania hasła wydaje się być niesprawny. Proszę użyć funkcji przypomnienia hasła.");
  250. DB::getPDO()->execSql("
  251. update PANEL_KLIENTA_BN_AUTH
  252. set REMIND_PASS_KEY = ''
  253. , REMIND_PASS_VALID_TILL = '0000-00-00'
  254. , PASSWD = :hash_passwd
  255. , A_RECORD_UPDATE_DATE = NOW()
  256. where LOGIN = :login
  257. -- and ID_BILLING_USERS = :id_user
  258. ", [
  259. // ':id_user' => $userInfo['ID'],
  260. // ':login' => $userInfo['LOGIN'],
  261. ':login' => $email,
  262. ':hash_passwd' => md5($newPasswd),
  263. ]);
  264. }
  265. static function preparePanelBNAuthTables() {
  266. DB::getPDO()->execSql("
  267. CREATE TABLE IF NOT EXISTS `PANEL_KLIENTA_BN_AUTH` (
  268. `ID` int(11) NOT NULL AUTO_INCREMENT,
  269. `ID_BILLING_USERS` int(11) NOT NULL,
  270. `LOGIN` varchar(255) NOT NULL DEFAULT '',
  271. `PASSWD` varchar(32) NOT NULL DEFAULT '',
  272. `REMIND_PASS_KEY` varchar(16) NOT NULL DEFAULT '',
  273. `REMIND_PASS_VALID_TILL` date NOT NULL DEFAULT '0000-00-00',
  274. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  275. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  276. `A_RECORD_CREATE_DATE` datetime NOT NULL,
  277. `A_RECORD_CREATE_AUTHOR` varchar(20) NOT NULL DEFAULT '',
  278. `A_RECORD_UPDATE_DATE` datetime NOT NULL,
  279. `A_RECORD_UPDATE_AUTHOR` varchar(20) NOT NULL DEFAULT '',
  280. PRIMARY KEY (`ID`),
  281. UNIQUE KEY `COMPANY_LOGIN` (`LOGIN`, `ID_BILLING_USERS`)
  282. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  283. ");
  284. DB::getPDO()->execSql("
  285. CREATE TABLE IF NOT EXISTS `PANEL_KLIENTA_BN_AUTH_HIST` (
  286. `ID` int(11) NOT NULL AUTO_INCREMENT,
  287. `ID_USERS2` int(11) NOT NULL,
  288. `ID_BILLING_USERS` varchar(11) NOT NULL DEFAULT 'N/S;',
  289. `LOGIN` varchar(255) NOT NULL DEFAULT 'N/S;',
  290. `PASSWD` varchar(32) NOT NULL DEFAULT 'N/S;',
  291. `REMIND_PASS_KEY` varchar(16) NOT NULL DEFAULT 'N/S;',
  292. `REMIND_PASS_VALID_TILL` varchar(10) NOT NULL DEFAULT 'N/S;',
  293. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT 'N/S;',
  294. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT 'N/S;',
  295. `A_RECORD_CREATE_DATE` varchar(10) NOT NULL DEFAULT 'N/S;',
  296. `A_RECORD_CREATE_AUTHOR` varchar(20) NOT NULL DEFAULT 'N/S;',
  297. `A_RECORD_UPDATE_DATE` varchar(10) NOT NULL DEFAULT 'N/S;',
  298. `A_RECORD_UPDATE_AUTHOR` varchar(20) NOT NULL DEFAULT 'N/S;',
  299. PRIMARY KEY (`ID`),
  300. KEY `ID_USERS2` (`ID_USERS2`)
  301. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  302. ");
  303. }
  304. }