7b5431437c836b7853ae6dc9f850f150a165465e
[platform/core/security/suspicious-activity-monitor.git] / servers / dsm / src / test / java / com / samsung / dsm / controller / AdminControllerTest.java
1 /*
2  * In Samsung Ukraine R&D Center (SRK under a contract between)
3  * LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
4  * Copyright (C) 2017 Samsung Electronics Co., Ltd. All rights reserved.
5  */
6 package com.samsung.dsm.controller;
7
8 import static org.hamcrest.Matchers.hasSize;
9 import static org.junit.Assert.assertEquals;
10 import static org.junit.Assert.assertFalse;
11 import static org.junit.Assert.assertNotEquals;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertNull;
14 import static org.junit.Assert.assertTrue;
15 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
16 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
17 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
18 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
19 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
20 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
21
22 import java.util.Date;
23
24 import org.junit.Before;
25 import org.junit.Test;
26 import org.junit.runner.RunWith;
27 import org.mockito.Mockito;
28 import org.springframework.beans.factory.annotation.Autowired;
29 import org.springframework.http.MediaType;
30 import org.springframework.security.core.Authentication;
31 import org.springframework.security.core.context.SecurityContext;
32 import org.springframework.security.core.context.SecurityContextHolder;
33 import org.springframework.security.core.userdetails.UserDetails;
34 import org.springframework.test.context.ContextConfiguration;
35 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
36 import org.springframework.test.context.web.WebAppConfiguration;
37 import org.springframework.test.web.servlet.MockMvc;
38 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
39 import org.springframework.web.context.WebApplicationContext;
40
41 import com.google.gson.Gson;
42 import com.samsung.commons.domain.CustomUserDetails;
43 import com.samsung.commons.domain.Role;
44 import com.samsung.commons.domain.User;
45 import com.samsung.commons.repository.UserRepository;
46 import com.samsung.commons.service.RoleService;
47 import com.samsung.commons.service.UserDetailsService;
48 import com.samsung.commons.service.UserService;
49 import com.samsung.commons.utils.TestUtils;
50 import com.samsung.dsm.security.authentication.PasswordEncoder;
51
52 /**
53  * The type Admin controller test.
54  */
55 @RunWith(SpringJUnit4ClassRunner.class)
56 @ContextConfiguration(locations = { "classpath:root-context.xml" })
57 @WebAppConfiguration
58 @SuppressWarnings("PMD.AvoidDuplicateLiterals")
59 public class AdminControllerTest {
60
61     private static final int HTTP_TEMP_MOVED_STATUS = 302;
62
63     private static final int SIZE = 3;
64
65     private static final String PASSWORD = "123456";
66
67     private static final String USER_NAME = "user";
68
69     private static final String ROLE_ID_FIELD = "roleId";
70
71     private static final String EMAIL_FIELD = "email";
72
73     private static final String NAME_FIELD = "name";
74
75     private static final String REPEAT_PASSWORD_FIELD = "repeatPassword";
76
77     private static final String PASSWORD_FIELD = "password";
78
79     private static final String ID_FIELD = "id";
80
81     private static final String ADMIN_NAME = "admin";
82
83     private static final String USERS = "users";
84
85     private static final String USER_MAIL = "user@mail";
86
87     private static final String ADMIN_MAIL = "admin@mail";
88
89     private MockMvc mockMvc;
90
91     @Autowired
92     private TestUtils testUtils;
93
94     @Autowired
95     private PasswordEncoder passEncoder;
96
97     @Autowired
98     private UserService userService;
99
100     @Autowired
101     private UserDetailsService userDetailsService;
102
103     @Autowired
104     private RoleService roleService;
105
106     @Autowired
107     private UserRepository userRepository;
108
109     @Autowired
110     private WebApplicationContext webApplicationContext;
111
112     private Role userRole;
113     private Role adminRole;
114     private static final String selfEmail = "self@mail";
115     private static final String selfPass = "selfpass";
116
117     /**
118      * Sets up.
119      */
120     @Before
121     public void setUp() {
122         adminRole = roleService.getByName(Role.Type.ADMIN.toString());
123         userRole = roleService.getByName(Role.Type.USER.toString());
124
125         UserDetails useDetails = Mockito.mock(UserDetails.class);
126         Authentication authentication = Mockito.mock(Authentication.class);
127         SecurityContext securityContext = Mockito.mock(SecurityContext.class);
128         Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
129         Mockito.when(authentication.getPrincipal()).thenReturn(useDetails);
130         Mockito.when(useDetails.getUsername()).thenReturn(selfEmail);
131         Mockito.when(useDetails.getPassword()).thenReturn(selfPass);
132         SecurityContextHolder.setContext(securityContext);
133         mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
134     }
135
136     /**
137      * Admin test.
138      *
139      * @throws Exception the exception
140      */
141     @Test
142     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
143     public void adminTest() throws Exception {
144         mockMvc.perform(get("/admin")).andExpect(status().is(HTTP_TEMP_MOVED_STATUS)).andExpect(view().name("redirect:/dashboard"));
145     }
146
147     /**
148      * Users test.
149      *
150      * @throws Exception the exception
151      */
152     @Test
153     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
154     public void usersTest() throws Exception {
155         User user1 = new User(ADMIN_NAME, ADMIN_MAIL, false, new Date(), adminRole);
156         User user2 = new User(USER_NAME, USER_MAIL, false, new Date(), userRole);
157         userService.save(user1);
158         userService.save(user2);
159         mockMvc.perform(get("/admin/users/")).andExpect(status().isOk()).andExpect(view().name(USERS))
160                 .andExpect(forwardedUrl(USERS)).andExpect(model().attribute(USERS, hasSize(SIZE)))
161                 .andExpect(model().attribute("roles", hasSize(2)));
162
163         userService.remove(user1);
164         userService.remove(user2);
165     }
166
167     /**
168      * Gets user test.
169      *
170      * @throws Exception the exception
171      */
172     @Test
173     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
174     public void getUserTest() throws Exception {
175         User user = new User(ADMIN_NAME, ADMIN_MAIL, false, new Date(), adminRole);
176         user = userService.save(user);
177         String response = mockMvc.perform(get("/admin/users/get/{id}", user.getId())).andExpect(status().isOk())
178                 .andExpect(forwardedUrl(null)).andReturn().getResponse().getContentAsString();
179
180         Gson gson = new Gson();
181         assertEquals(gson.toJson(user), response);
182         userService.remove(user);
183     }
184
185     /**
186      * New user negative test. - Wrong request - Email is occupied
187      *
188      * @throws Exception the exception
189      */
190     @Test
191     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
192     public void newUserNegativeTest() throws Exception {
193         String response = mockMvc.perform(post("/admin/users/new")).andReturn().getResponse().getContentAsString();
194
195         assertNotEquals("", response);
196
197         String email = USER_MAIL;
198         User user = new User(USER_NAME, email, false, new Date(), userRole);
199         user = userService.save(user);
200
201         response = mockMvc
202                 .perform(post("/admin/users/new").contentType(MediaType.APPLICATION_FORM_URLENCODED)
203                         .param(NAME_FIELD, "testName").param(EMAIL_FIELD, email)
204                         .param(ROLE_ID_FIELD, userRole.getId().toString()).param(PASSWORD_FIELD, PASSWORD)
205                         .param(REPEAT_PASSWORD_FIELD, PASSWORD))
206                 .andExpect(status().isOk()).andExpect(forwardedUrl(null)).andReturn().getResponse()
207                 .getContentAsString();
208
209         assertNotEquals("", response);
210         userService.remove(user);
211     }
212
213     /**
214      * New user test.
215      *
216      * @throws Exception the exception
217      */
218     @Test
219     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
220     public void newUserTest() throws Exception {
221         String email = "test@mail";
222         String response = mockMvc
223                 .perform(post("/admin/users/new").contentType(MediaType.APPLICATION_FORM_URLENCODED)
224                         .param(NAME_FIELD, "testName").param(EMAIL_FIELD, email)
225                         .param(ROLE_ID_FIELD, userRole.getId().toString()).param(PASSWORD_FIELD, PASSWORD)
226                         .param(REPEAT_PASSWORD_FIELD, PASSWORD))
227                 .andExpect(status().isOk()).andExpect(forwardedUrl(null)).andReturn().getResponse()
228                 .getContentAsString();
229
230         assertEquals("", response);
231         User user = userService.getUserByEmail(email);
232         CustomUserDetails details = userDetailsService.findByUserId(user.getId());
233         assertNotNull(user);
234         userDetailsService.remove(details);
235         userService.remove(user);
236     }
237
238     /**
239      * Edits the user negative test. - Wrong request
240      *
241      * @throws Exception the exception
242      */
243     @Test
244     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
245     public void editUserNegativeTest() throws Exception {
246         String response = mockMvc.perform(post("/admin/users/edit")).andExpect(status().isOk()).andReturn()
247                 .getResponse().getContentAsString();
248
249         assertNotNull(response);
250         assertNotEquals("", response);
251     }
252
253     /**
254      * Edit user test.
255      *
256      * @throws Exception the exception
257      */
258     @Test
259     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
260     public void editUserTest() throws Exception {
261         User user = testUtils.createAndSaveUser();
262
263         String newName = "new" + user.getUsername();
264         String newEmail = "new" + user.getEmail();
265         String response = mockMvc
266                 .perform(post("/admin/users/edit").contentType(MediaType.APPLICATION_FORM_URLENCODED)
267                         .param(ID_FIELD, user.getId().toString()).param(NAME_FIELD, newName)
268                         .param(EMAIL_FIELD, newEmail).param(ROLE_ID_FIELD, userRole.getId().toString()))
269                 .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
270
271         assertEquals("", response);
272         User updatedUser = userService.findById(user.getId());
273         assertEquals(newName, updatedUser.getUsername());
274         assertEquals(newEmail, updatedUser.getEmail());
275         userService.remove(updatedUser);
276     }
277
278     /**
279      * Edit user wrong user id test.
280      *
281      * @throws Exception the exception
282      */
283     @Test
284     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
285     public void editUserWrongUserIdTest() throws Exception {
286         String response = mockMvc
287                 .perform(post("/admin/users/edit").contentType(MediaType.APPLICATION_FORM_URLENCODED)
288                         .param(ID_FIELD, "42").param(NAME_FIELD, "newName").param(EMAIL_FIELD, "newEmail@example.com")
289                         .param(ROLE_ID_FIELD, "0"))
290                 .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
291
292         assertEquals("{\"edit\":\"Something went wrong during editing.\"}", response);
293     }
294
295     /**
296      * Reset password negative test. - Wrong request - Passwords don't match
297      *
298      * @throws Exception the exception
299      */
300     @Test
301     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
302     public void resetPasswordNegativeTest() throws Exception {
303         String res = mockMvc.perform(post("/admin/users/reset_pass")).andExpect(status().isOk()).andReturn()
304                 .getResponse().getContentAsString();
305
306         assertNotEquals("", res);
307
308         String oldPass = "121212";
309         String newPass = "222222";
310         String repNewPass = "222221";
311         User user = new User(USER_NAME, USER_MAIL, false, new Date(), userRole);
312         user = userService.save(user);
313         userDetailsService.save(new CustomUserDetails(oldPass, "link", user));
314
315         res = mockMvc
316                 .perform(post("/admin/users/reset_pass").contentType(MediaType.APPLICATION_FORM_URLENCODED)
317                         .param(ID_FIELD, user.getId().toString()).param(PASSWORD_FIELD, newPass)
318                         .param(REPEAT_PASSWORD_FIELD, repNewPass))
319                 .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
320
321         assertNotEquals("", res);
322         assertFalse(passEncoder.isValid(userDetailsService.findByUserId(user.getId()).getPassword(), newPass));
323         userService.remove(user);
324     }
325
326     /**
327      * Reset password test.
328      *
329      * @throws Exception the exception
330      */
331     @Test
332     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
333     public void resetPasswordTest() throws Exception {
334         String oldPass = "111111";
335         String newPass = "222222";
336         String repNewPass = "222222";
337         User user = new User(USER_NAME, USER_MAIL, false, new Date(), userRole);
338         user = userService.save(user);
339         userDetailsService.save(new CustomUserDetails(oldPass, "link", user));
340
341         String res = mockMvc
342                 .perform(post("/admin/users/reset_pass").contentType(MediaType.APPLICATION_FORM_URLENCODED)
343                         .param(ID_FIELD, user.getId().toString()).param(PASSWORD_FIELD, newPass)
344                         .param(REPEAT_PASSWORD_FIELD, repNewPass))
345                 .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
346
347         assertEquals("", res);
348         assertTrue(passEncoder.isValid(userDetailsService.findByUserId(user.getId()).getPassword(), newPass));
349         assertFalse(passEncoder.isValid(userDetailsService.findByUserId(user.getId()).getPassword(), oldPass));
350
351         userService.remove(user);
352     }
353
354     /**
355      * Switch lock status test.
356      *
357      * @throws Exception the exception
358      */
359     @Test
360     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
361     public void switchLockStatusTest() throws Exception {
362         User user = new User(USER_NAME, USER_MAIL, false, new Date(), userRole);
363         user = userService.save(user);
364         Boolean response = Boolean.parseBoolean(mockMvc.perform(get("/admin/users/switch_status/{id}", user.getId()))
365                 .andExpect(status().isOk()).andExpect(forwardedUrl(null)).andReturn().getResponse()
366                 .getContentAsString());
367
368         assertEquals(!user.getLocked(), response);
369         userService.remove(user);
370     }
371
372     /**
373      * Remove user test.
374      *
375      * @throws Exception the exception
376      */
377     @Test
378     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
379     public void removeUserTest() throws Exception {
380         User user = new User(USER_NAME, USER_MAIL, false, new Date(), userRole);
381         user = userService.save(user);
382         Boolean response = Boolean
383                 .parseBoolean(mockMvc.perform(get("/admin/users/remove/{id}", user.getId())).andExpect(status().isOk())
384                         .andExpect(forwardedUrl(null)).andReturn().getResponse().getContentAsString());
385
386         assertTrue(response);
387         assertNull(userService.findById(user.getId()));
388         userService.remove(user);
389     }
390
391     /**
392      * Remove self user test.
393      *
394      * @throws Exception the exception
395      */
396     @Test
397     @SuppressWarnings("PMD.SignatureDeclareThrowsException")
398     public void removeSelfUserTest() throws Exception {
399         User user = new User(USER_NAME, selfEmail, false, new Date(), userRole);
400         user = userRepository.save(user);
401         Boolean response = Boolean
402                 .parseBoolean(mockMvc.perform(get("/admin/users/remove/{id}", user.getId())).andExpect(status().isOk())
403                         .andExpect(forwardedUrl(null)).andReturn().getResponse().getContentAsString());
404
405         assertFalse(response);
406         assertNotNull(userService.findById(user.getId()));
407
408         userRepository.delete(user);
409     }
410 }