Skip to content

Commit 2a580ae

Browse files
authored
Merge pull request #71 from umbraco/feature/hubspot-access-token
Http codes validations and refactoring
2 parents 5ceb58d + 9aaf0ad commit 2a580ae

File tree

8 files changed

+123
-84
lines changed

8 files changed

+123
-84
lines changed

src/Umbraco.Cms.Integrations.Crm.Hubspot/App_Plugins/UmbracoCms.Integrations/Crm/Hubspot/js/formpicker.controller.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969

7070
if (response.isExpired === true || response.isValid === false) {
7171
vm.loading = false;
72-
notificationsService.warning("HubSpot API", "Unable to connect to HubSpot. Please review the settings of the form picker property's data type.");
72+
notificationsService.warning("HubSpot API", response.error);
7373
return;
7474
}
7575

@@ -78,7 +78,7 @@
7878
vm.hubspotFormsList = data.forms;
7979

8080
if (data.isValid === false || data.isExpired === true) {
81-
notificationsService.error("HubSpot API", "Unable to retrieve the list of forms from HubSpot. Please review the settings of the form picker property's data type.");
81+
notificationsService.error("HubSpot API", response.error);
8282
} else
8383
vm.isConnected = true;
8484
});
@@ -91,7 +91,7 @@
9191
vm.hubspotFormsList = data.forms;
9292

9393
if (data.isValid === false || data.isExpired === true) {
94-
notificationsService.error("HubSpot API", "Invalid API key");
94+
notificationsService.error("HubSpot API", data.error);
9595
} else
9696
vm.isConnected = true;
9797
});

src/Umbraco.Cms.Integrations.Crm.Hubspot/App_Plugins/UmbracoCms.Integrations/Crm/Hubspot/package.manifest

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "Umbraco.Cms.Integrations.Crm.Hubspot",
3-
"version": "1.1.6",
3+
"version": "2.0.0",
44
"allowPackageTelemetry": true,
55
"javascript": [
66
"~/App_Plugins/UmbracoCms.Integrations/Crm/Hubspot/js/formpicker.controller.js",

src/Umbraco.Cms.Integrations.Crm.Hubspot/Constants.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,21 @@ public static class Configuration
1717
public const string Settings = "Umbraco:Cms:Integrations:Crm:Hubspot:Settings";
1818
}
1919

20+
public static class ErrorMessages
21+
{
22+
public const string TokenPermissions = "Token does not have the required permissions.";
23+
24+
public const string InvalidApiKey = "Invalid API key.";
25+
26+
public const string ApiKeyMissing = "Cannot access Hubspot - API key is missing";
27+
28+
public const string AccessTokenMissing = "Cannot access Hubspot - Access Token is missing.";
29+
30+
public const string OAuthInvalidToken = "Unable to connect to HubSpot. Please review the settings of the form picker property's data type.";
31+
32+
public const string OAuthFetchFormsConfigurationFailed = "Unable to retrieve the list of forms from HubSpot. Please review the settings of the form picker property's data type.";
33+
}
34+
2035
internal static readonly JsonSerializerSettings SerializationSettings = new JsonSerializerSettings
2136
{
2237
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,

src/Umbraco.Cms.Integrations.Crm.Hubspot/Controllers/FormsController.cs

Lines changed: 99 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -92,59 +92,62 @@ public async Task<ResponseDto> GetAll()
9292
if (string.IsNullOrEmpty(hubspotApiKey))
9393
{
9494
#if NETCOREAPP
95-
_logger.LogInformation(message: LoggingResources.ApiKeyMissing);
95+
_logger.LogInformation(message: Constants.ErrorMessages.ApiKeyMissing);
9696
#else
97-
_logger.Info<FormsController>(message: LoggingResources.ApiKeyMissing);
97+
_logger.Info<FormsController>(message: Constants.ErrorMessages.ApiKeyMissing);
9898
#endif
9999

100-
return new ResponseDto { IsValid = false };
100+
return new ResponseDto { IsValid = false, Error = Constants.ErrorMessages.ApiKeyMissing };
101101
}
102102

103-
var requestMessage = CreateRequest(hubspotApiKey);
103+
string responseContent = string.Empty;
104+
try
105+
{
106+
var requestMessage = CreateRequest(hubspotApiKey);
104107

105-
var response = await ClientFactory().SendAsync(requestMessage);
108+
var response = await ClientFactory().SendAsync(requestMessage);
109+
110+
responseContent = await response.Content.ReadAsStringAsync();
111+
112+
response.EnsureSuccessStatusCode();
113+
114+
var forms = await response.Content.ReadAsStringAsync();
106115

107-
if (response.StatusCode == HttpStatusCode.Unauthorized)
116+
return new ResponseDto
117+
{
118+
IsValid = true,
119+
Forms = ParseForms(forms).ToList()
120+
};
121+
}
122+
catch (HttpRequestException ex) when (ex.Message.Contains(HttpStatusCode.Forbidden.ToString()))
108123
{
109124
#if NETCOREAPP
110-
_logger.LogError(string.Format(LoggingResources.ApiFetchFormsFailed, response.ReasonPhrase));
125+
_logger.LogError(string.Format(LoggingResources.ApiFetchFormsFailed, responseContent));
111126
#else
112-
_logger.Error<FormsController>(string.Format(LoggingResources.ApiFetchFormsFailed, response.ReasonPhrase));
127+
_logger.Error<FormsController>(string.Format(LoggingResources.ApiFetchFormsFailed, responseContent));
113128
#endif
114-
115-
return new ResponseDto { IsExpired = true };
129+
return new ResponseDto { IsValid = false, Error = Constants.ErrorMessages.TokenPermissions };
116130
}
117-
118-
if (response.IsSuccessStatusCode)
131+
catch (HttpRequestException ex) when (ex.Message.Contains(HttpStatusCode.Unauthorized.ToString()))
119132
{
120-
var forms = await response.Content.ReadAsStringAsync();
121-
var hubspotForms = HubspotForms.FromJson(forms);
133+
#if NETCOREAPP
134+
_logger.LogError(string.Format(LoggingResources.ApiFetchFormsFailed, responseContent));
135+
#else
136+
_logger.Error<FormsController>(string.Format(LoggingResources.ApiFetchFormsFailed, responseContent));
137+
#endif
122138

123-
var responseDto = new ResponseDto { IsValid = true };
124-
foreach (var hubspotForm in hubspotForms)
125-
{
126-
var hubspotFormDto = new HubspotFormDto
127-
{
128-
Name = hubspotForm.Name,
129-
PortalId = hubspotForm.PortalId.ToString(),
130-
Id = hubspotForm.Guid,
131-
Region = Options.Region,
132-
Fields = string.Join(", ", hubspotForm.FormFieldGroups.SelectMany(x => x.Fields).Select(y => y.Label))
133-
};
134-
135-
responseDto.Forms.Add(hubspotFormDto);
136-
}
137-
138-
return responseDto;
139+
return new ResponseDto { IsExpired = true, Error = Constants.ErrorMessages.InvalidApiKey };
139140
}
140-
141+
catch
142+
{
141143
#if NETCOREAPP
142-
_logger.LogError(string.Format(LoggingResources.ApiFetchFormsFailed, response.StatusCode + " " + response.ReasonPhrase));
144+
_logger.LogError(string.Format(LoggingResources.ApiFetchFormsFailed, responseContent));
143145
#else
144-
_logger.Error<FormsController>(string.Format(LoggingResources.ApiFetchFormsFailed, response.StatusCode + " " + response.ReasonPhrase));
146+
_logger.Error<FormsController>(string.Format(LoggingResources.ApiFetchFormsFailed, responseContent));
145147
#endif
146148

147-
return new ResponseDto();
149+
return new ResponseDto();
150+
}
148151
}
149152

150153
public async Task<ResponseDto> GetAllOAuth()
@@ -153,58 +156,74 @@ public async Task<ResponseDto> GetAllOAuth()
153156
if (string.IsNullOrEmpty(accessToken))
154157
{
155158
#if NETCOREAPP
156-
_logger.LogInformation(LoggingResources.AccessTokenMissing);
159+
_logger.LogInformation(Constants.ErrorMessages.AccessTokenMissing);
157160
#else
158-
_logger.Info<FormsController>(LoggingResources.AccessTokenMissing);
161+
_logger.Info<FormsController>(Constants.ErrorMessages.AccessTokenMissing);
159162
#endif
160163

161-
return new ResponseDto { IsValid = false };
164+
return new ResponseDto
165+
{
166+
IsValid = false,
167+
Error = Constants.ErrorMessages.OAuthFetchFormsConfigurationFailed
168+
};
162169
}
163170

164-
var requestMessage = CreateRequest(accessToken);
165-
166-
var response = await ClientFactory().SendAsync(requestMessage);
167-
if (response.StatusCode == HttpStatusCode.Unauthorized)
171+
string responseContent = string.Empty;
172+
try
168173
{
169-
#if NETCOREAPP
170-
_logger.LogError(string.Format(LoggingResources.OAuthFetchFormsFailed, response.ReasonPhrase));
171-
#else
172-
_logger.Error<FormsController>(string.Format(LoggingResources.OAuthFetchFormsFailed, response.ReasonPhrase));
173-
#endif
174+
var requestMessage = CreateRequest(accessToken);
174175

175-
return new ResponseDto { IsExpired = true };
176-
}
176+
var response = await ClientFactory().SendAsync(requestMessage);
177177

178-
if (response.IsSuccessStatusCode)
179-
{
180-
var forms = await response.Content.ReadAsStringAsync();
178+
responseContent = await response.Content.ReadAsStringAsync();
181179

182-
var hubspotForms = HubspotForms.FromJson(forms);
180+
response.EnsureSuccessStatusCode();
183181

184-
var responseDto = new ResponseDto { IsValid = true };
185-
foreach (var hubspotForm in hubspotForms)
182+
var forms = await response.Content.ReadAsStringAsync();
183+
184+
return new ResponseDto
186185
{
187-
var hubspotFormDto = new HubspotFormDto
188-
{
189-
Name = hubspotForm.Name,
190-
PortalId = hubspotForm.PortalId.ToString(),
191-
Id = hubspotForm.Guid,
192-
Region = Options.Region,
193-
Fields = string.Join(", ", hubspotForm.FormFieldGroups.SelectMany(x => x.Fields).Select(y => y.Label))
194-
};
195-
responseDto.Forms.Add(hubspotFormDto);
196-
}
197-
198-
return responseDto;
186+
IsValid = true,
187+
Forms = ParseForms(forms).ToList()
188+
};
199189
}
200-
190+
catch(HttpRequestException ex) when (ex.Message.Contains(HttpStatusCode.Unauthorized.ToString()))
191+
{
201192
#if NETCOREAPP
202-
_logger.LogError(string.Format(LoggingResources.OAuthFetchFormsFailed, response.StatusCode + " " + response.ReasonPhrase));
193+
_logger.LogError(string.Format(LoggingResources.OAuthFetchFormsFailed, responseContent));
203194
#else
204-
_logger.Error<FormsController>(string.Format(LoggingResources.OAuthFetchFormsFailed, response.StatusCode + " " + response.ReasonPhrase));
195+
_logger.Error<FormsController>(string.Format(LoggingResources.OAuthFetchFormsFailed, responseContent));
205196
#endif
197+
return new ResponseDto { IsExpired = true, Error = Constants.ErrorMessages.InvalidApiKey };
198+
}
199+
catch
200+
{
201+
#if NETCOREAPP
202+
_logger.LogError(string.Format(LoggingResources.OAuthFetchFormsFailed, responseContent));
203+
#else
204+
_logger.Error<FormsController>(string.Format(LoggingResources.OAuthFetchFormsFailed, responseContent));
205+
#endif
206+
207+
return new ResponseDto();
208+
}
209+
}
206210

207-
return new ResponseDto();
211+
private IEnumerable<HubspotFormDto> ParseForms(string json)
212+
{
213+
var hubspotForms = HubspotForms.FromJson(json);
214+
foreach (var hubspotForm in hubspotForms)
215+
{
216+
var hubspotFormDto = new HubspotFormDto
217+
{
218+
Name = hubspotForm.Name,
219+
PortalId = hubspotForm.PortalId.ToString(),
220+
Id = hubspotForm.Guid,
221+
Region = Options.Region,
222+
Fields = string.Join(", ", hubspotForm.FormFieldGroups.SelectMany(x => x.Fields).Select(y => y.Label))
223+
};
224+
225+
yield return hubspotFormDto;
226+
}
208227
}
209228

210229
private static HttpRequestMessage CreateRequest(string accessToken)
@@ -223,12 +242,12 @@ public HubspotFormPickerSettings CheckConfiguration()
223242
{
224243
return
225244
!string.IsNullOrEmpty(Options.ApiKey)
226-
? new HubspotFormPickerSettings { IsValid = true, Type = ConfigurationType.Api}
245+
? new HubspotFormPickerSettings { IsValid = true, Type = ConfigurationType.Api }
227246
: !string.IsNullOrEmpty(OAuthClientId)
228247
&& !string.IsNullOrEmpty(OAuthScopes)
229248
&& !string.IsNullOrEmpty(OAuthProxyBaseUrl)
230249
&& !string.IsNullOrEmpty(OAuthProxyEndpoint)
231-
? new HubspotFormPickerSettings { IsValid = true, Type = ConfigurationType.OAuth}
250+
? new HubspotFormPickerSettings { IsValid = true, Type = ConfigurationType.OAuth }
232251
: new HubspotFormPickerSettings();
233252
}
234253

@@ -322,7 +341,12 @@ public async Task<ResponseDto> ValidateAccessToken()
322341
{
323342
_tokenService.TryGetParameters(AccessTokenDbKey, out string accessToken);
324343

325-
if (string.IsNullOrEmpty(accessToken)) return new ResponseDto { IsValid = false };
344+
if (string.IsNullOrEmpty(accessToken))
345+
return new ResponseDto
346+
{
347+
IsValid = false,
348+
Error = Constants.ErrorMessages.OAuthInvalidToken
349+
};
326350

327351
var requestMessage = new HttpRequestMessage
328352
{
@@ -336,7 +360,8 @@ public async Task<ResponseDto> ValidateAccessToken()
336360
return new ResponseDto
337361
{
338362
IsValid = response.IsSuccessStatusCode,
339-
IsExpired = response.StatusCode == HttpStatusCode.Unauthorized
363+
IsExpired = response.StatusCode == HttpStatusCode.Unauthorized,
364+
Error = !response.IsSuccessStatusCode ? Constants.ErrorMessages.OAuthInvalidToken : string.Empty
340365
};
341366
}
342367

src/Umbraco.Cms.Integrations.Crm.Hubspot/Models/Dtos/ResponseDto.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ public ResponseDto()
2222
[JsonProperty("isExpired")]
2323
public bool IsExpired { get; set; }
2424

25+
[JsonProperty("error")]
26+
public string Error { get; set; }
27+
2528
[JsonProperty("forms")]
2629
public List<HubspotFormDto> Forms { get; set; }
2730
}

src/Umbraco.Cms.Integrations.Crm.Hubspot/Resources/LoggingResources.cs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,9 @@ namespace Umbraco.Cms.Integrations.Crm.Hubspot.Resources
33
{
44
public static class LoggingResources
55
{
6-
public const string ApiKeyMissing = "Cannot access Hubspot - API key is missing";
7-
86
public const string ApiFetchFormsFailed =
97
"Failed to fetch forms from Hubspot using API key: {0}";
108

119
public const string OAuthFetchFormsFailed = "Failed to fetch forms from Hubspot using OAuth: {0}";
12-
13-
public const string AccessTokenMissing = "Cannot access Hubspot - Access Token is missing.";
1410
}
1511
}

src/Umbraco.Cms.Integrations.Crm.Hubspot/Umbraco.Cms.Integrations.Crm.Hubspot.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
<PackageIconUrl></PackageIconUrl>
1111
<PackageProjectUrl>https://github.com/umbraco/Umbraco.Cms.Integrations/blob/main/src/Umbraco.Cms.Integrations.Crm.Hubspot</PackageProjectUrl>
1212
<RepositoryUrl>https://github.com/umbraco/Umbraco.Cms.Integrations</RepositoryUrl>
13-
<Version>1.1.6</Version>
13+
<Version>2.0.0</Version>
1414
<Authors>Umbraco HQ</Authors>
1515
<Company>Umbraco</Company>
1616
<PackageTags>Umbraco;Umbraco-Marketplace</PackageTags>

src/Umbraco.Cms.Integrations.Crm.Hubspot/package.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
<info>
44
<package>
55
<name>Umbraco.Cms.Integrations.Crm.Hubspot</name>
6-
<version>1.1.5</version>
6+
<version>2.0.0</version>
77
<iconUrl></iconUrl>
88
<licence url="https://opensource.org/licenses/MIT">MIT</licence>
99
<url>https://github.com/umbraco/Umbraco.Cms.Integrations</url>

0 commit comments

Comments
 (0)