1: <?php
2: /**
3: * Magento
4: *
5: * NOTICE OF LICENSE
6: *
7: * This source file is subject to the Open Software License (OSL 3.0)
8: * that is bundled with this package in the file LICENSE.txt.
9: * It is also available through the world-wide-web at this URL:
10: * http://opensource.org/licenses/osl-3.0.php
11: * If you did not receive a copy of the license and are unable to
12: * obtain it through the world-wide-web, please send an email
13: * to license@magentocommerce.com so we can send you a copy immediately.
14: *
15: * DISCLAIMER
16: *
17: * Do not edit or add to this file if you wish to upgrade Magento to newer
18: * versions in the future. If you wish to customize Magento for your
19: * needs please refer to http://www.magentocommerce.com for more information.
20: *
21: * @category Mage
22: * @package Mage_Oauth
23: * @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
24: * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
25: */
26:
27: /**
28: * oAuth token model
29: *
30: * @category Mage
31: * @package Mage_Oauth
32: * @author Magento Core Team <core@magentocommerce.com>
33: * @method string getName() Consumer name (joined from consumer table)
34: * @method Mage_Oauth_Model_Resource_Token_Collection getCollection()
35: * @method Mage_Oauth_Model_Resource_Token_Collection getResourceCollection()
36: * @method Mage_Oauth_Model_Resource_Token getResource()
37: * @method Mage_Oauth_Model_Resource_Token _getResource()
38: * @method int getConsumerId()
39: * @method Mage_Oauth_Model_Token setConsumerId() setConsumerId(int $consumerId)
40: * @method int getAdminId()
41: * @method Mage_Oauth_Model_Token setAdminId() setAdminId(int $adminId)
42: * @method int getCustomerId()
43: * @method Mage_Oauth_Model_Token setCustomerId() setCustomerId(int $customerId)
44: * @method string getType()
45: * @method Mage_Oauth_Model_Token setType() setType(string $type)
46: * @method string getVerifier()
47: * @method Mage_Oauth_Model_Token setVerifier() setVerifier(string $verifier)
48: * @method string getCallbackUrl()
49: * @method Mage_Oauth_Model_Token setCallbackUrl() setCallbackUrl(string $callbackUrl)
50: * @method string getCreatedAt()
51: * @method Mage_Oauth_Model_Token setCreatedAt() setCreatedAt(string $createdAt)
52: * @method string getToken()
53: * @method Mage_Oauth_Model_Token setToken() setToken(string $token)
54: * @method string getSecret()
55: * @method Mage_Oauth_Model_Token setSecret() setSecret(string $tokenSecret)
56: * @method int getRevoked()
57: * @method Mage_Oauth_Model_Token setRevoked() setRevoked(int $revoked)
58: * @method int getAuthorized()
59: * @method Mage_Oauth_Model_Token setAuthorized() setAuthorized(int $authorized)
60: */
61: class Mage_Oauth_Model_Token extends Mage_Core_Model_Abstract
62: {
63: /**#@+
64: * Token types
65: */
66: const TYPE_REQUEST = 'request';
67: const TYPE_ACCESS = 'access';
68: /**#@- */
69:
70: /**#@+
71: * Lengths of token fields
72: */
73: const LENGTH_TOKEN = 32;
74: const LENGTH_SECRET = 32;
75: const LENGTH_VERIFIER = 32;
76: /**#@- */
77:
78: /**#@+
79: * Customer types
80: */
81: const USER_TYPE_ADMIN = 'admin';
82: const USER_TYPE_CUSTOMER = 'customer';
83: /**#@- */
84:
85: /**
86: * Initialize resource model
87: *
88: * @return void
89: */
90: protected function _construct()
91: {
92: $this->_init('oauth/token');
93: }
94:
95: /**
96: * "After save" actions
97: *
98: * @return Mage_Oauth_Model_Token
99: */
100: protected function _afterSave()
101: {
102: parent::_afterSave();
103:
104: //Cleanup old entries
105: /** @var $helper Mage_Oauth_Helper_Data */
106: $helper = Mage::helper('oauth');
107: if ($helper->isCleanupProbability()) {
108: $this->_getResource()->deleteOldEntries($helper->getCleanupExpirationPeriod());
109: }
110: return $this;
111: }
112:
113: /**
114: * Authorize token
115: *
116: * @param int $userId Authorization user identifier
117: * @param string $userType Authorization user type
118: * @return Mage_Oauth_Model_Token
119: */
120: public function authorize($userId, $userType)
121: {
122: if (!$this->getId() || !$this->getConsumerId()) {
123: Mage::throwException('Token is not ready to be authorized');
124: }
125: if ($this->getAuthorized()) {
126: Mage::throwException('Token is already authorized');
127: }
128: if (self::USER_TYPE_ADMIN == $userType) {
129: $this->setAdminId($userId);
130: } elseif (self::USER_TYPE_CUSTOMER == $userType) {
131: $this->setCustomerId($userId);
132: } else {
133: Mage::throwException('User type is unknown');
134: }
135: /** @var $helper Mage_Oauth_Helper_Data */
136: $helper = Mage::helper('oauth');
137:
138: $this->setVerifier($helper->generateVerifier());
139: $this->setAuthorized(1);
140: $this->save();
141:
142: $this->getResource()->cleanOldAuthorizedTokensExcept($this);
143:
144: return $this;
145: }
146:
147: /**
148: * Convert token to access type
149: *
150: * @return Mage_Oauth_Model_Token
151: */
152: public function convertToAccess()
153: {
154: if (Mage_Oauth_Model_Token::TYPE_REQUEST != $this->getType()) {
155: Mage::throwException('Can not convert due to token is not request type');
156: }
157: /** @var $helper Mage_Oauth_Helper_Data */
158: $helper = Mage::helper('oauth');
159:
160: $this->setType(self::TYPE_ACCESS);
161: $this->setToken($helper->generateToken());
162: $this->setSecret($helper->generateTokenSecret());
163: $this->save();
164:
165: return $this;
166: }
167:
168: /**
169: * Generate and save request token
170: *
171: * @param int $consumerId Consumer identifier
172: * @param string $callbackUrl Callback URL
173: * @return Mage_Oauth_Model_Token
174: */
175: public function createRequestToken($consumerId, $callbackUrl)
176: {
177: /** @var $helper Mage_Oauth_Helper_Data */
178: $helper = Mage::helper('oauth');
179:
180: $this->setData(array(
181: 'consumer_id' => $consumerId,
182: 'type' => self::TYPE_REQUEST,
183: 'token' => $helper->generateToken(),
184: 'secret' => $helper->generateTokenSecret(),
185: 'callback_url' => $callbackUrl
186: ));
187: $this->save();
188:
189: return $this;
190: }
191:
192: /**
193: * Get OAuth user type
194: *
195: * @return string
196: * @throws Exception
197: */
198: public function getUserType()
199: {
200: if ($this->getAdminId()) {
201: return self::USER_TYPE_ADMIN;
202: } elseif ($this->getCustomerId()) {
203: return self::USER_TYPE_CUSTOMER;
204: } else {
205: Mage::throwException('User type is unknown');
206: }
207: }
208:
209: /**
210: * Get string representation of token
211: *
212: * @param string $format
213: * @return string
214: */
215: public function toString($format = '')
216: {
217: return http_build_query(array('oauth_token' => $this->getToken(), 'oauth_token_secret' => $this->getSecret()));
218: }
219:
220: /**
221: * Before save actions
222: *
223: * @return Mage_Oauth_Model_Consumer
224: */
225: protected function _beforeSave()
226: {
227: $this->validate();
228:
229: if ($this->isObjectNew() && null === $this->getCreatedAt()) {
230: $this->setCreatedAt(Varien_Date::now());
231: }
232: parent::_beforeSave();
233: return $this;
234: }
235:
236: /**
237: * Validate data
238: *
239: * @return array|bool
240: * @throw Mage_Core_Exception|Exception Throw exception on fail validation
241: */
242: public function validate()
243: {
244: /** @var $validatorUrl Mage_Core_Model_Url_Validator */
245: $validatorUrl = Mage::getSingleton('core/url_validator');
246: if (Mage_Oauth_Model_Server::CALLBACK_ESTABLISHED != $this->getCallbackUrl()
247: && !$validatorUrl->isValid($this->getCallbackUrl())
248: ) {
249: $messages = $validatorUrl->getMessages();
250: Mage::throwException(array_shift($messages));
251: }
252:
253: /** @var $validatorLength Mage_Oauth_Model_Consumer_Validator_KeyLength */
254: $validatorLength = Mage::getModel(
255: 'oauth/consumer_validator_keyLength');
256: $validatorLength->setLength(self::LENGTH_SECRET);
257: $validatorLength->setName('Token Secret Key');
258: if (!$validatorLength->isValid($this->getSecret())) {
259: $messages = $validatorLength->getMessages();
260: Mage::throwException(array_shift($messages));
261: }
262:
263: $validatorLength->setLength(self::LENGTH_TOKEN);
264: $validatorLength->setName('Token Key');
265: if (!$validatorLength->isValid($this->getToken())) {
266: $messages = $validatorLength->getMessages();
267: Mage::throwException(array_shift($messages));
268: }
269:
270: if (null !== ($verifier = $this->getVerifier())) {
271: $validatorLength->setLength(self::LENGTH_VERIFIER);
272: $validatorLength->setName('Verifier Key');
273: if (!$validatorLength->isValid($verifier)) {
274: $messages = $validatorLength->getMessages();
275: Mage::throwException(array_shift($messages));
276: }
277: }
278: return true;
279: }
280:
281: /**
282: * Get Token Consumer
283: *
284: * @return Mage_Oauth_Model_Consumer
285: */
286: public function getConsumer()
287: {
288: if (!$this->getData('consumer')) {
289: /** @var $consumer Mage_Oauth_Model_Consumer */
290: $consumer = Mage::getModel('oauth/consumer');
291: $consumer->load($this->getConsumerId());
292: $this->setData('consumer', $consumer);
293: }
294:
295: return $this->getData('consumer');
296: }
297: }
298: