-
-
Save dcomartin/a3fd4a77acabfccf58847e27db1c92e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SignUp | |
{ | |
private readonly DbContext _dbContext; | |
public SignUp(DbContext dbContext) | |
{ | |
_dbContext = dbContext; | |
} | |
public Task Handle(SignUpRequest request) | |
{ | |
if (string.IsNullOrWhiteSpace(request.Username)) | |
{ | |
throw new InvalidOperationException("Username is required."); | |
} | |
var existingUser = _dbContext.Users.SingleOrDefault(x => x.Username == request.Username); | |
if (IsExistingUserAlreadyActivated(request, existingUser)) | |
{ | |
throw new InvalidOperationException("You've already registered. Please active your account."); | |
} | |
if (existingUser != null) | |
{ | |
throw new InvalidOperationException("Username is already registered."); | |
} | |
var user = new User(request.Username, request.Email) | |
{ | |
Channels = FilterAgeAppropriateChannels(request) | |
}; | |
_dbContext.Users.Add(user); | |
_dbContext.Outbox.Add(new UserSignedUp(user.Username, user.Email)); | |
_dbContext.Save(); | |
return Task.CompletedTask; | |
} | |
private static bool IsExistingUserAlreadyActivated(SignUpRequest request, User? existingUser) | |
{ | |
return existingUser is { ActivationDate: null } && existingUser.Email.Equals(request.Email, StringComparison.InvariantCultureIgnoreCase); | |
} | |
public List<int> FilterAgeAppropriateChannels(SignUpRequest request) | |
{ | |
var channels = new List<int>(); | |
var now = DateTime.UtcNow; | |
if (request.Birthday.AddYears(18) > now) | |
{ | |
channels.AddRange(request.Channels); | |
return channels; | |
} | |
var kidsAllowedChannels = _dbContext.Channels | |
.Where(x => request.Channels.Contains(x.ChannelId) && x.Age18Required == false) | |
.Select(x => x.ChannelId) | |
.ToArray(); | |
channels.AddRange(kidsAllowedChannels); | |
return channels; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment