<?php
namespace Moto\Application\Profile; use Moto; use Moto\Json\Server; use Moto\Json\Request; use Moto\Json\Response; class Service extends Moto\Service\AbstractStaticService { protected static $_resourceName = 'profile'; protected static $_resourcePrivilegesMap = array( 'save' => 'set', 'get' => 'get', 'changePassword' => 'set', ); public static function save($request = null) { $currentUser = static::_authenticate(); if (null === $request) { $request = static::getRequest()->getParams(); } $request['id'] = $currentUser->id; $filter = new SaveProfileFilter(); $filter->setData($request); if (!$filter->isValid()) { throw new Server\Exception(Moto\System\Exception::ERROR_BAD_REQUEST_MESSAGE, Moto\System\Exception::ERROR_BAD_REQUEST_CODE, $filter->getMessagesKeys()); } $currentUser->fill($filter->getValues()); if (!$currentUser->save()) { throw new Moto\System\Exception(Moto\System\Exception::ERROR_BAD_REQUEST_MESSAGE, Moto\System\Exception::ERROR_BAD_REQUEST_CODE); } static::_updateIdentity(); return $currentUser; } public static function get() { return static::_authenticate(); } public static function changePassword($request = null) { if (null === $request) { $request = static::getRequest()->getParams(); } $filter = new ChangePasswordFilter(); $filter->setData($request); if (!$filter->isValid()) { throw new Server\Exception(Moto\System\Exception::ERROR_BAD_REQUEST_MESSAGE, Moto\System\Exception::ERROR_BAD_REQUEST_CODE, $filter->getMessagesKeys()); } $authUser = static::_authenticate(); $currentUser = Moto\Database\Models\User::find($authUser->id); if (!$currentUser) { throw new Moto\Json\Server\Exception(Moto\System\Exception::ERROR_AUTHORIZATION_DATA_MESSAGE, Moto\System\Exception::ERROR_AUTHORIZATION_DATA_CODE); } $filteredValues = $filter->getValues(); if (!$currentUser->isValidPassword($filteredValues['old_password'])) { throw new Server\Exception(Moto\System\Exception::ERROR_BAD_REQUEST_MESSAGE, Moto\System\Exception::ERROR_BAD_REQUEST_CODE, array('old_password' => array('MODULE.PROFILE.WRONG_PASSWORD_ERROR'))); } $currentUser->setPassword($filteredValues['new_password']); if (!$currentUser->save()) { throw new Moto\System\Exception(Moto\System\Exception::ERROR_BAD_REQUEST_MESSAGE, Moto\System\Exception::ERROR_BAD_REQUEST_CODE); } static::_updateIdentity(); return true; } protected static function _authenticate() { $user = Moto\Authentication\Service::getUser(); if (!$user) { throw new Moto\Json\Server\Exception(Moto\System\Exception::ERROR_AUTHORIZATION_DATA_MESSAGE, Moto\System\Exception::ERROR_AUTHORIZATION_DATA_CODE); } return $user; } protected static function _updateIdentity() { $user = Moto\Authentication\Service::getUser(); if (!$user) { return false; } $user = Moto\Database\Models\User::find($user->id); if (!$user) { return false; } Moto\Authentication\Service::updateUser($user); return true; } } 