Completed
Push — master ( 987505...ce3c0b )
by Hamish
8s
created

BehatExtension/Context/LoginContext.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace SilverStripe\BehatExtension\Context;
4
5
use Behat\Behat\Context\BehatContext;
6
use Behat\Behat\Context\Step;
7
use SilverStripe\ORM\DataObject;
8
use SilverStripe\Security\Group;
9
use SilverStripe\Security\Member;
10
11
12
13
// PHPUnit
14
require_once BASE_PATH . '/vendor/phpunit/phpunit/src/Framework/Assert/Functions.php';
15
16
/**
17
 * LoginContext
18
 *
19
 * Context used to define steps related to login and logout functionality
20
 */
21
class LoginContext extends BehatContext
22
{
23
    protected $context;
24
25
    /**
26
     * Cache for logInWithPermission()
27
     */
28
    protected $cache_generatedMembers = array();
29
30
    /**
31
     * Initializes context.
32
     * Every scenario gets it's own context object.
33
     *
34
     * @param array $parameters context parameters (set them up through behat.yml)
35
     */
36
    public function __construct(array $parameters)
37
    {
38
        // Initialize your context here
39
        $this->context = $parameters;
40
    }
41
42
    /**
43
     * Get Mink session from MinkContext
44
     */
45
    public function getSession($name = null)
46
    {
47
        return $this->getMainContext()->getSession($name);
48
    }
49
50
    /**
51
     * @Given /^I am logged in$/
52
     */
53
    public function stepIAmLoggedIn()
54
    {
55
        $c = $this->getMainContext();
56
        $adminUrl = $c->joinUrlParts($c->getBaseUrl(), $c->getAdminUrl());
57
        $loginUrl = $c->joinUrlParts($c->getBaseUrl(), $c->getLoginUrl());
58
59
        $this->getSession()->visit($adminUrl);
60
61
        if (0 == strpos($this->getSession()->getCurrentUrl(), $loginUrl)) {
62
            $this->stepILogInWith('admin', 'password');
63
            assertStringStartsWith($adminUrl, $this->getSession()->getCurrentUrl());
64
        }
65
    }
66
67
    /**
68
     * Creates a member in a group with the correct permissions.
69
     * Example: Given I am logged in with "ADMIN" permissions
70
     *
71
     * @Given /^I am logged in with "([^"]*)" permissions$/
72
     */
73
    function iAmLoggedInWithPermissions($permCode)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
74
    {
75
        if (!isset($this->cache_generatedMembers[$permCode])) {
76
            $group = Group::get()->filter('Title', "$permCode group")->first();
77
            if (!$group) {
78
                $group = \Injector::inst()->create('SilverStripe\\Security\\Group');
79
            }
80
81
            $group->Title = "$permCode group";
82
            $group->write();
83
84
            $permission = \Injector::inst()->create('SilverStripe\\Security\\Permission');
85
            $permission->Code = $permCode;
86
            $permission->write();
87
            $group->Permissions()->add($permission);
88
89
            $member = DataObject::get_one('SilverStripe\\Security\\Member', sprintf('"Email" = \'%s\'', "[email protected]"));
90
            if (!$member) {
91
                $member = \Injector::inst()->create('SilverStripe\\Security\\Member');
92
            }
93
94
            // make sure any validation for password is skipped, since we're not testing complexity here
95
            $validator = Member::password_validator();
96
            Member::set_password_validator(null);
97
            $member->FirstName = $permCode;
98
            $member->Surname = "User";
99
            $member->Email = "[email protected]";
100
            $member->PasswordEncryption = "none";
101
            $member->changePassword('Secret!123');
102
            $member->write();
103
            $group->Members()->add($member);
104
            Member::set_password_validator($validator);
105
106
            $this->cache_generatedMembers[$permCode] = $member;
107
        }
108
109
        return new Step\Given(sprintf('I log in with "%s" and "%s"', "[email protected]", 'Secret!123'));
110
    }
111
112
    /**
113
     * @Given /^I am not logged in$/
114
     */
115
    public function stepIAmNotLoggedIn()
116
    {
117
        $c = $this->getMainContext();
118
        $this->getSession()->visit($c->joinUrlParts($c->getBaseUrl(), 'Security/logout'));
119
    }
120
121
     /**
122
     * @When /^I log in with "(?<username>[^"]*)" and "(?<password>[^"]*)"$/
123
     */
124
    public function stepILogInWith($email, $password)
125
    {
126
        $c = $this->getMainContext();
127
        $loginUrl = $c->joinUrlParts($c->getBaseUrl(), $c->getLoginUrl());
128
        $this->getSession()->visit($loginUrl);
129
        $page = $this->getSession()->getPage();
130
        $forms = $page->findAll('xpath', '//form[contains(@action, "Security/LoginForm")]');
131
        assertNotNull($forms, 'Login form not found');
132
133
        // Try to find visible forms again on login page.
134
        $visibleForm = null;
135
        foreach($forms as $form) {
136
            if($form->isVisible() && $form->find('css', '[name=Email]')) {
137
                $visibleForm = $form;
138
            }
139
        }
140
141
        assertNotNull($visibleForm, 'Could not find login form');
142
143
        $emailField = $visibleForm->find('css', '[name=Email]');
144
        $passwordField = $visibleForm->find('css', '[name=Password]');
145
        $submitButton = $visibleForm->find('css', '[type=submit]');
146
        $securityID = $visibleForm->find('css', '[name=SecurityID]');
147
148
        assertNotNull($emailField, 'Email field on login form not found');
149
        assertNotNull($passwordField, 'Password field on login form not found');
150
        assertNotNull($submitButton, 'Submit button on login form not found');
151
        // @todo Once CSRF is mandatory, uncomment this
152
        // assertNotNull($securityID, 'CSRF token not found');
153
154
        $emailField->setValue($email);
155
        $passwordField->setValue($password);
156
        $submitButton->press();
157
    }
158
159
    /**
160
     * @Given /^I should see a log-in form$/
161
     */
162
    public function stepIShouldSeeALogInForm()
163
    {
164
        $page = $this->getSession()->getPage();
165
        $loginForm = $page->find('css', '#MemberLoginForm_LoginForm');
166
        assertNotNull($loginForm, 'I should see a log-in form');
167
    }
168
169
    /**
170
     * @Then /^I will see a "([^"]*)" log-in message$/
171
     */
172
    public function stepIWillSeeALogInMessage($type)
173
    {
174
        $page = $this->getSession()->getPage();
175
        $message = $page->find('css', sprintf('.message.%s', $type));
176
        assertNotNull($message, sprintf('%s message not found.', $type));
177
    }
178
179
    /**
180
     * @Then /^the password for "([^"]*)" should be "([^"]*)"$/
181
     */
182
    public function stepPasswordForEmailShouldBe($id, $password)
183
    {
184
        $member = Member::get()->filter('Email', $id)->First();
185
        assertNotNull($member);
186
        assertTrue($member->checkPassword($password)->valid());
187
    }
188
}
189