public async Task OnActionExecutedAsync(ResultExecutingContext context) { // The controller action didn't return a view result so no need to continue execution if (!(context.Result is ViewResult result)) { return; } // Check early to ensure we are working with a LayoutViewModel if (!(result?.Model is LayoutViewModel model)) { return; } // Get authenticated user from context var user = context.HttpContext.Features[typeof(User)] as User; // Get client details var ipV4Address = _clientIpAddress.GetIpV4Address(); var ipV6Address = _clientIpAddress.GetIpV6Address(); var userAgent = string.Empty; if (context.HttpContext.Request.Headers.ContainsKey("User-Agent")) { userAgent = context.HttpContext.Request.Headers["User-Agent"].ToString(); } // Get route data var url = context.HttpContext.Request.GetDisplayUrl(); // Get page title from context var title = context.HttpContext.Items[typeof(PageTitle)] is PageTitle pageTitle ? pageTitle.Title : string.Empty; // Get area name var areaName = string.Empty; if (context.RouteData.Values["area"] != null) { areaName = context.RouteData.Values["area"].ToString(); } // Get feature from area var feature = await _featureFacade.GetFeatureByIdAsync(areaName); // Add metric await _metricManager.CreateAsync(new Metric() { FeatureId = feature?.Id ?? 0, Title = title, Url = url, IpV4Address = ipV4Address, IpV6Address = ipV6Address, UserAgent = userAgent, CreatedUserId = user?.Id ?? 0, CreatedDate = DateTimeOffset.UtcNow }); }
public async Task OnActionExecutedAsync(ResultExecutingContext context) { // The controller action didn't return a view result so no need to continue execution var result = context.Result as ViewResult; // Check early to ensure we are working with a LayoutViewModel var model = result?.Model as LayoutViewModel; if (model == null) { return; } // Check for the id route value var id = context.RouteData.Values["opts.id"]; if (id == null) { return; } // To int var ok = int.TryParse(id.ToString(), out var entityId); // Id route value is not a valid int if (!ok) { return; } // Get authenticated user from context var user = context.HttpContext.Features[typeof(User)] as User; // Get client details var ipV4Address = _clientIpAddress.GetIpV4Address(); var ipV6Address = _clientIpAddress.GetIpV6Address(); var userAgent = ""; if (context.HttpContext.Request.Headers.ContainsKey("User-Agent")) { userAgent = context.HttpContext.Request.Headers["User-Agent"].ToString(); } // Add metric await _entityMetricManager.CreateAsync(new EntityMetric() { EntityId = entityId, IpV4Address = ipV4Address, IpV6Address = ipV6Address, UserAgent = userAgent, CreatedUserId = user?.Id ?? 0, CreatedDate = DateTimeOffset.UtcNow }); }
async Task <User> BuildUserAsync(LoginPage userLogin) { var user = await _platoUserStore.GetByUserNameAsync(userLogin.UserName); if (user == null) { return(null); } // Ensure we check against the IP address being used at the time of the login user.IpV4Address = _clientIpAddress.GetIpV4Address(); user.IpV6Address = _clientIpAddress.GetIpV6Address(); return(user); }
public override async Task <bool> ValidateModelAsync(UserRegistration registration, IUpdateModel updater) { // Build user to validate var user = new User() { UserName = registration.UserName, Email = registration.Email, IpV4Address = _clientIpAddress.GetIpV4Address(), IpV6Address = _clientIpAddress.GetIpV6Address() }; // Validate model within registered spam operators var results = await _spamOperatorManager.ValidateModelAsync(SpamOperations.Registration, user); // IF any operators failed ensure we display the operator error message var valid = true; if (results != null) { foreach (var result in results) { if (!result.Succeeded) { if (result.Operation.CustomMessage) { updater.ModelState.AddModelError(string.Empty, !string.IsNullOrEmpty(result.Operation.Message) ? result.Operation.Message : $"Sorry but we've identified your details have been used by known spammers."); valid = false; } } } } return(valid); }
public async Task <IActionResult> Post([FromBody] EntityRating model) { if (model.EntityId < 0) { throw new ArgumentOutOfRangeException(nameof(model.EntityId)); } // Get entity var entity = await _entityStore.GetByIdAsync(model.EntityId); // Ensure we found the reply if (entity == null) { return(NotFound()); } // Get permission var permission = model.EntityReplyId > 0 ? Permissions.VoteTopicReplies : Permissions.VoteTopics; // Ensure we have permission if (!await _authorizationService.AuthorizeAsync(User, entity.CategoryId, permission)) { return(Unauthorized()); } // Get authenticated user (if any) var user = await base.GetAuthenticatedUserAsync(); // Get client details var ipV4Address = _clientIpAddress.GetIpV4Address(); var ipV6Address = _clientIpAddress.GetIpV6Address(); var userAgent = ""; if (Request.Headers.ContainsKey("User-Agent")) { userAgent = Request.Headers["User-Agent"].ToString(); } // Track if existing votes were deleted var deleted = false; if (user != null) { // Delete all existing votes for authenticated user, We can only vote once var existingRatings = await _entityRatingsStore.SelectEntityRatingsByUserIdAndEntityId(user.Id, model.EntityId); if (existingRatings != null) { foreach (var rating in existingRatings.Where(r => r.EntityReplyId == model.EntityReplyId)) { var delete = await _entityRatingManager.DeleteAsync(rating); if (delete.Succeeded) { deleted = true; } } } } else { // Delete all existing votes for anonymous user using there // IP addresses & user agent as a unique identifier var existingRatings = await _entityRatingsStore.QueryAsync() .Select <EntityRatingsQueryParams>(q => { q.EntityId.Equals(model.EntityId); q.CreatedUserId.Equals(0); q.IpV4Address.Equals(ipV4Address); q.IpV6Address.Equals(ipV6Address); q.UserAgent.Equals(userAgent); }) .ToList(); if (existingRatings?.Data != null) { foreach (var rating in existingRatings.Data.Where(r => r.EntityReplyId == model.EntityReplyId)) { var delete = await _entityRatingManager.DeleteAsync(rating); if (delete.Succeeded) { deleted = true; } } } } if (deleted) { // Update reply if (model.EntityReplyId > 0) { // return 202 accepted to confirm delete with updated response return(base.AcceptedDelete(await UpdateEntityReplyRating(model.EntityReplyId))); } // Update entity if (model.EntityId > 0) { // return 202 accepted to confirm delete with updated response return(base.AcceptedDelete(await UpdateEntityRating(model.EntityId))); } } // Set created by model.CreatedUserId = user?.Id ?? 0; model.CreatedDate = DateTimeOffset.UtcNow; model.IpV4Address = ipV4Address; model.IpV6Address = ipV6Address; model.UserAgent = userAgent; // Add and return results var result = await _entityRatingManager.CreateAsync(model); if (result.Succeeded) { // Update reply if (model.EntityReplyId > 0) { // return 201 created return(base.Created(await UpdateEntityReplyRating(model.EntityReplyId))); } // Update entity if (model.EntityId > 0) { // return 201 created return(base.Created(await UpdateEntityRating(model.EntityId))); } } // We should not reach here return(base.InternalServerError()); }
public async Task <ICommandResult <TUser> > CreateAsync(TUser model, string password) { if (model == null) { throw new ArgumentNullException(nameof(model)); } var result = new CommandResult <TUser>(); // Validate // ------------------------- if (String.IsNullOrEmpty(model.UserName) || String.IsNullOrWhiteSpace(model.UserName)) { return(result.Failed(new CommandError("UserName", T["A username is required"]))); } if (String.IsNullOrEmpty(model.Email) || String.IsNullOrWhiteSpace(model.Email)) { return(result.Failed(new CommandError("Email", T["A email is required"]))); } if (string.IsNullOrWhiteSpace(password) || String.IsNullOrWhiteSpace(password)) { return(result.Failed(new CommandError("Password", T["A password is required"]))); } // Check Uniqueness // ------------------------- // Is this a unique email? if (await _userManager.FindByEmailAsync(model.Email) != null) { return(result.Failed(new CommandError("Email", T["The email already exists"]))); } // Is this a unique username? if (await _userManager.FindByNameAsync(model.UserName.Normalize()) != null) { return(result.Failed(new CommandError("UserName", T["The username already exists"]))); } // ------------------------- // Get site settings to populate some user defaults var settings = await _siteSettingsStore.GetAsync(); if (settings != null) { model.TimeZone = settings.TimeZone; } model.PhotoColor = _userColorProvider.GetColor(); model.SignatureHtml = await ParseSignatureHtml(model.Signature); if (String.IsNullOrEmpty(model.IpV4Address)) { model.IpV4Address = _clientIpAddress.GetIpV4Address(); } if (String.IsNullOrEmpty(model.IpV6Address)) { model.IpV6Address = _clientIpAddress.GetIpV6Address(); } // Add security stamp await _securityStampStore.SetSecurityStampAsync(model, System.Guid.NewGuid().ToString(), new CancellationToken()); // Invoke UserCreating subscriptions foreach (var handler in _broker.Pub <TUser>(this, "UserCreating")) { model = await handler.Invoke(new Message <TUser>(model, this)); } // Persist the user var identityResult = await _userManager.CreateAsync(model, password); if (identityResult.Succeeded) { // Get newly created user var updatedOrNewUser = await _userManager.FindByEmailAsync(model.Email); // Add roles from model if (updatedOrNewUser != null) { if (model.RoleNames != null) { foreach (var role in model.RoleNames) { if (!await _userManager.IsInRoleAsync(updatedOrNewUser, role)) { await _userManager.AddToRoleAsync(updatedOrNewUser, role); } } } } // Invoke UserCreated subscriptions foreach (var handler in _broker.Pub <TUser>(this, "UserCreated")) { updatedOrNewUser = await handler.Invoke(new Message <TUser>(updatedOrNewUser, this)); } // Return success return(result.Success(updatedOrNewUser)); } // User could not be created, accumulate errors var errors = new List <CommandError>(); foreach (var error in identityResult.Errors) { errors.Add(new CommandError(error.Code, T[error.Description])); } return(result.Failed(errors.ToArray())); }
public async Task <IActionResult> Post([FromBody] EntityReaction model) { // Get authenticated user (if any) var user = await base.GetAuthenticatedUserAsync(); // Get client details var ipV4Address = _clientIpAddress.GetIpV4Address(); var ipV6Address = _clientIpAddress.GetIpV6Address(); var userAgent = ""; if (Request.Headers.ContainsKey("User-Agent")) { userAgent = Request.Headers["User-Agent"].ToString(); } IEnumerable <EntityReaction> existingReactions = null; if (user != null) { // Has the user already reacted to the entity? existingReactions = await _entityReactionsStore.SelectEntityReactionsByUserIdAndEntityId(user.Id, model.EntityId); } else { // Delete all existing reactions for anonymous user using there // IP addresses & user agent as a unique identifier var anonymousReactions = await _entityReactionsStore.QueryAsync() .Select <EntityReactionsQueryParams>(q => { q.EntityId.Equals(model.EntityId); q.CreatedUserId.Equals(0); q.IpV4Address.Equals(ipV4Address); q.IpV6Address.Equals(ipV6Address); q.UserAgent.Equals(userAgent); }) .ToList(); existingReactions = anonymousReactions?.Data; } // Get reaction from existing reactions EntityReaction existingReaction = null; if (existingReactions != null) { foreach (var reaction in existingReactions.Where(r => r.EntityReplyId == model.EntityReplyId)) { if (reaction.ReactionName.Equals(model.ReactionName)) { existingReaction = reaction; break; } } } // Delete any existing reaction if (existingReaction != null) { var delete = await _entityReactionManager.DeleteAsync(existingReaction); if (delete.Succeeded) { // return 202 accepted to confirm delete return(base.AcceptedDelete(await _simpleReactionsStore.GetSimpleReactionsAsync(model.EntityId, model.EntityReplyId))); } } // Set created by model.CreatedUserId = user?.Id ?? 0; model.CreatedDate = DateTimeOffset.UtcNow; model.IpV4Address = ipV4Address; model.IpV6Address = ipV6Address; model.UserAgent = userAgent; // Add and return results var result = await _entityReactionManager.CreateAsync(model); if (result.Succeeded) { // return 201 created return(base.Created(await _simpleReactionsStore.GetSimpleReactionsAsync(model.EntityId, model.EntityReplyId))); } // We should not reach here return(base.InternalServerError()); }