8
8
import java .net .URI ;
9
9
import java .net .URLDecoder ;
10
10
import java .nio .charset .StandardCharsets ;
11
+ import java .time .Instant ;
12
+ import java .time .LocalDate ;
13
+ import java .time .LocalDateTime ;
14
+ import java .time .LocalTime ;
15
+ import java .time .ZoneOffset ;
11
16
import java .util .List ;
12
17
import java .util .Optional ;
13
18
36
41
import lombok .RequiredArgsConstructor ;
37
42
import mucsi96 .traininglog .model .TestAuthorizedClient ;
38
43
import mucsi96 .traininglog .repository .TestAuthorizedClientRepository ;
44
+ import mucsi96 .traininglog .weight .Weight ;
45
+ import mucsi96 .traininglog .weight .WeightRepository ;
39
46
import mucsi96 .traininglog .withings .oauth .WithingsClient ;
40
47
41
48
@ SpringBootTest (webEnvironment = SpringBootTest .WebEnvironment .RANDOM_PORT )
42
49
@ RequiredArgsConstructor
43
50
@ TestConstructor (autowireMode = TestConstructor .AutowireMode .ALL )
44
51
public class WeightControllerTests extends BaseIntegrationTest {
45
52
46
- // OAuth2AuthorizationCodeAuthenticationProvider
47
-
48
53
private final MockMvc mockMvc ;
49
54
private final TestAuthorizedClientRepository authorizedClientRepository ;
55
+ private final WeightRepository weightRepository ;
50
56
51
57
@ LocalServerPort
52
58
private int port ;
53
59
54
60
@ RegisterExtension
55
- static WireMockExtension withingsServer = WireMockExtension .newInstance ()
61
+ static WireMockExtension mockWithingsServer = WireMockExtension .newInstance ()
56
62
.options (wireMockConfig ().dynamicPort ())
57
63
.build ();
58
64
59
65
@ DynamicPropertySource
60
66
static void overrideProperties (DynamicPropertyRegistry registry ) {
61
67
62
68
registry .add ("spring.security.oauth2.client.provider.withings.authorization-uri" ,
63
- () -> withingsServer .baseUrl () + "/oauth2_user/authorize2" );
69
+ () -> mockWithingsServer .baseUrl () + "/oauth2_user/authorize2" );
64
70
registry .add (
65
71
"spring.security.oauth2.client.provider.withings.token-uri" ,
66
- () -> withingsServer .baseUrl () + "/v2/oauth2" );
72
+ () -> mockWithingsServer .baseUrl () + "/v2/oauth2" );
67
73
68
74
registry .add ("spring.security.oauth2.client.registration.withings-client.client-id" ,
69
75
() -> "test-withings-client-id" );
70
76
registry .add ("spring.security.oauth2.client.registration.withings-client.client-secret" ,
71
77
() -> "test-withings-client-secret" );
78
+ registry .add ("withings.api.uri" , () -> mockWithingsServer .baseUrl ());
72
79
}
73
80
74
81
@ AfterEach
75
82
void afterEach () {
76
83
authorizedClientRepository .deleteAll ();
84
+ weightRepository .deleteAll ();
85
+ }
86
+
87
+ private void authorizeWithingsOAuth2Client () {
88
+ TestAuthorizedClient authorizedClient = TestAuthorizedClient .builder ()
89
+ .clientRegistrationId ("withings-client" )
90
+ .principalName ("rob" )
91
+ .accessTokenType ("Bearer" )
92
+ .accessTokenValue ("test-access-token" .getBytes (StandardCharsets .UTF_8 ))
93
+ .accessTokenIssuedAt (LocalDateTime .now ())
94
+ .accessTokenExpiresAt (LocalDateTime .now ().plusDays (1 ))
95
+ .accessTokenScopes ("user.metrics" )
96
+ .refreshTokenValue ("test-refresh-token" .getBytes (StandardCharsets .UTF_8 ))
97
+ .refreshTokenIssuedAt (LocalDateTime .now ())
98
+ .build ();
99
+
100
+ authorizedClientRepository .save (authorizedClient );
77
101
}
78
102
79
103
@ Test
@@ -86,12 +110,40 @@ public void returns_not_authorized_if_no_preauth_headers_are_sent() throws Excep
86
110
assertThat (response .getStatus ()).isEqualTo (401 );
87
111
}
88
112
113
+ @ Test
114
+ public void returns_forbidden_if_user_has_no_user_role () throws Exception {
115
+ MockHttpServletResponse response = mockMvc
116
+ .perform (
117
+ get ("/weight" )
118
+ .headers (getAuthHeaders ("guest" )))
119
+ .andReturn ().getResponse ();
120
+
121
+ assertThat (response .getStatus ()).isEqualTo (403 );
122
+ }
123
+
124
+ @ Test
125
+ public void returns_weight_from_database () throws Exception {
126
+ Weight weight = Weight .builder ()
127
+ .value (83.5 )
128
+ .createdAt (Instant .now ())
129
+ .build ();
130
+ weightRepository .save (weight );
131
+
132
+ MockHttpServletResponse response = mockMvc
133
+ .perform (
134
+ get ("/weight" )
135
+ .headers (getAuthHeaders ("user" )))
136
+ .andReturn ().getResponse ();
137
+
138
+ assertThat (JsonPath .parse (response .getContentAsString ()).read ("$.weight" , Double .class )).isEqualTo (83.5 );
139
+ }
140
+
89
141
@ Test
90
142
public void returns_not_authorized_if_authorized_client_is_not_found () throws Exception {
91
143
MockHttpServletResponse response = mockMvc
92
144
.perform (
93
145
post ("/weight/pull-from-withings" )
94
- .headers (getAuthHeaders ("guest " )))
146
+ .headers (getAuthHeaders ("user " )))
95
147
.andReturn ().getResponse ();
96
148
97
149
assertThat (response .getStatus ()).isEqualTo (401 );
@@ -109,7 +161,7 @@ public void redirects_to_withings_request_authorization_page() throws Exception
109
161
assertThat (response .getStatus ()).isEqualTo (302 );
110
162
URI redirectUrl = new URI (response .getRedirectedUrl ());
111
163
assertThat (redirectUrl ).hasHost ("localhost" );
112
- assertThat (redirectUrl ).hasPort (withingsServer .getPort ());
164
+ assertThat (redirectUrl ).hasPort (mockWithingsServer .getPort ());
113
165
assertThat (redirectUrl ).hasPath ("/oauth2_user/authorize2" );
114
166
assertThat (redirectUrl ).hasParameter (OAuth2ParameterNames .RESPONSE_TYPE , "code" );
115
167
assertThat (redirectUrl ).hasParameter (OAuth2ParameterNames .CLIENT_ID , "test-withings-client-id" );
@@ -121,7 +173,7 @@ public void redirects_to_withings_request_authorization_page() throws Exception
121
173
122
174
@ Test
123
175
public void requests_withings_access_token_after_consent_is_granted () throws Exception {
124
- withingsServer .stubFor (WireMock .post ("/v2/oauth2" ).willReturn (
176
+ mockWithingsServer .stubFor (WireMock .post ("/v2/oauth2" ).willReturn (
125
177
WireMock .aResponse ()
126
178
.withHeader (HttpHeaders .CONTENT_TYPE , MediaType .APPLICATION_JSON_VALUE )
127
179
.withBodyFile ("withings-authorize.json" )));
@@ -147,20 +199,48 @@ public void requests_withings_access_token_after_consent_is_granted() throws Exc
147
199
assertThat (response2 .getStatus ()).isEqualTo (302 );
148
200
assertThat (response2 .getRedirectedUrl ()).isEqualTo ("http://localhost/" );
149
201
150
- List <LoggedRequest > requests = withingsServer .findAll (WireMock .postRequestedFor (WireMock .urlEqualTo ("/v2/oauth2" )));
202
+ List <LoggedRequest > requests = mockWithingsServer
203
+ .findAll (WireMock .postRequestedFor (WireMock .urlEqualTo ("/v2/oauth2" )));
151
204
assertThat (requests ).hasSize (1 );
152
205
URI uri = new URI ("?" + requests .get (0 ).getBodyAsString ());
153
206
154
207
Optional <TestAuthorizedClient > authorizedClient = authorizedClientRepository .findById (WithingsClient .id );
155
208
156
209
assertThat (authorizedClient .isPresent ()).isTrue ();
157
210
assertThat (authorizedClient .get ().getPrincipalName ()).isEqualTo ("rob" );
158
- assertThat (new String (authorizedClient .get ().getAccessTokenValue (), "UTF-8" )).isEqualTo ("test-access-token" );
159
- assertThat (new String (authorizedClient .get ().getRefreshTokenValue (), "UTF-8" )).isEqualTo ("test-refresh-token" );
211
+ assertThat (new String (authorizedClient .get ().getAccessTokenValue (), StandardCharsets .UTF_8 ))
212
+ .isEqualTo ("test-access-token" );
213
+ assertThat (new String (authorizedClient .get ().getRefreshTokenValue (), StandardCharsets .UTF_8 ))
214
+ .isEqualTo ("test-refresh-token" );
160
215
assertThat (uri ).hasParameter (OAuth2ParameterNames .GRANT_TYPE , "authorization_code" );
161
216
assertThat (uri ).hasParameter (OAuth2ParameterNames .CODE , "test-authorization-code" );
162
217
assertThat (uri ).hasParameter ("action" , "requesttoken" );
163
218
assertThat (uri ).hasParameter (OAuth2ParameterNames .CLIENT_ID , "test-withings-client-id" );
164
219
assertThat (uri ).hasParameter (OAuth2ParameterNames .CLIENT_SECRET , "test-withings-client-secret" );
165
220
}
221
+
222
+ @ Test
223
+ public void pulls_todays_weight_from_withings_to_database () throws Exception {
224
+ authorizeWithingsOAuth2Client ();
225
+ long startTime = LocalDateTime .of (LocalDate .now (), LocalTime .MIN ).toInstant (ZoneOffset .UTC ).getEpochSecond ();
226
+ long endTime = LocalDateTime .of (LocalDate .now (), LocalTime .MAX ).toInstant (ZoneOffset .UTC ).getEpochSecond ();
227
+ mockWithingsServer .stubFor (WireMock
228
+ .post (String .format ("/measure?action=getmeas&meastype=1&category=1&startdate=%s&enddate=%s" ,
229
+ startTime , endTime ))
230
+ .willReturn (
231
+ WireMock .aResponse ()
232
+ .withHeader (HttpHeaders .CONTENT_TYPE , MediaType .APPLICATION_JSON_VALUE )
233
+ .withBodyFile ("withings-measure.json" )));
234
+ MockHttpServletResponse response = mockMvc
235
+ .perform (
236
+ post ("/weight/pull-from-withings" )
237
+ .headers (getAuthHeaders ("user" )))
238
+ .andReturn ().getResponse ();
239
+
240
+ assertThat (response .getStatus ()).isEqualTo (200 );
241
+ Optional <Weight > weight = weightRepository .findAll ().stream ().findFirst ();
242
+ assertThat (weight .isPresent ()).isTrue ();
243
+ assertThat (weight .get ().getValue ()).isEqualTo (65.75 );
244
+ assertThat (weight .get ().getCreatedAt ().getEpochSecond ()).isEqualTo (1594245600L );
245
+ }
166
246
}
0 commit comments