| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526 |
- <?php
- Lib::loadClass('RouteBase');
- Lib::loadClass('ProcesHelper');
- Lib::loadClass('Config');
- class Route_Auth extends RouteBase {
- public function handleAuth() {
- if (!User::logged()) {
- $_SESSION['ADM_ACCOUNT'] = 'Anonymous';
- // throw new HttpException('Unauthorized', 401);
- }
- }
- public function defaultAction() {
- SE_Layout::gora();
- if (!User::logged()) {
- ?>
- <div class="container">
- <h1>Unauthorized</h1>
- <ul>
- <li><a href="index.php?_route=Auth&_task=registerForm">Register</a></li>
- <li><a href="index.php?_route=Auth&_task=loginForm">Login</a></li>
- <li><a href="index.php?_route=Auth&_task=activateForm">Activate</a></li>
- </ul>
- </div>
- <?php
- } else {
- ?>
- <div class="container">
- <h1>Auth</h1>
- ...
- </div>
- <?php
- }
- SE_Layout::dol();
- }
- public function loginFormAction() {
- SE_Layout::gora();
- ?>
- TODO: login...
- <?php
- SE_Layout::dol();
- }
- public function activateFormAction() {
- SE_Layout::gora();
- ?>
- <div class="container">
- <div id="ACTIVATE_FRM_<?php echo $tableHash; ?>_DBG_LOG" style="border:1px solid red;max-height:300px;overflow:scroll"></div>
- <div id="ACTIVATE_FRM_<?php echo $tableHash; ?>_MSGS"></div>
- <form class="form-horizontal"
- action=""
- method="post"
- id="ACTIVATE_FRM_<?php echo $tableHash; ?>">
- <fieldset>
- <legend>Aktywacja konta</legend>
- <div class="form-group">
- <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="activateHash">Kod aktywacyjny
- <i class="glyphicon glyphicon-info-sign frm-help"
- data-toggle="popover"
- data-trigger="hover"
- title=""
- data-content="Kod aktywacyjny otrzymany drogą mailową"
- data-original-title="Kod aktywacyjny"></i>
- </label>
- <div class="col-xs-12 col-sm-9 col-md-10">
- <input id="activateHash" name="activateHash" type="text" value="" tabindex="<?php echo (++$tabindex); ?>" maxlength="100" class="form-control">
- </div>
- </div>
- <div class="form-group">
- <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
- <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Aktywuj</button>
- </div>
- </div>
- </fieldset>
- </form>
- </div>
- <?php $this->_printFormFactoryJS(); ?>
- <script>
- jQuery(document).ready(function(){
- var formNode = $('#ACTIVATE_FRM_<?php echo $tableHash; ?>'),
- msgsNode = $('#ACTIVATE_FRM_<?php echo $tableHash; ?>_MSGS'),
- dbgNode = $('#ACTIVATE_FRM_<?php echo $tableHash; ?>_DBG_LOG'),
- form = FormFactory({
- formNode: formNode,
- msgsNode: msgsNode,
- dbgNode: dbgNode,
- url: 'index.php?_route=Auth&_task=activate'
- })
- ;
- jQuery('textarea').autosize();
- jQuery('.frm-help').popover({trigger:'hover'});
- formNode.on('submit', {form: form}, function(e) {
- if (e.data && e.data.form) {
- e.data.form.submit(e);
- }
- return false;
- });
- });
- </script>
- <?php
- SE_Layout::dol();
- }
- public function registerFormAction() {
- SE_Layout::gora();
- $tblAcl = $this->_getUsersTableAcl();
- $fieldsList = $this->_getRegisterValuesFromArray($_POST);
- DBG::_(true, true, "tblAcl", $tblAcl, __CLASS__, __FUNCTION__, __LINE__);
- DBG::_(true, true, "fieldsList", $fieldsList, __CLASS__, __FUNCTION__, __LINE__);
- $tableHash = 'routeAuthRegister';
- ?>
- <div class="container">
- <div id="CREATE_FRM_<?php echo $tableHash; ?>_DBG_LOG" style="border:1px solid red;max-height:300px;overflow:scroll"></div>
- <div id="CREATE_FRM_<?php echo $tableHash; ?>_MSGS"></div>
- <form class="form-horizontal"
- action=""
- method="post"
- id="CREATE_FRM_<?php echo $tableHash; ?>">
- <fieldset>
- <legend>Zarejestruj konto</legend>
- <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
- <?php if ($tblAcl->isAllowed($kID, 'C')) : ?>
- <div class="form-group">
- <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
- <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
- <?php $perms = $tblAcl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
- </label>
- <div class="col-xs-12 col-sm-9 col-md-10">
- <?php
- $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
- echo $tblAcl->showFormItem('C', $kID, "f{$kID}", $vCol['value'], $fieldParams);
- ?>
- </div>
- </div>
- <?php endif; ?>
- <?php endforeach; ?>
- <div class="form-group">
- <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
- <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Zarejestruj</button>
- </div>
- </div>
- </fieldset>
- </form>
- </div>
- <?php $this->_printFormFactoryJS(); ?>
- <script>
- jQuery(document).ready(function(){
- var formNode = $('#CREATE_FRM_<?php echo $tableHash; ?>'),
- msgsNode = $('#CREATE_FRM_<?php echo $tableHash; ?>_MSGS'),
- dbgNode = $('#CREATE_FRM_<?php echo $tableHash; ?>_DBG_LOG'),
- form = FormFactory({
- formNode: formNode,
- msgsNode: msgsNode,
- dbgNode: dbgNode,
- url: 'index.php?_route=Auth&_task=register'
- })
- ;
- jQuery('textarea').autosize();
- jQuery('.frm-help').popover({trigger:'hover'});
- formNode.on('submit', {form: form}, function(e) {
- if (e.data && e.data.form) {
- e.data.form.submit(e);
- }
- return false;
- });
- });
- </script>
- <?php
- SE_Layout::dol();
- }
- public function _printFormFactoryJS() {
- ?><script>
- var FormFactory = function(options) {
- var priv = {};
- priv.formNode = options.formNode;
- priv.msgsNode = options.msgsNode;
- priv.dbgNode = options.dbgNode;
- priv.url = options.url;
- priv.req = null;
- priv.reqCounter = 0;
- var showMsg = function(msg) {
- $('<div class="alert alert-info">' + msg + '</div>').appendTo(priv.msgsNode);
- }
- var log = function(msg, type) {
- var type = type || 'info';
- if (!priv.dbgNode) return false;
- $('<div class="alert alert-' + type + '">' + msg + '</div>').appendTo(priv.dbgNode);
- }
- var showSuccess = function(msg) {
- $('<div class="alert alert-success">' + msg + '</div>').appendTo(priv.msgsNode);
- }
- var showError = function(msg) {
- $('<div class="alert alert-danger">' + msg + '</div>').appendTo(priv.msgsNode);
- }
- var showWarning = function(msg) {
- $('<div class="alert alert-warning">' + msg + '</div>').appendTo(priv.msgsNode);
- }
- var showInfo = function(msg) {
- $('<div class="alert alert-info">' + msg + '</div>').appendTo(priv.msgsNode);
- }
- var clearMsgs = function(msg) {
- priv.msgsNode.empty();
- }
- var hideForm = function() {
- priv.formNode.hide();
- }
- var showForm = function() {
- priv.formNode.show();
- }
- var parseResponse = function(data) {
- var form = this,
- data = {
- type: ('type' in data)? data.type : 'error',
- msg: ('msg' in data)? data.msg : 'Nieznany błąd'
- }
- ;
- form.log('parseResponse... data:' + JSON.stringify(data), 'info');
- if (data.type == 'error' || data.type == 'warning') {
- form.showError('<h4>Wystąpiły błędy!</h4>' + data.msg);
- // TODO: show all fields errors
- }
- else if (data.type == 'success') {
- var msg = '';
- if (data.id && data.id > 0) {
- msg = 'Utworzono pomyślnie konto w systemie';
- } else if (data.msg) {
- msg = data.msg;
- } else {
- msg = 'OK';
- }
- form.showSuccess(msg);
- form.hideForm();
- } else {
- form.showError('<h4>Wystąpiły błędy!</h4>' + data.msg);
- }
- }
- var submit = function(e) {
- var data = priv.formNode.serialize(),
- form = this,
- reqCounter = 0 + priv.reqCounter
- ;
- e.preventDefault();
- priv.reqCounter++;
- form.clearMsgs();
- form.log('DBG:REQ('+reqCounter+'). sending form...', 'info');
- console.log('sending form... data:', data);
- if (priv.req) {
- form.log('DBG:REQ('+reqCounter+'). abort previous xhr', 'info');
- priv.req.abort();
- }
- priv.req = superagent
- .post(priv.url)
- .type('form')
- .send(data)
- .set('Accept', 'application/json')
- .end(function(err, res) {
- console.log('DBG:REQ('+reqCounter+') res:', res, 'res.body:', res.body);
- if (err || !res.ok) {
- form.log('DBG:REQ('+reqCounter+'). error', 'info');
- } else {
- //form.log('DBG:REQ('+reqCounter+'). res.status(' + res.status + ') body:' + JSON.stringify(res.body), 'info');
- if ('application/json' !== res.type) {
- form.showError('<h4>Wystąpiły błędy!</h4>' + res.text);
- return;
- }
- form.log('DBG:REQ('+reqCounter+'). res.status:' + res.status + '. res.body:' + JSON.stringify(res.body), 'info');
- form.parseResponse(res.body);
- }
- priv.req = null;
- });
- return false;
- }
- return {
- log: log,
- showMsg: showMsg,
- showSuccess: showSuccess,
- showError: showError,
- showWarning: showWarning,
- showInfo: showInfo,
- clearMsgs: clearMsgs,
- hideForm: hideForm,
- showForm: showForm,
- submit: submit,
- parseResponse: parseResponse
- };
- }
- </script>
- <?php
- }
- public function _getRegisterFormFields() {
- $formFields = array();
- $formFields[] = 'ADM_NAME';// Imię i nazwisko
- $formFields[] = 'EMAIL';// Adres e-mail
- $formFields[] = 'ADM_PASSWD';// Hasło
- // Potwierdź hasło
- // TODO: stanowisko - if allowed (TODO: in config? '.cnf--auth-{host}.ini.php')
- return $formFields;
- }
- public function _getUsersTableAcl() {
- static $_usersTblAcl = null;
- if (!$_usersTblAcl) $_usersTblAcl = $this->_fetchUsersTableAcl();
- if (!$_usersTblAcl) throw new Exception("Error No Table ACL!");
- return $_usersTblAcl;
- }
- public function _fetchUsersTableAcl() {
- $tableName = 'TEST_PERMS';//'ADMIN_USERS';
- $formFields = $this->_getRegisterFormFields();
- $overrideLabels = array();
- $overrideLabels['ADM_NAME'] = 'Imię i nazwisko';
- $overrideLabels['EMAIL'] = "Email";
- $overrideLabels['ADM_PASSWD'] = "Hasło";
- $idTable = ProcesHelper::getZasobTableID($tableName);
- if (!$idTable) throw new Exception("Brak id tabeli");
- //DBG::_(true, true, "idTable", $idTable, __CLASS__, __FUNCTION__, __LINE__);
- $userAcl = User::getAcl();
- //DBG::_(true, true, "userAcl", $userAcl, __CLASS__, __FUNCTION__, __LINE__);
- if (!$userAcl->hasTableAcl($idTable)) {
- // .cnf--auth-{host}.ini.php
- $conf = Config::getConfFile('auth');
- if (!$conf) throw new Exception("Config file for 'auth' not found!");
- $isRegisterAllowed = V::get('allow_register', false, $conf);
- //DBG::_(true, true, "conf (isRegisterAllowed={$isRegisterAllowed})", $conf, __CLASS__, __FUNCTION__, __LINE__);
- if (!$isRegisterAllowed) throw new Exception("Brak uprawnień do rejestracji");
- $zasobTblInfo = ProcesHelper::getZasobTableInfoByUri($tblUri = "default_db/{$tableName}");
- if (!$zasobTblInfo) throw new HttpException("Brak zasobu dla tabeli użytkowników", 404);
- //DBG::_(true, true, "zasobTblInfo", $zasobTblInfo, __CLASS__, __FUNCTION__, __LINE__);
- {
- $tableConfig = array();
- $tableConfig['ID_TABLE'] = $idTable;
- $tableConfig['db'] = $zasobTblInfo->P__ID;
- $tableConfig['name'] = $zasobTblInfo->DESC;
- $tableConfig['label'] = $zasobTblInfo->DESC_PL;
- $tableConfig['opis'] = $zasobTblInfo->OPIS;
- //DBG::_(true, true, "formFields", $formFields, __CLASS__, __FUNCTION__, __LINE__);
- //DBG::_(true, true, "tableConfig", $tableConfig, __CLASS__, __FUNCTION__, __LINE__);
- }
- {
- $fieldsConfig = array();
- $fldsInfo = ProcesHelper::getZasobTableFieldsInfo($idTable);
- //DBG::_(true, true, "fldsInfo", $fldsInfo, __CLASS__, __FUNCTION__, __LINE__);
- foreach ($fldsInfo as $fldInfo) {
- if (!in_array($fldInfo->DESC, $formFields)) continue;
- $fldConf = array();
- $fldConf['ID_CELL'] = $fldInfo->ID;
- $fldConf['CELL_NAME'] = $fldInfo->DESC;
- $fldConf['CELL_DESC'] = (array_key_exists($fldInfo->DESC, $overrideLabels))? $overrideLabels[$fldInfo->DESC] : $fldInfo->OPIS;
- $fldConf['CELL_LABEL'] = (array_key_exists($fldInfo->DESC, $overrideLabels))? $overrideLabels[$fldInfo->DESC] : $fldInfo->DESC_PL;
- $fldConf['SORT_PRIO'] = $fldInfo->SORT_PRIO;
- if ('ADM_PASSWD' == $fldInfo->DESC) {
- $fldConf['FORM_TREAT'] = 'WXC';
- } else {
- $fldConf['FORM_TREAT'] = 'RWXC';
- }
- $fieldsConfig[$fldInfo->ID] = $fldConf;
- }
- //DBG::_(true, true, "fieldsConfig", $fieldsConfig, __CLASS__, __FUNCTION__, __LINE__);
- }
- {// TODO: init and save in session default perms
- //DBG::_(true, true, "ses tbl cache[{$idTable}]", $_SESSION['TableAcl_cache'][$idTable], __CLASS__, __FUNCTION__, __LINE__);
- $tblAcl = TableAcl::buildInstance($idTable, $tableConfig);
- $tblAcl->initFieldsFromConfig($fieldsConfig);
- $tblAcl->save();
- //DBG::_(true, true, "ses tbl cache[{$idTable}]", $_SESSION['TableAcl_cache'][$idTable], __CLASS__, __FUNCTION__, __LINE__);
- }
- //throw new Exception("Brak uprawnień do tabeli ID={$idTable}");
- }
- //DBG::_(true, true, "_SESSION['UserAcl_cache']['foundTables']", $_SESSION['UserAcl_cache']['foundTables'], __CLASS__, __FUNCTION__, __LINE__);
- //$tblAcl = $userAcl->getTableAcl($idTable);
- if (!$tblAcl) throw new Exception("Brak tabeli");
- $tblAcl->init();
- //DBG::_(true, true, "tblAcl", $tblAcl, __CLASS__, __FUNCTION__, __LINE__);
- return $tblAcl;
- }
- public function _getRegisterValuesFromArray($args = array()) {
- $fieldsList = array();
- $tblAcl = $this->_getUsersTableAcl();
- $formFields = $this->_getRegisterFormFields();
- $fieldsListAll = $tblAcl->getFields();
- foreach ($formFields as $vColName) {
- $vColID = $tblAcl->getFieldIdByName($vColName);
- if (!isset($fieldsListAll[$vColID])) {
- throw new Exception("Brak uprawnień do pola '{$vColName}'");
- }
- $fieldsList[$vColID] = $fieldsListAll[$vColID];
- $value = '';
- $value = V::get("f{$vColID}", $value, $args);
- $fieldsList[$vColID]['value'] = $value;
- }
- return $fieldsList;
- }
- public function registerAction() {
- $args = $_POST;
- $resData = new stdClass();
- $resData->_args = $args;// TODO: DBG
- $resData->type = 'error';
- $resData->msg = 'Error';
- header('Content-type: application/json; charset="utf-8"');
- try {
- $itemData = array();
- $tblAcl = $this->_getUsersTableAcl();
- $fieldsList = $this->_getRegisterValuesFromArray($args);
- $ds = $tblAcl->getDataSource();
- foreach ($fieldsList as $idFld => $fldData) {
- $itemData[$fldData['name']] = $fldData['value'];
- }
- if (!filter_var($itemData['EMAIL'], FILTER_VALIDATE_EMAIL)) {
- throw new Exception("Proszę podać poprawny adres email");
- }
- $itemData['EMPLOYEE_TYPE'] = 'Anonymous';
- $itemData['A_STATUS'] = 'WAITING';// TODO: konto oczekuje aktywacji? z config
- //$itemData['ADM_ADMIN_LEVEL'] = '6';
- $itemData['A_AUTH_TOKEN'] = md5("ADMIN_USERS.auth_token." . time());
- $itemData['A_AUTH_TOKEN_VALID'] = date("Y-m-d H:i:s", mktime(6 + date('H'), date('i'), date('s'), date("m"), date("d"), date("Y")));
- $resData->userName = User::getName();
- $resData->id = $ds->addItem($itemData);
- {
- $resData->_fieldsList = $fieldsList;// TODO: DBG
- $resData->_tblAcl = $tblAcl;// TODO: DBG
- $resData->_itemData = $itemData;// TODO: DBG
- }
- if ($resData->id > 0) {
- $resData->type = 'success';
- $resData->msg = "Pomyślnie utworzono konto w systemie";
- // TODO: konto oczekuje aktywacji? z config
- }
- } catch (Exception $e) {
- $resData->type = 'error';
- $resData->msg = $e->getMessage();
- }
- echo json_encode($resData);
- }
- public function activateAction() {
- $args = $_REQUEST;
- $resData = new stdClass();
- $resData->_args = $args;// TODO: DBG
- $resData->type = 'error';
- $resData->msg = 'Error';
- header('Content-type: application/json; charset="utf-8"');
- try {
- $token = V::get('activateHash', '', $args);
- // e3360132c963ae5b21ff6de77bcbbed6
- if (32 != strlen($token)) throw new Exception("Wrong token");
- if (!preg_match('/^[a-fA-F0-9]+$/', $token)) throw new Exception("Wrong token");
- $tblAcl = $this->_getUsersTableAcl();
- $ds = $tblAcl->getDataSource();
- $tblName = $tblAcl->getName();
- $dbs = DB::getDataSource();
- $sqlToken = $dbs->_($token);
- $sql = "
- select t.`ID`
- from `{$tblName}` t
- where t.`A_AUTH_TOKEN`='{$sqlToken}'
- and t.`A_AUTH_TOKEN_VALID` is not null
- and t.`A_AUTH_TOKEN_VALID` > NOW()
- and t.`A_STATUS`='WAITING'
- ";
- //DBG::_(true, true, "sql", $sql, __CLASS__, __FUNCTION__, __LINE__);
- $items = $dbs->getListByQuery($sql);
- if (0 == count($items)) throw new Exception("Kod nieaktywny");
- $idUser = V::get('ID', 0, reset($items), 'int');
- if ($idUser <= 0) throw new Exception("Kod nieaktywny");
- //DBG::_(true, true, "items", $items, __CLASS__, __FUNCTION__, __LINE__);
- $itemData = array();
- $itemData['ID'] = $idUser;
- $itemData['A_STATUS'] = 'NORMAL';
- $itemData['A_AUTH_TOKEN_VALID'] = 'NULL';
- $ds->updateItem($itemData);
- {
- $resData->_fieldsList = $fieldsList;// TODO: DBG
- $resData->_tblAcl = $tblAcl;// TODO: DBG
- $resData->_itemData = $itemData;// TODO: DBG
- }
- $resData->type = 'success';
- $resData->msg = "Pomyślnie aktywowano konto w systemie";
- } catch (Exception $e) {
- $resData->type = 'error';
- $resData->msg = $e->getMessage();
- $resData->errorCode = $e->getLine();
- }
- echo json_encode($resData);
- }
- }
|