Skip to content

Package: UserServiceSteps$2

UserServiceSteps$2

nameinstructionbranchcomplexitylinemethod
call()
M: 8 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%
{...}
M: 9 C: 0
0%
M: 0 C: 0
100%
M: 1 C: 0
0%
M: 1 C: 0
0%
M: 1 C: 0
0%

Coverage

1: /*******************************************************************************
2: * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others
3: *
4: * This program and the accompanying materials are made
5: * available under the terms of the Eclipse Public License 2.0
6: * which is available at https://www.eclipse.org/legal/epl-2.0/
7: *
8: * SPDX-License-Identifier: EPL-2.0
9: *
10: * Contributors:
11: * Eurotech
12: *******************************************************************************/
13: package org.eclipse.kapua.service.user.steps;
14:
15: import cucumber.api.Scenario;
16: import cucumber.api.java.After;
17: import cucumber.api.java.Before;
18: import cucumber.api.java.en.And;
19: import cucumber.api.java.en.Given;
20: import cucumber.api.java.en.Then;
21: import cucumber.api.java.en.When;
22: import cucumber.runtime.java.guice.ScenarioScoped;
23: import org.apache.shiro.SecurityUtils;
24: import org.eclipse.kapua.KapuaException;
25: import org.eclipse.kapua.commons.model.id.KapuaEid;
26: import org.eclipse.kapua.commons.security.KapuaSecurityUtils;
27: import org.eclipse.kapua.commons.security.KapuaSession;
28: import org.eclipse.kapua.commons.util.xml.XmlUtil;
29: import org.eclipse.kapua.locator.KapuaLocator;
30: import org.eclipse.kapua.model.config.metatype.KapuaTocd;
31: import org.eclipse.kapua.model.domain.Actions;
32: import org.eclipse.kapua.model.domain.Domain;
33: import org.eclipse.kapua.model.id.KapuaId;
34: import org.eclipse.kapua.model.query.KapuaQuery;
35: import org.eclipse.kapua.model.query.predicate.AttributePredicate;
36: import org.eclipse.kapua.qa.common.DBHelper;
37: import org.eclipse.kapua.qa.common.StepData;
38: import org.eclipse.kapua.qa.common.TestBase;
39: import org.eclipse.kapua.qa.common.TestJAXBContextProvider;
40: import org.eclipse.kapua.qa.common.cucumber.CucConfig;
41: import org.eclipse.kapua.qa.common.cucumber.CucCredentials;
42: import org.eclipse.kapua.qa.common.cucumber.CucPermission;
43: import org.eclipse.kapua.qa.common.cucumber.CucUser;
44: import org.eclipse.kapua.service.account.Account;
45: import org.eclipse.kapua.service.authentication.AuthenticationService;
46: import org.eclipse.kapua.service.authentication.CredentialsFactory;
47: import org.eclipse.kapua.service.authentication.LoginCredentials;
48: import org.eclipse.kapua.service.authentication.credential.Credential;
49: import org.eclipse.kapua.service.authentication.credential.CredentialAttributes;
50: import org.eclipse.kapua.service.authentication.credential.CredentialCreator;
51: import org.eclipse.kapua.service.authentication.credential.CredentialListResult;
52: import org.eclipse.kapua.service.authentication.credential.CredentialFactory;
53: import org.eclipse.kapua.service.authentication.credential.CredentialService;
54: import org.eclipse.kapua.service.authentication.credential.CredentialStatus;
55: import org.eclipse.kapua.service.authentication.credential.CredentialType;
56: import org.eclipse.kapua.service.authentication.credential.CredentialQuery;
57: import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption;
58: import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionCreator;
59: import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionFactory;
60: import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionService;
61: import org.eclipse.kapua.service.authentication.credential.mfa.shiro.MfaOptionFactoryImpl;
62: import org.eclipse.kapua.service.authentication.credential.mfa.shiro.MfaOptionServiceImpl;
63: import org.eclipse.kapua.service.authentication.credential.shiro.CredentialQueryImpl;
64: import org.eclipse.kapua.service.authorization.access.AccessInfoCreator;
65: import org.eclipse.kapua.service.authorization.access.AccessInfoFactory;
66: import org.eclipse.kapua.service.authorization.access.AccessInfoService;
67: import org.eclipse.kapua.service.authorization.access.shiro.AccessPermissionQueryImpl;
68: import org.eclipse.kapua.service.authorization.access.AccessPermissionFactory;
69: import org.eclipse.kapua.service.authorization.access.AccessPermissionService;
70: import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery;
71: import org.eclipse.kapua.service.authorization.access.AccessPermission;
72: import org.eclipse.kapua.service.authorization.access.AccessPermissionAttributes;
73: import org.eclipse.kapua.service.authorization.domain.DomainFactory;
74: import org.eclipse.kapua.service.authorization.domain.DomainRegistryService;
75: import org.eclipse.kapua.service.authorization.permission.Permission;
76: import org.eclipse.kapua.service.authorization.permission.PermissionFactory;
77: import org.eclipse.kapua.service.user.User;
78: import org.eclipse.kapua.service.user.UserCreator;
79: import org.eclipse.kapua.service.user.UserFactory;
80: import org.eclipse.kapua.service.user.UserListResult;
81: import org.eclipse.kapua.service.user.UserQuery;
82: import org.eclipse.kapua.service.user.UserService;
83: import org.eclipse.kapua.service.user.UserStatus;
84: import org.eclipse.kapua.service.user.UserAttributes;
85: import org.junit.Assert;
86: import org.slf4j.Logger;
87: import org.slf4j.LoggerFactory;
88:
89: import javax.inject.Inject;
90: import java.math.BigInteger;
91: import java.text.MessageFormat;
92: import java.time.LocalDate;
93: import java.time.ZoneId;
94: import java.util.ArrayList;
95: import java.util.Date;
96: import java.util.HashMap;
97: import java.util.HashSet;
98: import java.util.Iterator;
99: import java.util.List;
100: import java.util.Map;
101: import java.util.Set;
102: import java.util.concurrent.Callable;
103:
104: /**
105: * Implementation of Gherkin steps used in user test scenarios.
106: * <p>
107: * MockedLocator is used for Location Service.
108: * Mockito is used to mock other services that UserService is dependent on.
109: */
110: @ScenarioScoped
111: public class UserServiceSteps extends TestBase {
112:
113: private static final Logger logger = LoggerFactory.getLogger(UserServiceSteps.class);
114:
115: private static final String USER_CREATOR = "UserCreator";
116: private static final String USER_LIST = "UserList";
117: private static final String USER_NOT_FOUND = "User %1s was not found!";
118: private static final String COUNT = "Count";
119: private static final String LAST_ACCOUNT = "LastAccount";
120: private static final String METADATA = "Metadata";
121: private static final String LAST_USER = "LastUser";
122: private static final String LAST_FOUND_ACCESS_PERMISSION = "LastFoundAccessPermission";
123: private static final String LAST_PERMISSION_ADDED_TO_USER = "LastPermissionAddedToUser";
124: private static final String FOUND_USERS = "FoundUsers";
125:
126: /**
127: * User service by locator.
128: */
129: private UserService userService;
130:
131: /**
132: * User factory by locator.
133: */
134: private UserFactory userFactory;
135:
136: /**
137: * Security services services by locator.
138: */
139: private AccessInfoService accessInfoService;
140: private AuthenticationService authenticationService;
141: private AccessInfoFactory accessInfoFactory;
142: private PermissionFactory permissionFactory;
143: private CredentialService credentialService;
144: private CredentialFactory credentialFactory;
145: private CredentialsFactory credentialsFactory;
146: private AccessPermissionService accessPermissionService;
147: private AccessPermissionFactory accessPermissionFactory;
148: private DomainRegistryService domainRegistryService;
149: private DomainFactory domainFactory;
150:
151: @Inject
152: public UserServiceSteps(StepData stepData, DBHelper dbHelper) {
153:
154: this.stepData = stepData;
155: this.database = dbHelper;
156: }
157:
158: // *************************************
159: // Definition of Cucumber scenario steps
160: // *************************************
161:
162: @Before
163: public void beforeScenario(Scenario scenario) {
164:
165: this.scenario = scenario;
166: database.setup();
167: stepData.clear();
168:
169: locator = KapuaLocator.getInstance();
170: userService = locator.getService(UserService.class);
171: userFactory = locator.getFactory(UserFactory.class);
172: authenticationService = locator.getService(AuthenticationService.class);
173: credentialService = locator.getService(CredentialService.class);
174: accessInfoService = locator.getService(AccessInfoService.class);
175: accessInfoFactory = locator.getFactory(AccessInfoFactory.class);
176: permissionFactory = locator.getFactory(PermissionFactory.class);
177: credentialFactory = locator.getFactory(CredentialFactory.class);
178: credentialsFactory = locator.getFactory(CredentialsFactory.class);
179: accessPermissionService = locator.getService(AccessPermissionService.class);
180: accessPermissionFactory = locator.getFactory(AccessPermissionFactory.class);
181: domainRegistryService = locator.getService(DomainRegistryService.class);
182: domainFactory = locator.getFactory(DomainFactory.class);
183:
184: if (isUnitTest()) {
185: // Create KapuaSession using KapuaSecurtiyUtils and kapua-sys user as logged in user.
186: // All operations on database are performed using system user.
187: // Only for unit tests. Integration tests assume that a real logon is performed.
188: KapuaSession kapuaSession = new KapuaSession(null, SYS_SCOPE_ID, SYS_USER_ID);
189: KapuaSecurityUtils.setSession(kapuaSession);
190: }
191:
192: // Setup JAXB context
193: XmlUtil.setContextProvider(new TestJAXBContextProvider());
194: }
195:
196: @After
197: public void afterScenario() {
198:
199: // Clean up the database
200: try {
201: logger.info("Logging out in cleanup");
202: if (isIntegrationTest()) {
203: database.deleteAll();
204: SecurityUtils.getSubject().logout();
205: } else {
206: database.dropAll();
207: database.close();
208: }
209: KapuaSecurityUtils.clearSession();
210: } catch (Exception e) {
211: logger.error("Failed to log out in @After", e);
212: }
213: }
214:
215: @Given("^User with name \"(.*)\" in scope with id (\\d+)$")
216: public void crateUserWithName(String userName, int scopeId) {
217: long now = (new Date()).getTime();
218: String userEmail = MessageFormat.format("testuser_{0,number,#}@organization.com", now);
219: String displayName = MessageFormat.format("User Display Name {0}", now);
220: KapuaEid scpId = new KapuaEid(BigInteger.valueOf(scopeId));
221:
222: UserCreator uc = userFactory.newCreator(scpId, userName);
223: uc.setDisplayName(displayName);
224: uc.setEmail(userEmail);
225: uc.setPhoneNumber("+1 555 123 4567");
226: uc.setStatus(UserStatus.ENABLED);
227:
228: stepData.put(USER_CREATOR, uc);
229:
230: scenario.write("User " + userName + " created.");
231: }
232:
233: @When("^I create user$")
234: public void createUser() throws Exception {
235: stepData.remove("User");
236: User user = userService.create((UserCreator) stepData.get(USER_CREATOR));
237: stepData.put("User", user);
238: }
239:
240: @Given("^An invalid user$")
241: public void provideInvalidUserObject() {
242: User user = userFactory.newEntity(getKapuaId());
243: user.setId(getKapuaId());
244: user.setName(getKapuaId().toString());
245: stepData.put("User", user);
246: }
247:
248: @When("^I change name to \"(.*)\"$")
249: public void changeUserName(String userName) throws Exception {
250: User user = (User) stepData.get("User");
251: user.setName(userName);
252: user = userService.update(user);
253: stepData.put("User", user);
254: }
255:
256: @When("^I change user to$")
257: public void changeUserTo(List<CucUser> userList) throws Exception {
258: User user = (User) stepData.get("User");
259: try {
260: for (CucUser userItem : userList) {
261: user.setName(userItem.getName());
262: user.setDisplayName(userItem.getDisplayName());
263: user.setEmail(userItem.getEmail());
264: user.setPhoneNumber(userItem.getPhoneNumber());
265: user.setStatus(userItem.getStatus());
266: user = userService.update(user);
267: }
268: stepData.put("User", user);
269: } catch (KapuaException kapuaException) {
270: verifyException(kapuaException);
271: }
272: }
273:
274: @When("^I delete user$")
275: public void deleteUser() throws Exception {
276: try {
277: primeException();
278: User user = (User) stepData.get("User");
279: userService.delete(user.getScopeId(), user.getId());
280: } catch (KapuaException ke) {
281: verifyException(ke);
282: }
283: }
284:
285: @When("^I search for user with name \"(.*)\"$")
286: public void searchUserWithName(String userName) throws Exception {
287: stepData.remove("User");
288: primeException();
289: try {
290: User user = userService.findByName(userName);
291: stepData.put("User", user);
292: } catch (KapuaException ex) {
293: verifyException(ex);
294: }
295: }
296:
297: @When("^I search for users")
298: public void searchForUsers() throws Exception {
299: KapuaId scpId = DEFAULT_ID;
300: Set<ComparableUser> iFoundUsers;
301:
302: stepData.remove(USER_LIST);
303:
304: KapuaQuery query = userFactory.newQuery(scpId);
305: UserListResult queryResult = userService.query(query);
306: iFoundUsers = new HashSet<>();
307: List<User> users = queryResult.getItems();
308: for (User userItem : users) {
309: iFoundUsers.add(new ComparableUser(userItem));
310: }
311: stepData.put(USER_LIST, iFoundUsers);
312: }
313:
314: @Then("^I find user with name \"(.*)\"$")
315: public void findUserWithName(String userName) throws Exception {
316: UserCreator userCreator = (UserCreator) stepData.get(USER_CREATOR);
317: User user = (User) stepData.get("User");
318:
319: assertNotNull(user.getId());
320: assertNotNull(user.getId().getId());
321: assertTrue(user.getOptlock() >= 0);
322: assertNotNull(user.getScopeId());
323: assertEquals(userName, user.getName());
324: assertNotNull(user.getCreatedOn());
325: assertNotNull(user.getCreatedBy());
326: assertNotNull(user.getModifiedOn());
327: assertNotNull(user.getModifiedBy());
328: assertEquals(userCreator.getDisplayName(), user.getDisplayName());
329: assertEquals(userCreator.getEmail(), user.getEmail());
330: assertEquals(userCreator.getPhoneNumber(), user.getPhoneNumber());
331: assertEquals(UserStatus.ENABLED, user.getStatus());
332: }
333:
334: @Then("^I don't find user with name \"(.*)\"$")
335: public void dontFindUserWithName(String userName) throws Exception {
336: User user = userService.findByName(userName);
337: assertNull(user);
338: }
339:
340: @Then("^I find user$")
341: public void findUserFull(List<CucUser> userList) {
342: User user = (User) stepData.get("User");
343:
344: for (CucUser userItem : userList) {
345: matchUserData(user, userItem);
346: }
347: }
348:
349: @Then("^I find users$")
350: public void findUsersFull(List<CucUser> userList) {
351:
352: Set<ComparableUser> iFoundUsers = (Set<ComparableUser>) stepData.get(USER_LIST);
353: boolean userChecks;
354:
355: for (CucUser userItem : userList) {
356: userChecks = false;
357: for (ComparableUser foundUserItem : iFoundUsers) {
358: if (foundUserItem.getUser().getName().equals(userItem.getName())) {
359: matchUserData(foundUserItem.getUser(), userItem);
360: userChecks = true;
361: break;
362: }
363: }
364: if (!userChecks) {
365: fail(String.format(USER_NOT_FOUND, userItem.getName()));
366: }
367: }
368: }
369:
370: @Then("^I find no user$")
371: public void noUserFound() {
372:
373: assertNull(stepData.get("User"));
374: }
375:
376: @When("^I search for user with id (\\d+) in scope with id (\\d+)$")
377: public void searchUserWithIdAndScopeId(int userId, int scopeId) throws Exception {
378: KapuaEid scpId = new KapuaEid(BigInteger.valueOf(scopeId));
379: KapuaEid usrId = new KapuaEid(BigInteger.valueOf(userId));
380: stepData.remove("User");
381: User user = userService.find(scpId, usrId);
382: stepData.put("User", user);
383: }
384:
385: @When("^I search for created user by id$")
386: public void searchUserById() throws Exception {
387: User user = (User) stepData.get("User");
388: user = userService.find(user.getId(), user.getScopeId());
389: stepData.put("User", user);
390: }
391:
392: @When("^I search for created user by name$")
393: public void searchUserByName() throws Exception {
394: User user = (User) stepData.get("User");
395: user = userService.findByName(user.getName());
396: stepData.put("User", user);
397: }
398:
399: @When("^I query for users in scope with id (\\d+)$")
400: public void queryForUsers(int scopeId) throws Exception {
401: stepData.remove(USER_LIST);
402: UserQuery query = userFactory.newQuery(new KapuaEid(BigInteger.valueOf(scopeId)));
403: UserListResult queryResult = userService.query(query);
404: Set<ComparableUser> iFoundUsers = new HashSet<>();
405: for (User userItem : queryResult.getItems()) {
406: iFoundUsers.add(new ComparableUser(userItem));
407: }
408: stepData.put(USER_LIST, iFoundUsers);
409: }
410:
411: @When("^I count users in scope (\\d+)$")
412: public void countUsersInScope(int scopeId) throws Exception {
413: UserQuery query = userFactory.newQuery(new KapuaEid(BigInteger.valueOf(scopeId)));
414: stepData.remove(COUNT);
415: Long userCnt = userService.count(query);
416: stepData.put(COUNT, userCnt);
417: }
418:
419: @Then("^I count (\\d+) (?:user|users)$")
420: public void countUserCount(Long cnt) {
421: assertEquals(cnt, stepData.get(COUNT));
422: }
423:
424: @Then("^I count (\\d+) (?:user|users) as query result list$")
425: public void countUserQuery(long cnt) {
426: Set<ComparableUser> userLst = (Set<ComparableUser>) stepData.get(USER_LIST);
427: assertEquals(cnt, userLst.size());
428: }
429:
430: @Then("^I create same user$")
431: public void createSameUser() throws Exception {
432: try {
433: primeException();
434: userService.create((UserCreator) stepData.get(USER_CREATOR));
435: } catch (KapuaException ke) {
436: verifyException(ke);
437: }
438: }
439:
440: @Given("^User that doesn't exist$")
441: public void createNonexistentUser() {
442: stepData.remove("User");
443: User user = createUserInstance(3234123, 1354133);
444: stepData.put("User", user);
445: }
446:
447: @When("^I update nonexistent user$")
448: public void updateNonexistenUser() throws Exception {
449: User user = (User) stepData.get("User");
450: try {
451: primeException();
452: userService.update(user);
453: } catch (KapuaException ke) {
454: verifyException(ke);
455: }
456: }
457:
458: @When("^I delete nonexistent user$")
459: public void deleteNonexistenUser() throws Exception {
460: User user = (User) stepData.get("User");
461: try {
462: primeException();
463: userService.delete(user.getScopeId(), user.getId());
464: } catch (KapuaException ke) {
465: verifyException(ke);
466: }
467: }
468:
469: @Given("^I have the following (?:user|users)$")
470: public void haveUsers(List<CucUser> userList) throws Exception {
471:
472: Account account = (Account) stepData.get(LAST_ACCOUNT);
473: KapuaId accountId = (KapuaId) stepData.get("LastAccountId");
474: KapuaId currentAccount;
475: Set<ComparableUser> iHaveUsers = new HashSet<>();
476: User lastUser = null;
477: stepData.remove(USER_LIST);
478:
479: if (account != null) {
480: currentAccount = account.getId();
481: } else if (accountId != null) {
482: currentAccount = accountId;
483: } else {
484: currentAccount = DEFAULT_ID;
485: }
486:
487: primeException();
488: try {
489: for (CucUser userItem : userList) {
490: String name = userItem.getName();
491: String displayName = userItem.getDisplayName();
492: String email = userItem.getEmail();
493: String phone = userItem.getPhoneNumber();
494: Date expirationDate = userItem.getExpirationDate();
495: UserCreator userCreator;
496: if (expirationDate == null) {
497: userCreator = userCreatorCreator(name, displayName, email, phone, currentAccount);
498: } else {
499: userCreator = userCreatorCreator(name, displayName, email, phone, currentAccount, expirationDate);
500: }
501: User user = userService.create(userCreator);
502: iHaveUsers.add(new ComparableUser(user));
503: lastUser = user;
504: }
505: } catch (KapuaException ke) {
506: verifyException(ke);
507: }
508: stepData.put(USER_LIST, iHaveUsers);
509: stepData.put("User", lastUser);
510: }
511:
512: @When("^I retrieve metadata in scope (\\d+)$")
513: public void getMetadata(int scopeId) throws KapuaException {
514: stepData.remove(METADATA);
515: KapuaTocd metadata = userService.getConfigMetadata(getKapuaId(scopeId));
516: stepData.put(METADATA, metadata);
517: }
518:
519: @Then("^I have metadata$")
520: public void haveMetadata() {
521: KapuaTocd metadata = (KapuaTocd) stepData.get(METADATA);
522: assertNotNull("Metadata should be retrieved.", metadata);
523: }
524:
525: @Given("^I add credentials$")
526: public void givenCredentials(List<CucCredentials> credentialsList) throws Exception {
527: CucCredentials cucCredentials = credentialsList.get(0);
528: createCredentials(cucCredentials);
529: }
530:
531: @Given("^I search for last created user's credentials$")
532: public void searchForLastCreatedCredentials() throws Exception {
533: ComparableUser comparableUser = (ComparableUser) stepData.get(LAST_USER);
534: primeException();
535: try {
536: CredentialQuery credentialQuery = new CredentialQueryImpl(getCurrentScopeId());
537: credentialQuery.setPredicate(credentialQuery.attributePredicate(CredentialAttributes.USER_ID, comparableUser.getUser().getId()));
538: CredentialListResult credentials = credentialService.query(credentialQuery);
539: stepData.put("CredentialsListFound", credentials);
540: stepData.put("CredentialsCount", credentials.getSize());
541: stepData.put("CredentialFound", credentials.getFirstItem());
542: } catch (KapuaException ke) {
543: verifyException(ke);
544: }
545: }
546:
547: @Given("^I find (\\d+) credentials$")
548: public void checkCredentialsNumber(int expectedCount) throws Exception {
549: int count = (int) stepData.get("CredentialsCount");
550: assertEquals(expectedCount, count);
551: }
552:
553: @Given("^I delete the last created user's credential$")
554: public void deleteLastCreatedUsersCredentials() throws Exception {
555: Credential credential = (Credential) stepData.get("CredentialFound");
556: primeException();
557: try {
558: credentialService.delete(getCurrentScopeId(), credential.getId());
559:
560: } catch (KapuaException ke) {
561: verifyException(ke);
562: }
563: }
564:
565: @Given("^Add permissions to the last created user$")
566: public void givenPermissions(List<CucPermission> permissionList) throws Exception {
567: createPermissions(permissionList, (ComparableUser) stepData.get(LAST_USER), (Account) stepData.get(LAST_ACCOUNT));
568: }
569:
570: @Given("^Full permissions$")
571: public void givenFullPermissions() throws Exception {
572: createPermissions(null, (ComparableUser) stepData.get(LAST_USER), (Account) stepData.get(LAST_ACCOUNT));
573: }
574:
575: @Given("^I delete the last permission added to the new User$")
576: public void deletePermissionForUser() throws Exception {
577: AccessPermission accessPermission = (AccessPermission) stepData.get(LAST_FOUND_ACCESS_PERMISSION);
578: primeException();
579: try {
580: accessPermissionService.delete(accessPermission.getScopeId(), accessPermission.getId());
581: } catch (KapuaException ex) {
582: verifyException(ex);
583: }
584: }
585:
586: @Given("^I query for the last permission added to the new User$")
587: public void queryForLastAddedPermission() throws Exception {
588: Permission permission = (Permission) stepData.get(LAST_PERMISSION_ADDED_TO_USER);
589: primeException();
590: try {
591: AccessPermissionQuery query = new AccessPermissionQueryImpl(getCurrentScopeId());
592: query.setPredicate(query.attributePredicate(AccessPermissionAttributes.PERMISSION, permission));
593: AccessPermission accessPermission = accessPermissionService.query(query).getFirstItem();
594: stepData.put(LAST_FOUND_ACCESS_PERMISSION, accessPermission);
595: } catch (KapuaException ex) {
596: verifyException(ex);
597: }
598: }
599:
600: @Given("I find the last permission added to the new user$")
601: public void checkForNullLastAddedPermission() {
602: AccessPermission accessPermission = (AccessPermission) stepData.get(LAST_FOUND_ACCESS_PERMISSION);
603: assertNotNull(accessPermission);
604: }
605:
606: @Given("^User A$")
607: public void givenUserA(List<CucUser> userList) throws Exception {
608: // User is created within account that was last created in steps
609: ComparableUser tmpUser = null;
610: HashSet<ComparableUser> createdList = createUsersInList(userList, (Account) stepData.get(LAST_ACCOUNT));
611: Iterator<ComparableUser> userIterator = createdList.iterator();
612: while (userIterator.hasNext()) {
613: tmpUser = userIterator.next();
614: }
615:
616: stepData.put("UserA", tmpUser);
617: stepData.put(LAST_USER, tmpUser);
618: stepData.put("User", tmpUser.getUser());
619: }
620:
621: @Given("^User B$")
622: public void givenUserB(List<CucUser> userList) throws Exception {
623: // User is created within account that was last created in steps
624: ComparableUser tmpUser = null;
625: HashSet<ComparableUser> createdList = createUsersInList(userList, (Account) stepData.get(LAST_ACCOUNT));
626: Iterator<ComparableUser> userIterator = createdList.iterator();
627: while (userIterator.hasNext()) {
628: tmpUser = userIterator.next();
629: }
630: stepData.put("UserB", tmpUser);
631: stepData.put(LAST_USER, tmpUser);
632: stepData.put("User", tmpUser.getUser());
633: }
634:
635: @Given("^A generic user$")
636: public void givenGenericUser(List<CucUser> userList) throws Exception {
637: // User is created within account that was last created in steps
638: ComparableUser tmpUser = null;
639: HashSet<ComparableUser> createdList = createUsersInList(userList, (Account) stepData.get(LAST_ACCOUNT));
640: Iterator<ComparableUser> userIterator = createdList.iterator();
641: while (userIterator.hasNext()) {
642: tmpUser = userIterator.next();
643: }
644: stepData.put(LAST_USER, tmpUser);
645: stepData.put("LastUserId", tmpUser.getUser().getId());
646: stepData.put("User", tmpUser.getUser());
647: }
648:
649: @When("^I login as user with name \"(.*)\" and password \"(.*)\"$")
650: public void loginUser(String userName, String password) throws Exception {
651:
652: LoginCredentials credentials = credentialsFactory.newUsernamePasswordCredentials(userName, password);
653: authenticationService.logout();
654:
655: primeException();
656: try {
657: authenticationService.login(credentials);
658: } catch (KapuaException e) {
659: verifyException(e);
660: }
661: }
662:
663: @When("^I try to login as user with name \"(.*)\" with wrong password (\\d+) times$")
664: public void loginUserNTimes(String userName, int n) throws Exception {
665:
666: String password = "wrongPassword";
667: LoginCredentials credentials = credentialsFactory.newUsernamePasswordCredentials(userName, password);
668: authenticationService.logout();
669:
670: for (int i = 0; i < n; i++) {
671: primeException();
672: try {
673: authenticationService.login(credentials);
674: } catch (KapuaException e) {
675: verifyException(e);
676: }
677: }
678: }
679:
680: @Then("^I try to delete user \"(.*)\"$")
681: public void thenDeleteUser(String userName) throws Exception {
682:
683: primeException();
684: try {
685: User userToDelete = userService.findByName(userName);
686: if (userToDelete != null) {
687: userService.delete(userToDelete.getScopeId(), userToDelete.getId());
688: }
689: } catch (KapuaException e) {
690: verifyException(e);
691: }
692: }
693:
694: @Then("^I find user \"(.*)\"$")
695: public void thenIFindUser(String userName) throws Exception {
696:
697: primeException();
698: try {
699: User user = userService.findByName(userName);
700: Assert.assertNotNull("User doesn't exist.", user);
701: } catch (KapuaException e) {
702: verifyException(e);
703: }
704: }
705:
706: @Then("^I don't find user \"(.*)\"$")
707: public void thenIdontFindUser(String userName) throws Exception {
708:
709: primeException();
710: try {
711: User user = userService.findByName(userName);
712: Assert.assertNull("User still exists.", user);
713: } catch (KapuaException e) {
714: verifyException(e);
715: }
716: }
717:
718: @Given("^Move User compact id from step data \"(.*)\" to \"(.*)\"$")
719: public void moveUserCompactIdStepData(String keyFrom, String keyTo) {
720:
721: ComparableUser comparableUser = (ComparableUser) stepData.get(keyFrom);
722: stepData.put(keyTo, comparableUser.getUser().getId().toCompactId());
723: }
724:
725: @When("^I configure user service$")
726: public void setUserServiceConfig(List<CucConfig> cucConfigs)
727: throws Exception {
728: Map<String, Object> valueMap = new HashMap<>();
729: KapuaId accId;
730: KapuaId scopeId;
731: Account tmpAccount = (Account) stepData.get(LAST_ACCOUNT);
732:
733: if (tmpAccount != null) {
734: accId = tmpAccount.getId();
735: scopeId = tmpAccount.getScopeId();
736: } else {
737: accId = SYS_SCOPE_ID;
738: scopeId = SYS_SCOPE_ID;
739: }
740:
741: for (CucConfig config : cucConfigs) {
742: config.addConfigToMap(valueMap);
743: }
744:
745: primeException();
746: try {
747: userService.setConfigValues(accId, scopeId, valueMap);
748: } catch (KapuaException ex) {
749: verifyException(ex);
750: }
751: }
752:
753: @When("^I configure the user service for the account with the id (\\d+)$")
754: public void setUserServiceConfig(int accountId, List<CucConfig> cucConfigs)
755: throws Exception {
756: Map<String, Object> valueMap = new HashMap<>();
757: KapuaId accId = new KapuaEid(BigInteger.valueOf(accountId));
758: KapuaId scopeId = SYS_SCOPE_ID;
759:
760: for (CucConfig config : cucConfigs) {
761: config.addConfigToMap(valueMap);
762: }
763:
764: primeException();
765: try {
766: userService.setConfigValues(accId, scopeId, valueMap);
767: } catch (KapuaException ex) {
768: verifyException(ex);
769: }
770: }
771:
772: @When("^I configure credential service$")
773: public void setCredentialServiceConfig(List<CucConfig> cucConfigs)
774: throws Exception {
775: Map<String, Object> valueMap = new HashMap<>();
776: KapuaId accId;
777: KapuaId scopeId;
778: Account tmpAccount = (Account) stepData.get(LAST_ACCOUNT);
779:
780: if (tmpAccount != null) {
781: accId = tmpAccount.getId();
782: scopeId = tmpAccount.getScopeId();
783: } else {
784:
785: accId = SYS_SCOPE_ID;
786: scopeId = SYS_SCOPE_ID;
787: }
788:
789: for (CucConfig config : cucConfigs) {
790: config.addConfigToMap(valueMap);
791: }
792:
793: primeException();
794: try {
795: credentialService.setConfigValues(accId, scopeId, valueMap);
796: } catch (KapuaException ex) {
797: verifyException(ex);
798: }
799: }
800:
801: @Then("^I logout$")
802: public void logout() throws KapuaException {
803: authenticationService.logout();
804: }
805:
806: // *******************
807: // * Private Helpers *
808: // *******************
809:
810: /**
811: * Extract list of users form step parameter table and create those users in
812: * kapua.
813: * Operation is performed in privileged mode, without access and authorization checks.
814: *
815: * @param userList list of users in step
816: * @param account account in which users are created
817: * @return Set of created users as ComparableUser Set
818: * @throws Exception
819: */
820: private HashSet<ComparableUser> createUsersInList(List<CucUser> userList, Account account) throws Exception {
821: HashSet<ComparableUser> users = new HashSet<>();
822: KapuaSecurityUtils.doPrivileged(() -> {
823: primeException();
824: try {
825: for (CucUser userItem : userList) {
826: String name = userItem.getName();
827: String displayName = userItem.getDisplayName();
828: String email = userItem.getEmail();
829: String phone = userItem.getPhoneNumber();
830: KapuaEid scopeId = (KapuaEid) account.getId();
831: Date expirationDate = userItem.getExpirationDate();
832:
833: UserCreator userCreator = userCreatorCreator(name, displayName, email, phone, scopeId, expirationDate);
834: User user = userService.create(userCreator);
835: users.add(new ComparableUser(user));
836: }
837: } catch (KapuaException ke) {
838: verifyException(ke);
839: }
840:
841: return null;
842: });
843:
844: return users;
845: }
846:
847: /**
848: * Create User object with user data filed with quasi random data for user name,
849: * email, display name. Scope id and user id is set to test wide id.
850: *
851: * @param userId unique user id
852: * @param scopeId user scope id
853: * @return User instance
854: */
855: private User createUserInstance(int userId, int scopeId) {
856: long now = (new Date()).getTime();
857: String username = MessageFormat.format("aaa_test_username_{0,number,#}", now);
858: String userEmail = MessageFormat.format("testuser_{0,number,#}@organization.com", now);
859: String displayName = MessageFormat.format("User Display Name {0}", now);
860: KapuaEid usrId = new KapuaEid(BigInteger.valueOf(userId));
861: KapuaEid scpId = new KapuaEid(BigInteger.valueOf(scopeId));
862:
863: User user = userFactory.newEntity(scpId);
864: user.setId(usrId);
865: user.setName(username);
866: user.setDisplayName(displayName);
867: user.setEmail(userEmail);
868:
869: return user;
870: }
871:
872: /**
873: * Create userCreator instance with full data about user.
874: *
875: * @return UserCreator instance for creating user
876: */
877: private UserCreator userCreatorCreator(String name, String displayName, String email, String phone, KapuaId scopeId) {
878: UserCreator userCreator = userFactory.newCreator(scopeId, name);
879:
880: userCreator.setName(name);
881: userCreator.setDisplayName(displayName);
882: userCreator.setEmail(email);
883: userCreator.setPhoneNumber(phone);
884:
885: return userCreator;
886: }
887:
888: private UserCreator userCreatorCreator(String name, String displayName, String email, String phone, KapuaId scopeId, Date expirationDate) {
889: UserCreator userCreator = userCreatorCreator(name, displayName, email, phone, scopeId);
890: userCreator.setExpirationDate(expirationDate);
891:
892: return userCreator;
893: }
894:
895: /**
896: * Create credentials for specific user, set users password.
897: * It finds user by name and sets its password.
898: *
899: * @param cucCredentials username and open password
900: * @return created credential
901: */
902: private Credential createCredentials(CucCredentials cucCredentials) throws Exception {
903: List<Credential> credentialList = new ArrayList<>();
904: primeException();
905: try {
906: User user = userService.findByName(cucCredentials.getName());
907: Credential credential = credentialService.create(credentialCreatorCreator(user.getScopeId(),
908: user.getId(), cucCredentials.getPassword(),
909: cucCredentials.getStatus(), cucCredentials.getExpirationDate()));
910: credentialList.add(credential);
911: } catch (KapuaException ke) {
912: verifyException(ke);
913: }
914:
915: return credentialList.size() == 1 ? credentialList.get(0) : null;
916: }
917:
918: /**
919: * Create credential creator for user with password.
920: *
921: * @param scopeId scopeId in which user is
922: * @param userId userId for which credetntials are set
923: * @param password open password as credetntials
924: * @param status status of credentials enabled or disabled
925: * @param expirationDate credential expiration date
926: * @return credential creator used for creating credentials
927: */
928: private CredentialCreator credentialCreatorCreator(KapuaId scopeId, KapuaId userId, String password, CredentialStatus status, Date expirationDate) {
929: CredentialCreator credentialCreator;
930:
931: credentialCreator = credentialFactory.newCreator(scopeId, userId, CredentialType.PASSWORD, password, status, expirationDate);
932:
933: return credentialCreator;
934: }
935:
936: /**
937: * Creates permissions for user with specified account. Permissions are created in priveledged mode.
938: *
939: * @param permissionList list of permissions for user, if targetScopeId is not set user scope that is
940: * specifed as account
941: * @param user user for whom permissions are set
942: * @param account account in which user is defined
943: * @throws Exception
944: */
945: private void createPermissions(List<CucPermission> permissionList, ComparableUser user, Account account)
946: throws Exception {
947:
948: KapuaSecurityUtils.doPrivileged(() -> {
949: primeException();
950: try {
951: accessInfoService.create(accessInfoCreatorCreator(permissionList, user, account));
952: } catch (KapuaException ke) {
953: verifyException(ke);
954: }
955:
956: return null;
957: });
958:
959: return;
960: }
961:
962: /**
963: * Create accessInfoCreator instance with data about user permissions.
964: * If target scope is not defined in permission list use account scope.
965: *
966: * @param permissionList list of all permissions
967: * @param user user for which permissions are set
968: * @param account that user belongs to
969: * @return AccessInfoCreator instance for creating user permissions
970: */
971: private AccessInfoCreator accessInfoCreatorCreator(List<CucPermission> permissionList, ComparableUser user, Account account) throws KapuaException {
972:
973: AccessInfoCreator accessInfoCreator = accessInfoFactory.newCreator(account.getId());
974: accessInfoCreator.setUserId(user.getUser().getId());
975: accessInfoCreator.setScopeId(user.getUser().getScopeId());
976: Set<Permission> permissions = new HashSet<>();
977: if (permissionList != null) {
978: for (CucPermission cucPermission : permissionList) {
979: stepData.remove(LAST_PERMISSION_ADDED_TO_USER);
980: Actions action = cucPermission.getAction();
981: KapuaEid targetScopeId = cucPermission.getTargetScopeId();
982: if (targetScopeId == null) {
983: targetScopeId = (KapuaEid) account.getId();
984: }
985: Domain domain = domainRegistryService.findByName(cucPermission.getDomain()).getDomain();
986: Permission permission = permissionFactory.newPermission(domain,
987: action, targetScopeId);
988: permissions.add(permission);
989: stepData.put(LAST_PERMISSION_ADDED_TO_USER, permission);
990: }
991: } else {
992: Permission permission = permissionFactory.newPermission(null, null, null);
993: permissions.add(permission);
994: }
995: accessInfoCreator.setPermissions(permissions);
996:
997: return accessInfoCreator;
998: }
999:
1000: private boolean matchUserData(User user, CucUser cucUser) {
1001: assertNotNull(user.getId());
1002: assertNotNull(user.getScopeId());
1003: if ((cucUser.getName() != null) && (cucUser.getName().length() > 0)) {
1004: assertEquals(cucUser.getName(), user.getName());
1005: }
1006: assertNotNull(user.getCreatedOn());
1007: assertNotNull(user.getCreatedBy());
1008: assertNotNull(user.getModifiedOn());
1009: assertNotNull(user.getModifiedBy());
1010: if ((cucUser.getDisplayName() != null) && (cucUser.getDisplayName().length() > 0)) {
1011: assertEquals(cucUser.getDisplayName(), user.getDisplayName());
1012: }
1013: if ((cucUser.getEmail() != null) && (cucUser.getEmail().length() > 0)) {
1014: assertEquals(cucUser.getEmail(), user.getEmail());
1015: }
1016: if ((cucUser.getPhoneNumber() != null) && (cucUser.getPhoneNumber().length() > 0)) {
1017: assertEquals(cucUser.getPhoneNumber(), user.getPhoneNumber());
1018: }
1019: if (cucUser.getStatus() != null) {
1020: assertEquals(cucUser.getStatus(), user.getStatus());
1021: }
1022: return true;
1023: }
1024:
1025: @And("^I create user with name \"([^\"]*)\"$")
1026: public void iCreateUserWithName(String userName) throws Exception {
1027: stepData.remove(USER_CREATOR);
1028: UserCreator userCreator = userFactory.newCreator(getCurrentScopeId());
1029: userCreator.setName(userName);
1030: stepData.put(USER_CREATOR, userCreator);
1031:
1032: try {
1033: primeException();
1034: stepData.remove("User");
1035: User user = userService.create(userCreator);
1036: stepData.put("User", user);
1037: } catch (KapuaException ex) {
1038: verifyException(ex);
1039: }
1040: }
1041:
1042: @Then("^I try to edit user to name \"([^\"]*)\"$")
1043: public void iTryToEditUserWithName(String newUserName) throws Exception {
1044: User user = (User) stepData.get("User");
1045: user.setName(newUserName);
1046:
1047: try {
1048: primeException();
1049: stepData.remove("User");
1050: User newUser = userService.update(user);
1051: stepData.put("User", newUser);
1052: } catch (KapuaException ex) {
1053: verifyException(ex);
1054: }
1055: }
1056:
1057: @And("^I create user with name \"([^\"]*)\" in account \"([^\"]*)\"$")
1058: public void iCreateUserWithNameInSubaccount(String name, String accountName) throws Exception {
1059: Account account = (Account) stepData.get(LAST_ACCOUNT);
1060: assertEquals(accountName, account.getName());
1061:
1062: UserCreator userCreator = userFactory.newCreator(account.getId());
1063: userCreator.setName(name);
1064: primeException();
1065: try {
1066: stepData.remove(USER_CREATOR);
1067: User childAccountUser = userService.create(userCreator);
1068: stepData.put(USER_CREATOR, userCreator);
1069: stepData.put("ChildAccountUser", childAccountUser);
1070: } catch (KapuaException ex) {
1071: verifyException(ex);
1072: }
1073: }
1074:
1075: @And("^I create users with following names$")
1076: public void iCreateUsersWithFollowingNames(List<CucUser> tmpUsers) throws Exception {
1077: UserCreator userCreator = userFactory.newCreator(getCurrentScopeId());
1078: ArrayList<User> userList = new ArrayList<>();
1079:
1080: for (CucUser tmpUser : tmpUsers) {
1081: userCreator.setName(tmpUser.getName());
1082: User user = userService.create(userCreator);
1083: userList.add(user);
1084: }
1085: stepData.put(USER_LIST, userList);
1086: }
1087:
1088: @Given("^I have the following user with expiration date in the future$")
1089: public void iHaveTheFollowingUserWithExpirationDateInTheFuture(List<CucUser> userList) throws Exception {
1090: Account account = (Account) stepData.get(LAST_ACCOUNT);
1091: KapuaId accountId = (KapuaId) stepData.get("LastAccountId");
1092: KapuaId currentAccount;
1093: Set<ComparableUser> iHaveUsers = new HashSet<>();
1094: User lastUser = null;
1095: stepData.remove(USER_LIST);
1096:
1097: if (account != null) {
1098: currentAccount = account.getId();
1099: } else if (accountId != null) {
1100: currentAccount = accountId;
1101: } else {
1102: currentAccount = DEFAULT_ID;
1103: }
1104:
1105: primeException();
1106: try {
1107: for (CucUser userItem : userList) {
1108: String name = userItem.getName();
1109: String displayName = userItem.getDisplayName();
1110: String email = userItem.getEmail();
1111: String phone = userItem.getPhoneNumber();
1112: Date expirationDate = userItem.getExpirationDate();
1113: UserCreator userCreator = userCreatorCreator(name, displayName, email, phone, currentAccount, expirationDate);
1114: User user = userService.create(userCreator);
1115: iHaveUsers.add(new ComparableUser(user));
1116: lastUser = user;
1117: }
1118: } catch (KapuaException ke) {
1119: verifyException(ke);
1120: }
1121: stepData.put(USER_LIST, iHaveUsers);
1122: stepData.put("User", lastUser);
1123: }
1124:
1125: @And("^I find user with expiration date in the future$")
1126: public void iFindUserWithExpirationDateInTheFuture(List<CucUser> userList) {
1127: Set<ComparableUser> iFoundUsers = (Set<ComparableUser>) stepData.get(USER_LIST);
1128: boolean userChecks;
1129:
1130: for (CucUser userItem : userList) {
1131: userChecks = false;
1132: for (ComparableUser foundUserItem : iFoundUsers) {
1133: Date t1 = foundUserItem.getUser().getExpirationDate();
1134: Date t2 = userItem.getExpirationDate();
1135:
1136: LocalDate localDate1 = t1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
1137: LocalDate localDate2 = t2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
1138:
1139: if (localDate1.getYear() == localDate2.getYear() && localDate1.getMonthValue() == localDate2.getMonthValue()
1140: && localDate1.getDayOfMonth() == localDate2.getDayOfMonth()) {
1141: matchUserData(foundUserItem.getUser(), userItem);
1142: userChecks = true;
1143: break;
1144: }
1145: }
1146: if (!userChecks) {
1147: fail(String.format(USER_NOT_FOUND, userItem.getExpirationDate()));
1148: }
1149: }
1150: }
1151:
1152: @Then("^I search for the user with expiration date in the present$")
1153: public void iSearchForTheUserWithExpirationDateInThePresent() throws KapuaException {
1154: KapuaId scpId = DEFAULT_ID;
1155: Set<ComparableUser> iFoundUsers;
1156:
1157: stepData.remove(USER_LIST);
1158: KapuaQuery query = userFactory.newQuery(scpId);
1159:
1160: UserListResult queryResult = userService.query(query);
1161: iFoundUsers = new HashSet<>();
1162: List<User> users = queryResult.getItems();
1163: for (User userItems : users){
1164: iFoundUsers.add(new ComparableUser(userItems));
1165: }
1166: stepData.put(USER_LIST, iFoundUsers);
1167:
1168: }
1169:
1170: @And("^I find user with expiration date in the present$")
1171: public void iFindUserWithExpirationDateInThePresent(List<CucUser> userList) {
1172: Set<ComparableUser> iFoundUsers = (Set<ComparableUser>) stepData.get(USER_LIST);
1173: boolean userChecks;
1174:
1175: for (CucUser userItem : userList) {
1176: userChecks = false;
1177: for (ComparableUser foundUserItem : iFoundUsers) {
1178: Date t1 = foundUserItem.getUser().getExpirationDate();
1179: Date t2 = userItem.getExpirationDate();
1180:
1181: LocalDate localDate1 = t1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
1182: LocalDate localDate2 = t2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
1183: if (localDate1.getYear() == localDate2.getYear() && localDate1.getMonthValue() == localDate2.getMonthValue()
1184: && localDate1.getDayOfMonth() == localDate2.getDayOfMonth()) {
1185: matchUserData(foundUserItem.getUser(), userItem);
1186: userChecks = true;
1187: break;
1188: }
1189: }
1190: if (!userChecks) {
1191: fail(String.format(USER_NOT_FOUND, userItem.getExpirationDate()));
1192: }
1193: }
1194: }
1195:
1196: @Then("^I search for the user with expiration date in the past$")
1197: public void iSearchForTheUserWithExpirationDateInThePast() throws KapuaException {
1198: KapuaId scpId = DEFAULT_ID;
1199: Set<ComparableUser> iFoundUsers;
1200:
1201: stepData.remove(USER_LIST);
1202: KapuaQuery query = userFactory.newQuery(scpId);
1203: UserListResult queryResult = userService.query(query);
1204: iFoundUsers = new HashSet<>();
1205: List<User> users = queryResult.getItems();
1206: for (User userItems : users){
1207: iFoundUsers.add(new ComparableUser(userItems));
1208: }
1209: stepData.put(USER_LIST, iFoundUsers);
1210: }
1211:
1212: @And("^I find user with expiration date in the past$")
1213: public void iFindUserWithExpirationDateInThePast(List<CucUser> userList) {
1214: Set<ComparableUser> iFoundUsers = (Set<ComparableUser>) stepData.get(USER_LIST);
1215: boolean userChecks;
1216:
1217: for (CucUser userItem : userList) {
1218: userChecks = false;
1219: for (ComparableUser foundUserItem : iFoundUsers) {
1220: Date t1 = foundUserItem.getUser().getExpirationDate();
1221: Date t2 = userItem.getExpirationDate();
1222:
1223: LocalDate localDate1 = t1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
1224: LocalDate localDate2 = t2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
1225: if (localDate1.getYear() == localDate2.getYear() && localDate1.getMonthValue() == localDate2.getMonthValue()
1226: && localDate1.getDayOfMonth() == localDate2.getDayOfMonth()) {
1227: matchUserData(foundUserItem.getUser(), userItem);
1228: userChecks = true;
1229: break;
1230: }
1231: }
1232: if (!userChecks) {
1233: fail(String.format(USER_NOT_FOUND, userItem.getExpirationDate()));
1234: }
1235: }
1236: }
1237:
1238: @And("^I find users with phone number \"([^\"]*)\"$")
1239: public void iFindUsersWithPhoneNumber(String phoneNumber) {
1240:
1241: UserListResult users = (UserListResult) stepData.get(FOUND_USERS);
1242: for (User user : users.getItems()){
1243: assertEquals(user.getPhoneNumber(),(phoneNumber));
1244: }
1245: stepData.put(USER_LIST, users);
1246:
1247: }
1248:
1249: @Then("^I find users with emails$")
1250: public void iFindUsersWithEmails(List<CucUser> userList) {
1251: Set<ComparableUser> iFoundUsers = (Set<ComparableUser>) stepData.get(USER_LIST);
1252: boolean userChecks;
1253:
1254: for (CucUser userItem : userList) {
1255: userChecks = false;
1256: for (ComparableUser foundUserItem : iFoundUsers) {
1257: if (foundUserItem.getUser().getEmail().equals(userItem.getEmail())) {
1258: matchUserData(foundUserItem.getUser(), userItem);
1259: userChecks = true;
1260: break;
1261: }
1262: }
1263: if (!userChecks) {
1264: fail(String.format(USER_NOT_FOUND, userItem.getEmail()));
1265: }
1266: }
1267: }
1268:
1269: @Then("^I find users with email$")
1270: public void iFindUsersWithTheSameEmailAddress(List<CucUser> userList) {
1271: Set<ComparableUser> iFoundUsers = (Set<ComparableUser>) stepData.get(USER_LIST);
1272: boolean userChecks;
1273:
1274: for (CucUser userItem : userList) {
1275: userChecks = false;
1276: for (ComparableUser foundUserItem : iFoundUsers) {
1277: if (foundUserItem.getUser().getEmail().equals(userItem.getEmail())) {
1278: matchUserData(foundUserItem.getUser(), userItem);
1279: userChecks = true;
1280: break;
1281: }
1282: }
1283: if (!userChecks) {
1284: fail(String.format(USER_NOT_FOUND, userItem.getName()));
1285: }
1286: }
1287: }
1288:
1289: @Then("^I find users with phone number$")
1290: public void iFindUsersWithPhoneNumber(List<CucUser> userList) {
1291: Set<ComparableUser> iFoundUsers = (Set<ComparableUser>) stepData.get(USER_LIST);
1292: boolean userChecks;
1293:
1294: for (CucUser userItem : userList) {
1295: userChecks = false;
1296: for (ComparableUser foundUserItem : iFoundUsers) {
1297: if (foundUserItem.getUser().getPhoneNumber().equals(userItem.getPhoneNumber())) {
1298: matchUserData(foundUserItem.getUser(), userItem);
1299: userChecks = true;
1300: break;
1301: }
1302: }
1303: if (!userChecks) {
1304: fail(String.format(USER_NOT_FOUND, userItem.getName()));
1305: }
1306: }
1307: }
1308:
1309: @And("^I search users with phone number \"([^\"]*)\"$")
1310: public void iSearchUsersWithPhoneNumber(String phoneNum) throws Throwable {
1311: UserQuery userQuery = userFactory.newQuery(DEFAULT_ID);
1312: userQuery.setPredicate(userQuery.attributePredicate(UserAttributes.PHONE_NUMBER, phoneNum, AttributePredicate.Operator.EQUAL));
1313: UserListResult userListResult = userService.query(userQuery);
1314: stepData.put(FOUND_USERS, userListResult);
1315: }
1316:
1317: @And("^I search users with email \"([^\"]*)\"$")
1318: public void iSearchForUsersWithEmail(String email) throws Throwable {
1319: UserQuery userQuery = userFactory.newQuery(DEFAULT_ID);
1320: userQuery.setPredicate(userQuery.attributePredicate(UserAttributes.EMAIL, email, AttributePredicate.Operator.EQUAL));
1321: UserListResult userListResult = userService.query(userQuery);
1322: stepData.put(FOUND_USERS, userListResult);
1323: }
1324:
1325: @Then("^I find users with email \"([^\"]*)\"$")
1326: public void iFindUsersWithEmail(String email) {
1327: UserListResult users = (UserListResult) stepData.get(FOUND_USERS);
1328: for (User user : users.getItems()){
1329: assertEquals(user.getEmail(), (email));
1330: }
1331: stepData.put(USER_LIST, users);
1332: }
1333:
1334: @And("^I enable mfa$")
1335: public void iEnableMfa() {
1336: KapuaId userId = KapuaSecurityUtils.getSession().getUserId();
1337: KapuaId scopeId = KapuaSecurityUtils.getSession().getScopeId();
1338:
1339: MfaOptionFactory mfaFactory = locator.getFactory(MfaOptionFactoryImpl.class);
1340: MfaOptionCreator mfaCreator = mfaFactory.newCreator(scopeId, userId, "mfaSecretKey");
1341: MfaOptionService mfaOptionService = locator.getService(MfaOptionServiceImpl.class);
1342: try {
1343: mfaOptionService.create(mfaCreator);
1344: } catch (KapuaException e) {
1345: e.printStackTrace();
1346: }
1347: }
1348:
1349: @Then("^I have mfa enable$")
1350: public void iHaveMfaIsEnable() {
1351: KapuaId userId = KapuaSecurityUtils.getSession().getUserId();
1352: KapuaId scopeId = KapuaSecurityUtils.getSession().getScopeId();
1353:
1354: MfaOptionService mfaOptionService = locator.getService(MfaOptionServiceImpl.class);
1355: MfaOption mfaOption = null;
1356: try {
1357: mfaOption = mfaOptionService.findByUserId(scopeId, userId);
1358: } catch (KapuaException e) {
1359: e.printStackTrace();
1360: }
1361: assertNotNull(mfaOption);
1362: }
1363:
1364: @Then("^The lockout error counter for user \"([^\"]*)\" is (\\d+)$")
1365: public void theLockoutErrorCounterForUserIs(String username, int expectedCounter) {
1366: KapuaId userIdTmp = null;
1367: KapuaId scopeIdTmp = null;
1368: try {
1369: userIdTmp = KapuaSecurityUtils.doPrivileged(new Callable<KapuaId>() {
1370: @Override
1371: public KapuaId call() throws Exception {
1372: return userService.findByName(username).getId();
1373: }
1374: });
1375: scopeIdTmp = KapuaSecurityUtils.doPrivileged(new Callable<KapuaId>() {
1376: @Override
1377: public KapuaId call() throws Exception {
1378: return userService.findByName(username).getScopeId();
1379: }
1380: });
1381: } catch (KapuaException e) {
1382: e.printStackTrace();
1383: }
1384:
1385: Credential credential = null;
1386: final KapuaId userId = userIdTmp;
1387: final KapuaId scopeId = scopeIdTmp;
1388: try {
1389: credential = KapuaSecurityUtils.doPrivileged(new Callable<Credential>() {
1390: @Override
1391: public Credential call() throws Exception {
1392: return credentialService.findByUserId(scopeId, userId).getFirstItem();
1393: }
1394: });
1395: } catch (KapuaException e) {
1396: e.printStackTrace();
1397: }
1398:
1399: assertEquals(expectedCounter, credential.getLoginFailures());
1400: }
1401:
1402: // *****************
1403: // * Inner Classes *
1404: // *****************
1405: private class ComparableUser {
1406:
1407: private User user;
1408:
1409: ComparableUser(User user) {
1410: this.user = user;
1411: }
1412:
1413: public User getUser() {
1414: return user;
1415: }
1416:
1417: @Override
1418: public int hashCode() {
1419: return 1;
1420: }
1421:
1422: @Override
1423: public boolean equals(Object obj) {
1424: if (obj instanceof ComparableUser) {
1425: ComparableUser other = (ComparableUser) obj;
1426: return compareAllUserAtt(user, other.getUser());
1427: } else {
1428: return false;
1429: }
1430: }
1431:
1432: private boolean compareAllUserAtt(User thisUser, User otherUser) {
1433: return thisUser.getName().equals(otherUser.getName()) &&
1434: thisUser.getDisplayName().equals(otherUser.getDisplayName()) &&
1435: thisUser.getEmail().equals(otherUser.getEmail()) &&
1436: thisUser.getPhoneNumber().equals(otherUser.getPhoneNumber()) &&
1437: thisUser.getStatus().equals(otherUser.getStatus());
1438: }
1439: }
1440: }