Пример #1
0
        public async Task <bool> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            var staffAccount = _staffRepo.GetByEmail(request.Email);

            if (staffAccount == null)
            {
                return(false);
            }

            var isMatching =
                _passwordHelper.ValidatePassword(request.Password, staffAccount.PasswordSalt, staffAccount.PasswordHash);

            if (!isMatching)
            {
                return(false);
            }

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

            var userIdentity  = new ClaimsIdentity(claims, "Basic");
            var userPrincipal = new ClaimsPrincipal(userIdentity);

            await _signInManager.SignInAsync(userPrincipal, false);

            _cache.Set(staffAccount.Id.ToString(), staffAccount.Role.ToString(), CacheHelper.CacheOptions());

            return(true);
        }
Пример #2
0
        public Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var attr = request.GetType().GetCustomAttribute <Authorize>(false);

            if (attr != null)
            {
                var requiredMinimumRole = attr.Role;

                if (!_currentUser.IsAuthenticated())
                {
                    throw new AuthenticationException();
                }

                var id = _currentUser.GetId();
                if (id <= 0)
                {
                    throw new AuthenticationException();
                }

                var foundInCache = _cache.TryGetValue(id, out Role staffRole);

                if (!foundInCache)
                {
                    var staff = _staffRepo.GetById(id);
                    staffRole = staff.Role;
                    _cache.Set(id, staffRole, CacheHelper.CacheOptions());
                }

                if (staffRole < requiredMinimumRole)
                {
                    throw new AuthorizeException();
                }
            }

            return(next());
        }