Add Google OAuth2 Provider
[platform/upstream/iotivity.git] / cloud / account / src / main / java / org / iotivity / cloud / accountserver / oauth / Google.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 package org.iotivity.cloud.accountserver.oauth;
23
24 import java.util.HashMap;
25
26 import org.apache.oltu.oauth2.client.OAuthClient;
27 import org.apache.oltu.oauth2.client.URLConnectionClient;
28 import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
29 import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
30 import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
31 import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
32 import org.apache.oltu.oauth2.client.response.OAuthResourceResponse;
33 import org.apache.oltu.oauth2.common.OAuth;
34 import org.apache.oltu.oauth2.common.OAuthProviderType;
35 import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
36 import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
37 import org.apache.oltu.oauth2.common.message.types.GrantType;
38 import org.iotivity.cloud.accountserver.db.TokenTable;
39 import org.iotivity.cloud.accountserver.db.UserTable;
40 import org.iotivity.cloud.base.exception.ServerException.InternalServerErrorException;
41 import org.iotivity.cloud.util.JSONUtil;
42 import org.iotivity.cloud.util.Log;;
43
44 /**
45  *
46  * This class provides a sample to make .jar that communicates with OAuth2
47  * provider.
48  *
49  */
50 public class Google implements OAuthProvider {
51
52     // do not use 'client_id' and 'secret' variables.
53     // should use values that are obtained from github.
54     final static private String client_id    = "447649044559-f9r5sl6op3kkk0312u384o4g6hhucje1.apps.googleusercontent.com";
55     final static private String secret       = "LyTe5_EQkv8-v9Zbq20PSCLR";
56     final static private String redirect_url = "http://www.example.com/oauth2callback";
57     final static private String resource_url = "https://www.googleapis.com/userinfo/v2/me";
58
59     @Override
60     public TokenTable requestAccessTokenInfo(String authCode, Object options) {
61
62         TokenTable tokenInfo = new TokenTable();
63
64         if (authCode == null) {
65
66             Log.w("authCode is null!");
67             return tokenInfo;
68         }
69
70         try {
71
72             OAuthClientRequest request = OAuthClientRequest
73                     .tokenProvider(OAuthProviderType.GOOGLE)
74                     .setGrantType(GrantType.AUTHORIZATION_CODE)
75                     .setClientId(client_id).setClientSecret(secret)
76                     .setCode(authCode).setRedirectURI(redirect_url)
77                     .buildBodyMessage();
78
79             OAuthClient oauthClient = new OAuthClient(
80                     new URLConnectionClient());
81
82             OAuthAccessTokenResponse oauthResponse = null;
83             Class<? extends OAuthAccessTokenResponse> cl = OAuthJSONAccessTokenResponse.class;
84
85             oauthResponse = oauthClient.accessToken(request, cl);
86
87             Log.d("OAuth response: " + oauthResponse.getBody());
88
89             tokenInfo.setAccesstoken(oauthResponse.getAccessToken());
90             tokenInfo.setRefreshtoken(oauthResponse.getRefreshToken());
91             tokenInfo.setExpiredtime(oauthResponse.getExpiresIn());
92
93         } catch (OAuthSystemException | OAuthProblemException e) {
94
95             e.printStackTrace();
96             throw new InternalServerErrorException(
97                     "OAuth provider(Google) error");
98         }
99
100         return tokenInfo;
101     }
102
103     @Override
104     public TokenTable requestRefreshTokenInfo(String refreshToken) {
105
106         TokenTable tokenInfo = new TokenTable();
107
108         if (refreshToken == null) {
109
110             Log.w("refreshToken is null!");
111             return tokenInfo;
112         }
113
114         try {
115
116             OAuthClientRequest request = OAuthClientRequest
117                     .tokenProvider(OAuthProviderType.GOOGLE)
118                     .setGrantType(GrantType.REFRESH_TOKEN)
119                     .setClientId(client_id).setClientSecret(secret)
120                     .setRefreshToken(refreshToken).buildBodyMessage();
121
122             OAuthClient oauthClient = new OAuthClient(
123                     new URLConnectionClient());
124
125             OAuthAccessTokenResponse oauthResponse = null;
126             Class<? extends OAuthAccessTokenResponse> cl = OAuthJSONAccessTokenResponse.class;
127
128             oauthResponse = oauthClient.accessToken(request, cl);
129
130             Log.d("OAuth response: " + oauthResponse.getBody());
131
132             tokenInfo.setAccesstoken(oauthResponse.getAccessToken());
133             // Google provides refreshToken in one time.
134             tokenInfo.setRefreshtoken(refreshToken);
135             tokenInfo.setExpiredtime(oauthResponse.getExpiresIn());
136
137         } catch (OAuthSystemException | OAuthProblemException e) {
138
139             e.printStackTrace();
140             throw new InternalServerErrorException(
141                     "OAuth provider(Google) error");
142         }
143
144         return tokenInfo;
145     }
146
147     @Override
148     public UserTable requestGetUserInfo(String accessToken, Object options) {
149
150         UserTable userInfo = new UserTable();
151
152         if (accessToken == null) {
153             Log.w("accessToken is null!");
154             return userInfo;
155         }
156
157         String response = null;
158
159         try {
160
161             OAuthClientRequest request = new OAuthBearerClientRequest(
162                     resource_url).setAccessToken(accessToken)
163                             .buildQueryMessage();
164
165             OAuthClient oAuthClient = new OAuthClient(
166                     new URLConnectionClient());
167             OAuthResourceResponse resourceResponse = oAuthClient.resource(
168                     request, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
169
170             response = resourceResponse.getBody();
171             Log.d("response: " + response);
172
173         } catch (OAuthSystemException | OAuthProblemException e) {
174             e.printStackTrace();
175             throw new InternalServerErrorException(
176                     "OAuth provider(Github) error");
177         }
178
179         String userIdKey = "name";
180
181         JSONUtil<HashMap<String, String>> util = new JSONUtil<>();
182         HashMap<String, String> parsedData = util.parseJSON(response,
183                 HashMap.class);
184
185         if (parsedData == null) {
186             Log.d("parsedData is null!");
187             return userInfo;
188         }
189
190         String userId = parsedData.get(userIdKey);
191         userInfo.setUserid(userId);
192
193         return userInfo;
194     }
195 }