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

Fixed Verifiy email using regex and modified Login action #236

Merged
merged 8 commits into from Oct 2, 2018
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Fan.Web/Controllers/AuthController.cs
Expand Up @@ -52,7 +52,7 @@ public async Task<IActionResult> Login([FromBody] LoginViewModel loginUser)
return BadRequest("Invalid credentials!");

// sign user in
var result = await _signInManager.PasswordSignInAsync(user.UserName, loginUser.Password,
var result = await _signInManager.PasswordSignInAsync(user, loginUser.Password,
loginUser.RememberMe, lockoutOnFailure: false);

if (!result.Succeeded)
Expand Down
64 changes: 64 additions & 0 deletions src/Fan/Helpers/RegexUtilities.cs
@@ -0,0 +1,64 @@
using System;
using System.Globalization;
using System.Text.RegularExpressions;

namespace Fan.Helpers
{
/// <summary>
/// A util class that uses regular expression to verify if a string is in valid email format.
/// </summary>
/// <remarks>
/// https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format
/// </remarks>
public static class RegexUtilities
{
public static bool IsValidEmail(string strIn)
{
if (String.IsNullOrEmpty(strIn))
return false;

// Use IdnMapping class to convert Unicode domain names.
try
{
strIn = Regex.Replace(strIn, @"(@)(.+)$", DomainMapper,
RegexOptions.None, TimeSpan.FromMilliseconds(200));
if(string.IsNullOrEmpty(strIn))
return false;
}
catch (Exception ex)
{
if(ex is RegexMatchTimeoutException || ex is ArgumentNullException)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you are checking for null on line 25, why would you check for ArgumentNullException on this line?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I forgot to remove it. My mistake!

return false;
}
// Return true if strIn is in valid email format.
try
{
return Regex.IsMatch(strIn,
@"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
}
catch (RegexMatchTimeoutException)
{
return false;
}
}

private static string DomainMapper(Match match)
{
// IdnMapping class with default property values.
IdnMapping idn = new IdnMapping();

string domainName = match.Groups[2].Value;
try
{
domainName = idn.GetAscii(domainName);
}
catch (ArgumentException)
{
return null;
}
return match.Groups[1].Value + domainName;
}
}
}
19 changes: 3 additions & 16 deletions src/Fan/Membership/UserService.cs
@@ -1,7 +1,6 @@
using Microsoft.AspNetCore.Identity;
using Fan.Helpers;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Mail;
using System.Threading.Tasks;

namespace Fan.Membership
Expand All @@ -10,7 +9,6 @@ public class UserService : IUserService
{
private readonly UserManager<User> _userManager;
private readonly ILogger<UserService> _logger;

public UserService(UserManager<User> userManager,
ILogger<UserService> logger)
{
Expand All @@ -25,18 +23,7 @@ public class UserService : IUserService
/// <returns></returns>
public async Task<User> FindByEmailOrUsernameAsync(string emailOrUsername)
{
bool isEmail;
try
{
new MailAddress(emailOrUsername);
isEmail = true;
}
catch (FormatException)
{
isEmail = false;
}

// get user
bool isEmail = RegexUtilities.IsValidEmail(emailOrUsername);
return isEmail ? await _userManager.FindByEmailAsync(emailOrUsername) :
await _userManager.FindByNameAsync(emailOrUsername);
}
Expand Down
40 changes: 40 additions & 0 deletions test/Fan.UnitTests/Helpers/RegexUtilitiesTest.cs
@@ -0,0 +1,40 @@
using Fan.Helpers;
using Xunit;

namespace Fan.UnitTests.Helpers
{
/// <summary>
/// Test for <see cref="RegexUtilities"/> class.
/// </summary>
public class RegexUtilitiesTest
{
/// <summary>
/// Test cases for <see cref="RegexUtilities.IsValidEmail(string)"/> method.
/// </summary>
/// <param name="email"></param>
/// <param name="expected"></param>
/// <remarks>
/// Test data provided by https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format#compiling-the-code
/// </remarks>
[Theory]
[InlineData("david.jones@proseware.com", true)]
[InlineData("d.j@server1.proseware.com", true)]
[InlineData("jones@ms1.proseware.com", true)]
[InlineData("j.@server1.proseware.com", false)]
[InlineData("j@proseware.com9", true)]
[InlineData("js#internal@proseware.com", true)]
[InlineData("j_9@[129.126.118.1]", true)]
[InlineData("j..s@proseware.com", false)]
[InlineData("js*@proseware.com", false)]
[InlineData("js@proseware..com", false)]
[InlineData("js@proseware.com9", true)]
[InlineData("j.s@server1.proseware.com", true)]
[InlineData(@"""j\""s\""""@proseware.com", true)]
[InlineData("js@contoso.中国", true)]
[InlineData("username", false)]
public void IsValidEmail_Test(string email, bool expected)
{
Assert.Equal(expected, RegexUtilities.IsValidEmail(email));
}
}
}