- = $this->Html->link(__d('CakeDC/Users', 'Change Password'), ['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'changePassword']); ?>
+ = $this->Html->link(__d('cake_d_c/users', 'Change Password'), ['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'changePassword']); ?>
-
+
= h($user->username) ?>
-
+
= h($user->email) ?>
+ = $this->User->socialConnectLinkList($user->social_accounts) ?>
social_accounts)):
?>
-
+
-
- = __d('CakeDC/Users', 'Avatar'); ?>
- = __d('CakeDC/Users', 'Provider'); ?>
- = __d('CakeDC/Users', 'Link'); ?>
-
+
+ = __d('cake_d_c/users', 'Avatar'); ?>
+ = __d('cake_d_c/users', 'Provider'); ?>
+ = __d('cake_d_c/users', 'Link'); ?>
+
social_accounts as $socialAccount):
$escapedUsername = h($socialAccount->username);
- $linkText = empty($escapedUsername) ? __d('CakeDC/Users', 'Link to {0}', h($socialAccount->provider)) : h($socialAccount->username)
+ $linkText = empty($escapedUsername) ? __d('cake_d_c/users', 'Link to {0}', h($socialAccount->provider)) : h($socialAccount->username)
?>
=
@@ -55,18 +59,18 @@
= h($socialAccount->provider) ?>
=
- $this->Html->link(
+ $socialAccount->link && $socialAccount->link != '#' ? $this->Html->link(
$linkText,
$socialAccount->link,
['target' => '_blank']
- ) ?>
+ ) : '-' ?>
-
-
diff --git a/templates/Users/register.php b/templates/Users/register.php
new file mode 100644
index 000000000..e82673b67
--- /dev/null
+++ b/templates/Users/register.php
@@ -0,0 +1,40 @@
+
+
+ = $this->Form->create($user); ?>
+
+ = __d('cake_d_c/users', 'Add User') ?>
+ Form->control('username', ['label' => __d('cake_d_c/users', 'Username')]);
+ echo $this->Form->control('email', ['label' => __d('cake_d_c/users', 'Email')]);
+ echo $this->Form->control('password', ['label' => __d('cake_d_c/users', 'Password')]);
+ echo $this->Form->control('password_confirm', [
+ 'required' => true,
+ 'type' => 'password',
+ 'label' => __d('cake_d_c/users', 'Confirm password')
+ ]);
+ echo $this->Form->control('first_name', ['label' => __d('cake_d_c/users', 'First name')]);
+ echo $this->Form->control('last_name', ['label' => __d('cake_d_c/users', 'Last name')]);
+ if (Configure::read('Users.Tos.required')) {
+ echo $this->Form->control('tos', ['type' => 'checkbox', 'label' => __d('cake_d_c/users', 'Accept TOS conditions?'), 'required' => true]);
+ }
+ if (Configure::read('Users.reCaptcha.registration')) {
+ echo $this->User->addReCaptcha();
+ }
+ ?>
+
+ = $this->Form->button(__d('cake_d_c/users', 'Submit')) ?>
+ = $this->Form->end() ?>
+
diff --git a/templates/Users/request_reset_password.php b/templates/Users/request_reset_password.php
new file mode 100644
index 000000000..cde49a009
--- /dev/null
+++ b/templates/Users/request_reset_password.php
@@ -0,0 +1,25 @@
+
+
+ = $this->Flash->render('auth') ?>
+ = $this->Form->create($user) ?>
+
+ = __d('cake_d_c/users', 'Please enter your email or username to reset your password') ?>
+ = $this->Form->control('reference') ?>
+
+ = $this->Form->button(__d('cake_d_c/users', 'Submit')); ?>
+ = $this->Form->end() ?>
+
diff --git a/templates/Users/resend_token_validation.php b/templates/Users/resend_token_validation.php
new file mode 100644
index 000000000..2023e3c18
--- /dev/null
+++ b/templates/Users/resend_token_validation.php
@@ -0,0 +1,22 @@
+
+
+ = $this->Form->create($user); ?>
+
+ = __d('cake_d_c/users', 'Resend Validation email') ?>
+ Form->control('reference', ['label' => __d('cake_d_c/users', 'Email or username')]);
+ ?>
+
+ = $this->Form->button(__d('cake_d_c/users', 'Submit')) ?>
+ = $this->Form->end() ?>
+
diff --git a/templates/Users/social_email.php b/templates/Users/social_email.php
new file mode 100644
index 000000000..55c1208e9
--- /dev/null
+++ b/templates/Users/social_email.php
@@ -0,0 +1,21 @@
+
+
+ = $this->Flash->render() ?>
+ = $this->Form->create() ?>
+
+ = __d('cake_d_c/users', 'Please enter your email') ?>
+ = $this->Form->control('email', ['type' => 'email', 'required' => true]) ?>
+
+ = $this->Form->button(__d('cake_d_c/users', 'Submit')); ?>
+ = $this->Form->end() ?>
+
diff --git a/templates/Users/u2f_authenticate.php b/templates/Users/u2f_authenticate.php
new file mode 100644
index 000000000..16ce1bf01
--- /dev/null
+++ b/templates/Users/u2f_authenticate.php
@@ -0,0 +1,59 @@
+Html->script('CakeDC/Users.u2f-api.js', ['block' => true]);
+?>
+
+Html->scriptStart(['block' => true]);
+?>
+ setTimeout(function() {
+ var req = = $req ?>;
+ var appId = req[0].appId;
+ var challenge = req[0].challenge;
+
+ u2f.sign(appId, challenge, req, function(data) {
+ var targetForm = document.getElementById('u2fAuthenticateFrm');
+ var targetInput = document.getElementById('authenticateResponse');
+ if(data.errorCode && data.errorCode != 0) {
+ alert("= __d('cake_d_c/users', 'Yubico key check has failed, please try again')?>");
+
+ return;
+ }
+ targetInput.value = JSON.stringify(data);
+ targetForm.submit();
+ });
+ }, 1000);
+Html->scriptEnd();?>
diff --git a/templates/Users/u2f_register.php b/templates/Users/u2f_register.php
new file mode 100644
index 000000000..0ea8da5af
--- /dev/null
+++ b/templates/Users/u2f_register.php
@@ -0,0 +1,64 @@
+Html->script('CakeDC/Users.u2f-api.js', ['block' => true]);
+?>
+
+ $registerRequest->appId,
+ 'version' => $registerRequest->version,
+ 'challenge' => $registerRequest->challenge,
+ 'attestation' => 'direct'
+]);
+$this->Html->scriptStart(['block' => true]);
+?>
+setTimeout(function() {
+ var req = = $req ?>;
+ var appId = req.appId;
+ var registerRequests = [req];
+ u2f.register(appId, registerRequests, [], function(data) {
+ var targetForm = document.getElementById('u2fRegisterFrm');
+ var targetInput = document.getElementById('registerResponse');
+
+ if(data.errorCode && data.errorCode != 0) {
+ alert("= __d('cake_d_c/users', 'Yubico key check has failed, please try again')?>");
+
+ return;
+ }
+ targetInput.value = JSON.stringify(data);
+ targetForm.submit();
+ });
+}, 1000);
+Html->scriptEnd();?>
diff --git a/templates/Users/verify.php b/templates/Users/verify.php
new file mode 100644
index 000000000..92648a029
--- /dev/null
+++ b/templates/Users/verify.php
@@ -0,0 +1,20 @@
+
diff --git a/templates/Users/view.php b/templates/Users/view.php
new file mode 100644
index 000000000..9e0d28106
--- /dev/null
+++ b/templates/Users/view.php
@@ -0,0 +1,90 @@
+
+
+
= __d('cake_d_c/users', 'Actions') ?>
+
+ = $this->Html->link(__d('cake_d_c/users', 'Edit User'), ['action' => 'edit', $Users->id]) ?>
+ = $this->Form->postLink(
+ __d('cake_d_c/users', 'Delete User'),
+ ['action' => 'delete', $Users->id],
+ ['confirm' => __d('cake_d_c/users', 'Are you sure you want to delete # {0}?', $Users->id)]
+ ) ?>
+ = $this->Html->link(__d('cake_d_c/users', 'List Users'), ['action' => 'index']) ?>
+ = $this->Html->link(__d('cake_d_c/users', 'New User'), ['action' => 'add']) ?>
+
+
+
+
= h($Users->id) ?>
+
+
+
+
= h($Users->id) ?>
+
+
= h($Users->username) ?>
+
+
= h($Users->email) ?>
+
+
= h($Users->first_name) ?>
+
+
= h($Users->last_name) ?>
+
+
= h($Users->role) ?>
+
+
= h($Users->token) ?>
+
+
= h($Users->api_token) ?>
+
+
+
+
= $this->Number->format($Users->active) ?>
+
+
+
+
= h($Users->token_expires) ?>
+
+
= h($Users->activation_date) ?>
+
+
= h($Users->tos_date) ?>
+
+
= h($Users->created) ?>
+
+
= h($Users->modified) ?>
+
+
+
+
diff --git a/templates/Users/webauthn2fa.php b/templates/Users/webauthn2fa.php
new file mode 100644
index 000000000..3c2b7c898
--- /dev/null
+++ b/templates/Users/webauthn2fa.php
@@ -0,0 +1,56 @@
+Html->script('CakeDC/Users.webauthn.js', ['block' => true]);
+$this->assign('title', __d('cake_d_c/users','Two-factor authentication'));
+?>
+
+ $this->Url->build(['action' => 'webauthn2faAuthenticate']),
+ 'authenticateOptionsUrl' => $this->Url->build(['action' => 'webauthn2faAuthenticateOptions']),
+ 'registerActionUrl' => $this->Url->build(['action' => 'webauthn2faRegister']),
+ 'registerOptionsUrl' => $this->Url->build(['action' => 'webauthn2faRegisterOptions']),
+ 'isRegister' => $isRegister,
+ 'username' => h($username),
+ 'registerElemId' => 'webauthn2faRegisterInfo',
+ 'authenticateElemId' => 'webauthn2faAuthenticateInfo',
+];
+$this->Html->scriptStart(['block' => true]);
+?>
+setTimeout(function() {
+ Webauthn2faHelper.run(= json_encode($options)?>);
+}, 1000);
+Html->scriptEnd();?>
diff --git a/templates/email/html/reset_password.php b/templates/email/html/reset_password.php
new file mode 100644
index 000000000..4009e9134
--- /dev/null
+++ b/templates/email/html/reset_password.php
@@ -0,0 +1,28 @@
+
+
+ = __d('cake_d_c/users', "Hi {0}", isset($first_name) ? $first_name : '') ?>,
+
+
+ = $this->Html->link(__d('cake_d_c/users', 'Reset your password here'), $activationUrl) ?>
+
+
+= __d(
+ 'cake_d_c/users',
+ "If the link is not correctly displayed, please copy the following address in your web browser {0}",
+ $this->Url->build($activationUrl)
+) ?>
+
+
+ = __d('cake_d_c/users', 'Thank you') ?>,
+
diff --git a/templates/email/html/social_account_validation.php b/templates/email/html/social_account_validation.php
new file mode 100644
index 000000000..01d2fab85
--- /dev/null
+++ b/templates/email/html/social_account_validation.php
@@ -0,0 +1,31 @@
+
+
+
+ = __d('cake_d_c/users', "Hi {0}", $user['first_name']) ?>,
+
+
+ Html->link($text, $activationUrl);
+ ?>
+
+
+= __d(
+ 'cake_d_c/users',
+ "If the link is not correctly displayed, please copy the following address in your web browser {0}",
+ $this->Url->build($activationUrl)
+) ?>
+
+
+ = __d('cake_d_c/users', 'Thank you') ?>,
+
diff --git a/templates/email/html/validation.php b/templates/email/html/validation.php
new file mode 100644
index 000000000..ad92d2f3e
--- /dev/null
+++ b/templates/email/html/validation.php
@@ -0,0 +1,27 @@
+
+
+ = __d('cake_d_c/users', "Hi {0}", isset($first_name) ? $first_name : '') ?>,
+
+
+ = $this->Html->link(__d('cake_d_c/users', 'Activate your account here'), $activationUrl) ?>
+
+
+= __d(
+ 'cake_d_c/users',
+ "If the link is not correctly displayed, please copy the following address in your web browser {0}",
+ $this->Url->build($activationUrl)
+) ?>
+
+
+ = __d('cake_d_c/users', 'Thank you') ?>,
+
diff --git a/templates/email/text/reset_password.php b/templates/email/text/reset_password.php
new file mode 100644
index 000000000..312ac428d
--- /dev/null
+++ b/templates/email/text/reset_password.php
@@ -0,0 +1,21 @@
+
+= __d('cake_d_c/users', "Hi {0}", isset($first_name) ? $first_name : '') ?>,
+
+= __d(
+ 'cake_d_c/users',
+ "Please copy the following address in your web browser {0}",
+ $this->Url->build($activationUrl)
+) ?>
+
+= __d('cake_d_c/users', 'Thank you') ?>,
+
diff --git a/templates/email/text/social_account_validation.php b/templates/email/text/social_account_validation.php
new file mode 100644
index 000000000..79dc496de
--- /dev/null
+++ b/templates/email/text/social_account_validation.php
@@ -0,0 +1,21 @@
+
+= __d('cake_d_c/users', "Hi {0}", $user['first_name']) ?>,
+
+= __d(
+ 'cake_d_c/users',
+ "Please copy the following address in your web browser to activate your social login {0}",
+ $this->Url->build($activationUrl)
+) ?>
+
+= __d('cake_d_c/users', 'Thank you') ?>,
+
diff --git a/templates/email/text/validation.php b/templates/email/text/validation.php
new file mode 100644
index 000000000..312ac428d
--- /dev/null
+++ b/templates/email/text/validation.php
@@ -0,0 +1,21 @@
+
+= __d('cake_d_c/users', "Hi {0}", isset($first_name) ? $first_name : '') ?>,
+
+= __d(
+ 'cake_d_c/users',
+ "Please copy the following address in your web browser {0}",
+ $this->Url->build($activationUrl)
+) ?>
+
+= __d('cake_d_c/users', 'Thank you') ?>,
+
diff --git a/templates/layout/email/html/default.php b/templates/layout/email/html/default.php
new file mode 100644
index 000000000..98d045608
--- /dev/null
+++ b/templates/layout/email/html/default.php
@@ -0,0 +1,20 @@
+
+
+
+
+
= $this->fetch('title') ?>
+
+
+ = $this->fetch('content') ?>
+
+
diff --git a/templates/layout/email/text/default.php b/templates/layout/email/text/default.php
new file mode 100644
index 000000000..4d493b97c
--- /dev/null
+++ b/templates/layout/email/text/default.php
@@ -0,0 +1,13 @@
+
+fetch('content');
diff --git a/tests/App/Controller/AppController.php b/tests/App/Controller/AppController.php
deleted file mode 100644
index 5899a4e41..000000000
--- a/tests/App/Controller/AppController.php
+++ /dev/null
@@ -1,24 +0,0 @@
-loadComponent('Flash');
- // $this->loadComponent('CakeDC/Users.UsersAuth');
- $this->loadComponent('RequestHandler');
- }
-}
diff --git a/tests/Fixture/PostsFixture.php b/tests/Fixture/PostsFixture.php
index fadeb7179..4057cbbb8 100644
--- a/tests/Fixture/PostsFixture.php
+++ b/tests/Fixture/PostsFixture.php
@@ -1,11 +1,11 @@
['type' => 'uuid', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null],
- 'title' => ['type' => 'string', 'length' => 255, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'user_id' => ['type' => 'uuid', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- '_constraints' => [
- 'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
- ],
- '_options' => [
- 'engine' => 'InnoDB',
- 'collation' => 'utf8_general_ci'
- ],
- ];
- // @codingStandardsIgnoreEnd
-
/**
* Records
*
diff --git a/tests/Fixture/PostsUsersFixture.php b/tests/Fixture/PostsUsersFixture.php
index f4cea2af2..5f5350e9e 100644
--- a/tests/Fixture/PostsUsersFixture.php
+++ b/tests/Fixture/PostsUsersFixture.php
@@ -1,11 +1,11 @@
['type' => 'uuid', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null],
- 'user_id' => ['type' => 'uuid', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'post_id' => ['type' => 'uuid', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- '_constraints' => [
- 'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
- ],
- '_options' => [
- 'engine' => 'InnoDB',
- 'collation' => 'utf8_general_ci'
- ],
- ];
- // @codingStandardsIgnoreEnd
-
/**
* Records
*
diff --git a/tests/Fixture/SocialAccountsFixture.php b/tests/Fixture/SocialAccountsFixture.php
index 7e014fa58..9789d2c45 100644
--- a/tests/Fixture/SocialAccountsFixture.php
+++ b/tests/Fixture/SocialAccountsFixture.php
@@ -1,46 +1,23 @@
['type' => 'uuid', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null],
- 'user_id' => ['type' => 'uuid', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'provider' => ['type' => 'string', 'length' => 255, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
- 'username' => ['type' => 'string', 'length' => 255, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'reference' => ['type' => 'string', 'length' => 255, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'avatar' => ['type' => 'string', 'length' => 255, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'description' => ['type' => 'text', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
- 'token' => ['type' => 'string', 'length' => 500, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'token_secret' => ['type' => 'string', 'length' => 500, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'token_expires' => ['type' => 'datetime', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
- 'active' => ['type' => 'boolean', 'length' => null, 'null' => false, 'default' => true, 'comment' => '', 'precision' => null],
- 'data' => ['type' => 'text', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null],
- 'created' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null],
- 'modified' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null],
- '_constraints' => [
- 'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
- ],
- '_options' => [
- 'engine' => 'InnoDB',
- 'collation' => 'utf8_general_ci'
- ],
- ];
- // @codingStandardsIgnoreEnd
-
/**
* Records
*
@@ -61,7 +38,7 @@ class SocialAccountsFixture extends TestFixture
'active' => false,
'data' => '',
'created' => '2015-05-22 21:52:44',
- 'modified' => '2015-05-22 21:52:44'
+ 'modified' => '2015-05-22 21:52:44',
],
[
'id' => '00000000-0000-0000-0000-000000000002',
@@ -77,7 +54,7 @@ class SocialAccountsFixture extends TestFixture
'active' => true,
'data' => '',
'created' => '2015-05-22 21:52:44',
- 'modified' => '2015-05-22 21:52:44'
+ 'modified' => '2015-05-22 21:52:44',
],
[
'id' => '00000000-0000-0000-0000-000000000003',
@@ -93,7 +70,7 @@ class SocialAccountsFixture extends TestFixture
'active' => true,
'data' => '',
'created' => '2015-05-22 21:52:44',
- 'modified' => '2015-05-22 21:52:44'
+ 'modified' => '2015-05-22 21:52:44',
],
[
'id' => '00000000-0000-0000-0000-000000000004',
@@ -109,7 +86,7 @@ class SocialAccountsFixture extends TestFixture
'active' => false,
'data' => '',
'created' => '2015-05-22 21:52:44',
- 'modified' => '2015-05-22 21:52:44'
+ 'modified' => '2015-05-22 21:52:44',
],
[
'id' => '00000000-0000-0000-0000-000000000005',
@@ -125,7 +102,7 @@ class SocialAccountsFixture extends TestFixture
'active' => false,
'data' => '',
'created' => '2015-05-22 21:52:44',
- 'modified' => '2015-05-22 21:52:44'
+ 'modified' => '2015-05-22 21:52:44',
],
];
}
diff --git a/tests/Fixture/UsersFixture.php b/tests/Fixture/UsersFixture.php
index 1577a0783..d48f6dc55 100644
--- a/tests/Fixture/UsersFixture.php
+++ b/tests/Fixture/UsersFixture.php
@@ -1,243 +1,262 @@
['type' => 'uuid', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null],
- 'username' => ['type' => 'string', 'length' => 255, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'email' => ['type' => 'string', 'length' => 255, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'password' => ['type' => 'string', 'length' => 255, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'first_name' => ['type' => 'string', 'length' => 50, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'last_name' => ['type' => 'string', 'length' => 50, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'token' => ['type' => 'string', 'length' => 255, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'token_expires' => ['type' => 'datetime', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
- 'api_token' => ['type' => 'string', 'length' => 255, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
- 'activation_date' => ['type' => 'datetime', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
- 'tos_date' => ['type' => 'datetime', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
- 'active' => ['type' => 'boolean', 'length' => null, 'null' => false, 'default' => true, 'comment' => '', 'precision' => null],
- 'is_superuser' => ['type' => 'boolean', 'length' => null, 'unsigned' => false, 'null' => false, 'default' => false, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
- 'role' => ['type' => 'string', 'length' => 255, 'null' => true, 'default' => 'user', 'comment' => '', 'precision' => null, 'fixed' => null],
- 'created' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null],
- 'modified' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null],
- '_constraints' => [
- 'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
- ],
- '_options' => [
- 'engine' => 'InnoDB',
- 'collation' => 'utf8_general_ci'
- ],
- ];
- // @codingStandardsIgnoreEnd
+ public function init(): void
+ {
+ $this->records = [
+ [
+ 'id' => '00000000-0000-0000-0000-000000000001',
+ 'username' => 'user-1',
+ 'email' => 'user-1@test.com',
+ 'password' => '12345',
+ 'first_name' => 'first1',
+ 'last_name' => 'last1',
+ 'token' => 'ae93ddbe32664ce7927cf0c5c5a5e59d',
+ 'token_expires' => '2035-06-24 17:33:54',
+ 'api_token' => 'yyy',
+ 'activation_date' => '2015-06-24 17:33:54',
+ 'secret' => 'yyy',
+ 'secret_verified' => false,
+ 'tos_date' => '2015-06-24 17:33:54',
+ 'active' => false,
+ 'is_superuser' => true,
+ 'role' => 'admin',
+ 'created' => '2015-06-24 17:33:54',
+ 'modified' => '2015-06-24 17:33:54',
+ 'additional_data' => [
+ 'u2f_registration' => [
+ 'keyHandle' => 'fake key handle',
+ 'publicKey' => 'afdoaj0-23u423-ad ujsf-as8-0-afsd',
+ 'certificate' => '23jdsfoasdj0f9sa082304823423',
+ 'counter' => 1,
+ ],
+ 'webauthn_credentials' => [
+ 'MTJiMzc0ODYtOTI5OS00MzMxLWFjMzMtODViMmQ5ODViNmZl' => [
+ 'publicKeyCredentialId' => '12b37486-9299-4331-ac33-85b2d985b6fe',
+ 'type' => 'public-key',
+ 'transports' => [],
+ 'attestationType' => 'none',
+ 'trustPath' => [
+ 'type' => 'Webauthn\TrustPath\EmptyTrustPath',
+ ],
+ 'aaguid' => '00000000-0000-0000-0000-000000000000',
+ 'credentialPublicKey' => Base64Url::encode('000000000000000000000000000000000000-9999999999999999999999999999999999999999-XXXXXXXXXXXXX-ZZZZZZZZZZZ'),
+ 'userHandle' => Base64Url::encode('00000000-0000-0000-0000-000000000001'),
+ 'counter' => 190,
+ 'otherUI' => null,
+ ],
+ ],
+ ],
+ 'last_login' => '2015-06-24 17:33:54',
+ ],
+ [
+ 'id' => '00000000-0000-0000-0000-000000000002',
+ 'username' => 'user-2',
+ 'email' => 'user-2@test.com',
+ //The password real value is 12345
+ 'password' => '$2y$10$Nvu7ipP.z8tiIl75OdUvt.86vuG6iKMoHIOc7O7mboFI85hSyTEde',
+ 'first_name' => 'user',
+ 'last_name' => 'second',
+ 'token' => '6614f65816754310a5f0553436dd89e9',
+ 'token_expires' => '2015-06-24 17:33:54',
+ 'api_token' => 'xxx',
+ 'activation_date' => '2015-06-24 17:33:54',
+ 'secret' => 'xxx',
+ 'secret_verified' => false,
+ 'tos_date' => '2015-06-24 17:33:54',
+ 'active' => true,
+ 'is_superuser' => true,
+ 'role' => 'admin',
+ 'created' => '2015-06-24 17:33:54',
+ 'modified' => '2015-06-24 17:33:54',
+ 'last_login' => '2015-06-24 17:33:54',
+ ],
+ [
+ 'id' => '00000000-0000-0000-0000-000000000003',
+ 'username' => 'user-3',
+ 'email' => 'user-3@test.com',
+ 'password' => '12345',
+ 'first_name' => 'user',
+ 'last_name' => 'third',
+ 'token' => 'token-3',
+ 'token_expires' => '2030-06-20 17:33:54',
+ 'api_token' => 'xxx',
+ 'activation_date' => '2015-06-24 17:33:54',
+ 'secret' => 'xxx',
+ 'secret_verified' => true,
+ 'is_superuser' => true,
+ 'tos_date' => '2015-06-24 17:33:54',
+ 'active' => false,
+ 'role' => 'admin',
+ 'created' => '2015-06-24 17:33:54',
+ 'modified' => '2015-06-24 17:33:54',
+ ],
+ [
+ 'id' => '00000000-0000-0000-0000-000000000004',
+ 'username' => 'user-4',
+ 'email' => '4@example.com',
+ 'password' => '$2y$10$Nvu7ipP.z8tiIl75OdUvt.86vuG6iKMoHIOc7O7mboFI85hSyTEde',
+ 'first_name' => 'FirstName4',
+ 'last_name' => 'Lorem ipsum dolor sit amet',
+ 'token' => 'token-4',
+ 'token_expires' => '2030-06-24 17:33:54',
+ 'api_token' => 'Lorem ipsum dolor sit amet',
+ 'activation_date' => '2015-06-24 17:33:54',
+ 'secret' => 'Lorem ipsum dolor sit amet',
+ 'secret_verified' => true,
+ 'is_superuser' => false,
+ 'tos_date' => '2015-06-24 17:33:54',
+ 'active' => true,
+ 'role' => 'Lorem ipsum dolor sit amet',
+ 'created' => '2015-06-24 17:33:54',
+ 'modified' => '2015-06-24 17:33:54',
+ ],
+ [
+ 'id' => '00000000-0000-0000-0000-000000000005',
+ 'username' => 'user-5',
+ 'email' => 'test@example.com',
+ 'password' => '12345',
+ 'first_name' => 'first-user-5',
+ 'last_name' => 'firts name 5',
+ 'token' => 'token-5',
+ 'token_expires' => '2015-06-24 17:33:54',
+ 'api_token' => '',
+ 'activation_date' => '2015-06-24 17:33:54',
+ 'secret' => '',
+ 'secret_verified' => false,
+ 'tos_date' => '2015-06-24 17:33:54',
+ 'active' => true,
+ 'is_superuser' => false,
+ 'role' => 'user',
+ 'created' => '2015-06-24 17:33:54',
+ 'modified' => '2015-06-24 17:33:54',
+ ],
+ [
+ 'id' => '00000000-0000-0000-0000-000000000006',
+ 'username' => 'user-6',
+ 'email' => '6@example.com',
+ 'password' => '$2y$10$IPPgJNSfvATsMBLbv/2r8OtpyTBibyM1g5GDxD4PivW9qBRwRkRbC',
+ 'first_name' => 'first-user-6',
+ 'last_name' => 'firts name 6',
+ 'token' => 'token-6',
+ 'token_expires' => '2015-06-24 17:33:54',
+ 'api_token' => '',
+ 'activation_date' => '2015-06-24 17:33:54',
+ 'secret' => '',
+ 'secret_verified' => false,
+ 'tos_date' => '2015-06-24 17:33:54',
+ 'active' => true,
+ 'is_superuser' => false,
+ 'role' => 'user',
+ 'created' => '2015-06-24 17:33:54',
+ 'modified' => '2015-06-24 17:33:54',
+ ],
+ [
+ 'id' => '00000000-0000-0000-0000-000000000007',
+ 'username' => 'Lorem ipsum dolor sit amet',
+ 'email' => 'Lorem ipsum dolor sit amet',
+ 'password' => 'Lorem ipsum dolor sit amet',
+ 'first_name' => 'Lorem ipsum dolor sit amet',
+ 'last_name' => 'Lorem ipsum dolor sit amet',
+ 'token' => 'Lorem ipsum dolor sit amet',
+ 'token_expires' => '2015-06-24 17:33:54',
+ 'api_token' => 'Lorem ipsum dolor sit amet',
+ 'activation_date' => '2015-06-24 17:33:54',
+ 'secret' => 'Lorem ipsum dolor sit amet',
+ 'secret_verified' => false,
+ 'tos_date' => '2015-06-24 17:33:54',
+ 'active' => true,
+ 'is_superuser' => false,
+ 'role' => 'Lorem ipsum dolor sit amet',
+ 'created' => '2015-06-24 17:33:54',
+ 'modified' => '2015-06-24 17:33:54',
+ ],
+ [
+ 'id' => '00000000-0000-0000-0000-000000000008',
+ 'username' => 'Lorem ipsum dolor sit amet',
+ 'email' => 'Lorem ipsum dolor sit amet',
+ 'password' => 'Lorem ipsum dolor sit amet',
+ 'first_name' => 'Lorem ipsum dolor sit amet',
+ 'last_name' => 'Lorem ipsum dolor sit amet',
+ 'token' => 'Lorem ipsum dolor sit amet',
+ 'token_expires' => '2015-06-24 17:33:54',
+ 'api_token' => 'Lorem ipsum dolor sit amet',
+ 'activation_date' => '2015-06-24 17:33:54',
+ 'secret' => 'Lorem ipsum dolor sit amet',
+ 'secret_verified' => false,
+ 'tos_date' => '2015-06-24 17:33:54',
+ 'active' => true,
+ 'is_superuser' => false,
+ 'role' => 'Lorem ipsum dolor sit amet',
+ 'created' => '2015-06-24 17:33:54',
+ 'modified' => '2015-06-24 17:33:54',
+ ],
+ [
+ 'id' => '00000000-0000-0000-0000-000000000009',
+ 'username' => 'Lorem ipsum dolor sit amet',
+ 'email' => 'Lorem ipsum dolor sit amet',
+ 'password' => 'Lorem ipsum dolor sit amet',
+ 'first_name' => 'Lorem ipsum dolor sit amet',
+ 'last_name' => 'Lorem ipsum dolor sit amet',
+ 'token' => 'Lorem ipsum dolor sit amet',
+ 'token_expires' => '2015-06-24 17:33:54',
+ 'api_token' => 'Lorem ipsum dolor sit amet',
+ 'activation_date' => '2015-06-24 17:33:54',
+ 'secret' => 'Lorem ipsum dolor sit amet',
+ 'secret_verified' => false,
+ 'tos_date' => '2015-06-24 17:33:54',
+ 'active' => true,
+ 'is_superuser' => false,
+ 'role' => 'Lorem ipsum dolor sit amet',
+ 'created' => '2015-06-24 17:33:54',
+ 'modified' => '2015-06-24 17:33:54',
+ ],
+ [
+ 'id' => '00000000-0000-0000-0000-000000000010',
+ 'username' => 'Lorem ipsum dolor sit amet',
+ 'email' => 'Lorem ipsum dolor sit amet',
+ 'password' => 'Lorem ipsum dolor sit amet',
+ 'first_name' => 'Lorem ipsum dolor sit amet',
+ 'last_name' => 'Lorem ipsum dolor sit amet',
+ 'token' => 'Lorem ipsum dolor sit amet',
+ 'token_expires' => '2015-06-24 17:33:54',
+ 'api_token' => 'Lorem ipsum dolor sit amet',
+ 'activation_date' => '2015-06-24 17:33:54',
+ 'secret' => 'Lorem ipsum dolor sit amet',
+ 'secret_verified' => false,
+ 'tos_date' => '2015-06-24 17:33:54',
+ 'active' => true,
+ 'is_superuser' => false,
+ 'role' => 'Lorem ipsum dolor sit amet',
+ 'created' => '2015-06-24 17:33:54',
+ 'modified' => '2015-06-24 17:33:54',
+ ],
+ ];
- /**
- * Records
- *
- * @var array
- */
- public $records = [
- [
- 'id' => '00000000-0000-0000-0000-000000000001',
- 'username' => 'user-1',
- 'email' => 'user-1@test.com',
- 'password' => '12345',
- 'first_name' => 'first1',
- 'last_name' => 'last1',
- 'token' => 'ae93ddbe32664ce7927cf0c5c5a5e59d',
- 'token_expires' => '2035-06-24 17:33:54',
- 'api_token' => 'yyy',
- 'activation_date' => '2015-06-24 17:33:54',
- 'tos_date' => '2015-06-24 17:33:54',
- 'active' => false,
- 'is_superuser' => true,
- 'role' => 'admin',
- 'created' => '2015-06-24 17:33:54',
- 'modified' => '2015-06-24 17:33:54'
- ],
- [
- 'id' => '00000000-0000-0000-0000-000000000002',
- 'username' => 'user-2',
- 'email' => 'user-2@test.com',
- 'password' => '12345',
- 'first_name' => 'user',
- 'last_name' => 'second',
- 'token' => '6614f65816754310a5f0553436dd89e9',
- 'token_expires' => '2015-06-24 17:33:54',
- 'api_token' => 'xxx',
- 'activation_date' => '2015-06-24 17:33:54',
- 'tos_date' => '2015-06-24 17:33:54',
- 'active' => true,
- 'is_superuser' => true,
- 'role' => 'admin',
- 'created' => '2015-06-24 17:33:54',
- 'modified' => '2015-06-24 17:33:54'
- ],
- [
- 'id' => '00000000-0000-0000-0000-000000000003',
- 'username' => 'user-3',
- 'email' => 'user-3@test.com',
- 'password' => '12345',
- 'first_name' => 'user',
- 'last_name' => 'third',
- 'token' => 'token-3',
- 'token_expires' => '2030-06-20 17:33:54',
- 'api_token' => 'xxx',
- 'activation_date' => '2015-06-24 17:33:54',
- 'tos_date' => '2015-06-24 17:33:54',
- 'active' => false,
- 'is_superuser' => true,
- 'role' => 'admin',
- 'created' => '2015-06-24 17:33:54',
- 'modified' => '2015-06-24 17:33:54'
- ],
- [
- 'id' => '00000000-0000-0000-0000-000000000004',
- 'username' => 'user-4',
- 'email' => '4@example.com',
- 'password' => 'Lorem ipsum dolor sit amet',
- 'first_name' => 'FirstName4',
- 'last_name' => 'Lorem ipsum dolor sit amet',
- 'token' => 'token-4',
- 'token_expires' => '2030-06-24 17:33:54',
- 'api_token' => 'Lorem ipsum dolor sit amet',
- 'activation_date' => '2015-06-24 17:33:54',
- 'tos_date' => '2015-06-24 17:33:54',
- 'active' => true,
- 'is_superuser' => false,
- 'role' => 'Lorem ipsum dolor sit amet',
- 'created' => '2015-06-24 17:33:54',
- 'modified' => '2015-06-24 17:33:54'
- ],
- [
- 'id' => '00000000-0000-0000-0000-000000000005',
- 'username' => 'user-5',
- 'email' => 'test@example.com',
- 'password' => '12345',
- 'first_name' => 'first-user-5',
- 'last_name' => 'firts name 5',
- 'token' => 'token-5',
- 'token_expires' => '2015-06-24 17:33:54',
- 'api_token' => '',
- 'activation_date' => '2015-06-24 17:33:54',
- 'tos_date' => '2015-06-24 17:33:54',
- 'active' => true,
- 'is_superuser' => false,
- 'role' => 'user',
- 'created' => '2015-06-24 17:33:54',
- 'modified' => '2015-06-24 17:33:54'
- ],
- [
- 'id' => '00000000-0000-0000-0000-000000000006',
- 'username' => 'user-6',
- 'email' => '6@example.com',
- 'password' => '$2y$10$IPPgJNSfvATsMBLbv/2r8OtpyTBibyM1g5GDxD4PivW9qBRwRkRbC',
- 'first_name' => 'first-user-6',
- 'last_name' => 'firts name 6',
- 'token' => 'token-6',
- 'token_expires' => '2015-06-24 17:33:54',
- 'api_token' => '',
- 'activation_date' => '2015-06-24 17:33:54',
- 'tos_date' => '2015-06-24 17:33:54',
- 'active' => true,
- 'is_superuser' => false,
- 'role' => 'user',
- 'created' => '2015-06-24 17:33:54',
- 'modified' => '2015-06-24 17:33:54'
- ],
- [
- 'id' => '00000000-0000-0000-0000-000000000007',
- 'username' => 'Lorem ipsum dolor sit amet',
- 'email' => 'Lorem ipsum dolor sit amet',
- 'password' => 'Lorem ipsum dolor sit amet',
- 'first_name' => 'Lorem ipsum dolor sit amet',
- 'last_name' => 'Lorem ipsum dolor sit amet',
- 'token' => 'Lorem ipsum dolor sit amet',
- 'token_expires' => '2015-06-24 17:33:54',
- 'api_token' => 'Lorem ipsum dolor sit amet',
- 'activation_date' => '2015-06-24 17:33:54',
- 'tos_date' => '2015-06-24 17:33:54',
- 'active' => true,
- 'is_superuser' => false,
- 'role' => 'Lorem ipsum dolor sit amet',
- 'created' => '2015-06-24 17:33:54',
- 'modified' => '2015-06-24 17:33:54'
- ],
- [
- 'id' => '00000000-0000-0000-0000-000000000008',
- 'username' => 'Lorem ipsum dolor sit amet',
- 'email' => 'Lorem ipsum dolor sit amet',
- 'password' => 'Lorem ipsum dolor sit amet',
- 'first_name' => 'Lorem ipsum dolor sit amet',
- 'last_name' => 'Lorem ipsum dolor sit amet',
- 'token' => 'Lorem ipsum dolor sit amet',
- 'token_expires' => '2015-06-24 17:33:54',
- 'api_token' => 'Lorem ipsum dolor sit amet',
- 'activation_date' => '2015-06-24 17:33:54',
- 'tos_date' => '2015-06-24 17:33:54',
- 'active' => true,
- 'is_superuser' => false,
- 'role' => 'Lorem ipsum dolor sit amet',
- 'created' => '2015-06-24 17:33:54',
- 'modified' => '2015-06-24 17:33:54'
- ],
- [
- 'id' => '00000000-0000-0000-0000-000000000009',
- 'username' => 'Lorem ipsum dolor sit amet',
- 'email' => 'Lorem ipsum dolor sit amet',
- 'password' => 'Lorem ipsum dolor sit amet',
- 'first_name' => 'Lorem ipsum dolor sit amet',
- 'last_name' => 'Lorem ipsum dolor sit amet',
- 'token' => 'Lorem ipsum dolor sit amet',
- 'token_expires' => '2015-06-24 17:33:54',
- 'api_token' => 'Lorem ipsum dolor sit amet',
- 'activation_date' => '2015-06-24 17:33:54',
- 'tos_date' => '2015-06-24 17:33:54',
- 'active' => true,
- 'is_superuser' => false,
- 'role' => 'Lorem ipsum dolor sit amet',
- 'created' => '2015-06-24 17:33:54',
- 'modified' => '2015-06-24 17:33:54'
- ],
- [
- 'id' => '00000000-0000-0000-0000-000000000010',
- 'username' => 'Lorem ipsum dolor sit amet',
- 'email' => 'Lorem ipsum dolor sit amet',
- 'password' => 'Lorem ipsum dolor sit amet',
- 'first_name' => 'Lorem ipsum dolor sit amet',
- 'last_name' => 'Lorem ipsum dolor sit amet',
- 'token' => 'Lorem ipsum dolor sit amet',
- 'token_expires' => '2015-06-24 17:33:54',
- 'api_token' => 'Lorem ipsum dolor sit amet',
- 'activation_date' => '2015-06-24 17:33:54',
- 'tos_date' => '2015-06-24 17:33:54',
- 'active' => true,
- 'is_superuser' => false,
- 'role' => 'Lorem ipsum dolor sit amet',
- 'created' => '2015-06-24 17:33:54',
- 'modified' => '2015-06-24 17:33:54'
- ],
- ];
+ parent::init();
+ }
}
diff --git a/tests/TestCase/Auth/ApiKeyAuthenticateTest.php b/tests/TestCase/Auth/ApiKeyAuthenticateTest.php
deleted file mode 100644
index 90a95c28e..000000000
--- a/tests/TestCase/Auth/ApiKeyAuthenticateTest.php
+++ /dev/null
@@ -1,167 +0,0 @@
-getMockBuilder('Cake\Controller\Controller')
- ->setMethods(null)
- ->setConstructorArgs([$request, $response])
- ->getMock();
- $registry = new ComponentRegistry($controller);
- $this->apiKey = new ApiKeyAuthenticate($registry, ['require_ssl' => false]);
- }
-
- /**
- * Tears down the fixture, for example, closes a network connection.
- * This method is called after a test is executed.
- */
- public function tearDown()
- {
- unset($this->apiKey, $this->controller);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testAuthenticateHappy()
- {
- $request = new Request('/?api_key=yyy');
- $result = $this->apiKey->authenticate($request, new Response());
- $this->assertEquals('user-1', $result['username']);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testAuthenticateFail()
- {
- $request = new Request('/');
- $result = $this->apiKey->authenticate($request, new Response());
- $this->assertFalse($result);
-
- $request = new Request('/?api_key=none');
- $result = $this->apiKey->authenticate($request, new Response());
- $this->assertFalse($result);
-
- $request = new Request('/?api_key=');
- $result = $this->apiKey->authenticate($request, new Response());
- $this->assertFalse($result);
- }
-
- /**
- * test
- *
- * @expectedException \OutOfBoundsException
- * @expectedExceptionMessage Type wrong is not valid
- *
- */
- public function testAuthenticateWrongType()
- {
- $this->apiKey->config('type', 'wrong');
- $request = new Request('/');
- $this->apiKey->authenticate($request, new Response());
- }
-
- /**
- * test
- *
- * @expectedException \Cake\Network\Exception\ForbiddenException
- * @expectedExceptionMessage SSL is required for ApiKey Authentication
- *
- */
- public function testAuthenticateRequireSSL()
- {
- $this->apiKey->config('require_ssl', true);
- $request = new Request('/?api_key=test');
- $this->apiKey->authenticate($request, new Response());
- }
-
- /**
- * test
- *
- */
- public function testAuthenticateRequireSSLNoKey()
- {
- $this->apiKey->config('require_ssl', true);
- $request = new Request('/');
- $this->assertFalse($this->apiKey->authenticate($request, new Response()));
- }
-
-
- /**
- * test
- *
- * @return void
- */
- public function testHeaderHappy()
- {
- $request = $this->getMockBuilder('\Cake\Network\Request')
- ->setMethods(['header'])
- ->getMock();
- $request->expects($this->once())
- ->method('header')
- ->with('api_key')
- ->will($this->returnValue('yyy'));
- $this->apiKey->config('type', 'header');
- $result = $this->apiKey->authenticate($request, new Response());
- $this->assertEquals('user-1', $result['username']);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testAuthenticateHeaderFail()
- {
- $request = $this->getMockBuilder('\Cake\Network\Request')
- ->setMethods(['header'])
- ->getMock();
- $request->expects($this->once())
- ->method('header')
- ->with('api_key')
- ->will($this->returnValue('wrong'));
- $this->apiKey->config('type', 'header');
- $result = $this->apiKey->authenticate($request, new Response());
- $this->assertFalse($result);
- }
-}
diff --git a/tests/TestCase/Auth/RememberMeAuthenticateTest.php b/tests/TestCase/Auth/RememberMeAuthenticateTest.php
deleted file mode 100644
index 4a5eb09b7..000000000
--- a/tests/TestCase/Auth/RememberMeAuthenticateTest.php
+++ /dev/null
@@ -1,172 +0,0 @@
-controller = $this->getMockBuilder('Cake\Controller\Controller')
- ->setMethods(null)
- ->setConstructorArgs([$request, $response])
- ->getMock();
- $registry = new ComponentRegistry($this->controller);
- $this->rememberMe = new RememberMeAuthenticate($registry);
- }
-
- /**
- * Tears down the fixture, for example, closes a network connection.
- * This method is called after a test is executed.
- */
- public function tearDown()
- {
- unset($this->rememberMe, $this->controller);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testAuthenticateHappy()
- {
- $request = new Request('/');
- $request->env('HTTP_USER_AGENT', 'user-agent');
- $mockCookie = $this->getMockBuilder('Cake\Controller\Component\CookieComponent')
- ->disableOriginalConstructor()
- ->setMethods(['check', 'read'])
- ->getMock();
- $mockCookie
- ->expects($this->once())
- ->method('read')
- ->with('remember_me')
- ->will($this->returnValue([
- 'id' => '00000000-0000-0000-0000-000000000001',
- 'user_agent' => 'user-agent'
- ]));
- $registry = new ComponentRegistry($this->controller);
- $registry->set('Cookie', $mockCookie);
- $this->rememberMe = new RememberMeAuthenticate($registry);
- $result = $this->rememberMe->authenticate($request, new Response());
- $this->assertEquals('user-1', $result['username']);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testAuthenticateBadUser()
- {
- $request = new Request('/');
- $request->env('HTTP_USER_AGENT', 'user-agent');
- $mockCookie = $this->getMockBuilder('Cake\Controller\Component\CookieComponent')
- ->disableOriginalConstructor()
- ->setMethods(['check', 'read'])
- ->getMock();
- $mockCookie
- ->expects($this->once())
- ->method('read')
- ->with('remember_me')
- ->will($this->returnValue([
- //bad-user
- 'id' => '00000000-0000-0000-0000-000000000000',
- 'user_agent' => 'user-agent'
- ]));
- $registry = new ComponentRegistry($this->controller);
- $registry->set('Cookie', $mockCookie);
- $this->rememberMe = new RememberMeAuthenticate($registry);
- $result = $this->rememberMe->authenticate($request, new Response());
- $this->assertFalse($result);
- }
-
-
- /**
- * test
- *
- * @return void
- */
- public function testAuthenticateBadAgent()
- {
- $request = new Request('/');
- $request->env('HTTP_USER_AGENT', 'user-agent');
- $mockCookie = $this->getMockBuilder('Cake\Controller\Component\CookieComponent')
- ->disableOriginalConstructor()
- ->setMethods(['check', 'read'])
- ->getMock();
- $mockCookie
- ->expects($this->once())
- ->method('read')
- ->with('remember_me')
- ->will($this->returnValue([
- 'id' => '00000000-0000-0000-0000-000000000001',
- 'user_agent' => 'bad-agent'
- ]));
- $registry = new ComponentRegistry($this->controller);
- $registry->set('Cookie', $mockCookie);
- $this->rememberMe = new RememberMeAuthenticate($registry);
- $result = $this->rememberMe->authenticate($request, new Response());
- $this->assertFalse($result);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testAuthenticateNoCookie()
- {
- $request = new Request('/');
- $request->env('HTTP_USER_AGENT', 'user-agent');
- $mockCookie = $this->getMockBuilder('Cake\Controller\Component\CookieComponent')
- ->disableOriginalConstructor()
- ->setMethods(['check', 'read'])
- ->getMock();
- $mockCookie
- ->expects($this->once())
- ->method('read')
- ->with('remember_me')
- ->will($this->returnValue(null));
-
- $registry = new ComponentRegistry($this->controller);
- $registry->set('Cookie', $mockCookie);
- $this->rememberMe = new RememberMeAuthenticate($registry);
- $result = $this->rememberMe->authenticate($request, new Response());
- $this->assertFalse($result);
- }
-}
diff --git a/tests/TestCase/Auth/Rules/OwnerTest.php b/tests/TestCase/Auth/Rules/OwnerTest.php
deleted file mode 100644
index eac550ec8..000000000
--- a/tests/TestCase/Auth/Rules/OwnerTest.php
+++ /dev/null
@@ -1,263 +0,0 @@
-Owner = new Owner();
- $this->request = $this->getMockBuilder('\Cake\Network\Request')
- ->getMock();
- }
-
- /**
- * Tears down the fixture, for example, closes a network connection.
- * This method is called after a test is executed.
- */
- public function tearDown()
- {
- unset($this->Owner);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testAllowed()
- {
- $this->request->params = [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Posts',
- 'pass' => ['00000000-0000-0000-0000-000000000001']
- ];
- $user = [
- 'id' => '00000000-0000-0000-0000-000000000001',
- ];
- $this->assertTrue($this->Owner->allowed($user, 'user', $this->request));
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testAllowedUsingTableAlias()
- {
- $this->Owner = new Owner([
- 'table' => 'Posts'
- ]);
- $this->request->params = [
- 'pass' => ['00000000-0000-0000-0000-000000000001']
- ];
- $user = [
- 'id' => '00000000-0000-0000-0000-000000000001',
- ];
- $this->assertTrue($this->Owner->allowed($user, 'user', $this->request));
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testAllowedUsingTableInstance()
- {
- $this->Owner = new Owner([
- 'table' => TableRegistry::get('CakeDC/Users.Posts'),
- ]);
- $this->request->params = [
- 'pass' => ['00000000-0000-0000-0000-000000000001']
- ];
- $user = [
- 'id' => '00000000-0000-0000-0000-000000000001',
- ];
- $this->assertTrue($this->Owner->allowed($user, 'user', $this->request));
- }
-
- /**
- * test
- *
- * @return void
- * @expectedException \OutOfBoundsException
- * @expectedExceptionMessage Table alias is empty, please define a table alias, we could not extract a default table from the request
- */
- public function testAllowedShouldThrowExceptionBecauseEmptyAliasFromRequest()
- {
- $this->request->params = [
- 'pass' => ['00000000-0000-0000-0000-000000000001']
- ];
- $user = [
- 'id' => '00000000-0000-0000-0000-000000000001',
- ];
- $this->Owner->allowed($user, 'user', $this->request);
- }
-
- /**
- * test
- *
- * @return void
- * @expectedException \OutOfBoundsException
- * @expectedExceptionMessage Missing column column_not_found in table Posts while checking ownership permissions for user 00000000-0000-0000-0000-000000000001
- */
- public function testAllowedShouldThrowExceptionBecauseForeignKeyNotPresentInTable()
- {
- $this->Owner = new Owner([
- 'table' => TableRegistry::get('CakeDC/Users.Posts'),
- 'ownerForeignKey' => 'column_not_found',
- ]);
- $this->request->params = [
- 'pass' => ['00000000-0000-0000-0000-000000000001']
- ];
- $user = [
- 'id' => '00000000-0000-0000-0000-000000000001',
- ];
- $this->Owner->allowed($user, 'user', $this->request);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testNotAllowedBecauseNotOwner()
- {
- $this->request->params = [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Posts',
- 'pass' => ['00000000-0000-0000-0000-000000000002']
- ];
- $user = [
- 'id' => '00000000-0000-0000-0000-000000000001',
- ];
- $this->assertFalse($this->Owner->allowed($user, 'user', $this->request));
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testNotAllowedBecauseUserNotFound()
- {
- $this->request->params = [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Posts',
- 'pass' => ['00000000-0000-0000-0000-000000000002']
- ];
- $user = [
- 'id' => '99999999-0000-0000-0000-000000000000',
- ];
- $this->assertFalse($this->Owner->allowed($user, 'user', $this->request));
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testNotAllowedBecausePostNotFound()
- {
- $this->request->params = [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Posts',
- 'pass' => ['99999999-0000-0000-0000-000000000000'] //not found
- ];
- $user = [
- 'id' => '00000000-0000-0000-0000-000000000001',
- ];
- $this->assertFalse($this->Owner->allowed($user, 'user', $this->request));
- }
-
- /**
- * test
- *
- * @return void
- * @expectedException \OutOfBoundsException
- * @expectedExceptionMessage Missing column user_id in table NoDefaultTable while checking ownership permissions for user 00000000-0000-0000-0000-000000000001
- */
- public function testNotAllowedBecauseNoDefaultTable()
- {
- $this->request->params = [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'NoDefaultTable',
- 'pass' => ['00000000-0000-0000-0000-000000000001']
- ];
- $user = [
- 'id' => '00000000-0000-0000-0000-000000000001',
- ];
- $this->assertFalse($this->Owner->allowed($user, 'user', $this->request));
- }
-
- /**
- * Test using the Owner rule in a belongsToMany association
- * Posts belongsToMany Users
- * @return void
- */
- public function testAllowedBelongsToMany()
- {
- $this->Owner = new Owner([
- 'table' => 'PostsUsers',
- 'id' => 'post_id',
- ]);
- $this->request->params = [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'IsNotUsed',
- 'pass' => ['00000000-0000-0000-0000-000000000001']
- ];
- $user = [
- 'id' => '00000000-0000-0000-0000-000000000001',
- ];
- $this->assertTrue($this->Owner->allowed($user, 'user', $this->request));
- }
-
- /**
- * Test using the Owner rule in a belongsToMany association
- * Posts belongsToMany Users
- * @return void
- */
- public function testNotAllowedBelongsToMany()
- {
- $this->Owner = new Owner([
- 'table' => 'PostsUsers',
- 'id' => 'post_id',
- ]);
- $this->request->params = [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'IsNotUsed',
- 'pass' => ['00000000-0000-0000-0000-000000000002']
- ];
- $user = [
- 'id' => '00000000-0000-0000-0000-000000000001',
- ];
- $this->assertFalse($this->Owner->allowed($user, 'user', $this->request));
- }
-}
diff --git a/tests/TestCase/Auth/SimpleRbacAuthorizeTest.php b/tests/TestCase/Auth/SimpleRbacAuthorizeTest.php
deleted file mode 100644
index 205064230..000000000
--- a/tests/TestCase/Auth/SimpleRbacAuthorizeTest.php
+++ /dev/null
@@ -1,857 +0,0 @@
- 'admin',
- 'plugin' => '*',
- 'controller' => '*',
- 'action' => '*',
- ],
- //specific actions allowed for the user role in Users plugin
- [
- 'role' => 'user',
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Users',
- 'action' => ['profile', 'logout'],
- ],
- //all roles allowed to Pages/display
- [
- 'role' => '*',
- 'plugin' => null,
- 'controller' => ['Pages'],
- 'action' => ['display'],
- ],
- ];
-
-
- /**
- * Sets up the fixture, for example, opens a network connection.
- * This method is called before a test is executed.
- */
- public function setUp()
- {
- $request = new Request();
- $response = new Response();
-
- $this->controller = $this->getMockBuilder('Cake\Controller\Controller')
- ->setMethods(null)
- ->setConstructorArgs([$request, $response])
- ->getMock();
- $this->registry = new ComponentRegistry($this->controller);
- }
-
- /**
- * Tears down the fixture, for example, closes a network connection.
- * This method is called after a test is executed.
- */
- public function tearDown()
- {
- unset($this->simpleRbacAuthorize, $this->controller);
- }
-
- /**
- * @covers CakeDC\Users\Auth\SimpleRbacAuthorize::__construct
- */
- public function testConstruct()
- {
- //don't autoload config
- $this->simpleRbacAuthorize = new SimpleRbacAuthorize($this->registry, ['autoload_config' => false]);
- $this->assertEmpty($this->simpleRbacAuthorize->config('permissions'));
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testLoadPermissions()
- {
- $this->simpleRbacAuthorize = $this->getMockBuilder('CakeDC\Users\Auth\SimpleRbacAuthorize')
- ->disableOriginalConstructor()
- ->getMock();
- $reflectedClass = new ReflectionClass($this->simpleRbacAuthorize);
- $loadPermissions = $reflectedClass->getMethod('_loadPermissions');
- $loadPermissions->setAccessible(true);
- $permissions = $loadPermissions->invoke($this->simpleRbacAuthorize, 'missing');
- $this->assertEquals($this->defaultPermissions, $permissions);
- }
-
- /**
- * @covers CakeDC\Users\Auth\SimpleRbacAuthorize::__construct
- */
- public function testConstructMissingPermissionsFile()
- {
- $this->simpleRbacAuthorize = $this->getMockBuilder('CakeDC\Users\Auth\SimpleRbacAuthorize')
- ->setMethods(null)
- ->setConstructorArgs([$this->registry, ['autoload_config' => 'does-not-exist']])
- ->getMock();
- //we should have the default permissions
- $this->assertEquals($this->defaultPermissions, $this->simpleRbacAuthorize->config('permissions'));
- }
-
- protected function assertConstructorPermissions($instance, $config, $permissions)
- {
- $reflectedClass = new ReflectionClass($instance);
- $constructor = $reflectedClass->getConstructor();
- $constructor->invoke($this->simpleRbacAuthorize, $this->registry, $config);
-
- //we should have the default permissions
- $resultPermissions = $this->simpleRbacAuthorize->config('permissions');
- $this->assertEquals($permissions, $resultPermissions);
- }
-
- /**
- * @covers CakeDC\Users\Auth\SimpleRbacAuthorize::__construct
- */
- public function testConstructPermissionsFileHappy()
- {
- $permissions = [[
- 'controller' => 'Test',
- 'action' => 'test'
- ]];
- $className = 'CakeDC\Users\Auth\SimpleRbacAuthorize';
- $this->simpleRbacAuthorize = $this->getMockBuilder($className)
- ->setMethods(['_loadPermissions'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->simpleRbacAuthorize
- ->expects($this->once())
- ->method('_loadPermissions')
- ->with('permissions-happy')
- ->will($this->returnValue($permissions));
- $this->assertConstructorPermissions($className, ['autoload_config' => 'permissions-happy'], $permissions);
- }
-
- protected function preparePermissions($permissions)
- {
- $className = 'CakeDC\Users\Auth\SimpleRbacAuthorize';
- $simpleRbacAuthorize = $this->getMockBuilder($className)
- ->setMethods(['_loadPermissions'])
- ->disableOriginalConstructor()
- ->getMock();
- $simpleRbacAuthorize->config('permissions', $permissions);
-
- return $simpleRbacAuthorize;
- }
-
- /**
- * @dataProvider providerAuthorize
- */
- public function testAuthorize($permissions, $user, $requestParams, $expected, $msg = null)
- {
- $this->simpleRbacAuthorize = $this->preparePermissions($permissions);
- $request = new Request();
- $request->plugin = Hash::get($requestParams, 'plugin');
- $request->controller = $requestParams['controller'];
- $request->action = $requestParams['action'];
- $prefix = Hash::get($requestParams, 'prefix');
- $request->params = [];
- if ($prefix) {
- $request->params['prefix'] = $prefix;
- }
- $extension = Hash::get($requestParams, '_ext');
- if ($extension) {
- $request->params['_ext'] = $extension;
- }
-
- $result = $this->simpleRbacAuthorize->authorize($user, $request);
- $this->assertSame($expected, $result, $msg);
- }
-
- public function providerAuthorize()
- {
- $trueRuleMock = $this->getMockBuilder(Rule::class)
- ->setMethods(['allowed'])
- ->getMock();
- $trueRuleMock->expects($this->any())
- ->method('allowed')
- ->willReturn(true);
-
- return [
- 'happy-strict-all' => [
- //permissions
- [[
- 'plugin' => 'Tests',
- 'role' => 'test',
- 'controller' => 'Tests',
- 'action' => 'test',
- 'allowed' => true,
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Tests',
- 'controller' => 'Tests',
- 'action' => 'test'
- ],
- //expected
- true
- ],
- 'happy-strict-all-deny' => [
- //permissions
- [[
- 'plugin' => 'Tests',
- 'role' => 'test',
- 'controller' => 'Tests',
- 'action' => 'test',
- 'allowed' => false,
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Tests',
- 'controller' => 'Tests',
- 'action' => 'test'
- ],
- //expected
- false
- ],
- 'happy-plugin-null-allowed-null' => [
- //permissions
- [[
- 'role' => 'test',
- 'controller' => 'Tests',
- 'action' => 'test',
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => null,
- 'controller' => 'Tests',
- 'action' => 'test'
- ],
- //expected
- true
- ],
- 'happy-plugin-asterisk' => [
- //permissions
- [[
- 'plugin' => '*',
- 'role' => 'test',
- 'controller' => 'Tests',
- 'action' => 'test',
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Any',
- 'controller' => 'Tests',
- 'action' => 'test'
- ],
- //expected
- true
- ],
- 'happy-plugin-asterisk-main-app' => [
- //permissions
- [[
- 'plugin' => '*',
- 'role' => 'test',
- 'controller' => 'Tests',
- 'action' => 'test',
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => null,
- 'controller' => 'Tests',
- 'action' => 'test'
- ],
- //expected
- true
- ],
- 'happy-role-asterisk' => [
- //permissions
- [[
- 'role' => '*',
- 'controller' => 'Tests',
- 'action' => 'test',
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'any-role',
- ],
- //request
- [
- 'plugin' => null,
- 'controller' => 'Tests',
- 'action' => 'test'
- ],
- //expected
- true
- ],
- 'happy-controller-asterisk' => [
- //permissions
- [[
- 'plugin' => 'Tests',
- 'role' => 'test',
- 'controller' => '*',
- 'action' => 'test',
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Tests',
- 'controller' => 'Tests',
- 'action' => 'test'
- ],
- //expected
- true
- ],
- 'happy-action-asterisk' => [
- //permissions
- [[
- 'plugin' => 'Tests',
- 'role' => 'test',
- 'controller' => 'Tests',
- 'action' => '*',
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Tests',
- 'controller' => 'Tests',
- 'action' => 'any'
- ],
- //expected
- true
- ],
- 'happy-some-asterisk-allowed' => [
- //permissions
- [[
- 'plugin' => '*',
- 'role' => 'test',
- 'controller' => '*',
- 'action' => '*',
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Tests',
- 'controller' => 'Tests',
- 'action' => 'any'
- ],
- //expected
- true
- ],
- 'happy-some-asterisk-deny' => [
- //permissions
- [[
- 'plugin' => '*',
- 'role' => 'test',
- 'controller' => '*',
- 'action' => '*',
- 'allowed' => false,
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Tests',
- 'controller' => 'Tests',
- 'action' => 'any'
- ],
- //expected
- false
- ],
- 'all-deny' => [
- //permissions
- [[
- 'plugin' => '*',
- 'role' => '*',
- 'controller' => '*',
- 'action' => '*',
- 'allowed' => false,
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Any',
- 'controller' => 'Any',
- 'action' => 'any'
- ],
- //expected
- false
- ],
- 'dasherized' => [
- //permissions
- [[
- 'plugin' => 'Tests',
- 'role' => 'test',
- 'controller' => 'TestTests',
- 'action' => 'TestAction',
- 'allowed' => true,
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'tests',
- 'controller' => 'test-tests',
- 'action' => 'test-action'
- ],
- //expected
- true
- ],
- 'happy-array' => [
- //permissions
- [[
- 'plugin' => ['Tests'],
- 'role' => ['test'],
- 'controller' => ['Tests'],
- 'action' => ['one', 'two'],
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Tests',
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- true
- ],
- 'happy-array' => [
- //permissions
- [[
- 'plugin' => ['Tests'],
- 'role' => ['test'],
- 'controller' => ['Tests'],
- 'action' => ['one', 'two'],
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Tests',
- 'controller' => 'Tests',
- 'action' => 'three'
- ],
- //expected
- false
- ],
- 'happy-callback-check-params' => [
- //permissions
- [[
- 'plugin' => ['Tests'],
- 'role' => ['test'],
- 'controller' => ['Tests'],
- 'action' => ['one', 'two'],
- 'allowed' => function ($user, $role, $request) {
- return $user['id'] === 1 && $role = 'test' && $request->plugin == 'Tests';
- }
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Tests',
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- true
- ],
- 'happy-callback-deny' => [
- //permissions
- [[
- 'plugin' => ['*'],
- 'role' => ['test'],
- 'controller' => ['Tests'],
- 'action' => ['one', 'two'],
- 'allowed' => function ($user, $role, $request) {
- return false;
- }
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'plugin' => 'Tests',
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- false
- ],
- 'happy-prefix' => [
- //permissions
- [[
- 'role' => ['test'],
- 'prefix' => ['admin'],
- 'controller' => ['Tests'],
- 'action' => ['one', 'two'],
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'prefix' => 'admin',
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- true
- ],
- 'deny-prefix' => [
- //permissions
- [[
- 'role' => ['test'],
- 'prefix' => ['admin'],
- 'controller' => ['Tests'],
- 'action' => ['one', 'two'],
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- false
- ],
- 'star-prefix' => [
- //permissions
- [[
- 'role' => ['test'],
- 'prefix' => '*',
- 'controller' => ['Tests'],
- 'action' => ['one', 'two'],
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'prefix' => 'admin',
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- true
- ],
- 'array-prefix' => [
- //permissions
- [[
- 'role' => ['test'],
- 'prefix' => ['one', 'admin'],
- 'controller' => '*',
- 'action' => '*',
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'prefix' => 'admin',
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- true
- ],
- 'array-prefix' => [
- //permissions
- [
- [
- 'role' => ['test'],
- 'prefix' => ['one', 'admin'],
- 'controller' => '*',
- 'action' => 'one',
- 'allowed' => false,
- ],
- [
- 'role' => ['test'],
- 'prefix' => ['one', 'admin'],
- 'controller' => '*',
- 'action' => '*',
- ],
- ],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'prefix' => 'admin',
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- false
- ],
- 'happy-ext' => [
- //permissions
- [[
- 'role' => ['test'],
- 'prefix' => ['admin'],
- 'extension' => ['csv'],
- 'controller' => ['Tests'],
- 'action' => ['one', 'two'],
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'prefix' => 'admin',
- '_ext' => 'csv',
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- true
- ],
- 'deny-ext' => [
- //permissions
- [[
- 'role' => ['test'],
- 'extension' => ['csv'],
- 'controller' => ['Tests'],
- 'action' => ['one', 'two'],
- 'allowed' => false,
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'controller' => 'Tests',
- '_ext' => 'csv',
- 'action' => 'one'
- ],
- //expected
- false
- ],
- 'star-ext' => [
- //permissions
- [[
- 'role' => ['test'],
- 'prefix' => '*',
- 'extension' => '*',
- 'controller' => ['Tests'],
- 'action' => ['one', 'two'],
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'prefix' => 'admin',
- '_ext' => 'other',
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- true
- ],
- 'array-ext' => [
- //permissions
- [[
- 'role' => ['test'],
- 'extension' => ['csv', 'pdf'],
- 'controller' => '*',
- 'action' => '*',
- ]],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- '_ext' => 'csv',
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- true
- ],
- 'array-ext' => [
- //permissions
- [
- [
- 'role' => ['test'],
- 'extension' => ['csv', 'docx'],
- 'controller' => '*',
- 'action' => 'one',
- 'allowed' => false,
- ],
- [
- 'role' => ['test'],
- 'extension' => ['csv', 'docx'],
- 'controller' => '*',
- 'action' => '*',
- ],
- ],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'prefix' => 'csv',
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- false
- ],
- 'rule-class' => [
- //permissions
- [
- [
- 'role' => ['test'],
- 'controller' => '*',
- 'action' => 'one',
- 'allowed' => $trueRuleMock,
- ],
- ],
- //user
- [
- 'id' => 1,
- 'username' => 'luke',
- 'role' => 'test',
- ],
- //request
- [
- 'controller' => 'Tests',
- 'action' => 'one'
- ],
- //expected
- true
- ],
- ];
- }
-}
diff --git a/tests/TestCase/Auth/SocialAuthenticateTest.php b/tests/TestCase/Auth/SocialAuthenticateTest.php
deleted file mode 100644
index 392bdcb40..000000000
--- a/tests/TestCase/Auth/SocialAuthenticateTest.php
+++ /dev/null
@@ -1,485 +0,0 @@
-Table = TableRegistry::get('CakeDC/Users.Users');
-
- $this->Token = $this->getMockBuilder('League\OAuth2\Client\Token\AccessToken')
- ->setMethods(['getToken', 'getExpires'])
- ->disableOriginalConstructor()
- ->getMock();
-
- $this->controller = $this->getMockBuilder('Cake\Controller\Controller')
- ->setMethods(['failedSocialLogin', 'dispatchEvent'])
- ->setConstructorArgs([$request, $response])
- ->getMock();
-
- $this->controller->expects($this->any())
- ->method('dispatchEvent')
- ->will($this->returnValue(new Event('test')));
-
- $this->Request = $request;
- $this->SocialAuthenticate = $this->_getSocialAuthenticateMockMethods(['_authenticate', '_getProviderName',
- '_mapUser', '_socialLogin', 'dispatchEvent', '_validateConfig', '_getController']);
-
- $this->SocialAuthenticate->expects($this->any())
- ->method('_getController')
- ->will($this->returnValue($this->controller));
- }
-
- /**
- * Tears down the fixture, for example, closes a network connection.
- * This method is called after a test is executed.
- */
- public function tearDown()
- {
- unset($this->SocialAuthenticate, $this->controller);
- }
-
- protected function _getSocialAuthenticateMock()
- {
- return $this->getMockBuilder('CakeDC\Users\Auth\SocialAuthenticate')
- ->disableOriginalConstructor()
- ->getMock();
- }
-
- protected function _getSocialAuthenticateMockMethods($methods)
- {
- return $this->getMockBuilder('CakeDC\Users\Auth\SocialAuthenticate')
- ->disableOriginalConstructor()
- ->setMethods($methods)
- ->getMock();
- }
-
- /**
- * Test getUser
- *
- * @dataProvider providerGetUser
- */
- public function testGetUserAuth($rawData, $mapper)
- {
- $user = $this->Table->get('00000000-0000-0000-0000-000000000002', ['contain' => ['SocialAccounts']]);
-
- $this->controller->expects($this->once())
- ->method('dispatchEvent')
- ->with(UsersAuthComponent::EVENT_AFTER_REGISTER, compact('user'));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_authenticate')
- ->with($this->Request)
- ->will($this->returnValue($rawData));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_getProviderName')
- ->will($this->returnValue('facebook'));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_mapUser')
- ->will($this->returnValue($mapper));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_socialLogin')
- ->will($this->returnValue($user));
-
-
- $result = $this->SocialAuthenticate->getUser($this->Request);
- $this->assertTrue($result['active']);
- $this->assertEquals('00000000-0000-0000-0000-000000000002', $result['id']);
- }
-
- /**
- * Provider for getUser test method
- *
- */
- public function providerGetUser()
- {
- return [
- [
- 'rawData' => [
- 'token' => 'token',
- 'id' => 'reference-2-1',
- 'name' => 'User S',
- 'first_name' => 'user',
- 'last_name' => 'second',
- 'email' => 'userSecond@example.com',
- 'cover' => [
- 'id' => 'reference-2-1'
- ],
- 'gender' => 'female',
- 'locale' => 'en_US',
- 'link' => 'link',
- ],
- 'mappedData' => [
- 'id' => 'reference-2-1',
- 'username' => null,
- 'full_name' => 'User S',
- 'first_name' => 'user',
- 'last_name' => 'second',
- 'email' => 'userSecond@example.com',
- 'link' => 'link',
- 'bio' => null,
- 'locale' => 'en_US',
- 'validated' => true,
- 'credentials' => [
- 'token' => 'token',
- 'secret' => null,
- 'expires' => 1458423682
- ],
- 'raw' => [
-
- ],
- 'provider' => 'Facebook'
- ],
- ]
-
- ];
- }
-
- /**
- * Test getUser
- *
- */
- public function testGetUserSessionData()
- {
- $user = ['username' => 'username', 'email' => 'myemail@test.com'];
- $this->SocialAuthenticate = $this->_getSocialAuthenticateMockMethods(['_authenticate',
- '_getProviderName', '_mapUser', '_touch', '_validateConfig' ]);
-
- $session = $this->getMockBuilder('Cake\Network\Session')
- ->setMethods(['read', 'delete'])
- ->getMock();
- $session->expects($this->once())
- ->method('read')
- ->with('Users.social')
- ->will($this->returnValue($user));
-
- $session->expects($this->once())
- ->method('delete')
- ->with('Users.social');
-
- $this->Request = $this->getMockBuilder('Cake\Network\Request')
- ->setMethods(['session'])
- ->getMock();
- $this->Request->expects($this->any())
- ->method('session')
- ->will($this->returnValue($session));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_touch')
- ->will($this->returnValue($user));
-
- $this->SocialAuthenticate->getUser($this->Request);
- }
-
- /**
- * Test getUser
- *
- * @dataProvider providerGetUser
- */
- public function testGetUserNotEmailProvided($rawData, $mapper)
- {
- $this->SocialAuthenticate->expects($this->once())
- ->method('_authenticate')
- ->with($this->Request)
- ->will($this->returnValue($rawData));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_getProviderName')
- ->will($this->returnValue('facebook'));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_mapUser')
- ->will($this->returnValue($mapper));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_socialLogin')
- ->will($this->throwException(new MissingEmailException('missing email')));
-
- $this->controller->expects($this->once())
- ->method('dispatchEvent')
- ->with(UsersAuthComponent::EVENT_FAILED_SOCIAL_LOGIN);
-
- $this->controller->expects($this->once())
- ->method('failedSocialLogin');
-
- $this->SocialAuthenticate->getUser($this->Request);
- }
-
- /**
- * Test getUser
- *
- * @dataProvider providerGetUser
- */
- public function testGetUserNotActive($rawData, $mapper)
- {
- $this->SocialAuthenticate->expects($this->once())
- ->method('_authenticate')
- ->with($this->Request)
- ->will($this->returnValue($rawData));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_getProviderName')
- ->will($this->returnValue('facebook'));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_mapUser')
- ->will($this->returnValue($mapper));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_socialLogin')
- ->will($this->throwException(new UserNotActiveException('user not active')));
-
- $this->SocialAuthenticate->getUser($this->Request);
- }
-
- /**
- * Test getUser
- *
- * @dataProvider providerGetUser
- */
- public function testGetUserNotActiveAccount($rawData, $mapper)
- {
- $this->SocialAuthenticate->expects($this->once())
- ->method('_authenticate')
- ->with($this->Request)
- ->will($this->returnValue($rawData));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_getProviderName')
- ->will($this->returnValue('facebook'));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_mapUser')
- ->will($this->returnValue($mapper));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_socialLogin')
- ->will($this->throwException(new AccountNotActiveException('user not active')));
-
- $this->SocialAuthenticate->getUser($this->Request);
- }
-
- /**
- * Test getUser
- *
- * @dataProvider providerTwitter
- */
- public function testGetUserNotEmailProvidedTwitter($rawData, $mapper)
- {
- $this->SocialAuthenticate->expects($this->once())
- ->method('_authenticate')
- ->with($this->Request)
- ->will($this->returnValue($rawData));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_getProviderName')
- ->will($this->returnValue('twitter'));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_mapUser')
- ->will($this->returnValue($mapper));
-
- $this->SocialAuthenticate->expects($this->once())
- ->method('_socialLogin')
- ->will($this->throwException(new MissingEmailException('missing email')));
-
- $this->SocialAuthenticate->getUser($this->Request);
- }
-
- /**
- * Provider for getUser test method
- *
- */
- public function providerTwitter()
- {
- return [
- [
- 'rawData' => [
- 'token' => 'token',
- 'id' => 'reference-2-1',
- 'name' => 'User S',
- 'first_name' => 'user',
- 'last_name' => 'second',
- 'email' => 'userSecond@example.com',
- 'cover' => [
- 'id' => 'reference-2-1'
- ],
- 'gender' => 'female',
- 'locale' => 'en_US',
- 'link' => 'link',
- ],
- 'mappedData' => [
- 'id' => 'reference-2-1',
- 'username' => null,
- 'full_name' => 'User S',
- 'first_name' => 'user',
- 'last_name' => 'second',
- 'email' => 'userSecond@example.com',
- 'link' => 'link',
- 'bio' => null,
- 'locale' => 'en_US',
- 'validated' => true,
- 'credentials' => [
- 'token' => 'token',
- 'secret' => null,
- 'expires' => 1458423682
- ],
- 'raw' => [
-
- ],
- 'provider' => 'Twitter'
- ],
- ]
-
- ];
- }
-
- /**
- * Test _socialLogin
- *
- * @dataProvider providerMapper
- */
- public function testSocialLogin()
- {
- $this->SocialAuthenticate = $this->_getSocialAuthenticateMock();
-
- $reflectedClass = new ReflectionClass($this->SocialAuthenticate);
- $socialLogin = $reflectedClass->getMethod('_socialLogin');
- $socialLogin->setAccessible(true);
- $data = [
- 'id' => 'reference-2-1',
- 'provider' => 'Facebook'
- ];
- $result = $socialLogin->invoke($this->SocialAuthenticate, $data);
- $this->assertEquals($result->id, '00000000-0000-0000-0000-000000000002');
- $this->assertTrue($result->active);
- }
-
- /**
- * Test _mapUser
- *
- * @dataProvider providerMapper
- */
- public function testMapUser($data, $mappedData)
- {
- $data['token'] = $this->Token;
- $this->SocialAuthenticate = $this->_getSocialAuthenticateMock();
-
- $reflectedClass = new ReflectionClass($this->SocialAuthenticate);
- $mapUser = $reflectedClass->getMethod('_mapUser');
- $mapUser->setAccessible(true);
-
- $this->Token->expects($this->once())
- ->method('getToken')
- ->will($this->returnValue('token'));
-
- $this->Token->expects($this->once())
- ->method('getExpires')
- ->will($this->returnValue(1458510952));
-
- $result = $mapUser->invoke($this->SocialAuthenticate, 'Facebook', $data);
- unset($result['raw']);
- $this->assertEquals($mappedData, $result);
- }
-
- /**
- * Provider for _mapUser test method
- *
- */
- public function providerMapper()
- {
- return [
- [
- 'rawData' => [
- 'id' => 'my-facebook-id',
- 'name' => 'My name.',
- 'first_name' => 'My first name',
- 'last_name' => 'My lastname.',
- 'email' => 'myemail@example.com',
- 'gender' => 'female',
- 'locale' => 'en_US',
- 'link' => 'https://www.facebook.com/app_scoped_user_id/my-facebook-id/',
- ],
- 'mappedData' => [
- 'id' => 'my-facebook-id',
- 'username' => null,
- 'full_name' => 'My name.',
- 'first_name' => 'My first name',
- 'last_name' => 'My lastname.',
- 'email' => 'myemail@example.com',
- 'avatar' => 'https://graph.facebook.com/my-facebook-id/picture?type=large',
- 'gender' => 'female',
- 'link' => 'https://www.facebook.com/app_scoped_user_id/my-facebook-id/',
- 'bio' => null,
- 'locale' => 'en_US',
- 'validated' => true,
- 'credentials' => [
- 'token' => 'token',
- 'secret' => null,
- 'expires' => (int)1458510952
- ],
- 'provider' => 'Facebook'
- ],
- ]
-
- ];
- }
-
- /**
- * Test _mapUser
- *
- * @expectedException CakeDC\Users\Exception\MissingProviderException
- */
- public function testMapUserException()
- {
- $data = [];
- $this->SocialAuthenticate = $this->_getSocialAuthenticateMock();
-
- $reflectedClass = new ReflectionClass($this->SocialAuthenticate);
- $mapUser = $reflectedClass->getMethod('_mapUser');
- $mapUser->setAccessible(true);
- $mapUser->invoke($this->SocialAuthenticate, null, $data);
- }
-}
diff --git a/tests/TestCase/Auth/SuperuserAuthorizeTest.php b/tests/TestCase/Auth/SuperuserAuthorizeTest.php
deleted file mode 100644
index 29d12d1b9..000000000
--- a/tests/TestCase/Auth/SuperuserAuthorizeTest.php
+++ /dev/null
@@ -1,92 +0,0 @@
-controller = $this->getMockBuilder('Cake\Controller\Controller')
- ->setMethods(null)
- ->setConstructorArgs([$request, $response])
- ->getMock();
- $registry = new ComponentRegistry($this->controller);
- $this->superuserAuthorize = new SuperuserAuthorize($registry);
- }
-
- /**
- * Tears down the fixture, for example, closes a network connection.
- * This method is called after a test is executed.
- */
- public function tearDown()
- {
- unset($this->superuserAuthorize, $this->controller);
- }
-
- /**
- * @covers CakeDC\Users\Auth\SuperuserAuthorize::authorize
- */
- public function testAuthorizeIsSuperuser()
- {
- $user = [
- 'is_superuser' => true,
- ];
- $request = new Request();
- $result = $this->superuserAuthorize->authorize($user, $request);
- $this->assertTrue($result);
- }
-
- /**
- * @covers CakeDC\Users\Auth\SuperuserAuthorize::authorize
- */
- public function testAuthorizeIsNotSuperuser()
- {
- $user = [
- 'is_superuser' => false,
- ];
- $request = new Request();
- $result = $this->superuserAuthorize->authorize($user, $request);
- $this->assertFalse($result);
- }
-
- /**
- * @covers CakeDC\Users\Auth\SuperuserAuthorize::authorize
- */
- public function testAuthorizeWeirdUser()
- {
- $request = new Request();
- $user = 'non array';
- $result = $this->superuserAuthorize->authorize($user, $request);
- $this->assertFalse($result);
- }
-}
diff --git a/tests/TestCase/Authenticator/SocialAuthenticatorTest.php b/tests/TestCase/Authenticator/SocialAuthenticatorTest.php
new file mode 100644
index 000000000..981f63ea2
--- /dev/null
+++ b/tests/TestCase/Authenticator/SocialAuthenticatorTest.php
@@ -0,0 +1,610 @@
+Provider = $this->getMockBuilder('\League\OAuth2\Client\Provider\Facebook')->setConstructorArgs([
+ [
+ 'graphApiVersion' => 'v2.8',
+ 'redirectUri' => '/auth/facebook',
+ 'linkSocialUri' => '/link-social/facebook',
+ 'callbackLinkSocialUri' => '/callback-link-social/facebook',
+ 'clientId' => '10003030300303',
+ 'clientSecret' => 'secretpassword',
+ ],
+ [],
+ ])->setMethods([
+ 'getAccessToken', 'getState', 'getAuthorizationUrl', 'getResourceOwner',
+ ])->getMock();
+
+ $config = [
+ 'service' => 'CakeDC\Auth\Social\Service\OAuth2Service',
+ 'className' => $this->Provider,
+ 'mapper' => 'CakeDC\Auth\Social\Mapper\Facebook',
+ 'options' => [
+ 'state' => '__TEST_STATE__',
+ 'graphApiVersion' => 'v2.8',
+ 'redirectUri' => '/auth/facebook',
+ 'linkSocialUri' => '/link-social/facebook',
+ 'callbackLinkSocialUri' => '/callback-link-social/facebook',
+ 'clientId' => '10003030300303',
+ 'clientSecret' => 'secretpassword',
+ ],
+ 'collaborators' => [],
+ 'signature' => null,
+ 'mapFields' => [],
+ 'path' => [
+ 'plugin' => 'CakeDC/Users',
+ 'controller' => 'Users',
+ 'action' => 'socialLogin',
+ 'prefix' => null,
+ ],
+ ];
+ Configure::write('OAuth.providers.facebook', $config);
+
+ $this->Request = ServerRequestFactory::fromGlobals();
+ }
+
+ /**
+ * Test authenticate method without social service
+ *
+ * @return void
+ */
+ public function testAuthenticateNoSocialService()
+ {
+ $uri = new Uri('/auth/facebook');
+ $this->Request = $this->Request->withUri($uri);
+ $this->Request = $this->Request->withQueryParams([
+ 'code' => 'ZPO9972j3092304230',
+ 'state' => '__TEST_STATE__',
+ ]);
+ $this->Request = $this->Request->withAttribute('params', [
+ 'plugin' => 'CakeDC/Users',
+ 'controller' => 'Users',
+ 'action' => 'socialLogin',
+ 'provider' => 'facebook',
+ ]);
+ $this->Request->getSession()->write('oauth2state', '__TEST_STATE__');
+
+ $identifiers = new IdentifierCollection([
+ 'CakeDC/Users.Social',
+ ]);
+ $Authenticator = new SocialAuthenticator($identifiers);
+ $Response = new Response();
+ $result = $Authenticator->authenticate($this->Request, $Response);
+ $this->assertInstanceOf(Result::class, $result);
+ $this->assertEquals(Result::FAILURE_CREDENTIALS_MISSING, $result->getStatus());
+ $actual = $result->getData();
+ $this->assertEmpty($actual);
+ }
+
+ /**
+ * Test authenticate method with successfull authentication
+ *
+ * @return void
+ */
+ public function testAuthenticateSuccessfullyAuthenticated()
+ {
+ $uri = new Uri('/auth/facebook');
+ $this->Request = $this->Request->withUri($uri);
+ $this->Request = $this->Request->withQueryParams([
+ 'code' => 'ZPO9972j3092304230',
+ 'state' => '__TEST_STATE__',
+ ]);
+ $this->Request = $this->Request->withAttribute('params', [
+ 'plugin' => 'CakeDC/Users',
+ 'controller' => 'Users',
+ 'action' => 'socialLogin',
+ 'provider' => 'facebook',
+ ]);
+ $this->Request->getSession()->write('oauth2state', '__TEST_STATE__');
+
+ $Token = new \League\OAuth2\Client\Token\AccessToken([
+ 'access_token' => 'test-token',
+ 'expires' => 1490988496,
+ ]);
+
+ $user = new FacebookUser([
+ 'id' => '1',
+ 'name' => 'Test User',
+ 'first_name' => 'Test',
+ 'last_name' => 'User',
+ 'email' => 'test@gmail.com',
+ 'hometown' => [
+ 'id' => '108226049197930',
+ 'name' => 'Madrid',
+ ],
+ 'picture' => [
+ 'data' => [
+ 'url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'is_silhouette' => false,
+ ],
+ ],
+ 'cover' => [
+ 'source' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'id' => '1',
+ ],
+ 'gender' => 'male',
+ 'locale' => 'en_US',
+ 'link' => 'https://www.facebook.com/app_scoped_user_id/1/',
+ 'timezone' => -5,
+ 'age_range' => [
+ 'min' => 21,
+ ],
+ 'bio' => 'I am the best test user in the world.',
+ 'picture_url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'is_silhouette' => false,
+ 'cover_photo_url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ ]);
+
+ $this->Provider->expects($this->never())
+ ->method('getAuthorizationUrl');
+
+ $this->Provider->expects($this->never())
+ ->method('getState');
+
+ $this->Provider->expects($this->any())
+ ->method('getAccessToken')
+ ->with(
+ $this->equalTo('authorization_code'),
+ $this->equalTo(['code' => 'ZPO9972j3092304230'])
+ )
+ ->will($this->returnValue($Token));
+
+ $this->Provider->expects($this->any())
+ ->method('getResourceOwner')
+ ->with(
+ $this->equalTo($Token)
+ )
+ ->will($this->returnValue($user));
+
+ $service = (new ServiceFactory())->createFromProvider('facebook');
+ $this->Request = $this->Request->withAttribute('socialService', $service);
+ $identifiers = new IdentifierCollection([
+ 'CakeDC/Users.Social',
+ ]);
+ $Authenticator = new SocialAuthenticator($identifiers);
+ $Response = new Response();
+ $result = $Authenticator->authenticate($this->Request, $Response);
+ $this->assertInstanceOf(Result::class, $result);
+ $this->assertEquals(Result::SUCCESS, $result->getStatus());
+ $actual = $result->getData();
+ $this->assertInstanceOf(User::class, $actual);
+ $this->assertEquals('test@gmail.com', $actual->email);
+ }
+
+ /**
+ * Test authenticate method with error, getRawData is null
+ *
+ * @return void
+ */
+ public function testAuthenticateGetRawDataNull()
+ {
+ $uri = new Uri('/auth/facebook');
+ $this->Request = $this->Request->withUri($uri);
+ $this->Request = $this->Request->withQueryParams([
+ 'code' => 'ZPO9972j3092304230',
+ 'state' => '__TEST_STATE__',
+ ]);
+ $this->Request = $this->Request->withAttribute('params', [
+ 'plugin' => 'CakeDC/Users',
+ 'controller' => 'Users',
+ 'action' => 'socialLogin',
+ 'provider' => 'facebook',
+ ]);
+ $this->Request->getSession()->write('oauth2state', '__TEST_STATE__');
+
+ $Token = new \League\OAuth2\Client\Token\AccessToken([
+ 'access_token' => 'test-token',
+ 'expires' => 1490988496,
+ ]);
+
+ $this->Provider->expects($this->never())
+ ->method('getAuthorizationUrl');
+
+ $this->Provider->expects($this->never())
+ ->method('getState');
+
+ $this->Provider->expects($this->any())
+ ->method('getAccessToken')
+ ->with(
+ $this->equalTo('authorization_code'),
+ $this->equalTo(['code' => 'ZPO9972j3092304230'])
+ )
+ ->will($this->returnValue($Token));
+
+ $this->Provider->expects($this->any())
+ ->method('getResourceOwner')
+ ->with(
+ $this->equalTo($Token)
+ )
+ ->will($this->throwException(new \UnexpectedValueException('User not found')));
+
+ $service = (new ServiceFactory())->createFromProvider('facebook');
+ $this->Request = $this->Request->withAttribute('socialService', $service);
+ $identifiers = new IdentifierCollection([
+ 'CakeDC/Users.Social',
+ ]);
+ $Authenticator = new SocialAuthenticator($identifiers);
+ $Response = new Response();
+ $result = $Authenticator->authenticate($this->Request, $Response);
+ $this->assertInstanceOf(Result::class, $result);
+ $this->assertEquals(Result::FAILURE_IDENTITY_NOT_FOUND, $result->getStatus());
+ $actual = $result->getData();
+ $this->assertEmpty($actual);
+ }
+
+ /**
+ * Test authenticate method when social users does not have email
+ *
+ * @return void
+ */
+ public function testAuthenticateErrorNoEmail()
+ {
+ $uri = new Uri('/auth/facebook');
+ $this->Request = $this->Request->withUri($uri);
+ $this->Request = $this->Request->withQueryParams([
+ 'code' => 'ZPO9972j3092304230',
+ 'state' => '__TEST_STATE__',
+ ]);
+ $this->Request = $this->Request->withAttribute('params', [
+ 'plugin' => 'CakeDC/Users',
+ 'controller' => 'Users',
+ 'action' => 'socialLogin',
+ 'provider' => 'facebook',
+ ]);
+ $this->Request->getSession()->write('oauth2state', '__TEST_STATE__');
+
+ $Token = new \League\OAuth2\Client\Token\AccessToken([
+ 'access_token' => 'test-token',
+ 'expires' => 1490988496,
+ ]);
+
+ $user = new FacebookUser([
+ 'id' => '1',
+ 'name' => 'Test User',
+ 'first_name' => 'Test',
+ 'last_name' => 'User',
+ 'hometown' => [
+ 'id' => '108226049197930',
+ 'name' => 'Madrid',
+ ],
+ 'picture' => [
+ 'data' => [
+ 'url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'is_silhouette' => false,
+ ],
+ ],
+ 'cover' => [
+ 'source' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'id' => '1',
+ ],
+ 'gender' => 'male',
+ 'locale' => 'en_US',
+ 'link' => 'https://www.facebook.com/app_scoped_user_id/1/',
+ 'timezone' => -5,
+ 'age_range' => [
+ 'min' => 21,
+ ],
+ 'bio' => 'I am the best test user in the world.',
+ 'picture_url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'is_silhouette' => false,
+ 'cover_photo_url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ ]);
+
+ $this->Provider->expects($this->never())
+ ->method('getAuthorizationUrl');
+
+ $this->Provider->expects($this->never())
+ ->method('getState');
+
+ $this->Provider->expects($this->any())
+ ->method('getAccessToken')
+ ->with(
+ $this->equalTo('authorization_code'),
+ $this->equalTo(['code' => 'ZPO9972j3092304230'])
+ )
+ ->will($this->returnValue($Token));
+
+ $this->Provider->expects($this->any())
+ ->method('getResourceOwner')
+ ->with(
+ $this->equalTo($Token)
+ )
+ ->will($this->returnValue($user));
+
+ $service = (new ServiceFactory())->createFromProvider('facebook');
+ $this->Request = $this->Request->withAttribute('socialService', $service);
+ $identifiers = new IdentifierCollection([
+ 'CakeDC/Users.Social',
+ ]);
+ $Authenticator = new SocialAuthenticator($identifiers);
+ $Response = new Response();
+ $result = false;
+ try {
+ $Authenticator->authenticate($this->Request, $Response);
+ } catch (SocialAuthenticationException $e) {
+ $rawData = ['token' => $Token] + $user->toArray();
+ $mapper = new MapUser();
+ $expected = [
+ 'rawData' => $mapper($service, $rawData),
+ ];
+ $actual = $e->getAttributes();
+ $this->assertEquals($expected, $actual);
+ $this->assertEquals(400, $e->getCode());
+
+ $this->assertInstanceOf(MissingEmailException::class, $e->getPrevious());
+ $result = true;
+ }
+ $this->assertTrue($result);
+ }
+
+ /**
+ * Test authenticate method when social identifier return null
+ *
+ * @return void
+ */
+ public function testAuthenticateIdentifierReturnedNull()
+ {
+ $uri = new Uri('/auth/facebook');
+ $this->Request = $this->Request->withUri($uri);
+ $this->Request = $this->Request->withQueryParams([
+ 'code' => 'ZPO9972j3092304230',
+ 'state' => '__TEST_STATE__',
+ ]);
+ $this->Request = $this->Request->withAttribute('params', [
+ 'plugin' => 'CakeDC/Users',
+ 'controller' => 'Users',
+ 'action' => 'socialLogin',
+ 'provider' => 'facebook',
+ ]);
+ $this->Request->getSession()->write('oauth2state', '__TEST_STATE__');
+
+ $Token = new \League\OAuth2\Client\Token\AccessToken([
+ 'access_token' => 'test-token',
+ 'expires' => 1490988496,
+ ]);
+
+ $user = new FacebookUser([
+ 'id' => '1',
+ 'name' => 'Test User',
+ 'first_name' => 'Test',
+ 'last_name' => 'User',
+ 'hometown' => [
+ 'id' => '108226049197930',
+ 'name' => 'Madrid',
+ ],
+ 'picture' => [
+ 'data' => [
+ 'url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'is_silhouette' => false,
+ ],
+ ],
+ 'cover' => [
+ 'source' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'id' => '1',
+ ],
+ 'gender' => 'male',
+ 'locale' => 'en_US',
+ 'link' => 'https://www.facebook.com/app_scoped_user_id/1/',
+ 'timezone' => -5,
+ 'age_range' => [
+ 'min' => 21,
+ ],
+ 'bio' => 'I am the best test user in the world.',
+ 'picture_url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'is_silhouette' => false,
+ 'cover_photo_url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ ]);
+
+ $this->Provider->expects($this->never())
+ ->method('getAuthorizationUrl');
+
+ $this->Provider->expects($this->never())
+ ->method('getState');
+
+ $this->Provider->expects($this->any())
+ ->method('getAccessToken')
+ ->with(
+ $this->equalTo('authorization_code'),
+ $this->equalTo(['code' => 'ZPO9972j3092304230'])
+ )
+ ->will($this->returnValue($Token));
+
+ $this->Provider->expects($this->any())
+ ->method('getResourceOwner')
+ ->with(
+ $this->equalTo($Token)
+ )
+ ->will($this->returnValue($user));
+
+ $service = (new ServiceFactory())->createFromProvider('facebook');
+ $this->Request = $this->Request->withAttribute('socialService', $service);
+ $identifiers = new IdentifierCollection([]);
+ $Authenticator = new SocialAuthenticator($identifiers);
+ $Response = new Response();
+ $Authenticator->authenticate($this->Request, $Response);
+ $result = $Authenticator->authenticate($this->Request, $Response);
+ $this->assertInstanceOf(Result::class, $result);
+ $this->assertEquals(Result::FAILURE_IDENTITY_NOT_FOUND, $result->getStatus());
+ $actual = $result->getData();
+ $this->assertEmpty($actual);
+ }
+
+ /**
+ * Data provider for testAuthenticateErrorException
+ *
+ * @return array
+ */
+ public function dataProviderAuthenticateErrorException()
+ {
+ return [
+ [
+ new AccountNotActiveException('Not Active'),
+ SocialAuthenticator::FAILURE_ACCOUNT_NOT_ACTIVE,
+ ],
+ [
+ new UserNotActiveException('Not Active'),
+ SocialAuthenticator::FAILURE_USER_NOT_ACTIVE,
+ ],
+ ];
+ }
+
+ /**
+ * Test authenticate method with successfull authentication
+ *
+ * @param \Exception $exception thrown exception
+ * @param string $status expected status from Result object
+ * @dataProvider dataProviderAuthenticateErrorException
+ * @return void
+ */
+ public function testAuthenticateErrorException($exception, $status)
+ {
+ $uri = new Uri('/auth/facebook');
+ $this->Request = $this->Request->withUri($uri);
+ $this->Request = $this->Request->withQueryParams([
+ 'code' => 'ZPO9972j3092304230',
+ 'state' => '__TEST_STATE__',
+ ]);
+ $this->Request = $this->Request->withAttribute('params', [
+ 'plugin' => 'CakeDC/Users',
+ 'controller' => 'Users',
+ 'action' => 'socialLogin',
+ 'provider' => 'facebook',
+ ]);
+ $this->Request->getSession()->write('oauth2state', '__TEST_STATE__');
+
+ $Token = new \League\OAuth2\Client\Token\AccessToken([
+ 'access_token' => 'test-token',
+ 'expires' => 1490988496,
+ ]);
+
+ $user = new FacebookUser([
+ 'id' => '1',
+ 'name' => 'Test User',
+ 'first_name' => 'Test',
+ 'last_name' => 'User',
+ 'email' => 'test@gmail.com',
+ 'hometown' => [
+ 'id' => '108226049197930',
+ 'name' => 'Madrid',
+ ],
+ 'picture' => [
+ 'data' => [
+ 'url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'is_silhouette' => false,
+ ],
+ ],
+ 'cover' => [
+ 'source' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'id' => '1',
+ ],
+ 'gender' => 'male',
+ 'locale' => 'en_US',
+ 'link' => 'https://www.facebook.com/app_scoped_user_id/1/',
+ 'timezone' => -5,
+ 'age_range' => [
+ 'min' => 21,
+ ],
+ 'bio' => 'I am the best test user in the world.',
+ 'picture_url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'is_silhouette' => false,
+ 'cover_photo_url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ ]);
+
+ $this->Provider->expects($this->never())
+ ->method('getAuthorizationUrl');
+
+ $this->Provider->expects($this->never())
+ ->method('getState');
+
+ $this->Provider->expects($this->any())
+ ->method('getAccessToken')
+ ->with(
+ $this->equalTo('authorization_code'),
+ $this->equalTo(['code' => 'ZPO9972j3092304230'])
+ )
+ ->will($this->returnValue($Token));
+
+ $this->Provider->expects($this->any())
+ ->method('getResourceOwner')
+ ->with(
+ $this->equalTo($Token)
+ )
+ ->will($this->returnValue($user));
+
+ $service = (new ServiceFactory())->createFromProvider('facebook');
+ $this->Request = $this->Request->withAttribute('socialService', $service);
+ $identifiers = $this->getMockBuilder(IdentifierCollection::class)->getMock();
+ $identifiers->expects($this->once())
+ ->method('identify')
+ ->will($this->throwException($exception));
+
+ $Authenticator = new SocialAuthenticator($identifiers);
+ $Response = new Response();
+ $result = $Authenticator->authenticate($this->Request, $Response);
+ $this->assertInstanceOf(Result::class, $result);
+ $this->assertEquals($status, $result->getStatus());
+ $actual = $result->getData();
+ $this->assertEmpty($actual);
+ }
+}
diff --git a/tests/TestCase/Authenticator/SocialPendingEmailAuthenticatorTest.php b/tests/TestCase/Authenticator/SocialPendingEmailAuthenticatorTest.php
new file mode 100644
index 000000000..949153707
--- /dev/null
+++ b/tests/TestCase/Authenticator/SocialPendingEmailAuthenticatorTest.php
@@ -0,0 +1,187 @@
+Request = ServerRequestFactory::fromGlobals();
+ }
+
+ /**
+ * testAuthenticate
+ *
+ * @return void
+ */
+ public function testAuthenticateInvalidUrl()
+ {
+ $builder = Router::createRouteBuilder('/');
+ $builder->connect('/users/validate-email/*', [
+ 'plugin' => 'CakeDC/Users',
+ 'controller' => 'Users',
+ 'action' => 'socialEmail',
+ ]);
+
+ $user = $this->getUserData();
+ $requestNoEmail = ServerRequestFactory::fromGlobals(
+ ['REQUEST_URI' => '/users/users/social-email-invalid'],
+ [],
+ []
+ );
+ $requestNoEmail->getSession()->write(Configure::read('Users.Key.Session.social'), $user);
+ $Response = new Response();
+ $identifiers = new IdentifierCollection([
+ 'CakeDC/Users.Social',
+ ]);
+ $Authenticator = new SocialPendingEmailAuthenticator($identifiers);
+ $result = $Authenticator->authenticate($requestNoEmail, $Response);
+ $this->assertInstanceOf(Result::class, $result);
+ $this->assertEquals(Result::FAILURE_OTHER, $result->getStatus());
+ }
+
+ /**
+ * testAuthenticate
+ *
+ * @return void
+ */
+ public function testAuthenticateBaseFailed()
+ {
+ $builder = Router::createRouteBuilder('/');
+ $builder->connect('/users/social-email/*', [
+ 'plugin' => 'CakeDC/Users',
+ 'controller' => 'Users',
+ 'action' => 'socialEmail',
+ ]);
+
+ $user = $this->getUserData();
+ $requestNoEmail = ServerRequestFactory::fromGlobals(
+ ['REQUEST_URI' => '/users/social-email', 'PHP_SELF' => ''],
+ [],
+ []
+ );
+ $request = ServerRequestFactory::fromGlobals(
+ ['REQUEST_URI' => '/users/social-email', 'PHP_SELF' => ''],
+ [],
+ ['email' => 'testAuthenticateBaseFailed@example.com']
+ );
+ Configure::write('Users.Email.validate', false);
+ $request->getSession()->write(Configure::read('Users.Key.Session.social'), $user);
+ $requestNoEmail->getSession()->write(Configure::read('Users.Key.Session.social'), $user);
+ $Response = new Response();
+ $identifiers = new IdentifierCollection([
+ 'CakeDC/Users.Social',
+ ]);
+ $Authenticator = new SocialPendingEmailAuthenticator($identifiers);
+ $result = $Authenticator->authenticate($requestNoEmail, $Response);
+ $this->assertInstanceOf(Result::class, $result);
+ $this->assertEquals(Result::FAILURE_CREDENTIALS_MISSING, $result->getStatus());
+
+ $Authenticator = new SocialPendingEmailAuthenticator($identifiers);
+ $result = $Authenticator->authenticate($request, $Response);
+
+ $this->assertInstanceOf(Result::class, $result);
+ $this->assertEquals(Result::SUCCESS, $result->getStatus());
+ $data = $result->getData();
+ $this->assertInstanceOf(User::class, $data);
+ $this->assertEquals('testAuthenticateBaseFailed@example.com', $data['email']);
+ }
+
+ /**
+ * Get social user data for test
+ *
+ * @return mixed
+ */
+ protected function getUserData()
+ {
+ $Token = new \League\OAuth2\Client\Token\AccessToken([
+ 'access_token' => 'test-token',
+ 'expires' => 1490988496,
+ ]);
+
+ $data = [
+ 'token' => $Token,
+ 'id' => '1',
+ 'name' => 'Test User',
+ 'first_name' => 'Test',
+ 'last_name' => 'User',
+ 'hometown' => [
+ 'id' => '108226049197930',
+ 'name' => 'Madrid',
+ ],
+ 'picture' => [
+ 'data' => [
+ 'url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'is_silhouette' => false,
+ ],
+ ],
+ 'cover' => [
+ 'source' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'id' => '1',
+ ],
+ 'gender' => 'male',
+ 'locale' => 'en_US',
+ 'link' => 'https://www.facebook.com/app_scoped_user_id/1/',
+ 'timezone' => -5,
+ 'age_range' => [
+ 'min' => 21,
+ ],
+ 'bio' => 'I am the best test user in the world.',
+ 'picture_url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ 'is_silhouette' => false,
+ 'cover_photo_url' => 'https://scontent.xx.fbcdn.net/v/test.jpg',
+ ];
+
+ $mapper = new Facebook();
+ $user = $mapper($data);
+ $user['provider'] = 'facebook';
+ $user['validated'] = true;
+
+ return $user;
+ }
+}
diff --git a/tests/TestCase/Controller/Component/RememberMeComponentTest.php b/tests/TestCase/Controller/Component/RememberMeComponentTest.php
deleted file mode 100644
index 701bdf587..000000000
--- a/tests/TestCase/Controller/Component/RememberMeComponentTest.php
+++ /dev/null
@@ -1,201 +0,0 @@
-request = new Request('controller_posts/index');
- $this->request->params['pass'] = [];
- $this->controller = $this->getMockBuilder('Cake\Controller\Controller')
- ->setMethods(['redirect'])
- ->setConstructorArgs([$this->request])
- ->getMock();
- $this->registry = new ComponentRegistry($this->controller);
- $this->rememberMeComponent = new RememberMeComponent($this->registry, []);
- }
-
- /**
- * tearDown method
- *
- * @return void
- */
- public function tearDown()
- {
- unset($this->rememberMeComponent);
-
- parent::tearDown();
- }
-
- /**
- * Test initialize method
- *
- * @return void
- */
- public function testInitialize()
- {
- $cookieOptions = [
- 'expires' => '1 month',
- 'httpOnly' => true,
- 'path' => '',
- 'domain' => '',
- 'secure' => false,
- 'key' => '2a20bac195a9eb2e28f05b7ac7090afe599365a8fe480b7d8a5ce0f79687346e',
- 'encryption' => 'aes',
- 'enabled' => false
- ];
- $this->assertEquals($cookieOptions, $this->rememberMeComponent->Cookie->configKey('remember_me'));
- }
-
- /**
- * Test initialize method
- *
- * @return void
- */
- public function testInitializeException()
- {
- $salt = Security::salt();
- Security::salt('too small');
- try {
- $this->rememberMeComponent = new RememberMeComponent($this->registry, []);
- } catch (InvalidArgumentException $ex) {
- $this->assertEquals('Invalid app salt, app salt must be at least 256 bits (32 bytes) long', $ex->getMessage());
- }
-
- Security::salt($salt);
- }
-
- /**
- * Test
- *
- * @return void
- */
- public function testSetLoginCookie()
- {
- $event = new Event('event');
- $this->rememberMeComponent->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->rememberMeComponent->Auth->expects($this->once())
- ->method('user')
- ->with('id')
- ->will($this->returnValue(1));
- $this->rememberMeComponent->Cookie = $this->getMockBuilder('Cake\Controller\Component\CookieComponent')
- ->setMethods(['write'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->rememberMeComponent->request = (new Request('/'))->env('HTTP_USER_AGENT', 'user-agent');
- $this->rememberMeComponent->Cookie->expects($this->once())
- ->method('write')
- ->with('remember_me', ['id' => 1, 'user_agent' => 'user-agent']);
- $this->rememberMeComponent->setLoginCookie($event);
- }
-
- /**
- * Test
- *
- * @return void
- */
- public function testBeforeFilter()
- {
- $event = new Event('event');
- $this->rememberMeComponent->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'identify', 'setUser', 'redirectUrl'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->rememberMeComponent->Auth->expects($this->once())
- ->method('user');
- $user = ['id' => 1];
- $this->rememberMeComponent->Auth->expects($this->once())
- ->method('identify')
- ->will($this->returnValue($user));
- $this->rememberMeComponent->Auth->expects($this->once())
- ->method('setUser')
- ->with($user);
- $this->rememberMeComponent->Auth->expects($this->once())
- ->method('redirectUrl')
- ->will($this->returnValue('/login'));
- $this->controller->expects($this->once())
- ->method('redirect')
- ->with('/login');
- $this->rememberMeComponent->beforeFilter($event);
- }
-
- /**
- * Test
- *
- * @return void
- */
- public function testBeforeFilterNotIdentified()
- {
- $event = new Event('event');
- $this->rememberMeComponent->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'identify', 'setUser', 'redirectUrl'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->rememberMeComponent->Auth->expects($this->at(0))
- ->method('user');
- $this->rememberMeComponent->Auth->expects($this->at(1))
- ->method('identify');
-
- $this->assertNull($this->rememberMeComponent->beforeFilter($event));
- }
-
- /**
- * Test
- *
- * @return void
- */
- public function testBeforeFilterUserLoggedIn()
- {
- $event = new Event('event');
- $this->rememberMeComponent->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'identify', 'setUser', 'redirectUrl'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->rememberMeComponent->Auth->expects($this->once())
- ->method('user')
- ->will($this->returnValue([
- 'id' => 1,
- ]));
- $this->assertNull($this->rememberMeComponent->beforeFilter($event));
- }
-}
diff --git a/tests/TestCase/Controller/Component/SetupComponentTest.php b/tests/TestCase/Controller/Component/SetupComponentTest.php
new file mode 100644
index 000000000..d685949a2
--- /dev/null
+++ b/tests/TestCase/Controller/Component/SetupComponentTest.php
@@ -0,0 +1,102 @@
+Controller = new Controller();
+ }
+
+ /**
+ * tearDown method
+ *
+ * @return void
+ */
+ public function tearDown(): void
+ {
+ unset($this->Controller, $this->Component);
+
+ parent::tearDown();
+ }
+
+ /**
+ * Data provider for testInitialization
+ *
+ * @return array
+ */
+ public function dataProviderInitialization()
+ {
+ return [
+ [true, true, true],
+ [false, true, true],
+ [true, false, true],
+ [true, true, false],
+ [false, false, false],
+ ];
+ }
+
+ /**
+ * Test initial setup
+ *
+ * @param bool $authentication Should use authentication component
+ * @param booll $authorization Should use authorization component
+ * @param booll $oneTimePass Should use OneTimePassword component
+ * @throws \Exception
+ * @dataProvider dataProviderInitialization
+ * @return void
+ */
+ public function testInitialization($authentication, $authorization, $oneTimePass)
+ {
+ Configure::write('Auth.AuthenticationComponent.load', $authentication);
+ Configure::write('Auth.AuthorizationComponent.enable', $authorization);
+ Configure::write('OneTimePasswordAuthenticator.login', $oneTimePass);
+ $registry = new ComponentRegistry($this->Controller);
+ $this->Component = new SetupComponent($registry);
+ $this->Component->initialize([]);
+ $this->assertSame($authentication, $this->Controller->components()->has('Authentication'));
+ $this->assertSame($authorization, $this->Controller->components()->has('Authorization'));
+ $this->assertSame($oneTimePass, $this->Controller->components()->has('OneTimePasswordAuthenticator'));
+ }
+}
diff --git a/tests/TestCase/Controller/Component/UsersAuthComponentTest.php b/tests/TestCase/Controller/Component/UsersAuthComponentTest.php
deleted file mode 100644
index e6db00b79..000000000
--- a/tests/TestCase/Controller/Component/UsersAuthComponentTest.php
+++ /dev/null
@@ -1,436 +0,0 @@
-backupUsersConfig = Configure::read('Users');
-
- Router::reload();
- Plugin::routes('CakeDC/Users');
- Router::connect('/route/*', [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Users',
- 'action' => 'requestResetPassword'
- ]);
- Router::connect('/notAllowed/*', [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Users',
- 'action' => 'edit'
- ]);
- Security::salt('YJfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi');
- Configure::write('App.namespace', 'Users');
- $this->request = $this->getMockBuilder('Cake\Network\Request')
- ->setMethods(['is', 'method'])
- ->getMock();
- $this->request->expects($this->any())->method('is')->will($this->returnValue(true));
- $this->response = $this->getMockBuilder('Cake\Network\Response')
- ->setMethods(['stop'])
- ->getMock();
- $this->Controller = new Controller($this->request, $this->response);
- $this->Registry = $this->Controller->components();
- $this->Controller->UsersAuth = new UsersAuthComponent($this->Registry);
- }
-
- /**
- * tearDown method
- *
- * @return void
- */
- public function tearDown()
- {
- parent::tearDown();
-
- $_SESSION = [];
- unset($this->Controller, $this->UsersAuth);
- Configure::write('Users', $this->backupUsersConfig);
- }
-
- /**
- * Test initialize
- *
- */
- public function testInitialize()
- {
- $this->Registry->unload('Auth');
- $this->Controller->UsersAuth = new UsersAuthComponent($this->Registry);
- $this->assertInstanceOf('CakeDC\Users\Controller\Component\UsersAuthComponent', $this->Controller->UsersAuth);
- }
-
- /**
- * Test initialize with not rememberMe component needed
- *
- */
- public function testInitializeNoRequiredRememberMe()
- {
- Configure::write('Users.RememberMe.active', false);
- $class = 'CakeDC\Users\Controller\Component\UsersAuthComponent';
- $this->Controller->UsersAuth = $this->getMockBuilder($class)
- ->setMethods(['_loadRememberMe', '_initAuth', '_loadSocialLogin', '_attachPermissionChecker'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->UsersAuth->expects($this->once())
- ->method('_initAuth');
- $this->Controller->UsersAuth->expects($this->never())
- ->method('_loadRememberMe');
- $this->Controller->UsersAuth->initialize([]);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testIsUrlAuthorizedUserNotLoggedIn()
- {
- $event = new Event('event');
- $event->data = [
- 'url' => '/route',
- ];
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->Auth->expects($this->once())
- ->method('user')
- ->will($this->returnValue(false));
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- $this->assertFalse($result);
- }
-
- /**
- * test The user is not logged in, but the controller action is public $this->Auth->allow()
- *
- * @return void
- */
- public function testIsUrlAuthorizedUserNotLoggedInActionAllowed()
- {
- $event = new Event('event');
- $event->data = [
- 'url' => '/route',
- ];
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->Auth->allowedActions = ['requestResetPassword'];
- $this->Controller->Auth->expects($this->never())
- ->method('user');
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- $this->assertTrue($result);
- }
-
- /**
- * test The user is logged in and not allowed by rules to access this action,
- * but the controller action is public $this->Auth->allow()
- *
- * @return void
- */
- public function testIsUrlAuthorizedUserLoggedInNotAllowedActionAllowed()
- {
- $event = new Event('event');
- $event->data = [
- 'url' => '/notAllowed',
- ];
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->Auth->allowedActions = ['edit'];
- $this->Controller->Auth->expects($this->never())
- ->method('user');
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- $this->assertTrue($result);
- }
-
- /**
- * test The user is logged in and allowed by rules to access this action,
- * and the controller action is public $this->Auth->allow()
- *
- * @return void
- */
- public function testIsUrlAuthorizedUserLoggedInAllowedActionAllowed()
- {
- $event = new Event('event');
- $event->data = [
- 'url' => '/route',
- ];
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->Auth->allowedActions = ['requestResetPassword'];
- $this->Controller->Auth->expects($this->never())
- ->method('user');
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- $this->assertTrue($result);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testIsUrlAuthorizedNoUrl()
- {
- $event = new Event('event');
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- $this->assertFalse($result);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testIsUrlAuthorizedUrlRelativeString()
- {
- $event = new Event('event');
- $event->data = [
- 'url' => '/route',
- ];
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->Auth->expects($this->once())
- ->method('user')
- ->will($this->returnValue(['id' => 1]));
- $request = new Request('/route');
- $request->params = [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Users',
- 'action' => 'requestResetPassword',
- 'pass' => [],
- '_matchedRoute' => '/route/*',
- ];
- $this->Controller->Auth->expects($this->once())
- ->method('isAuthorized')
- ->with(null, $request)
- ->will($this->returnValue(true));
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- $this->assertTrue($result);
- }
-
- /**
- * test
- *
- * @return void
- * @expectedException Cake\Routing\Exception\MissingRouteException
- */
- public function testIsUrlAuthorizedMissingRouteString()
- {
- $event = new Event('event');
- $event->data = [
- 'url' => '/missingRoute',
- ];
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->Auth->expects($this->never())
- ->method('user');
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- }
-
- /**
- * test
- *
- * @return void
- * @expectedException Cake\Routing\Exception\MissingRouteException
- */
- public function testIsUrlAuthorizedMissingRouteArray()
- {
- $event = new Event('event');
- $event->data = [
- 'url' => [
- 'controller' => 'missing',
- 'action' => 'missing',
- ],
- ];
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->Auth->expects($this->never())
- ->method('user');
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testIsUrlAuthorizedUrlAbsoluteForCurrentAppString()
- {
- $event = new Event('event');
- $event->data = [
- 'url' => Router::fullBaseUrl() . '/route',
- ];
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->Auth->expects($this->once())
- ->method('user')
- ->will($this->returnValue(['id' => 1]));
- $request = new Request('/route');
- $request->params = [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Users',
- 'action' => 'requestResetPassword',
- 'pass' => [],
- '_matchedRoute' => '/route/*',
- ];
- $this->Controller->Auth->expects($this->once())
- ->method('isAuthorized')
- ->with(null, $request)
- ->will($this->returnValue(true));
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- $this->assertTrue($result);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testIsUrlAuthorizedUrlRelativeForCurrentAppString()
- {
- $event = new Event('event');
- $event->data = [
- 'url' => 'route',
- ];
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->Auth->expects($this->once())
- ->method('user')
- ->will($this->returnValue(['id' => 1]));
- $request = new Request('/route');
- $request->params = [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Users',
- 'action' => 'requestResetPassword',
- 'pass' => [],
- '_matchedRoute' => '/route/*',
- ];
- $this->Controller->Auth->expects($this->once())
- ->method('isAuthorized')
- ->with(null, $request)
- ->will($this->returnValue(true));
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- $this->assertTrue($result);
- }
-
- /**
- *
- *
- * @return void
- */
- public function testIsUrlAuthorizedUrlAbsoluteForOtherAppString()
- {
- $event = new Event('event');
- $event->data = [
- 'url' => 'http://example.com',
- ];
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->Auth->expects($this->never())
- ->method('user');
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- $this->assertTrue($result);
- }
-
- /**
- * test
- *
- * @return void
- */
- public function testIsUrlAuthorizedUrlArray()
- {
- $event = new Event('event');
- $event->data = [
- 'url' => [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Users',
- 'action' => 'requestResetPassword',
- 'pass-one'
- ],
- ];
- $this->Controller->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'isAuthorized'])
- ->disableOriginalConstructor()
- ->getMock();
- $this->Controller->Auth->expects($this->once())
- ->method('user')
- ->will($this->returnValue(['id' => 1]));
- $request = new Request('/route/pass-one');
- $request->params = [
- 'plugin' => 'CakeDC/Users',
- 'controller' => 'Users',
- 'action' => 'requestResetPassword',
- 'pass' => ['pass-one'],
- '_matchedRoute' => '/route/*',
- ];
- $this->Controller->Auth->expects($this->once())
- ->method('isAuthorized')
- ->with(null, $request)
- ->will($this->returnValue(true));
- $result = $this->Controller->UsersAuth->isUrlAuthorized($event);
- $this->assertTrue($result);
- }
-}
diff --git a/tests/TestCase/Controller/SocialAccountsControllerTest.php b/tests/TestCase/Controller/SocialAccountsControllerTest.php
index c85dc2e86..47a544d7e 100644
--- a/tests/TestCase/Controller/SocialAccountsControllerTest.php
+++ b/tests/TestCase/Controller/SocialAccountsControllerTest.php
@@ -1,23 +1,22 @@
'Debug'
- ]);
- $this->configEmail = Email::config('default');
- Email::config('default', [
+ TransportFactory::setConfig('test', ['className' => 'Debug']);
+ $this->configEmail = Email::getConfig('default');
+ Email::drop('default');
+ Email::setConfig('default', [
'transport' => 'test',
- 'from' => 'cakedc@example.com'
+ 'from' => 'cakedc@example.com',
]);
- $request = new Request('/users/users/index');
- $request->params['plugin'] = 'CakeDC/Users';
+ $request = new ServerRequest(['url' => '/users/users/index']);
+ $request = $request->withParam('plugin', 'CakeDC/Users');
$this->Controller = $this->getMockBuilder('CakeDC\Users\Controller\SocialAccountsController')
- ->setMethods(['redirect', 'render'])
+ ->onlyMethods(['redirect', 'render'])
->setConstructorArgs([$request, null, 'SocialAccounts'])
->getMock();
- $this->Controller->SocialAccounts = $this->getMockForModel('CakeDC\Users.SocialAccounts', ['sendSocialValidationEmail'], [
- 'className' => 'CakeDC\Users\Model\Table\SocialAccountsTable'
- ]);
}
/**
@@ -72,11 +67,11 @@ public function setUp()
*
* @return void
*/
- public function tearDown()
+ public function tearDown(): void
{
Email::drop('default');
- Email::dropTransport('test');
- Email::config('default', $this->configEmail);
+ TransportFactory::drop('test');
+ //Email::setConfig('default', $this->configEmail);
Configure::write('Opauth', $this->configOpauth);
Configure::write('Users.RememberMe.active', $this->configRememberMe);
@@ -93,9 +88,9 @@ public function testValidateAccountHappy()
{
$this->Controller->expects($this->once())
->method('redirect')
- ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login']);
+ ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login', 'prefix' => false]);
$this->Controller->validateAccount('Facebook', 'reference-1-1234', 'token-1234');
- $this->assertEquals('Account validated successfully', $this->Controller->request->session()->read('Flash.flash.0.message'));
+ $this->assertEquals('Account validated successfully', $this->Controller->getRequest()->getSession()->read('Flash.flash.0.message'));
}
/**
@@ -107,9 +102,9 @@ public function testValidateAccountInvalidToken()
{
$this->Controller->expects($this->once())
->method('redirect')
- ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login']);
+ ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login', 'prefix' => false]);
$this->Controller->validateAccount('Facebook', 'reference-1-1234', 'token-not-found');
- $this->assertEquals('Invalid token and/or social account', $this->Controller->request->session()->read('Flash.flash.0.message'));
+ $this->assertEquals('Invalid token and/or social account', $this->Controller->getRequest()->getSession()->read('Flash.flash.0.message'));
}
/**
@@ -121,9 +116,9 @@ public function testValidateAccountAlreadyActive()
{
$this->Controller->expects($this->once())
->method('redirect')
- ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login']);
+ ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login', 'prefix' => false]);
$this->Controller->validateAccount('Twitter', 'reference-1-1234', 'token-1234');
- $this->assertEquals('Social Account already active', $this->Controller->request->session()->read('Flash.flash.0.message'));
+ $this->assertEquals('Social Account already active', $this->Controller->getRequest()->getSession()->read('Flash.flash.0.message'));
}
/**
@@ -134,7 +129,7 @@ public function testValidateAccountAlreadyActive()
public function testResendValidationHappy()
{
$behaviorMock = $this->getMockBuilder('CakeDC\Users\Model\Behavior\SocialAccountBehavior')
- ->setMethods(['sendSocialValidationEmail'])
+ ->onlyMethods(['sendSocialValidationEmail'])
->setConstructorArgs([$this->Controller->SocialAccounts])
->getMock();
$this->Controller->SocialAccounts->behaviors()->set('SocialAccount', $behaviorMock);
@@ -143,10 +138,10 @@ public function testResendValidationHappy()
->will($this->returnValue(true));
$this->Controller->expects($this->once())
->method('redirect')
- ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login']);
+ ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login', 'prefix' => false]);
$this->Controller->resendValidation('Facebook', 'reference-1-1234');
- $this->assertEquals('Email sent successfully', $this->Controller->request->session()->read('Flash.flash.0.message'));
+ $this->assertEquals('Email sent successfully', $this->Controller->getRequest()->getSession()->read('Flash.flash.0.message'));
}
/**
@@ -157,7 +152,7 @@ public function testResendValidationHappy()
public function testResendValidationEmailError()
{
$behaviorMock = $this->getMockBuilder('CakeDC\Users\Model\Behavior\SocialAccountBehavior')
- ->setMethods(['sendSocialValidationEmail'])
+ ->onlyMethods(['sendSocialValidationEmail'])
->setConstructorArgs([$this->Controller->SocialAccounts])
->getMock();
$this->Controller->SocialAccounts->behaviors()->set('SocialAccount', $behaviorMock);
@@ -166,10 +161,10 @@ public function testResendValidationEmailError()
->will($this->returnValue(false));
$this->Controller->expects($this->once())
->method('redirect')
- ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login']);
+ ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login', 'prefix' => false]);
$this->Controller->resendValidation('Facebook', 'reference-1-1234');
- $this->assertEquals('Email could not be sent', $this->Controller->request->session()->read('Flash.flash.0.message'));
+ $this->assertEquals('Email could not be sent', $this->Controller->getRequest()->getSession()->read('Flash.flash.0.message'));
}
/**
@@ -181,9 +176,9 @@ public function testResendValidationInvalid()
{
$this->Controller->expects($this->once())
->method('redirect')
- ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login']);
+ ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login', 'prefix' => false]);
$this->Controller->resendValidation('Facebook', 'reference-invalid');
- $this->assertEquals('Invalid account', $this->Controller->request->session()->read('Flash.flash.0.message'));
+ $this->assertEquals('Invalid account', $this->Controller->getRequest()->getSession()->read('Flash.flash.0.message'));
}
/**
@@ -195,8 +190,8 @@ public function testResendValidationAlreadyActive()
{
$this->Controller->expects($this->once())
->method('redirect')
- ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login']);
+ ->with(['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'login', 'prefix' => false]);
$this->Controller->validateAccount('Twitter', 'reference-1-1234', 'token-1234');
- $this->assertEquals('Social Account already active', $this->Controller->request->session()->read('Flash.flash.0.message'));
+ $this->assertEquals('Social Account already active', $this->Controller->getRequest()->getSession()->read('Flash.flash.0.message'));
}
}
diff --git a/tests/TestCase/Controller/Traits/BaseTraitTest.php b/tests/TestCase/Controller/Traits/BaseTraitTest.php
index 299de8ba5..693940e8a 100644
--- a/tests/TestCase/Controller/Traits/BaseTraitTest.php
+++ b/tests/TestCase/Controller/Traits/BaseTraitTest.php
@@ -1,22 +1,40 @@
loadPlugins(['CakeDC/Users' => ['routes' => true]]);
$traitMockMethods = array_unique(array_merge(['getUsersTable'], $this->traitMockMethods));
- $this->table = TableRegistry::get('CakeDC/Users.Users');
+ $this->table = TableRegistry::getTableLocator()->get('CakeDC/Users.Users');
try {
$this->Trait = $this->getMockBuilder($this->traitClassName)
->setMethods($traitMockMethods)
- ->getMockForTrait();
+ ->getMock();
$this->Trait->expects($this->any())
->method('getUsersTable')
->will($this->returnValue($this->table));
} catch (PHPUnit_Framework_MockObject_RuntimeException $ex) {
debug($ex);
- $this->fail("Unit tests extending BaseTraitTest should declare the trait class name in the \$traitClassName variable before calling setUp()");
+ $this->fail('Unit tests extending BaseTraitTest should declare the trait class name in the $traitClassName variable before calling setUp()');
}
if ($this->mockDefaultEmail) {
- Email::configTransport('test', [
- 'className' => 'Debug'
+ TransportFactory::setConfig('test', [
+ 'className' => 'Debug',
]);
- $this->configEmail = Email::config('default');
- Email::config('default', [
+ $this->configEmail = Email::getConfig('default');
+ Email::drop('default');
+ Email::setConfig('default', [
'transport' => 'test',
- 'from' => 'cakedc@example.com'
+ 'from' => 'cakedc@example.com',
]);
}
}
@@ -76,13 +112,13 @@ public function setUp()
*
* @return void
*/
- public function tearDown()
+ public function tearDown(): void
{
unset($this->table, $this->Trait);
if ($this->mockDefaultEmail) {
Email::drop('default');
- Email::dropTransport('test');
- Email::config('default', $this->configEmail);
+ TransportFactory::drop('test');
+ //Email::setConfig('default', $this->setConfigEmail);
}
parent::tearDown();
}
@@ -90,20 +126,23 @@ public function tearDown()
/**
* Mock session and mock session attributes
*
- * @return void
+ * @return \Cake\Http\Session
*/
protected function _mockSession($attributes)
{
- $session = new \Cake\Network\Session();
+ $session = new \Cake\Http\Session();
foreach ($attributes as $field => $value) {
$session->write($field, $value);
}
- $this->Trait->request
+ $this->Trait
+ ->getRequest()
->expects($this->any())
- ->method('session')
+ ->method('getSession')
->willReturn($session);
+
+ return $session;
}
/**
@@ -113,19 +152,20 @@ protected function _mockSession($attributes)
*/
protected function _mockRequestGet($withSession = false)
{
- $methods = ['is', 'referer', 'data'];
+ $methods = ['is', 'referer', 'getData'];
if ($withSession) {
- $methods[] = 'session';
+ $methods[] = 'getSession';
}
- $this->Trait->request = $this->getMockBuilder('Cake\Network\Request')
+ $request = $this->getMockBuilder('Cake\Http\ServerRequest')
->setMethods($methods)
->getMock();
- $this->Trait->request->expects($this->any())
+ $request->expects($this->any())
->method('is')
->with('post')
->will($this->returnValue(false));
+ $this->Trait->setRequest($request);
}
/**
@@ -149,13 +189,14 @@ protected function _mockFlash()
*/
protected function _mockRequestPost($with = 'post')
{
- $this->Trait->request = $this->getMockBuilder('Cake\Network\Request')
- ->setMethods(['is', 'data', 'allow'])
+ $request = $this->getMockBuilder('Cake\Http\ServerRequest')
+ ->setMethods(['is', 'getData', 'allow'])
->getMock();
- $this->Trait->request->expects($this->any())
+ $request->expects($this->any())
->method('is')
->with($with)
->will($this->returnValue(true));
+ $this->Trait->setRequest($request);
}
/**
@@ -165,47 +206,152 @@ protected function _mockRequestPost($with = 'post')
*/
protected function _mockAuthLoggedIn($user = [])
{
- $this->Trait->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'identify', 'setUser', 'redirectUrl'])
- ->disableOriginalConstructor()
- ->getMock();
$user += [
'id' => '00000000-0000-0000-0000-000000000001',
'password' => '12345',
];
- $this->Trait->Auth->expects($this->any())
- ->method('identify')
- ->will($this->returnValue($user));
- $this->Trait->Auth->expects($this->any())
- ->method('user')
- ->with('id')
- ->will($this->returnValue($user['id']));
+
+ $this->_mockAuthentication($user);
}
/**
- * Mock the Auth component
+ * Mock the Authentication service
*
+ * @param array $user
+ * @param array $failures
+ * @param \Authentication\Identifier\IdentifierCollection $identifiers custom identifiers collection
* @return void
*/
- protected function _mockAuth()
+ protected function _mockAuthentication($user = null, $failures = [], $identifiers = null)
{
- $this->Trait->Auth = $this->getMockBuilder('Cake\Controller\Component\AuthComponent')
- ->setMethods(['user', 'identify', 'setUser', 'redirectUrl'])
- ->disableOriginalConstructor()
- ->getMock();
+ if ($identifiers === null) {
+ $passwordIdentifier = $this->getMockBuilder(PasswordIdentifier::class)
+ ->setMethods(['needsPasswordRehash'])
+ ->getMock();
+ $passwordIdentifier->expects($this->any())
+ ->method('needsPasswordRehash')
+ ->willReturn(false);
+ $identifiers = new IdentifierCollection([]);
+ $identifiers->set('Password', $passwordIdentifier);
+ }
+
+ $config = [
+ 'identifiers' => [
+ 'Authentication.Password',
+ ],
+ 'authenticators' => [
+ 'Authentication.Session',
+ 'Authentication.Form',
+ ],
+ ];
+ $authentication = $this->getMockBuilder(AuthenticationService::class)->setConstructorArgs([$config])->setMethods([
+ 'getResult',
+ 'getFailures',
+ 'identifiers',
+ ])->getMock();
+
+ if ($user) {
+ $user = new User($user);
+ $identity = new Identity($user);
+ $result = new Result($user, Result::SUCCESS);
+ $this->Trait->setRequest($this->Trait->getRequest()->withAttribute('identity', $identity));
+ } else {
+ $result = new Result($user, Result::FAILURE_CREDENTIALS_MISSING);
+ }
+
+ $authentication->expects($this->any())
+ ->method('getResult')
+ ->will($this->returnValue($result));
+
+ $authentication->expects($this->any())
+ ->method('getFailures')
+ ->will($this->returnValue($failures));
+
+ $authentication->expects($this->any())
+ ->method('identifiers')
+ ->will($this->returnValue($identifiers));
+
+ $this->Trait->setRequest($this->Trait->getRequest()->withAttribute('authentication', $authentication));
+
+ $controller = new Controller($this->Trait->getRequest());
+ $registry = new ComponentRegistry($controller);
+ $this->Trait->Authentication = new AuthenticationComponent($registry, [
+ 'loginRedirect' => $this->successLoginRedirect,
+ 'logoutRedirect' => $this->logoutRedirect,
+ 'loginAction' => $this->loginAction,
+ ]);
+ }
+
+ /**
+ * Mock the Authentication service with a Password Rehash being required.
+ *
+ * @param array $user
+ * @param array $failures
+ * @return void
+ */
+ protected function _mockAuthenticationWithPasswordRehash($user = null, $failures = [])
+ {
+ $config = [
+ 'identifiers' => [
+ 'Authentication.Password',
+ ],
+ 'authenticators' => [
+ 'Authentication.Session',
+ 'Authentication.Form',
+ ],
+ ];
+ $authentication = $this->getMockBuilder(AuthenticationService::class)->setConstructorArgs([$config])->setMethods([
+ 'getResult',
+ 'getFailures',
+ 'identifiers',
+ ])->getMock();
+ $authentication->expects($this->any())
+ ->method('identifiers')
+ ->willReturn($identifiers);
+ if ($user) {
+ $user = is_object($user) ? $user : new User($user);
+ $identity = new Identity($user);
+ $result = new Result($user, Result::SUCCESS);
+ $this->Trait->setRequest($this->Trait->getRequest()->withAttribute('identity', $identity));
+ } else {
+ $result = new Result($user, Result::FAILURE_CREDENTIALS_MISSING);
+ }
+
+ $authentication->expects($this->any())
+ ->method('getResult')
+ ->will($this->returnValue($result));
+
+ $authentication->expects($this->any())
+ ->method('getFailures')
+ ->will($this->returnValue($failures));
+
+ $this->Trait->setRequest($this->Trait->getRequest()->withAttribute('authentication', $authentication));
+
+ //$controller = new Controller($this->Trait->getRequest());
+ $registry = new ComponentRegistry($this->Trait);
+ $this->Trait->Authentication = new AuthenticationComponent($registry, [
+ 'loginRedirect' => $this->successLoginRedirect,
+ 'logoutRedirect' => $this->logoutRedirect,
+ 'loginAction' => $this->loginAction,
+ ]);
}
/**
* mock utility
*
* @param Event $event event
+ * @param array $result array of data
* @return void
*/
- protected function _mockDispatchEvent(Event $event = null)
+ protected function _mockDispatchEvent(?Event $event = null, $result = [])
{
if (is_null($event)) {
$event = new Event('cool-name-here');
}
+
+ if (!empty($result)) {
+ $event->setResult(new Entity($result));
+ }
$this->Trait->expects($this->any())
->method('dispatchEvent')
->will($this->returnValue($event));
diff --git a/tests/TestCase/Controller/Traits/CustomUsersTableTraitTest.php b/tests/TestCase/Controller/Traits/CustomUsersTableTraitTest.php
index 89c000651..8bad2e04b 100644
--- a/tests/TestCase/Controller/Traits/CustomUsersTableTraitTest.php
+++ b/tests/TestCase/Controller/Traits/CustomUsersTableTraitTest.php
@@ -1,11 +1,13 @@
controller = $this->getMockBuilder('Cake\Controller\Controller')
@@ -25,7 +27,7 @@ public function setUp()
$this->controller->Trait = $this->getMockForTrait('CakeDC\Users\Controller\Traits\CustomUsersTableTrait');
}
- public function tearDown()
+ public function tearDown(): void
{
parent::tearDown();
}
@@ -33,7 +35,7 @@ public function tearDown()
public function testGetUsersTable()
{
$table = $this->controller->Trait->getUsersTable();
- $this->assertEquals('CakeDC/Users.Users', $table->registryAlias());
+ $this->assertEquals('CakeDC/Users.Users', $table->getRegistryAlias());
$newTable = new Table();
$this->controller->Trait->setUsersTable($newTable);
$this->assertSame($newTable, $this->controller->Trait->getUsersTable());
diff --git a/tests/TestCase/Controller/Traits/Integration/LoginTraitIntegrationTest.php b/tests/TestCase/Controller/Traits/Integration/LoginTraitIntegrationTest.php
new file mode 100644
index 000000000..9bf8d74d4
--- /dev/null
+++ b/tests/TestCase/Controller/Traits/Integration/LoginTraitIntegrationTest.php
@@ -0,0 +1,297 @@
+get('CakeDC/Users.Users')
+ ->get($id);
+
+ $this->session(['Auth' => $user]);
+ }
+
+ /**
+ * Test login action with get request
+ *
+ * @return void
+ */
+ public function testRedirectToLogin()
+ {
+ $this->enableRetainFlashMessages();
+ $this->get('/pages/home');
+ $this->assertRedirectContains('/login?redirect=http%3A%2F%2Flocalhost%2Fpages%2Fhome');
+ $this->assertFlashMessage('You are not authorized to access that location.');
+ }
+
+ /**
+ * Test login action with get request
+ *
+ * @return void
+ */
+ public function testLoginGetRequestNoSocialLogin()
+ {
+ EventManager::instance()->on('TestApp.afterPluginBootstrap', function () {
+ Configure::write(['Users.Social.login' => false]);
+ });
+
+ $this->get('/login');
+ $this->assertResponseOk();
+ $this->assertResponseNotContains('Username or password is incorrect');
+ $this->assertResponseContains('