diff options
Diffstat (limited to 'Timeline/Services/UserService.cs')
-rw-r--r-- | Timeline/Services/UserService.cs | 82 |
1 files changed, 80 insertions, 2 deletions
diff --git a/Timeline/Services/UserService.cs b/Timeline/Services/UserService.cs index 28218612..0993d3dc 100644 --- a/Timeline/Services/UserService.cs +++ b/Timeline/Services/UserService.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging;
using System;
using System.Linq;
+using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Timeline.Entities;
using Timeline.Models;
@@ -102,6 +103,74 @@ namespace Timeline.Services public long RequiredVersion { get; private set; }
}
+ /// <summary>
+ /// Thrown when username is of bad format.
+ /// </summary>
+ [Serializable]
+ public class UsernameBadFormatException : Exception
+ {
+ public UsernameBadFormatException(string username, string message) : base(message) { Username = username; }
+ public UsernameBadFormatException(string username, string message, Exception inner) : base(message, inner) { Username = username; }
+ protected UsernameBadFormatException(
+ System.Runtime.Serialization.SerializationInfo info,
+ System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
+
+ /// <summary>
+ /// Username of bad format.
+ /// </summary>
+ public string Username { get; private set; }
+ }
+
+ public class UsernameValidator
+ {
+ public const int MaxLength = 26;
+ public const string RegexPattern = @"^[a-zA-Z0-9_][a-zA-Z0-9-_]*$";
+
+ private readonly Regex _regex = new Regex(RegexPattern);
+
+ /// <summary>
+ /// Validate a username.
+ /// </summary>
+ /// <param name="username">The username. Can't be null.</param>
+ /// <param name="message">Set as error message if there is error. Or null if no error.</param>
+ /// <returns>True if validation passed. Otherwise false.</returns>
+ /// <exception cref="ArgumentNullException">Thrown when <paramref name="username"/> is null.</exception>
+ public bool Validate(string username, out string message)
+ {
+ if (username == null)
+ throw new ArgumentNullException(nameof(username));
+
+ if (username.Length == 0)
+ {
+ message = "An empty string is not permitted.";
+ return false;
+ }
+
+ if (username.Length > 26)
+ {
+ message = $"Too long, more than 26 characters is not premitted, found {username.Length}.";
+ return false;
+ }
+
+ foreach ((char c, int i) in username.Select((c, i) => (c, i)))
+ if (char.IsWhiteSpace(c))
+ {
+ message = $"A whitespace is found at {i} . Whitespace is not permited.";
+ return false;
+ }
+
+ var match = _regex.Match(username);
+ if (!match.Success)
+ {
+ message = "Regex match failed.";
+ return false;
+ }
+
+ message = null;
+ return true;
+ }
+ }
+
public interface IUserService
{
/// <summary>
@@ -144,14 +213,14 @@ namespace Timeline.Services /// <summary>
/// Create or modify a user with given username.
- /// Return <see cref="PutUserResult.Created"/> if a new user is created.
- /// Return <see cref="PutUserResult.Modified"/> if a existing user is modified.
+ /// Username must be match with [a-zA-z0-9-_].
/// </summary>
/// <param name="username">Username of user.</param>
/// <param name="password">Password of user.</param>
/// <param name="administrator">Whether the user is administrator.</param>
/// <returns>Return <see cref="PutResult.Created"/> if a new user is created.
/// Return <see cref="PutResult.Modified"/> if a existing user is modified.</returns>
+ /// <exception cref="UsernameBadFormatException">Thrown when <paramref name="username"/> is of bad format.</exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="username"/> or <paramref name="password"/> is null.</exception>
Task<PutResult> PutUser(string username, string password, bool administrator);
@@ -209,6 +278,8 @@ namespace Timeline.Services private readonly IJwtService _jwtService;
private readonly IPasswordService _passwordService;
+ private readonly UsernameValidator _usernameValidator;
+
public UserService(ILogger<UserService> logger, IMemoryCache memoryCache, DatabaseContext databaseContext, IJwtService jwtService, IPasswordService passwordService)
{
_logger = logger;
@@ -216,6 +287,8 @@ namespace Timeline.Services _databaseContext = databaseContext;
_jwtService = jwtService;
_passwordService = passwordService;
+
+ _usernameValidator = new UsernameValidator();
}
private string GenerateCacheKeyByUserId(long id) => $"user:{id}";
@@ -308,6 +381,11 @@ namespace Timeline.Services if (password == null)
throw new ArgumentNullException(nameof(password));
+ if (!_usernameValidator.Validate(username, out var message))
+ {
+ throw new UsernameBadFormatException(username, message);
+ }
+
var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync();
if (user == null)
|