Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/login url handling and errors #52

Merged
merged 3 commits into from
Dec 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/App/Pages/Accounts/LoginPageViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Bit.App.Utilities;
using Xamarin.Forms;
using System.Windows.Input;
using System.Net;

namespace Bit.App.Pages
{
Expand Down Expand Up @@ -141,7 +142,7 @@ await _platformUtilsService.ShowDialogAsync(
#region cozy
// Email field is used as CozyURL, it is not renamed not to change the original code
// too much.
var cozyURL = Email;
var cozyURL = UrlHelper.SanitizeUrl(Email);
await _cozyClientService.ConfigureEnvironmentFromCozyURLAsync(cozyURL);
var email = _cozyClientService.GetEmailFromCozyURL(cozyURL);
var response = await _authService.LogInAsync(email, MasterPassword, _captchaToken);
Expand Down Expand Up @@ -187,15 +188,40 @@ await _platformUtilsService.ShowDialogAsync(
LogInSuccessAction?.Invoke();
}
}
// Cozy customization, intercept SanitizeUrl exceptions
//*
catch (CozyException e)
{
await _deviceActionService.HideLoadingAsync();
var translatedErrorMessage = AppResources.ResourceManager.GetString(e.GetType().Name, AppResources.Culture);
await _platformUtilsService.ShowDialogAsync(translatedErrorMessage, AppResources.AnErrorHasOccurred, AppResources.Ok);
}
//*/
catch (ApiException e)
{
_captchaToken = null;
MasterPassword = string.Empty;
await _deviceActionService.HideLoadingAsync();
if (e?.Error != null)
{
// Cozy customization, set custom message for 401 response
// As the stack does not translate error messages and 401 is the most common error
// then we intercept this specific error to translate it on client side
/*
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred, AppResources.Ok);
/*/
if (e.Error.StatusCode == HttpStatusCode.Unauthorized)
Ldoppea marked this conversation as resolved.
Show resolved Hide resolved
{
var translatedErrorMessage = AppResources.ResourceManager.GetString("CozyInvalidLoginException", AppResources.Culture);
await _platformUtilsService.ShowDialogAsync(translatedErrorMessage, AppResources.AnErrorHasOccurred, AppResources.Ok);
}
else
{
await _platformUtilsService.ShowDialogAsync(e.Error.GetSingleMessage(),
AppResources.AnErrorHasOccurred, AppResources.Ok);
}
//*/
}
}
}
Expand Down
16 changes: 16 additions & 0 deletions src/App/Resources/AppResources.fr.resx
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,22 @@
<data name="CozyHomeHaveAccount" xml:space="preserve">
<value>J'ai déjà mon Cozy</value>
</data>
<data name="CozyUrlRequiredException" xml:space="preserve">
<value>L'adresse du Cozy est requise</value>
<comment>Exception message when no CozyUrl is set</comment>
</data>
<data name="NoEmailAsCozyUrlException" xml:space="preserve">
<value>L'adresse de votre Cozy n'est pas votre email</value>
<comment>Exception message when no user set an email in login field</comment>
</data>
<data name="HasMispelledCozyException" xml:space="preserve">
<value>Oups, ce n'est pas la bonne adresse. Essayez d'écrire "cozy" avec un "z" !</value>
Ldoppea marked this conversation as resolved.
Show resolved Hide resolved
<comment>Exception message when user mispels Cozy with Cosy</comment>
</data>
<data name="CozyInvalidLoginException" xml:space="preserve">
<value>L'adresse et le mot de passe que vous avez saisi ne semblent pas correspondre</value>
<comment>Exception message when user enter wrong login or password</comment>
</data>
<data name="Credits" xml:space="preserve">
<value>Remerciements</value>
<comment>Title for page that we use to give credit to resources that we use.</comment>
Expand Down
16 changes: 16 additions & 0 deletions src/App/Resources/AppResources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,22 @@
<data name="CozyHomeHaveAccount" xml:space="preserve">
<value>I already have my Cozy</value>
</data>
<data name="CozyUrlRequiredException" xml:space="preserve">
<value>Cozy address is required</value>
<comment>Exception message when no CozyUrl is set</comment>
</data>
<data name="NoEmailAsCozyUrlException" xml:space="preserve">
<value>The Cozy address is not your email</value>
<comment>Exception message when no user set an email in login field</comment>
</data>
<data name="HasMispelledCozyException" xml:space="preserve">
<value>Woops, the address is not correct. Try with "cozy" with a "z"!</value>
<comment>Exception message when user mispels Cozy with Cosy</comment>
</data>
<data name="CozyInvalidLoginException" xml:space="preserve">
<value>The address and password you entered seems to not match</value>
<comment>Exception message when user enter wrong login or password</comment>
</data>
<data name="Credits" xml:space="preserve">
<value>Credits</value>
<comment>Title for page that we use to give credit to resources that we use.</comment>
Expand Down
8 changes: 8 additions & 0 deletions src/Core/Exceptions/CozyException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using System;

namespace Bit.Core.Exceptions
{
public class CozyException : Exception
{
}
}
23 changes: 23 additions & 0 deletions src/Core/Models/Response/ErrorResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ public ErrorResponse(JObject response, HttpStatusCode status, bool identityRespo
if (errorModel != null)
{
var model = errorModel.ToObject<ErrorModel>();

// Cozy customization, add specific parser for Stack error messages
// CozyStack error messages do not fit Bitwarden's errors format
// so we have to create a custom parser for them
//*
if (model.Message == null && model.ValidationErrors == null)
{
var cozyModel = errorModel.ToObject<CozyErrorModel>();

model.Message = cozyModel.Error;
}
//*/

Message = model.Message;
ValidationErrors = model.ValidationErrors ?? new Dictionary<string, List<string>>();
CaptchaSiteKey = ValidationErrors.ContainsKey("HCaptcha_SiteKey") ?
Expand Down Expand Up @@ -72,5 +85,15 @@ private class ErrorModel
public string Message { get; set; }
public Dictionary<string, List<string>> ValidationErrors { get; set; }
}

// Cozy customization, add specific parser for Stack error messages
// CozyStack error messages do not fit Bitwarden's errors format
// so we have to create a custom parser for them
//*
private class CozyErrorModel
{
public string Error { get; set; }
}
//*/
}
}
120 changes: 120 additions & 0 deletions src/Core/Utilities/UrlHelper.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Bit.Core.Exceptions;
using Flurl;

namespace Bit.Core.Utilities
{
public static class UrlHelper
{
public static string COZY_DOMAIN = ".mycozy.cloud";

// Code taken from CozyClient.EnsureFirstSlash()
private static string EnsureFirstSlash(string path)
{
Expand Down Expand Up @@ -76,5 +80,121 @@ string subDomainType

return url.ToString();
}

/// <summary>
/// Sanitize the given url in order to fit CozyUrl format
/// A CozyUrl :
/// - should not be null
/// - should not be an email
/// - should not misspell Cozy with Cosy
/// - has a valid scheme (http or https)
/// - has a hostname
/// - do not has an app slug in it (except for custom domains)
/// - do no ends with a trailing space
///
/// To have a complete list of CozyUrl rules, please refer to UrlHelperTests.cs tests
/// </summary>
/// <param name="inputUrl">Url to sanitize</param>
/// <returns>Sanitized url</returns>
public static string SanitizeUrl(string inputUrl)
{
// Prevent empty url
if (string.IsNullOrEmpty(inputUrl))
{
throw new CozyUrlRequiredException();
}

// Prevent email input
if (inputUrl.Contains('@'))
{
throw new NoEmailAsCozyUrlException();
}

if (HasMispelledCozy(inputUrl))
{
throw new HasMispelledCozyException();
}

return NormalizeUrl(inputUrl, COZY_DOMAIN);
}

private static string NormalizeUrl(string value, string defaultDomain)
{
var valueWithProtocol = PrependProtocol(value);
var valueWithoutTrailingSlash = RemoveTrailingSlash(valueWithProtocol);
var valueWithProtocolAndDomain = AppendDomain(
valueWithoutTrailingSlash,
defaultDomain
);

var isDefaultDomain = valueWithProtocolAndDomain.Contains(defaultDomain);

return isDefaultDomain
? RemoveAppSlug(valueWithProtocolAndDomain)
: valueWithProtocolAndDomain;
}

private static bool HasMispelledCozy(string value)
{
return value.Contains("mycosy");
}

private static string AppendDomain(string value, string domain)
{
var regex = new Regex(@"\.", RegexOptions.IgnoreCase);
if (regex.IsMatch(value))
{
return value;
}

return $"{value}{domain}";
}

private static string PrependProtocol(string value)
{
var regex = new Regex(@"^http(s)?:\/\/", RegexOptions.IgnoreCase);
if (regex.IsMatch(value))
{
return value;
}

return $"https://{value}";
}

private static string RemoveTrailingSlash(string value)
{
if (value.EndsWith("/"))
{
return value.Substring(0, value.Length - 1);
}

return value;
}

private static string RemoveAppSlug(string value)
{
var regex = new Regex(@"^https?:\/\/\w+(-\w+)\.", RegexOptions.IgnoreCase);

var matches = regex.Match(value);

if (matches.Groups.Count > 1)
{
return value.Replace(matches.Groups[1].Value, "");
}

return value;
}
}

public class CozyUrlRequiredException : CozyException
{
}

public class NoEmailAsCozyUrlException : CozyException
{
}

public class HasMispelledCozyException : CozyException
{
}
}
Loading