Пример #1
0
 public Task SendMessage(CredentialEntity credentialEntity, string recipient)
 {
     // TODO: write the content of this function that will send the credentials to a recipient.
     // It should use the EmailSender class as a dummy email sender
     // If the email sender throws an exception, it should retry exactly 4 times with a 10 minute interval, then stop retrying
     return(Task.CompletedTask);
 }
Пример #2
0
        public IResult Generate(LoginDto login)
        {
            //TODO:
            //CONSULTAR USUARIO PARA AUTENTICAR

            CredentialEntity credentialEntity = new CredentialEntity(login.User);

            if (credentialEntity.Invalid || !_consumerRepository.Exists(long.Parse(login.User)))
            {
                return(new ValidateResult(credentialEntity.Notifications, false, "Probleamas ao obter acesso"));
            }

            SymmetricSecurityKey symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));

            SigningCredentials signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);

            List <Claim> claims = new List <Claim>
            {
                new Claim(nameof(login.User), login.User)
            };

            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                issuer: _configuration["Jwt:Issuer"],
                audience: _configuration["Jwt:Audience"],
                expires: DateTime.Now.AddMinutes(120),
                claims: claims,
                signingCredentials: signingCredentials);

            string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

            return(new ValidateResult(token, true, "Acesso permitido"));
        }
        public void Insert_ShouldInsertIntoDatabaseWithMultipleRoles()
        {
            // Arrange
            var dataMapper = new CredentialDataMapper(_context);

            CredentialEntity credential1 = new CredentialEntityBuilder().SetDummy().SetEmail("*****@*****.**").SetDummyRole("Gebruiker").Create();
            CredentialEntity credential2 = new CredentialEntityBuilder().SetDummy().SetEmail("*****@*****.**").SetDummyRole("Klant").SetDummyRole("Sales").Create();
            CredentialEntity credential3 = new CredentialEntityBuilder().SetDummy().SetEmail("*****@*****.**").SetDummyRole("Klant").SetDummyRole("Sales").Create();

            // Act
            credential1 = dataMapper.Insert(credential1);
            credential2 = dataMapper.Insert(credential2);
            credential3 = dataMapper.Insert(credential3);

            // Changing a category should cause the artikel3 assert to fail
            credential3.CredentialRoles.ElementAt(0).Role.Name = "Hotdogverkoper";

            CredentialEntity result1 = dataMapper.Find(x => x.Id == credential1.Id).FirstOrDefault();
            CredentialEntity result2 = dataMapper.Find(x => x.Id == credential2.Id).FirstOrDefault();
            CredentialEntity result3 = dataMapper.Find(x => x.Id == credential3.Id).FirstOrDefault();

            // Assert
            Assert.IsNotNull(result1);
            Assert.IsNotNull(result2);
            Assert.IsNotNull(result3);

            Assert.AreEqual(3, _context.RoleEntities.Count());

            Assert.IsTrue(credential1.IsEqual(result1));
            Assert.IsTrue(credential2.IsEqual(result2));
            Assert.IsTrue(credential3.IsEqual(result3));
        }
        public CredentialEntity Insert(CredentialEntity entity)
        {
            InsertRoleIfNonExistant(entity);

            CredentialEntity credentialEntity = _context.CredentialEntities.Add(entity).Entity;

            _context.SaveChanges();
            return(credentialEntity);
        }
        public void Update(CredentialEntity entity)
        {
            InsertRoleIfNonExistant(entity);

            var removedRelations = _context.CredentialRoleEntities.Where(x => x.CredentialId == entity.Id &&
                                                                         entity.CredentialRoles.FirstOrDefault(y => y.Role.Name == x.Role.Name) == null);

            _context.CredentialEntities.Update(entity);
            _context.CredentialRoleEntities.RemoveRange(removedRelations);

            _context.SaveChanges();
        }
        public void Update_CredentialsWithMultipleRolesInDatabase()
        {
            // Arrange
            var dataMapper = new CredentialDataMapper(_context);

            CredentialEntity credential1 = new CredentialEntityBuilder().SetDummy().SetEmail("*****@*****.**").SetDummyRole("Gebruiker").Create();
            CredentialEntity credential2 = new CredentialEntityBuilder().SetDummy().SetEmail("*****@*****.**").SetDummyRole("Klant").SetDummyRole("Sales").Create();
            CredentialEntity credential3 = new CredentialEntityBuilder().SetDummy().SetEmail("*****@*****.**").SetDummyRole("Klant").SetDummyRole("Sales").Create();

            credential1 = dataMapper.Insert(credential1);
            credential2 = dataMapper.Insert(credential2);
            credential3 = dataMapper.Insert(credential3);

            // Act
            credential2.CredentialRoles.Remove(credential2.CredentialRoles.First());
            dataMapper.Update(credential2);

            var cat = credential3.CredentialRoles.ElementAt(0);

            credential3.CredentialRoles.Remove(cat);

            var newCat = new CredentialRoleEntity {
                Role = new RoleEntity {
                    Name = "Metzger"
                }
            };

            credential3.CredentialRoles.Add(newCat);
            dataMapper.Update(credential3);

            CredentialEntity result1 = dataMapper.Find(x => x.Email == "*****@*****.**").FirstOrDefault();
            CredentialEntity result2 = dataMapper.Find(x => x.Email == "*****@*****.**").FirstOrDefault();
            CredentialEntity result3 = dataMapper.Find(x => x.Email == "*****@*****.**").FirstOrDefault();

            // Assert
            Assert.IsNotNull(result1);
            Assert.IsNotNull(result2);
            Assert.IsNotNull(result3);

            Assert.AreEqual(4, _context.RoleEntities.Count());

            Assert.AreEqual(1, result1.CredentialRoles.Count());
            Assert.AreEqual(1, result2.CredentialRoles.Count());
            Assert.AreEqual(2, result3.CredentialRoles.Count());

            Assert.IsTrue(credential1.IsEqual(result1));
            Assert.IsTrue(credential2.IsEqual(result2));
            Assert.IsTrue(credential3.IsEqual(result3));
        }
        public void Insert_ShouldInsertIntoDatabase()
        {
            // Arrange
            var dataMapper = new CredentialDataMapper(_context);
            CredentialEntity credential = new CredentialEntityBuilder().SetDummy().Create();

            // Act
            dataMapper.Insert(credential);

            CredentialEntity result = dataMapper.Find(x => x.Id == credential.Id).FirstOrDefault();

            // Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(credential.IsEqual(result));
        }
 private void InsertRoleIfNonExistant(CredentialEntity entity)
 {
     foreach (var credentialRole in entity.CredentialRoles)
     {
         var role = _context.RoleEntities.FirstOrDefault(x => x.Name == credentialRole.Role.Name);
         if (role == null)
         {
             _context.RoleEntities.Add(credentialRole.Role);
         }
         else
         {
             credentialRole.Role = role;
         }
     }
 }
        public void Find_ShouldReturnItemsSpecifiedByExpression()
        {
            // Arrange
            var dataMapper = new CredentialDataMapper(_context);
            CredentialEntity credential = new CredentialEntityBuilder().SetDummy().Create();

            _context.CredentialEntities.Add(credential);
            _context.SaveChanges();

            // Act
            CredentialEntity result = dataMapper.Find(x => x.Id == credential.Id).FirstOrDefault();

            // Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(credential.IsEqual(result));
        }
Пример #10
0
        public HttpResponseMessage <ServiceResponseWithResultData <Guid?> > Login(UserLogin userLogin)
        {
            if (userLogin == null || string.IsNullOrEmpty(userLogin.EmailAddress) || string.IsNullOrEmpty(userLogin.Password))
            {
                return(CompleteResponseWithData(new ServiceResponseWithResultData <Guid?> {
                    State = ServiceResponseStateType.FailedValidation
                }));
            }
            // Define Query
            ISingleResultQuery <CredentialQueryStrategy, CredentialEntity> query = QueryFactory.CreateNewSingleResultQuery <CredentialQueryStrategy, CredentialEntity>();

            string hash = AuthenticationHashHelper.GenerateCredentialHash(userLogin.EmailAddress, userLogin.Password);

            query.QueryStrategy.WithHash(hash);

            // Retrieve Data
            query = CredentialRepository.Retrieve(query, false);
            CredentialEntity queryResults = query.Result;

            var responseData = new ServiceResponseWithResultData <Guid?>
            {
                State      = queryResults == null ? ServiceResponseStateType.FailedAuthentication : ServiceResponseStateType.Succeeded,
                ResultData = queryResults == null ? (Guid?)null : queryResults.UserRsn
            };

            // Complete the response
            HttpResponseMessage <ServiceResponseWithResultData <Guid?> > response = CompleteResponseWithData(responseData);

            // If authentication has succeeded then return now.
            if (responseData.State != ServiceResponseStateType.Succeeded || responseData.ResultData == null)
            {
                return(response);
            }

            // Copy encrypted auth token to X-Token for SignalR
            string authenticationTokenName = DependencyResolver.Current.Resolve <IConfigurationManager>().GetSetting("Cqrs.Web.AuthenticationTokenName") ?? "X-Token";
            var    cookie = new CookieHeaderValue(authenticationTokenName, responseData.ResultData.Value.ToString("N"))
            {
                Expires = DateTimeOffset.Now.AddDays(1),
            };

            response.Headers.AddCookies(new[] { cookie });

            return(response);
        }
Пример #11
0
        public bool Login(CredentialEntity credential)
        {
            _Authenticated = false;

            if (Company.Connect() == 0)
            {
                AuthenticateUserResultsEnum result;
                result = Company.AuthenticateUser(credential.UserName, credential.Password);
                if (result == AuthenticateUserResultsEnum.aturUsernamePasswordMatch)
                {
                    _Authenticated = true;
                }
            }

            Company.Disconnect();

            return(_Authenticated);
        }
        private CredentialEntity AddRole(CredentialEntity entity, Roles role)
        {
            var credentialRoleEntity = new CredentialRoleEntity()
            {
                Credential = entity,
                Role       = new RoleEntity()
                {
                    Name            = role.ToString(),
                    CredentialRoles = new HashSet <CredentialRoleEntity>()
                }
            };

            credentialRoleEntity.Credential.CredentialRoles.Add(credentialRoleEntity);
            credentialRoleEntity.Role.CredentialRoles.Add(credentialRoleEntity);

            _credentialDataMapper.Update(entity);
            return(entity);
        }
Пример #13
0
        public void AddRole_ShouldReturn_True()
        {
            // Arrange
            var credentials = new Credential
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            var credentialEntities = new List <CredentialEntity>()
            {
                new CredentialEntity()
                {
                    Email = credentials.Email, Password = credentials.Password, CredentialRoles = new List <CredentialRoleEntity>()
                }
            };
            CredentialEntity updateParam = null;

            var mapperMock = new Mock <ICredentialDataMapper>(MockBehavior.Strict);

            mapperMock.Setup(x => x.Find(It.IsAny <Expression <Func <CredentialEntity, bool> > >())).Returns(credentialEntities);
            mapperMock.Setup(x => x.Update(It.IsAny <CredentialEntity>()))
            .Callback <CredentialEntity>(entity =>
            {
                updateParam = entity;
            });

            var listener = new AccountListener(mapperMock.Object, new LoggerFactory());

            var roleRequest = new RoleRequest()
            {
                Email = credentials.Email, Role = Roles.Sales
            };

            // Act
            var result = listener.AddRole(new AddRoleCommand(roleRequest, ""));

            // Assert
            mapperMock.VerifyAll();
            Assert.IsTrue(result);
            Assert.IsNotNull(updateParam);
            Assert.AreEqual(roleRequest.Email, updateParam.Email);
            Assert.AreEqual(roleRequest.Role.ToString(), updateParam.CredentialRoles.FirstOrDefault().Role.Name);
        }
        public CredentialEntity Create()
        {
            var credEntity = new CredentialEntity()
            {
                Id              = Id,
                Email           = Email,
                Password        = Password,
                CredentialRoles = CredentialRoles
            };


            foreach (var cr in credEntity.CredentialRoles)
            {
                cr.Credential   = credEntity;
                cr.CredentialId = credEntity.Id;
                cr.RoleId       = cr.RoleId;
            }

            return(credEntity);
        }
        public static bool IsEqual(this CredentialEntity entity, CredentialEntity comparable)
        {
            if (entity.GetHashCode() != comparable.GetHashCode())
            {
                return(false);
            }

            if (entity.Id != comparable.Id)
            {
                return(false);
            }
            if (entity.Email != comparable.Email)
            {
                return(false);
            }
            if (entity.Password != comparable.Password)
            {
                return(false);
            }
            if (entity.CredentialRoles.Count != comparable.CredentialRoles.Count)
            {
                return(false);
            }

            var entityListList     = entity.CredentialRoles.OrderBy(x => x.Role.Name);
            var comparableRoleList = comparable.CredentialRoles.OrderBy(x => x.Role.Name);

            for (int i = 0; i < entityListList.Count(); ++i)
            {
                if (entityListList.ElementAt(i)?.Role.Name !=
                    comparableRoleList.ElementAt(i)?.Role.Name)
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #16
0
        /// <summary>
        /// Validate the provided <paramref name="serviceRequest">credentials</paramref> are valid.
        /// </summary>
        /// <param name="serviceRequest">The user credentials to validate.</param>
        /// <returns>The users identifier.</returns>
        public virtual IServiceResponseWithResultData <Guid?> Login(IServiceRequestWithData <Guid, LoginParameters> serviceRequest)
        {
            AuthenticationTokenHelper.SetAuthenticationToken(serviceRequest.AuthenticationToken);
            CorrelationIdHelper.SetCorrelationId(serviceRequest.CorrelationId);

            var userLogin = serviceRequest.Data;

            if (userLogin == null || string.IsNullOrEmpty(userLogin.EmailAddress) || string.IsNullOrEmpty(userLogin.Password))
            {
                return(CompleteResponse(new ServiceResponseWithResultData <Guid?> {
                    State = ServiceResponseStateType.FailedValidation
                }));
            }

            // Define Query
            ISingleResultQuery <CredentialQueryStrategy, CredentialEntity> query = QueryFactory.CreateNewSingleResultQuery <CredentialQueryStrategy, CredentialEntity>();

            string hash = AuthenticationHashHelper.GenerateCredentialHash(userLogin.EmailAddress, userLogin.Password);

            query.QueryStrategy.WithHash(hash);

            // Retrieve Data
            query = CredentialRepository.Retrieve(query, false);
            CredentialEntity queryResults = query.Result;

            var responseData = new ServiceResponseWithResultData <Guid?>
            {
                State      = queryResults == null ? ServiceResponseStateType.FailedAuthentication : ServiceResponseStateType.Succeeded,
                ResultData = queryResults == null ? (Guid?)null : queryResults.UserRsn
            };

            // Complete the response
            ServiceResponseWithResultData <Guid?> response = CompleteResponse(responseData);

            return(response);
        }
Пример #17
0
        private async Task <List <CredentialEntity> > ParseCsv(string assetName, IFormFile file, List <string> columns)
        {
            var mapping = new Dictionary <string, int>();

            var credentialDict = new Dictionary <string, CredentialEntity>();

            columns.Add(SetIdColumn);
            columns.Add(HackerNameColumn);
            columns.ForEach(c => mapping.Add(c, -1));
            var rowNumbers = new Dictionary <string, int>();

            using var reader = new StreamReader(file.OpenReadStream(), Encoding.UTF8);
            var firstLine = true;
            var header    = Array.Empty <string>();

            while (!reader.EndOfStream)
            {
                var line = await reader.ReadLineAsync();

                if (line == null)
                {
                    continue;
                }
                if (firstLine)
                {
                    header = line.GetCsvElements().ToArray();
                    for (var i = 0; i < header.Length; i++)
                    {
                        if (mapping.ContainsKey(header[i]))
                        {
                            mapping[header[i]] = i;
                        }
                    }

                    if (mapping.ContainsValue(-1))
                    {
                        throw new ArgumentException($"Invalid header. Missing columns: {string.Join(",", mapping.Where(x => x.Value == -1).Select(x => x.Key))}");
                    }

                    firstLine = false;
                    continue;
                }

                var lineData = line.GetCsvElements().ToArray();
                if (lineData.Length != header.Length)
                {
                    throw new ArgumentException($"Invalid line: {line}");
                }

                var setId      = lineData[mapping[SetIdColumn]];
                var hackerName = lineData[mapping[HackerNameColumn]];

                if (!credentialDict.ContainsKey(setId))
                {
                    credentialDict[setId] = new CredentialEntity {
                        AssetName = assetName, Key = setId, HackerName = hackerName
                    };
                    rowNumbers[setId] = 0;
                }

                var credential = credentialDict[setId];
                if (credential.HackerName != hackerName)
                {
                    throw new ArgumentException($"SetId: {setId} has different hacker name on rows, set hacker name:{credential.HackerName}, line hacker name: {hackerName}");
                }



                rowNumbers[setId]++;

                credential.Rows.AddRange(mapping.Where(map => map.Key != SetIdColumn && map.Key != HackerNameColumn)
                                         .Select(map => new CredentialValueEntity
                {
                    AssetName   = assetName,
                    ColumnName  = map.Key,
                    ColumnValue = lineData[map.Value],
                    RowNumber   = rowNumbers[setId],
                    Key         = setId
                }));
            }

            return(credentialDict.Values.ToList());
        }
 public void Delete(CredentialEntity entity)
 {
     throw new NotImplementedException();
 }
Пример #19
0
 public static Credential ToDomainModel(this CredentialEntity entity)
 {
     return(new Credential(entity.Id, entity.Subject));
 }