[SECARSP-149] *server side unit tests
[platform/core/security/suspicious-activity-monitor.git] / server / samserver / src / test / java / com / samsung / samserver / web / rest / controller / impl / RestDashboardTest.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) 2018 Samsung Electronics Co., Ltd. All rights reserved.
5  */
6 package com.samsung.samserver.web.rest.controller.impl;
7
8 import com.samsung.samserver.SamserverApp;
9 import com.samsung.samserver.config.Constants;
10 import com.samsung.samserver.domain.*;
11 import com.samsung.samserver.repository.UserRepository;
12 import com.samsung.samserver.security.AuthoritiesConstants;
13 import com.samsung.samserver.service.*;
14 import com.samsung.samserver.service.dto.UserDTO;
15 import com.samsung.samserver.web.rest.TestUtil;
16 import com.samsung.samserver.web.rest.errors.ExceptionTranslator;
17 import com.samsung.samserver.web.rest.service.vm.*;
18 import org.apache.commons.lang3.RandomStringUtils;
19 import org.springframework.beans.factory.annotation.Autowired;
20 import org.springframework.boot.test.context.SpringBootTest;
21 import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
22 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
23 import org.springframework.security.crypto.password.PasswordEncoder;
24 import org.springframework.security.test.context.support.WithMockUser;
25 import org.springframework.test.context.junit4.SpringRunner;
26 import org.springframework.test.web.servlet.*;
27 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
28 import org.springframework.transaction.annotation.Transactional;
29 import org.junit.runner.RunWith;
30 import org.junit.*;
31 import java.util.*;
32
33 import static com.samsung.samserver.web.rest.TestUtil.createFormattingConversionService;
34 import static org.assertj.core.api.Assertions.assertThat;
35 import static org.hamcrest.Matchers.*;
36 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
37 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
38 import static com.samsung.samserver.web.rest.controller.impl.SampleObject.*;
39
40 /**
41  * Test class for the Dashboard REST controller.
42  *
43  * @see RestDashboardTest
44  */
45 @RunWith(SpringRunner.class)
46 @SpringBootTest(classes = SamserverApp.class)
47 public class RestDashboardTest {
48
49     @Autowired
50     private RestDashboard restDashboard;
51
52     @Autowired
53     private UserRepository userRepository;
54
55     @Autowired
56     private PasswordEncoder passwordEncoder;
57
58     @Autowired
59     private DeviceTypeService deviceTypeService;
60
61     @Autowired
62     private DeviceService deviceService;
63
64     @Autowired
65     private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
66
67     @Autowired
68     private ExceptionTranslator exceptionTranslator;
69
70     @Autowired
71     private MappingJackson2HttpMessageConverter jacksonMessageConverter;
72
73     private MockMvc mockMvc;
74
75     @Before
76     public void setup() {
77         this.mockMvc = MockMvcBuilders.standaloneSetup(restDashboard)
78             .setCustomArgumentResolvers(pageableArgumentResolver)
79             .setControllerAdvice(exceptionTranslator)
80             .setConversionService(createFormattingConversionService())
81             .setMessageConverters(jacksonMessageConverter)
82             .build();
83     }
84
85     @Test
86     @Transactional
87     public void testRegisterAccount() throws Exception {
88         UIRegistration uiRegistration = createRandomUIRegistration();
89         assertThat(userRepository.findOneByLogin(uiRegistration.getEmail()).isPresent()).isFalse();
90
91         mockMvc.perform(post("/dashboard/auth/register")
92                 .contentType(TestUtil.APPLICATION_JSON_UTF8)
93                 .content(TestUtil.convertObjectToJsonBytes(uiRegistration)))
94                 .andExpect(status().isCreated());
95         assertThat(userRepository.findOneByLogin(uiRegistration.getEmail()).isPresent()).isTrue();
96     }
97
98     @Test
99     @Transactional
100     public void testLogin() throws Exception {
101
102         User user = createRandomUser();
103         assertThat(userRepository.findOneByLogin(user.getEmail()).isPresent()).isFalse();
104         user.setPassword(passwordEncoder.encode("test"));
105         userRepository.saveAndFlush(user);
106         assertThat(userRepository.findOneByLogin(user.getEmail()).isPresent()).isTrue();
107
108         UILogin uiLogin = new UILogin();
109         uiLogin.setEmail(user.getEmail());
110         uiLogin.setPassword("test");
111         mockMvc.perform(post("/dashboard/auth/login")
112                 .contentType(TestUtil.APPLICATION_JSON_UTF8)
113                 .content(TestUtil.convertObjectToJsonBytes(uiLogin)))
114                 .andExpect(status().isOk())
115                 .andExpect(jsonPath("$.id_token").isString())
116                 .andExpect(jsonPath("$.id_token").isNotEmpty())
117                 .andExpect(header().string("Authorization", not(nullValue())))
118                 .andExpect(header().string("Authorization", not(isEmptyString())));
119     }
120
121     @Test
122     @Transactional
123     public void testLogout() throws Exception {
124         mockMvc.perform(delete("/dashboard/auth/logout")).andExpect(status().isOk());
125     }
126
127     @Test
128     @Transactional
129     public void testGetAllDevices() throws Exception {
130
131         Device device = createRandomDevice();
132         assertThat(deviceService.findOne(device.getDuid()).isPresent()).isFalse();
133         deviceTypeService.save(device.getDtype());
134         deviceService.save(device);
135         assertThat(deviceService.findOne(device.getDuid()).isPresent()).isTrue();
136
137         int c = deviceService.findAll().size();
138         String p = "$.[?(@.id=="+device.getId()+")]";
139         mockMvc.perform(get("/dashboard/devices"))
140                 .andExpect(status().isOk())
141                 .andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
142                 .andExpect(jsonPath("$", hasSize(c)))
143                 .andExpect(jsonPath(p+".duid", hasItem(device.getDuid())))
144                 .andExpect(jsonPath(p+".ctime", hasItem(device.getCtime().toString())))
145                 .andExpect(jsonPath(p+".model", hasItem(device.getModel())))
146                 .andExpect(jsonPath(p+".sn", hasItem(device.getSn())))
147                 .andExpect(jsonPath(p+".os.sw", hasItem(device.getSw())))
148                 .andExpect(jsonPath(p+".os.name", hasItem(device.getOsname())))
149                 .andExpect(jsonPath(p+".os.version", hasItem(device.getOsver())))
150                 .andExpect(jsonPath(p+".geo.ip", hasItem(device.getIpaddr())))
151                 .andExpect(jsonPath(p+".type.name",hasItem(device.getDtype().getName())))
152                 .andExpect(jsonPath(p+".type.descr",hasItem(device.getDtype().getDescr())))
153         ;
154     }
155
156     @Test
157     public void testUpdateDevice() throws Exception {
158
159         Device device = createRandomDevice();
160         assertThat(deviceService.findOne(device.getDuid()).isPresent()).isFalse();
161         deviceTypeService.save(device.getDtype());
162         deviceService.save(device);
163         assertThat(deviceService.findOne(device.getDuid()).isPresent()).isTrue();
164
165         UIDeviceUpdate uiDeviceUpdate = createUIDeviceUpdate(device.getId());;
166
167         mockMvc.perform(put("/dashboard/devices/update")
168                 .contentType(TestUtil.APPLICATION_JSON_UTF8)
169                 .content(TestUtil.convertObjectToJsonBytes(uiDeviceUpdate)))
170                 .andExpect(status().isOk())
171                 .andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
172                 .andExpect(jsonPath("$", hasSize(1)))
173                 .andExpect(jsonPath("$[0].locked", is(1)))
174                 .andExpect(jsonPath("$[0].duid", is(device.getDuid())))
175                 .andExpect(jsonPath("$[0].ctime", is(device.getCtime().toString())))
176                 .andExpect(jsonPath("$[0].model", is(device.getModel())))
177                 .andExpect(jsonPath("$[0].sn", is(device.getSn())))
178                 .andExpect(jsonPath("$[0].os.sw", is(device.getSw())))
179                 .andExpect(jsonPath("$[0].os.name", is(device.getOsname())))
180                 .andExpect(jsonPath("$[0].os.version", is(device.getOsver())))
181                 .andExpect(jsonPath("$[0].geo.ip", is(device.getIpaddr())))
182                 .andExpect(jsonPath("$[0].type.name",is(device.getDtype().getName())))
183                 .andExpect(jsonPath("$[0].type.descr",is(device.getDtype().getDescr())))
184         ;
185     }
186
187     @Test
188     public void testSendDashboardLogs() throws Exception {
189         UIDashboardLog uiDashboardLog = new UIDashboardLog();
190         uiDashboardLog.setLevel("level");
191         uiDashboardLog.setMessage("message");
192         uiDashboardLog.setTimestamp("timestamp");
193         uiDashboardLog.setAdditional(new ArrayList<>());
194         mockMvc.perform(delete("/dashboard/auth/logout")
195                 .contentType(TestUtil.APPLICATION_JSON_UTF8)
196                 .content(TestUtil.convertObjectToJsonBytes(uiDashboardLog)))
197                 .andExpect(status().isOk());
198     }
199
200
201     @Test
202     @Transactional
203     public void testAuthorizeWithRememberMe() throws Exception {
204         User user = new User();
205         user.setLogin("dashboard-user-remember-me@example.com");
206         user.setEmail("dashboard-user-remember-me@example.com");
207         user.setActivated(true);
208         user.setPassword(passwordEncoder.encode("test"));
209
210         userRepository.saveAndFlush(user);
211
212         UILogin login = new UILogin();
213         login.setEmail("dashboard-user-remember-me@example.com");
214         login.setPassword("test");
215         login.setRememberMe(true);
216         mockMvc.perform(post("/dashboard/auth/login")
217             .contentType(TestUtil.APPLICATION_JSON_UTF8)
218             .content(TestUtil.convertObjectToJsonBytes(login)))
219             .andExpect(status().isOk())
220             .andExpect(jsonPath("$.id_token").isString())
221             .andExpect(jsonPath("$.id_token").isNotEmpty())
222             .andExpect(header().string("Authorization", not(nullValue())))
223             .andExpect(header().string("Authorization", not(isEmptyString())));
224     }
225
226     @Test
227     @Transactional
228     public void testAuthorizeFails() throws Exception {
229         UILogin login = new UILogin();
230         login.setEmail("wrong-user@example.com");
231         login.setPassword("wrong password");
232         mockMvc.perform(post("/dashboard/auth/login")
233             .contentType(TestUtil.APPLICATION_JSON_UTF8)
234             .content(TestUtil.convertObjectToJsonBytes(login)))
235             .andExpect(status().isUnauthorized())
236             .andExpect(jsonPath("$.id_token").doesNotExist())
237             .andExpect(header().doesNotExist("Authorization"));
238     }
239
240     //@Test
241     @Transactional
242     public void testRegisterInvalidLogin() throws Exception {
243         UIRegistration uiRegistration = new UIRegistration();
244         uiRegistration.setEmail("funky-log!n@example.com");
245         uiRegistration.setPassword("test");
246         uiRegistration.setFullName("Funky-fullName");
247
248         mockMvc.perform(
249                 post("/dashboard/auth/register")
250                         .contentType(TestUtil.APPLICATION_JSON_UTF8)
251                         .content(TestUtil.convertObjectToJsonBytes(uiRegistration)))
252                 .andExpect(status().isBadRequest());
253
254         Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky-log!n@example.com");
255         assertThat(user.isPresent()).isFalse();
256     }
257
258     @Test
259     @Transactional
260     public void testRegisterInvalidPassword() throws Exception {
261         UIRegistration uiRegistration = createRandomUIRegistration();
262         uiRegistration.setPassword("123");
263         mockMvc.perform(
264                 post("/dashboard/auth/register")
265                         .contentType(TestUtil.APPLICATION_JSON_UTF8)
266                         .content(TestUtil.convertObjectToJsonBytes(uiRegistration)))
267                 .andExpect(status().isBadRequest());
268
269         Optional<User> user = userRepository.findOneByEmailIgnoreCase(uiRegistration.getEmail());
270         assertThat(user.isPresent()).isFalse();
271     }
272
273     @Test
274     @Transactional
275     public void testRegisterNullPassword() throws Exception {
276         UIRegistration uiRegistration = new UIRegistration();
277         uiRegistration.setEmail("dashboard-user@example.com");
278         uiRegistration.setPassword(null);// invalid null password
279         uiRegistration.setFullName("dashboard-user-fullName");
280
281         mockMvc.perform(
282                 post("/dashboard/auth/register")
283                         .contentType(TestUtil.APPLICATION_JSON_UTF8)
284                         .content(TestUtil.convertObjectToJsonBytes(uiRegistration)))
285                 .andExpect(status().isBadRequest());
286
287         Optional<User> user = userRepository.findOneByEmailIgnoreCase("dashboard-user@example.com");
288         assertThat(user.isPresent()).isFalse();
289     }
290
291     @Test
292     @Transactional
293     public void testRegisterDuplicateEmail() throws Exception {
294         // Good
295         UIRegistration uiRegistration = new UIRegistration();
296         uiRegistration.setEmail("dashboard-user@example.com");
297         uiRegistration.setPassword(passwordEncoder.encode("test"));
298         uiRegistration.setFullName("dashboard-user-fullName");
299
300         // Duplicate email
301         UIRegistration duplicatedRegistration = new UIRegistration();
302         duplicatedRegistration.setEmail("dashboard-user@example.com");
303         duplicatedRegistration.setPassword(passwordEncoder.encode("test"));
304         duplicatedRegistration.setFullName("dashboard-user-fullName");
305
306         // Good user
307         mockMvc.perform(
308                 post("/dashboard/auth/register")
309                         .contentType(TestUtil.APPLICATION_JSON_UTF8)
310                         .content(TestUtil.convertObjectToJsonBytes(uiRegistration)))
311                 .andExpect(status().isCreated());
312
313         // Duplicate email
314         mockMvc.perform(
315                 post("/dashboard/auth/register")
316                         .contentType(TestUtil.APPLICATION_JSON_UTF8)
317                         .content(TestUtil.convertObjectToJsonBytes(duplicatedRegistration)))
318                 .andExpect(status().is4xxClientError());
319
320         // Duplicate email - with uppercase email address
321         UIRegistration duplicatedWithUpperCaseEmailRegistration = new UIRegistration();
322         duplicatedWithUpperCaseEmailRegistration.setEmail(uiRegistration.getEmail().toUpperCase());
323         duplicatedWithUpperCaseEmailRegistration.setPassword(passwordEncoder.encode("test"));
324         duplicatedWithUpperCaseEmailRegistration.setFullName("dashboard-user-fullName");
325
326         mockMvc.perform(
327                 post("/dashboard/auth/register")
328                         .contentType(TestUtil.APPLICATION_JSON_UTF8)
329                         .content(TestUtil.convertObjectToJsonBytes(duplicatedRegistration)))
330                 .andExpect(status().is4xxClientError());
331     }
332
333     @Test
334     @Transactional
335     @WithMockUser("save-invalid-email")
336     public void testSaveInvalidEmail() throws Exception {
337         User user = new User();
338         user.setLogin("save-invalid-email");
339         user.setEmail("save-invalid-email@example.com");
340         user.setPassword(RandomStringUtils.random(60));
341         user.setActivated(true);
342
343         userRepository.saveAndFlush(user);
344
345         UserDTO userDTO = new UserDTO();
346         userDTO.setLogin("not-used");
347         userDTO.setFirstName("firstname");
348         userDTO.setLastName("lastname");
349         userDTO.setEmail("invalid email");
350         userDTO.setActivated(false);
351         userDTO.setImageUrl("http://placehold.it/50x50");
352         userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
353         userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
354
355         mockMvc.perform(
356                 post("/dashboard/auth/register")
357                         .contentType(TestUtil.APPLICATION_JSON_UTF8)
358                         .content(TestUtil.convertObjectToJsonBytes(userDTO)))
359                 .andExpect(status().isBadRequest());
360
361         assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent();
362     }
363
364     @Test
365     @Transactional
366     @WithMockUser("save-existing-email")
367     public void testSaveExistingEmail() throws Exception {
368         User user = new User();
369         user.setLogin("save-existing-email");
370         user.setEmail("save-existing-email@example.com");
371         user.setPassword(RandomStringUtils.random(60));
372         user.setActivated(true);
373
374         userRepository.saveAndFlush(user);
375
376         User anotherUser = new User();
377         anotherUser.setLogin("save-existing-email2");
378         anotherUser.setEmail("save-existing-email2@example.com");
379         anotherUser.setPassword(RandomStringUtils.random(60));
380         anotherUser.setActivated(true);
381
382         userRepository.saveAndFlush(anotherUser);
383
384         UserDTO userDTO = new UserDTO();
385         userDTO.setLogin("not-used");
386         userDTO.setFirstName("firstname");
387         userDTO.setLastName("lastname");
388         userDTO.setEmail("save-existing-email2@example.com");
389         userDTO.setActivated(false);
390         userDTO.setImageUrl("http://placehold.it/50x50");
391         userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
392         userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
393
394         mockMvc.perform(
395                 post("/dashboard/auth/register")
396                         .contentType(TestUtil.APPLICATION_JSON_UTF8)
397                         .content(TestUtil.convertObjectToJsonBytes(userDTO)))
398                 .andExpect(status().isBadRequest());
399
400         User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null);
401         assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com");
402     }
403
404 }