application/ controllers/ IndexController.php FooController.php models/ Abstract/ AbstractMapper.php AbstractModel.php DBTable/ FooTable.php DeviceTable.php Mapper/ FooMapper.php DeviceMapper.php Foo.php Device.php services/ DeviceService.php FooService.php views/
class DeviceapiController extends Zend_Controller_Action { public function init() { $this->_helper->viewRenderer->setNoRender(true); } /** * Login user from API Request * @method POST * @param json rawBody {"data":{"login": "admin", "password": "password"}} * @param string login in JSON * @param string password in JSON * * @return string SecretKey * @return HTTP STATUS 200 if ok * @return HTTP STATUS 400 if fields doesn't valid * @return HTTP STATUS 409 if user already exist */ public function loginAction() { $request = $this->getRequest(); $data = $request->getRawBody(); if ($data) { // decode from json params $params = Zend_Json::decode($data); $result = Application_Service_DeviceService::login($params); if (!is_null($result['secretKey'])) { $this->getResponse() ->setHttpResponseCode(200) ->setHeader('Content-type', 'application/json', true) ->setBody(Zend_Json::encode($result)); $this->_setSecretKeyToCookies($result['secretKey']); return; } $this->getResponse() ->setHttpResponseCode(401); return; } $this->getResponse() ->setHttpResponseCode(405); return; } /** * Profile from API Request * * @method GET * @param Request Header Cookie secretKey * * @return json string {"id":"","email":"","realName":""} * @return HTTP STATUS 200 OK */ public function profileAction() { $cookies = $this->getRequest()->getCookie(); if (!isset($cookies['secretKey']) || (!Application_Service_DeviceService::isAuthenticated($cookies['secretKey']))) { $this->getResponse() ->setHttpResponseCode(401) ->setHeader('Content-Type', 'application/json') ->setBody(Zend_Json::encode(array("message" => "Unauthorized"))); return; } $result = Application_Service_DeviceService::getProfile($cookies['secretKey'])->toArray(); unset($result['password']); unset($result['passwordSalt']); $this->getResponse() ->setHttpResponseCode(200) ->setHeader('Content-type', 'application/json', true) ->setBody(Zend_Json::encode($result)); return; } /** * Logout from API Request * @method POST * @param Request Header Cookie secretKey * * @return HTTP STATUS 200 OK */ public function logoutAction() { $cookies = $this->getRequest()->getCookie(); if ($cookies['secretKey']) { $device = new Application_Model_Device(); $device->deleteByKey($cookies['secretKey']); $this->_setSecretKeyToCookies($cookies['secretKey'], -1); if(Zend_Auth::getInstance()->hasIdentity()) { Zend_Auth::getInstance()->clearIdentity(); } } $this->getResponse() ->setHttpResponseCode(200); return; } /** * Signup user from API Request * @method POST * @param json string {"email": "", "password": "", “realName”: “”} * * @return string SecretKey * @return HTTP STATUS 201 Created * @return HTTP STATUS 400 Bad request * @return HTTP STATUS 409 Conflict - user already exist */ public function signupAction() { $request = $this->getRequest(); $data = $request->getRawBody(); // decode from json params $params = Zend_Json::decode($data); $email = $params['email']; $name = $params['realName']; $password = $params['password']; $err = array(); if (!isset($email) || !isset($name) || !isset($password) || (filter_var($email, FILTER_VALIDATE_EMAIL)==FALSE)) { if (!isset($email)) { $err['email'] = "Email is missing"; } if (!isset($name)) { $err['name'] = "Name is missing"; } if (!isset($password)) { $err['password'] = "Password are missing"; } if (filter_var($email, FILTER_VALIDATE_EMAIL)==FALSE) { $err['valid_email'] = "Email is not valid"; } } if (!empty($err)) { $this->getResponse() ->setHttpResponseCode(400) ->setBody(Zend_Json::encode(array ("invalid" => $err))); return; } $service = new Application_Service_DeviceService(); $params = array("email" => $email, "username" => $name, "password" => $password); try { $result = $service->signup($params); } catch (Zend_Exception_UserAlreadyExist $e) { $this->getResponse() ->setHttpResponseCode(409) ->setBody(Zend_Json::encode(array("message" => "User already exist"))); return; } $this->getResponse() ->setHttpResponseCode(201) ->setHeader('Content-type', 'application/json', true) ->setBody(Zend_Json::encode($result)); $this->_setSecretKeyToCookies($result['secretKey']); return; } /** * Protected local method to set Secretkey to Cookies * @param string $secretKey * @param int | null $timeFlg */ protected function _setSecretKeyToCookies($secretKey,$timeFlg = 1) { $cookie = new Zend_Http_Header_SetCookie(); $cookie->setName('secretKey') ->setValue($secretKey) ->setPath('/') ->setExpires(time() + (1* 365 * 24 * 60 * 60)*$timeFlg); $this->getResponse()->setRawHeader($cookie); return; } }
class LoginControllerTest extends Zend_Test_PHPUnit_ControllerTestCase { /* * Fixtures: * User with `email@example.com` and `password` */ public function setUp() { $this->bootstrap = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini'); parent::setUp(); } public function testSuccessfulLoginAction() { $request = $this->getRequest(); $email = 'email@example.com'; $request-> setMethod('POST')-> setHeader('Content-Type', 'application/json')-> setRawBody(Zend_Json::encode(array( 'email' => $email, 'password' => 'password', ))); $this->dispatch('/login'); $this->assertResponseCode(200); $this->assertNotRedirect(); $this->assertHeaderContains('Content-Type', 'application/json'); $data = $this->getResponse()->getBody(); $data = Zend_Json::decode($data, true); $this->assertArrayHasKey('secretKey', $data); $this->resetRequest() ->resetResponse(); // Test logout $request-> setMethod('POST')-> setHeader('Content-Type', 'application/json')-> setCookie('secretKey', $data['secretKey']); $this->dispatch('/logout'); $this->assertResponseCode(200); $this->resetRequest() ->resetResponse(); } public function testLoginWithEmptyParamsAction() { $request = $this->getRequest(); $request-> setMethod('POST')-> setHeader('Content-Type', 'application/json')-> setRawBody(Zend_Json::encode(array( 'email' => '', 'password' => '', ))); $this->dispatch('/login'); $this->assertResponseCode(401); $this->resetRequest() ->resetResponse(); } public function testLoginWithoutParamsAction() { $request = $this->getRequest(); $request-> setMethod('POST')-> setHeader('Content-Type', 'application/json'); $this->dispatch('/login'); $this->assertResponseCode(405); $this->resetRequest() ->resetResponse(); } public function testSignupAction() { $request = $this->getRequest(); $email = "newemail_".substr(MD5(uniqid(rand(), true)), 0, 12)."@".substr(MD5(uniqid(rand(), true)), 0, 5).".com"; $request-> setMethod('POST')-> setHeader('Content-Type', 'application/json')-> setRawBody(Zend_Json::encode(array( 'email' => $email, 'password' => 'password', 'realName' => 'John Dow', ))); $this->dispatch('/signup'); $this->assertResponseCode(201); $this->assertHeaderContains('Content-Type', 'application/json'); $data = json_decode($this->getResponse()->outputBody(), true); $this->assertArrayHasKey('secretKey', $data); $secretKey = $data['secretKey']; $this->assertArrayHasKey('user', $data); $this->resetRequest() ->resetResponse(); $request-> setMethod('POST')-> setHeader('Content-Type', 'application/json')-> setRawBody(json_encode(array( 'email' => '2', 'password' => '11', 'realName' => '23s', ))); $this->dispatch('/signup'); $this->assertResponseCode(400); $data = json_decode($this->getResponse()->outputBody(), true); $this->assertArrayHasKey('invalid', $data); $invalid = $data['invalid']; $this->assertArrayHasKey('email', $invalid); $this->assertArrayHasKey('password', $invalid); $this->resetRequest() ->resetResponse(); } public function testAlreadyExistUserSignup() { $request = $this->getRequest(); $request-> setMethod('POST')-> setHeader('Content-Type', 'application/json')-> setRawBody(Zend_Json::encode(array( 'email' => 'email@example.com', 'password' => 'password', 'realName' => 'John Dow', ))); $this->dispatch('/signup'); $this->assertResponseCode(409); $this->resetRequest() ->resetResponse(); } }
class Application_Service_DeviceService { public static function login (array $params) { if (!empty($params) && !empty($params['email']) && !empty($params['password'])) { $user = new Application_Model_User(); $device = new Application_Model_Device(); $adapter = new Zend_Auth_Adapter_DbTable( Zend_Controller_Front::getInstance()->getParam('bootstrap')->getPluginResource("db")->getDbAdapter(), 'user', 'email', 'password', 'MD5(CONCAT(?, passwordSalt,"' //MD5( + + ) . Zend_Controller_Front::getInstance()->getParam('bootstrap')->getOption('salt') . '"))' ); // $adapter->setIdentity($params["email"]); // Zend_Registry::get('authQuery') $adapter->setCredential($params["password"]); $auth = Zend_Auth::getInstance(); if ($auth->authenticate($adapter)->isValid()) // { $id = $user->getCurrentUserId(); $secretKey = $user->generateSecretKey(); try { $device->userId = $id; $device->secretKey = $secretKey; $device->lastUsage = time(); $device->save(); } catch (Exception $e) { throw new Exception("Couldn't save with error ".$e); } $user->loadById($id); return array("secretKey" => $secretKey, "user" => array("email" => $user->{Application_Model_User::ATTRIBUTE_EMAIL}, "realName" => $user->{Application_Model_User::ATTRIBUTE_REALNAME}, "id" => $user->{Application_Model_User::ATTRIBUTE_ID})); } } return NULL; } public function signup (array $params) { // $user = new Application_Model_User(); if ($user->findExistUserByEmail($params['email'])) { throw new Zend_Exception_UserAlreadyExist(); } $user->email = $params['email']; $user->realName = $params['username']; $user->passwordSalt = $user->generatePwdSalt(); $user->password = $user->generatePwd($params['password']); $user->save(); return $this->login($params); }
class Application_Model_Device extends Application_Model_Abstract_AbstractModel { const ATTRIBUTE_ID = "id"; const ATTRIBUTE_USER_ID = "userId"; const ATTRIBUTE_SECRET_KEY = "secretKey"; const ATTRIBUTE_LAST_USAGE = "lastUsage"; protected $_id, $_userId, $_secretKey, $_lastUsage; public function __construct(array $options = null, $mapper = null) { // for future decorate if (is_null($mapper)) $this->_mapper = new Application_Model_DeviceMapper(); else $this->_mapper = $mapper; if (is_array($options)) { $this->setOptions($options); } } /** * Wrapper block */ public function fromProps() { return $data = array( self::ATTRIBUTE_USER_ID => $this->userId, self::ATTRIBUTE_SECRET_KEY => $this->secretKey, self::ATTRIBUTE_LAST_USAGE => $this->lastUsage, ); } /* * Start describe behaivors of object */ public function getDeviceByKey ($key) { return $this->_mapper->findByKey($key); } public function deleteByKey($key) { return $this->_mapper->deleteByCriteria('secretKey', $key); } }
/** * Delete File in DB and unlink physical file * */ public function deleteFile() { $id = $this->id; if (empty($id)) { throw new Exception('Invalid id'); return false; } $imageFile = UPLOAD_PATH.'/'.$this->{self::ATTRIBUTE_REAL_NAME}; $thImageFile = THUMB_PATH.'/'.$this->{self::ATTRIBUTE_TH_NAME}; // $this->_mapper->deleteById($id); // unlink($imageFile); unlink($thImageFile); }
class Application_Model_DeviceMapper extends Application_Model_Abstract_AbstractMapper { const MODEL_TABLE = "Application_Model_DBTable_DeviceTable"; const MODEL_CLASS = "Application_Model_Device"; /** * Get DBTable * * @return string $dbTable return current dbTable object */ public function getDbTable() { if (null === $this->_dbTable) { $this->setDbTable(self::MODEL_TABLE); } return $this->_dbTable; } public function _getModel() { return new Application_Model_Device(); } public function update(array $data, $where) { // add a timestamp if (empty($data['updated'])) { $data['updated'] = time(); } return parent::update($data, $where); } /** * @param string $key * @throws Zend_Exception_Unauthtorize */ public function findByKey($key) { $result = $this->getDbTable()->fetchRow($this->getDbTable()->select()->where("secretKey = ?", $key)); if (0 == count($result)) { throw new Zend_Exception_Unauthtorize(); } return $result; } }
class Application_Model_DBTable_DeviceTable extends Zend_Db_Table_Abstract { protected $_name = 'deviceKey'; protected $_primary = 'id'; protected $_referenceMap = array( 'Token' => array( 'columns' => 'userId', 'refTableClass' => 'Application_Model_DBTable_UserTable', 'refColumns' => 'id', 'onDelete' => self::CASCADE, 'onUpdate' => self::CASCADE, )); public function __construct($config = array()) { $this->_setAdapter(Zend_Db_Table::getDefaultAdapter()); parent::__construct(); } }
Source: https://habr.com/ru/post/169537/
All Articles