[IOT-1556] Changes in cloud according to the stateless in CloudInterface and AccountS...
[iotivity.git] / cloud / account / src / test / java / org / iotivity / cloud / accountserver / resources / account / session / SessionResourceTest.java
1 /*
2  * //******************************************************************
3  * //
4  * // Copyright 2016 Samsung Electronics All Rights Reserved.
5  * //
6  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7  * //
8  * // Licensed under the Apache License, Version 2.0 (the "License");
9  * // you may not use this file except in compliance with the License.
10  * // You may obtain a copy of the License at
11  * //
12  * //      http://www.apache.org/licenses/LICENSE-2.0
13  * //
14  * // Unless required by applicable law or agreed to in writing, software
15  * // distributed under the License is distributed on an "AS IS" BASIS,
16  * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * // See the License for the specific language governing permissions and
18  * // limitations under the License.
19  * //
20  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21  */
22
23 package org.iotivity.cloud.accountserver.resources.account.session;
24
25 import static org.junit.Assert.assertTrue;
26
27 import java.text.DateFormat;
28 import java.text.SimpleDateFormat;
29 import java.util.Date;
30 import java.util.HashMap;
31 import java.util.concurrent.CountDownLatch;
32
33 import org.iotivity.cloud.accountserver.Constants;
34 import org.iotivity.cloud.accountserver.db.AccountDBManager;
35 import org.iotivity.cloud.accountserver.db.MongoDB;
36 import org.iotivity.cloud.accountserver.db.TokenTable;
37 import org.iotivity.cloud.accountserver.db.UserTable;
38 import org.iotivity.cloud.accountserver.util.TypeCastingManager;
39 import org.iotivity.cloud.base.device.CoapDevice;
40 import org.iotivity.cloud.base.exception.ServerException;
41 import org.iotivity.cloud.base.protocols.IRequest;
42 import org.iotivity.cloud.base.protocols.IResponse;
43 import org.iotivity.cloud.base.protocols.MessageBuilder;
44 import org.iotivity.cloud.base.protocols.coap.CoapResponse;
45 import org.iotivity.cloud.base.protocols.enums.ContentFormat;
46 import org.iotivity.cloud.base.protocols.enums.RequestMethod;
47 import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
48 import org.iotivity.cloud.util.Cbor;
49 import org.junit.After;
50 import org.junit.Before;
51 import org.junit.Test;
52 import org.mockito.Mockito;
53 import org.mockito.MockitoAnnotations;
54 import org.mockito.invocation.InvocationOnMock;
55 import org.mockito.stubbing.Answer;
56
57 public class SessionResourceTest {
58     private static final String            DEFAULT_AUTH_LOGIN        = Constants.ACCOUNT_SESSION_FULL_URI;
59     private static final String            DEFAULT_AUTH_LOGOUT       = Constants.ACCOUNT_SESSION_FULL_URI;
60     private static final String            DEVICE_ID                 = "d0001";
61     private static final String            ACCESS_TOKEN              = "5f5536c896da7dd437316585b86ef9dd03441c40";
62     private static final String            REFRESH_TOKEN             = "rt0001";
63     private static final String            USER_UUID                 = "bc38f243-aab5-44d3-8eb9-4a54ebbaf359";
64     private static final String            AUTH_PROVIDER             = "Github";
65     private TypeCastingManager<UserTable>  mUserTableCastingManager  = new TypeCastingManager<>();
66     private TypeCastingManager<TokenTable> mTokenTableCastingManager = new TypeCastingManager<>();
67     private CountDownLatch                 mLatch                    = new CountDownLatch(
68             1);
69     private CoapDevice                     mMockDevice               = Mockito
70             .mock(CoapDevice.class);
71     private Cbor<HashMap<String, Object>>  mCbor                     = new Cbor<>();
72     private IResponse                      mResponse                 = null;
73     private SessionResource                mSessionResource          = new SessionResource();
74
75     @Before
76     public void setUp() throws Exception {
77         MockitoAnnotations.initMocks(this);
78         // reset data base
79         resetDB();
80         // register the token table and user table to the DB
81         HashMap<String, Object> tokenInfo = mTokenTableCastingManager
82                 .convertObjectToMap(makeTokenTable());
83         HashMap<String, Object> userInfo = mUserTableCastingManager
84                 .convertObjectToMap(makeUserTable());
85         AccountDBManager.getInstance()
86                 .insertAndReplaceRecord(Constants.TOKEN_TABLE, tokenInfo);
87         AccountDBManager.getInstance().insertRecord(Constants.USER_TABLE,
88                 userInfo);
89         // response handler mock
90         Mockito.doAnswer(new Answer<Object>() {
91             @Override
92             public CoapResponse answer(InvocationOnMock invocation)
93                     throws Throwable {
94
95                 Object[] args = invocation.getArguments();
96                 CoapResponse resp = (CoapResponse) args[0];
97                 System.out.println(
98                         "\t----------payload : " + resp.getPayloadString());
99                 System.out.println("\t---------method : " + resp.getStatus());
100                 mResponse = resp;
101                 mLatch.countDown();
102                 return null;
103             }
104         }).when(mMockDevice).sendResponse(Mockito.anyObject());
105     }
106
107     @After
108     public void resetAccountDatabase() throws Exception {
109         MongoDB mongoDB = new MongoDB(Constants.DB_NAME);
110         mongoDB.createTable(Constants.USER_TABLE);
111         mongoDB.createTable(Constants.TOKEN_TABLE);
112         mongoDB.createTable(Constants.GROUP_TABLE);
113     }
114
115     @Test
116     public void testSignInOnDefaultRequestReceived() throws Exception {
117         getTestMethodName();
118         SignIn(DEVICE_ID, ACCESS_TOKEN);
119         assertTrue(hashmapCheck(mResponse, "expiresin"));
120         assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
121     }
122
123     @Test(expected = ServerException.UnAuthorizedException.class)
124     public void testSignInExpiredTokenOnDefaultRequestReceived()
125             throws Exception {
126         getTestMethodName();
127         TokenTable tokenTable = makeTokenTable();
128         tokenTable.setExpiredtime(0);
129         HashMap<String, Object> tokenInfo = mTokenTableCastingManager
130                 .convertObjectToMap(tokenTable);
131         Thread.sleep(500);
132         AccountDBManager.getInstance()
133                 .insertAndReplaceRecord(Constants.TOKEN_TABLE, tokenInfo);
134         SignIn(DEVICE_ID, ACCESS_TOKEN);
135     }
136
137     @Test(expected = ServerException.BadRequestException.class)
138     public void testSignInWithInvalidMethodOnDefaultRequestReceived()
139             throws Exception {
140         getTestMethodName();
141         SignInWithInvalidMethod(DEVICE_ID, ACCESS_TOKEN);
142     }
143
144     @Test(expected = ServerException.UnAuthorizedException.class)
145     public void testWrongAccessTokenSignInOnDefaultRequestReceived()
146             throws Exception {
147         getTestMethodName();
148         String accessTokenNotStored = "5689c70ffa245effc563017fee36d250";
149         // sign in request
150         SignIn(DEVICE_ID, accessTokenNotStored);
151     }
152
153     @Test(expected = ServerException.UnAuthorizedException.class)
154     public void testInvalidDeviceIdSignInOnDefaultRequestReceived()
155             throws Exception {
156         getTestMethodName();
157         String diNotStored = "F371C481-38E6-4D47-8320-7688D8A5B58C";
158         SignIn(diNotStored, ACCESS_TOKEN);
159     }
160
161     @Test
162     public void testSignOutOnDefaultRequestReceived() throws Exception {
163         getTestMethodName();
164         SignOut(DEVICE_ID, ACCESS_TOKEN);
165         assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
166     }
167
168     public void getTestMethodName() {
169         StackTraceElement[] stacks = new Throwable().getStackTrace();
170         StackTraceElement currentStack = stacks[1];
171         System.out.println("\t---Test Name : " + currentStack.getMethodName());
172     }
173
174     @Test(expected = ServerException.BadRequestException.class)
175     public void testSignInWithNullPayloadOnDefaultRequestReceived()
176             throws Exception {
177         getTestMethodName();
178         SignInWithNullPayload();
179     }
180
181     @Test(expected = ServerException.BadRequestException.class)
182     public void testSignOutWithNullPayloadOnDefaultRequestReceived()
183             throws Exception {
184         getTestMethodName();
185         SignOutWithNullPayload();
186     }
187
188     @Test(expected = ServerException.PreconditionFailedException.class)
189     public void testSignInWithBlankHashMapPayloadOnDefaultRequestReceived()
190             throws Exception {
191         getTestMethodName();
192         SignInWithBlankHashMapPayload();
193     }
194
195     @Test(expected = ServerException.PreconditionFailedException.class)
196     public void testSignOutWithBlankHashMapPayloadOnDefaultRequestReceived()
197             throws Exception {
198         getTestMethodName();
199         SignOutWithBlankHashMapPayload();
200     }
201
202     private void SignInWithInvalidMethod(String di, String accessToken)
203             throws Exception {
204         System.out.println("-----Sign In With Invalid Method (GET)");
205         IRequest request = null;
206         request = SignInWithInvalidMethodRequest(di, accessToken);
207         mSessionResource.onDefaultRequestReceived(mMockDevice, request);
208     }
209
210     private void SignIn(String di, String accessToken) throws Exception {
211         System.out.println("-----Sign In");
212         IRequest request = null;
213         request = SignInRequest(di, accessToken);
214         mSessionResource.onDefaultRequestReceived(mMockDevice, request);
215     }
216
217     private void SignInWithBlankHashMapPayload() throws Exception {
218         System.out.println("-----Sign In With Blank Hashmap Payload");
219         IRequest request = null;
220         request = SignInBlankHashmapPayloadRequest();
221         mSessionResource.onDefaultRequestReceived(mMockDevice, request);
222     }
223
224     private void SignInWithNullPayload() throws Exception {
225         System.out.println("-----Sign In With Null Payload");
226         IRequest request = null;
227         request = SignInNullPayloadRequest();
228         mSessionResource.onDefaultRequestReceived(mMockDevice, request);
229     }
230
231     private void SignOut(String di, String accessToken) throws Exception {
232         System.out.println("-----Sign Out");
233         IRequest request = null;
234         request = SignOutRequest(di, accessToken);
235         mSessionResource.onDefaultRequestReceived(mMockDevice, request);
236     }
237
238     private void SignOutWithBlankHashMapPayload() throws Exception {
239         System.out.println("-----Sign Out With Blank Hashmap Payload");
240         IRequest request = null;
241         request = SignOutBlankHashmapPayloadRequest();
242         mSessionResource.onDefaultRequestReceived(mMockDevice, request);
243     }
244
245     private void SignOutWithNullPayload() throws Exception {
246         System.out.println("-----Sign Out With Null Payload");
247         IRequest request = null;
248         request = SignOutNullPayloadRequest();
249         mSessionResource.onDefaultRequestReceived(mMockDevice, request);
250     }
251
252     private IRequest SignInNullPayloadRequest() {
253         IRequest request = null;
254         request = MessageBuilder.createRequest(RequestMethod.POST,
255                 DEFAULT_AUTH_LOGIN, null);
256         return request;
257     }
258
259     private IRequest SignInBlankHashmapPayloadRequest() {
260         IRequest request = null;
261         HashMap<String, Object> payloadData = new HashMap<String, Object>();
262         request = MessageBuilder.createRequest(RequestMethod.POST,
263                 DEFAULT_AUTH_LOGIN, null, ContentFormat.APPLICATION_CBOR,
264                 mCbor.encodingPayloadToCbor(payloadData));
265         return request;
266     }
267
268     private IRequest SignOutNullPayloadRequest() {
269         IRequest request = null;
270         request = MessageBuilder.createRequest(RequestMethod.POST,
271                 DEFAULT_AUTH_LOGOUT, null);
272         return request;
273     }
274
275     private IRequest SignOutBlankHashmapPayloadRequest() {
276         IRequest request = null;
277         HashMap<String, Object> payloadData = new HashMap<String, Object>();
278         request = MessageBuilder.createRequest(RequestMethod.POST,
279                 DEFAULT_AUTH_LOGOUT, null, ContentFormat.APPLICATION_CBOR,
280                 mCbor.encodingPayloadToCbor(payloadData));
281         return request;
282     }
283
284     private IRequest SignInWithInvalidMethodRequest(String deviceId,
285             String accessToken) {
286         IRequest request = null;
287         HashMap<String, Object> payloadData = new HashMap<String, Object>();
288         payloadData.put("accesstoken", accessToken);
289         payloadData.put("status", true);
290         payloadData.put("di", deviceId);
291         request = MessageBuilder.createRequest(RequestMethod.GET,
292                 DEFAULT_AUTH_LOGIN, null, ContentFormat.APPLICATION_CBOR,
293                 mCbor.encodingPayloadToCbor(payloadData));
294         return request;
295     }
296
297     private IRequest SignInRequest(String deviceId, String accessToken) {
298         IRequest request = null;
299         HashMap<String, Object> payloadData = new HashMap<String, Object>();
300         payloadData.put("accesstoken", accessToken);
301         payloadData.put("login", true);
302         payloadData.put("di", deviceId);
303         payloadData.put("uid", USER_UUID);
304         request = MessageBuilder.createRequest(RequestMethod.POST,
305                 DEFAULT_AUTH_LOGIN, null, ContentFormat.APPLICATION_CBOR,
306                 mCbor.encodingPayloadToCbor(payloadData));
307         return request;
308     }
309
310     private IRequest SignOutRequest(String deviceId, String accessToken) {
311         IRequest request = null;
312         HashMap<String, Object> payloadData = new HashMap<String, Object>();
313         payloadData.put("accesstoken", accessToken);
314         payloadData.put("login", false);
315         payloadData.put("di", deviceId);
316         StringBuffer query = new StringBuffer();
317         query.append("uid=" + USER_UUID);
318         request = MessageBuilder.createRequest(RequestMethod.POST,
319                 DEFAULT_AUTH_LOGOUT, query.toString(),
320                 ContentFormat.APPLICATION_CBOR,
321                 mCbor.encodingPayloadToCbor(payloadData));
322         return request;
323     }
324
325     private boolean hashmapCheck(IResponse response, String propertyName) {
326         HashMap<String, Object> payloadData = mCbor
327                 .parsePayloadFromCbor(response.getPayload(), HashMap.class);
328         if (payloadData.get(propertyName) != null)
329             return true;
330         else
331             return false;
332     }
333
334     private boolean methodCheck(IResponse response,
335             ResponseStatus responseStatus) {
336         if (responseStatus == response.getStatus())
337             return true;
338         else
339             return false;
340     }
341
342     private TokenTable makeTokenTable() {
343         TokenTable tokenInfo = new TokenTable();
344         tokenInfo.setUuid(USER_UUID);
345         tokenInfo.setDid(DEVICE_ID);
346         tokenInfo.setAccesstoken(ACCESS_TOKEN);
347         tokenInfo.setRefreshtoken(REFRESH_TOKEN);
348         tokenInfo.setProvider(AUTH_PROVIDER);
349         tokenInfo.setExpiredtime(-1);
350         Date currentTime = new Date();
351         DateFormat transFormat = new SimpleDateFormat("yyyyMMddkkmm");
352         tokenInfo.setIssuedtime(transFormat.format(currentTime));
353         return tokenInfo;
354     }
355
356     private UserTable makeUserTable() {
357         UserTable userInfo = new UserTable();
358         userInfo.setUuid(USER_UUID);
359         userInfo.setProvider(AUTH_PROVIDER);
360         userInfo.setUserid("userId");
361         return userInfo;
362     }
363
364     private void resetDB() throws Exception {
365         MongoDB mongoDB = new MongoDB(Constants.DB_NAME);
366         mongoDB.deleteTable(Constants.GROUP_TABLE);
367         mongoDB.createTable(Constants.GROUP_TABLE);
368         mongoDB.deleteTable(Constants.USER_TABLE);
369         mongoDB.createTable(Constants.USER_TABLE);
370         mongoDB.deleteTable(Constants.TOKEN_TABLE);
371         mongoDB.createTable(Constants.TOKEN_TABLE);
372     }
373 }