示例#1
0
        public async Task <GetConfigurationManagementResponse> GetConfigurationManagement()
        {
            var response = new GetConfigurationManagementResponse();

            var configuration = await _cache.Configuration();

            response.ConfigurationItems = configuration.Items;

            return(response);
        }
        public async Task SendAccountActivation(SendAccountActivationRequest request)
        {
            var activationToken = string.Empty;

            UserEntity user;

            using (var uow = _uowFactory.GetUnitOfWork())
            {
                user = await uow.UserRepo.GetUserById(new Infrastructure.Repositories.UserRepo.Models.GetUserByIdRequest()
                {
                    Id = request.UserId
                });

                activationToken = GenerateUniqueUserToken(uow);

                await uow.UserRepo.CreateUserToken(new Infrastructure.Repositories.UserRepo.Models.CreateUserTokenRequest()
                {
                    User_Id    = request.UserId,
                    Token      = new Guid(activationToken),
                    Type_Id    = (int)TokenTypeEnum.AccountActivation,
                    Created_By = ApplicationConstants.SystemUserId,
                });

                uow.Commit();
            }

            var configuration = await _cache.Configuration();

            var baseUrl = _httpContextAccessor.HttpContext.Request.GetBaseUrl();

            var templates = await _cache.EmailTemplates();

            var templateEntity = templates.FirstOrDefault(t => t.Key == EmailTemplateKeys.AccountActivation);

            var template = new AccountActivationTemplate(templateEntity.Body)
            {
                ActivationUrl  = $"{baseUrl}/activate-account?token={activationToken}",
                ApplicationUrl = baseUrl
            };

            await _emailProvider.Send(new Infrastructure.Email.Models.SendRequest()
            {
                FromAddress = configuration.System_From_Email_Address,
                ToAddress   = user.Email_Address,
                Subject     = template.Subject,
                Body        = template.GetHTMLContent()
            });
        }
示例#3
0
        public async Task <GetHomeResponse> GetHome()
        {
            var response = new GetHomeResponse();
            var config   = await _cache.Configuration();

            response.DisplayPromoBanner = config.Home_Promo_Banner_Is_Enabled;

            return(response);
        }
示例#4
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // validate feature is enabled
            var config = await _cache.Configuration();

            if (!config.Session_Logging_Is_Enabled)
            {
                await next();

                return;
            }

            var session = await _sessionService.GetSession();

            int sessionLogId;

            using (var uow = _uowFactory.GetUnitOfWork())
            {
                var dbRequest = new Infrastructure.Repositories.SessionRepo.Models.CreateSessionLogRequest()
                {
                    Session_Id = session.Id,
                    Method     = context.HttpContext.Request.Method,
                    Controller = (string)context.RouteData.Values["Controller"],
                    Action     = (string)context.RouteData.Values["Action"],
                    Url        = context.HttpContext.Request.GetDisplayUrl(),
                    Created_By = ApplicationConstants.SystemUserId
                };

                if (context.ActionArguments.Any())
                {
                    var jsonString = JsonConvert.SerializeObject(context.ActionArguments, Formatting.Indented).Trim();
                    dbRequest.Action_Data_JSON = JsonHelper.ObfuscateFieldValues(jsonString, ApplicationConstants.ObfuscatedActionArgumentFields);
                }

                sessionLogId = await uow.SessionRepo.CreateSessionLog(dbRequest);

                uow.Commit();

                // required for session event logging
                await _sessionProvider.Set(SessionConstants.SessionLogId, sessionLogId);
            }

            // do something before the action executes
            var resultContext = await next();

            // do something after the action executes; resultContext.Result will be set

            if (resultContext.Exception != null && !resultContext.ExceptionHandled)
            {
                var events = await _cache.SessionEvents();

                var eventItem = events.FirstOrDefault(e => e.Key == SessionEventKeys.Error);

                using (var uow = _uowFactory.GetUnitOfWork())
                {
                    var dbRequest = new Infrastructure.Repositories.SessionRepo.Models.CreateSessionLogEventRequest()
                    {
                        Session_Log_Id = sessionLogId,
                        Event_Id       = eventItem.Id,
                        Message        = resultContext.Exception.Message,
                        Created_By     = ApplicationConstants.SystemUserId
                    };

                    await uow.SessionRepo.CreateSessionLogEvent(dbRequest);

                    uow.Commit();
                }
            }
        }
        public async Task <LoginResponse> Login(LoginRequest request)
        {
            var response = new LoginResponse();
            var config   = await _cache.Configuration();

            var session = await _sessionService.GetSession();

            UserEntity user;

            using (var uow = _uowFactory.GetUnitOfWork())
            {
                user = await uow.UserRepo.GetUserByUsername(new Infrastructure.Repositories.UserRepo.Models.GetUserByUsernameRequest()
                {
                    Username = request.Username
                });

                // check if we found a user or if their password was incorrect
                if (user == null || !PasswordHelper.Verify(request.Password, user.Password_Hash))
                {
                    // if we found the user, handle invalid login attempts else generic fail message
                    if (user != null)
                    {
                        // check if we need to lock the user
                        if (user.Invalid_Login_Attempts >= config.Max_Login_Attempts && !user.Is_Locked_Out)
                        {
                            await uow.UserRepo.LockoutUser(new Infrastructure.Repositories.UserRepo.Models.LockoutUserRequest()
                            {
                                Id          = user.Id,
                                Lockout_End = DateTime.Now.AddMinutes(config.Account_Lockout_Expiry_Minutes),
                                Updated_By  = ApplicationConstants.SystemUserId
                            });

                            await _sessionService.WriteSessionLogEvent(new Models.ServiceModels.Session.CreateSessionLogEventRequest()
                            {
                                EventKey = SessionEventKeys.UserLocked
                            });
                        }
                        else
                        {
                            var dbRequest = new Infrastructure.Repositories.UserRepo.Models.AddInvalidLoginAttemptRequest()
                            {
                                User_Id    = user.Id,
                                Updated_By = ApplicationConstants.SystemUserId
                            };

                            // if we are already locked out then extend the lockout time
                            if (user.Lockout_End.HasValue)
                            {
                                dbRequest.Lockout_End = DateTime.Now.AddMinutes(config.Account_Lockout_Expiry_Minutes);
                            }

                            await uow.UserRepo.AddInvalidLoginAttempt(dbRequest);
                        }
                        uow.Commit();
                    }
                    response.Notifications.AddError("Username or password is incorrect");
                    return(response);
                }

                if (user.Is_Locked_Out)
                {
                    if (user.Lockout_End <= DateTime.Now)
                    {
                        await uow.UserRepo.UnlockUser(new Infrastructure.Repositories.UserRepo.Models.UnlockUserRequest()
                        {
                            Id         = user.Id,
                            Updated_By = ApplicationConstants.SystemUserId
                        });

                        uow.Commit();

                        await _sessionService.WriteSessionLogEvent(new Models.ServiceModels.Session.CreateSessionLogEventRequest()
                        {
                            EventKey = SessionEventKeys.UserUnlocked
                        });
                    }
                    else
                    {
                        response.Notifications.AddError($"Your account has been locked, please try again in {config.Account_Lockout_Expiry_Minutes} minute(s)");
                        return(response);
                    }
                }
                else if (user.Invalid_Login_Attempts > 0) // cleanup of old invalid login attempts
                {
                    await uow.UserRepo.UnlockUser(new Infrastructure.Repositories.UserRepo.Models.UnlockUserRequest()
                    {
                        Id         = user.Id,
                        Updated_By = ApplicationConstants.SystemUserId
                    });

                    uow.Commit();
                }

                if (!user.Is_Enabled)
                {
                    response.Notifications.AddError("Your account has been disabled, please contact the website administrator");
                    return(response);
                }

                if (!user.Registration_Confirmed)
                {
                    response.Notifications.AddError("Please check your email to activate your account");
                    return(response);
                }

                var sessionEntity = await uow.SessionRepo.AddUserToSession(new Infrastructure.Repositories.SessionRepo.Models.AddUserToSessionRequest()
                {
                    Id         = session.Id,
                    User_Id    = user.Id,
                    Updated_By = ApplicationConstants.SystemUserId
                });

                uow.Commit();
                await _sessionProvider.Set(SessionConstants.SessionEntity, sessionEntity);
            }

            await _sessionService.WriteSessionLogEvent(new Models.ServiceModels.Session.CreateSessionLogEventRequest()
            {
                EventKey = SessionEventKeys.UserLoggedIn
            });

            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, session.Id.ToString())
            };

            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);

            await _httpContextAccessor.HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity)); // user principal is controlled in session

            return(response);
        }