api key authorization

This commit is contained in:
yuri
2018-10-26 12:06:20 +03:00
parent 778b212bd0
commit fef6ed5f34
12 changed files with 211 additions and 48 deletions
+14
View File
@@ -113,4 +113,18 @@ class User extends \Espo\Core\Controllers\Record
return $this->getRecordService()->generateNewApiKeyForEntity($data->id)->getValueMap();
}
public function actionCreateLink($params, $data, $request)
{
if (!$this->getUser()->isAdmin()) throw new Forbidden();
return parent::actionCreateLink($params, $data, $request);
}
public function actionRemoveLink($params, $data, $request)
{
if (!$this->getUser()->isAdmin()) throw new Forbidden();
return parent::actionRemoveLink($params, $data, $request);
}
}
+19 -14
View File
@@ -58,15 +58,21 @@ class Auth extends \Slim\Middleware
$authenticationMethod = null;
$hmacAuthorizationHeader = $request->headers('X-Hmac-Authorization');
if ($hmacAuthorizationHeader) {
$authenticationMethod = 'Hmac';
list($username, $password) = explode(':', base64_decode($hmacAuthorizationHeader), 2);
$espoAuthorizationHeader = $request->headers('Http-Espo-Authorization');
if (isset($espoAuthorizationHeader)) {
list($username, $password) = explode(':', base64_decode($espoAuthorizationHeader), 2);
} else {
$espoAuthorizationHeader = $request->headers('HTTP_ESPO_AUTHORIZATION');
if (isset($espoAuthorizationHeader)) {
list($username, $password) = explode(':', base64_decode($espoAuthorizationHeader), 2);
$hmacAuthorizationHeader = $request->headers('X-Hmac-Authorization');
if ($hmacAuthorizationHeader) {
$authenticationMethod = 'Hmac';
list($username, $password) = explode(':', base64_decode($hmacAuthorizationHeader), 2);
} else {
$apiKeyHeader = $request->headers('X-Api-Key');
if ($apiKeyHeader) {
$authenticationMethod = 'ApiKey';
$username = $apiKeyHeader;
$password = null;
}
}
}
@@ -78,9 +84,9 @@ class Auth extends \Slim\Middleware
}
if (!isset($username) && !isset($password)) {
$espoCgiAuth = $request->headers('HTTP_ESPO_CGI_AUTH');
$espoCgiAuth = $request->headers('Http-Espo-Cgi-Auth');
if (empty($espoCgiAuth)) {
$espoCgiAuth = $request->headers('REDIRECT_HTTP_ESPO_CGI_AUTH');
$espoCgiAuth = $request->headers('Redirect-Http-Espo-Cgi-Auth');
}
if (!empty($espoCgiAuth)) {
list($username, $password) = explode(':' , base64_decode(substr($espoCgiAuth, 6)));
@@ -120,7 +126,7 @@ class Auth extends \Slim\Middleware
}
}
if ($username && $password) {
if ($username) {
try {
$isAuthenticated = $this->auth->login($username, $password, $authenticationMethod);
} catch (\Exception $e) {
@@ -165,9 +171,8 @@ class Auth extends \Slim\Middleware
{
$request = $this->app->request();
$httpXRequestedWith = $request->headers('HTTP_X_REQUESTED_WITH');
if (isset($httpXRequestedWith) && strtolower($httpXRequestedWith) == 'xmlhttprequest') {
$httpXRequestedWith = $request->headers('Http-X-Requested-With');
if ($httpXRequestedWith && strtolower($httpXRequestedWith) == 'xmlhttprequest') {
return true;
}
+2 -2
View File
@@ -137,7 +137,7 @@ class Auth
$isByTokenOnly = false;
if (!$authenticationMethod) {
if ($this->request->headers->get('HTTP_ESPO_AUTHORIZATION_BY_TOKEN') === 'true') {
if ($this->request->headers->get('Http-Espo-Authorization-By-Token') === 'true') {
$isByTokenOnly = true;
}
}
@@ -247,7 +247,7 @@ class Auth
$this->getEntityManager()->setUser($user);
$this->getContainer()->setUser($user);
if ($this->request->headers->get('HTTP_ESPO_AUTHORIZATION')) {
if ($this->request->headers->get('Http-Espo-Authorization')) {
if (!$authToken) {
$authToken = $this->getEntityManager()->getEntity('AuthToken');
$token = $this->generateToken();
@@ -0,0 +1,50 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2018 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
* Website: http://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Core\Utils\Authentication;
use \Espo\Core\Exceptions\Error;
class ApiKey extends Base
{
public function login($username, $password, $authToken = null, $params = [], $request)
{
$apiKey = $username;
$user = $this->getEntityManager()->getRepository('User')->findOne([
'whereClause' => [
'type' => 'api',
'apiKey' => $apiKey,
'authMethod' => 'ApiKey'
]
]);
return $user;
}
}
@@ -41,7 +41,8 @@ class Hmac extends Base
$user = $this->getEntityManager()->getRepository('User')->findOne([
'whereClause' => [
'type' => 'api',
'apiKey' => $apiKey
'apiKey' => $apiKey,
'authMethod' => 'Hmac'
]
]);
+19 -2
View File
@@ -70,6 +70,13 @@ class User extends \Espo\Core\ORM\Repositories\RDB
if ($entity->isAttributeChanged('userName')) {
$entity->set('lastName', $entity->get('userName'));
}
if ($entity->has('authMethod') && $entity->get('authMethod') !== 'Hmac') {
$entity->clear('secretKey');
}
} else {
if ($entity->isAttributeChanged('type')) {
$entity->set('authMethod', null);
}
}
parent::beforeSave($entity, $options);
@@ -126,10 +133,20 @@ class User extends \Espo\Core\ORM\Repositories\RDB
parent::afterSave($entity, $options);
if ($entity->isApi()) {
if ($entity->get('apiKey') && $entity->get('secretKey') && $entity->isAttributeChanged('apiKey')) {
if (
$entity->get('apiKey') && $entity->get('secretKey') &&
(
$entity->isAttributeChanged('apiKey') || $entity->isAttributeChanged('authMethod')
)
) {
$apiKeyUtil = new \Espo\Core\Utils\ApiKey($this->getConfig());
$apiKeyUtil->storeSecretKeyForUserId($entity->id, $entity->get('secretKey'));
}
if ($entity->isAttributeChanged('authMethod') && $entity->get('authMethod') !== 'Hmac') {
$apiKeyUtil = new \Espo\Core\Utils\ApiKey($this->getConfig());
$apiKeyUtil->removeSecretKeyForUserId($entity->id);
}
}
}
@@ -137,7 +154,7 @@ class User extends \Espo\Core\ORM\Repositories\RDB
{
parent::afterRemove($entity, $options);
if ($entity->isApi()) {
if ($entity->isApi() && $entity->get('authMethod') === 'Hmac') {
$apiKeyUtil = new \Espo\Core\Utils\ApiKey($this->getConfig());
$apiKeyUtil->removeSecretKeyForUserId($entity->id);
}
@@ -32,7 +32,8 @@
"isSuperAdmin": "Is Super Admin",
"lastAccess": "Last Access",
"apiKey": "API Key",
"secretKey": "Secret Key"
"secretKey": "Secret Key",
"authMethod": "Authentication Method"
},
"links": {
"teams": "Teams",
@@ -99,6 +100,10 @@
"system": "System",
"super-admin": "Super-Admin",
"api": "API"
},
"authMethod": {
"ApiKey": "API Key",
"Hmac": "HMAC"
}
},
"boolFilters": {
@@ -37,6 +37,15 @@
"disabled": true,
"notStorable": true
},
"authMethod": {
"type": "enum",
"options": ["ApiKey", "Hmac"],
"maxLength": 24,
"layoutMassUpdateDisabled": true,
"layoutDetailDisabled": true,
"layoutFiltersDisabled": true,
"layoutListDisabled": true
},
"apiKey": {
"type": "varchar",
"maxLength": 100,
+30 -4
View File
@@ -69,8 +69,12 @@ class Record extends \Espo\Core\Services\Base
protected $internalAttributeList = [];
protected $onlyAdminAttributeList = [];
protected $readOnlyAttributeList = [];
protected $nonAdminReadOnlyAttributeList = [];
protected $readOnlyLinkList = [];
protected $linkSelectParams = [];
@@ -625,9 +629,21 @@ class Record extends \Espo\Core\Services\Base
$data->$key = $this->filterInputAttribute($key, $data->$key);
}
if (!$this->getUser()->isAdmin()) {
foreach ($this->onlyAdminAttributeList as $attribute) {
unset($data->$attribute);
}
}
foreach ($this->getAcl()->getScopeForbiddenAttributeList($this->entityType, 'edit') as $attribute) {
unset($data->$attribute);
}
if (!$this->getUser()->isAdmin()) {
foreach ($this->nonAdminReadOnlyAttributeList as $attribute) {
unset($data->$attribute);
}
}
}
protected function handleInput($data)
@@ -640,10 +656,10 @@ class Record extends \Espo\Core\Services\Base
if (empty($data->forceDuplicate)) {
$duplicates = $this->checkEntityForDuplicate($entity, $data);
if (!empty($duplicates)) {
$reason = array(
$reason = [
'reason' => 'Duplicate',
'data' => $duplicates
);
];
throw new Conflict(json_encode($reason));
}
}
@@ -1595,6 +1611,11 @@ class Record extends \Espo\Core\Services\Base
if (in_array($attribute, $this->internalAttributeList)) {
return false;
}
if (!$this->getUser()->isAdmin() && in_array($attribute, $this->onlyAdminAttributeList)) {
return true;
}
if (!$isExportAllFields) {
return true;
}
@@ -1858,8 +1879,13 @@ class Record extends \Espo\Core\Services\Base
public function prepareEntityForOutput(Entity $entity)
{
foreach ($this->internalAttributeList as $field) {
$entity->clear($field);
foreach ($this->internalAttributeList as $attribute) {
$entity->clear($attribute);
}
if (!$this->getUser()->isAdmin()) {
foreach ($this->onlyAdminAttributeList as $attribute) {
$entity->clear($attribute);
}
}
foreach ($this->getAcl()->getScopeForbiddenAttributeList($entity->getEntityType(), 'read') as $attribute) {
$entity->clear($attribute);
+41 -21
View File
@@ -62,14 +62,24 @@ class User extends Record
'isAdmin',
'isPortalUser',
'teamsIds',
'teamsColumns',
'teamsNames',
'rolesIds',
'rolesNames',
'password',
'portalsIds',
'portalRolesIds',
'contactId',
'accountsIds',
'type',
'apiKey'
'apiKey',
'secretKey'
];
protected $onlyAdminAttributeList = [
'authMethod',
'apiKey',
'secretKey'
];
protected $mandatorySelectAttributeList = [
@@ -80,13 +90,13 @@ class User extends Record
'type'
];
protected $linkSelectParams = array(
'targetLists' => array(
'additionalColumns' => array(
protected $linkSelectParams = [
'targetLists' => [
'additionalColumns' => [
'optedOut' => 'isOptedOut'
)
)
);
]
]
];
protected function getMailSender()
{
@@ -258,9 +268,6 @@ class User extends Record
}
if (!$this->getUser()->isAdmin()) {
foreach ($this->nonAdminReadOnlyAttributeList as $attribute) {
unset($data->$attribute);
}
if (!$this->getAcl()->checkScope('Team')) {
unset($data->defaultTeamId);
}
@@ -324,8 +331,10 @@ class User extends Record
if ($entity->isApi()) {
if ($this->getUser()->isAdmin()) {
$secretKey = $this->getSecretKeyForUserId($entity->id);
$entity->set('secretKey', $secretKey);
if ($entity->get('authMethod') === 'Hmac') {
$secretKey = $this->getSecretKeyForUserId($entity->id);
$entity->set('secretKey', $secretKey);
}
} else {
$entity->clear('apiKey');
$entity->clear('secretKey');
@@ -350,8 +359,10 @@ class User extends Record
$apiKey = \Espo\Core\Utils\Util::generateApiKey();
$entity->set('apiKey', $apiKey);
$secretKey = \Espo\Core\Utils\Util::generateKey();
$entity->set('secretKey', $secretKey);
if ($entity->get('authMethod') === 'Hmac') {
$secretKey = \Espo\Core\Utils\Util::generateKey();
$entity->set('secretKey', $secretKey);
}
$this->getEntityManager()->saveEntity($entity);
@@ -396,18 +407,20 @@ class User extends Record
$apiKey = \Espo\Core\Utils\Util::generateApiKey();
$entity->set('apiKey', $apiKey);
$secretKey = \Espo\Core\Utils\Util::generateKey();
$entity->set('secretKey', $secretKey);
if ($entity->get('authMethod') === 'Hmac') {
$secretKey = \Espo\Core\Utils\Util::generateKey();
$entity->set('secretKey', $secretKey);
}
}
}
protected function beforeUpdateEntity(Entity $user, $data)
protected function beforeUpdateEntity(Entity $entity, $data)
{
if ($this->getConfig()->get('userLimit') && !$this->getUser()->isSuperAdmin()) {
if (
($user->get('isActive') && $user->isAttributeChanged('isActive') && !$user->isPortal())
($entity->get('isActive') && $entity->isAttributeChanged('isActive') && !$entity->isPortal())
||
(!$user->isPortal() && $user->isAttributeChanged('type'))
(!$entity->isPortal() && $entity->isAttributeChanged('type'))
) {
$userCount = $this->getInternalUserCount();
if ($userCount >= $this->getConfig()->get('userLimit')) {
@@ -417,9 +430,9 @@ class User extends Record
}
if ($this->getConfig()->get('portalUserLimit') && !$this->getUser()->isSuperAdmin()) {
if (
($user->get('isActive') && $user->isAttributeChanged('isActive') && $user->isPortal())
($entity->get('isActive') && $entity->isAttributeChanged('isActive') && $entity->isPortal())
||
($user->isPortal() && $user->isAttributeChanged('type'))
($entity->isPortal() && $entity->isAttributeChanged('type'))
) {
$portalUserCount = $this->getPortalUserCount();
if ($portalUserCount >= $this->getConfig()->get('portalUserLimit')) {
@@ -427,6 +440,13 @@ class User extends Record
}
}
}
if ($entity->isApi()) {
if ($entity->isAttributeChanged('authMethod') && $entity->get('authMethod') === 'Hmac') {
$secretKey = \Espo\Core\Utils\Util::generateKey();
$entity->set('secretKey', $secretKey);
}
}
}
protected function sendPassword(Entity $user, $password)
+10 -3
View File
@@ -75,7 +75,7 @@ Espo.define('views/user/record/detail', 'views/record/detail', function (Dep) {
setupActionItems: function () {
Dep.prototype.setupActionItems.call(this);
if (this.model.isApi()) {
if (this.model.isApi() && this.getUser().isAdmin()) {
this.addDropdownItem({
'label': 'Generate New API Key',
'name': 'generateNewApiKey'
@@ -144,6 +144,12 @@ Espo.define('views/user/record/detail', 'views/record/detail', function (Dep) {
this.hideField('name');
this.hideField('gender');
if (this.model.get('authMethod') === 'Hmac') {
this.showField('secretKey');
} else {
this.hideField('secretKey');
}
} else {
this.showField('title');
}
@@ -240,9 +246,10 @@ Espo.define('views/user/record/detail', 'views/record/detail', function (Dep) {
if (this.getUser().isAdmin() && this.model.isApi()) {
layout.push({
"name": "apiKey",
"name": "auth",
"rows": [
[{"name":"apiKey"}, {"name":"secretKey"}]
[{"name":"authMethod"}, false],
[{"name":"apiKey"}, {"name":"secretKey"}],
]
});
}
+9
View File
@@ -161,6 +161,15 @@ Espo.define('views/user/record/edit', ['views/record/edit', 'views/user/record/d
});
}
if (this.getUser().isAdmin() && this.model.isApi()) {
layout.push({
"name": "auth",
"rows": [
[{"name":"authMethod"}, false]
]
});
}
var gridLayout = {
type: 'record',
layout: this.convertDetailLayout(layout),