private void AddLog(int idSystem, int idOrganization, String message)
        {
            String formattedMessage = string.Format(Constants.LogMessage1,
                                                    new object[] { Environment.NewLine, DateTime.Now, idSystem, idOrganization, message });

            // Criar uma nova entidade de log
            IEntity newEntity = new Model.Entity()
            {
                IdSystem         = idSystem,
                IdOrganization   = idOrganization,
                Name             = Constants.LOG,
                Code             = RNGKey.New(),
                EntityAttributes = new List <IEntityAttribute>()
            };

            newEntity.EntityAttributes.Add(new EntityAttribute()
            {
                Name = Constants.MESSAGE,
                Type = EntityAttributeType.TinyString,
                EntityAttributeValue = new EntityAttributeValue()
                {
                    Value = formattedMessage
                }
            });

            this.EntityRepository.Create(idSystem, idOrganization, newEntity,
                                         new CreateCallback()
            {
                Created    = (idSystem_, idOrganization_, entity_) => { },
                NotCreated = (idSystem_, idOrganization_, entity_) => { },
                Exception  = (idSystem_, idOrganization_, entity_, exception_) => { }
            });
        }
        public async Task <String> Authenticate([FromBody] AuthenticateForm authenticateForm)
        {
            int idSystem       = Convert.ToInt32(ConfigurationManager.AppSettings["IdSystem"]);
            int idOrganization = Convert.ToInt32(ConfigurationManager.AppSettings["IdOrganization"]);

            // Cria um hash do password
            string hashedPass = SHA.GenerateSHA512String(authenticateForm.Password);

            IList <IAttribute> attributes = new List <IAttribute>();

            attributes.Add(new Entity.Model.Attribute()
            {
                Name = "Email", Value1 = authenticateForm.Email, Operator = Enum.GetName(typeof(AttributeOperator), AttributeOperator.Equals)
            });
            attributes.Add(new Entity.Model.Attribute()
            {
                Name = "Password", Value1 = hashedPass, Operator = Enum.GetName(typeof(AttributeOperator), AttributeOperator.Equals)
            });

            // Recupera a credencial comparando o email e seu password
            IList <IEntity> credentials = await this._EntityController.GetByAttributes(idSystem, idOrganization, attributes);

            // Se existir a credencial
            if (credentials != null && credentials.Count > 0)
            {
                var credential = credentials[0];
                // Verificar se já tem uma credencial, caso contrário cria

                IList <IAttribute> attrToken = new List <IAttribute>();
                attrToken.Add(new Entity.Model.Attribute()
                {
                    Name = "IdCredential", Value1 = credential.Id, Operator = Enum.GetName(typeof(AttributeOperator), AttributeOperator.Equals)
                });
                attrToken.Add(new Entity.Model.Attribute()
                {
                    Name = "Enabled", Value1 = true, Operator = Enum.GetName(typeof(AttributeOperator), AttributeOperator.Equals)
                });

                // Recupera a token pelo id, mas somente se estiver habilitada
                IList <IEntity> tokens = await this._EntityController.GetByAttributes(idSystem, idOrganization, attrToken);

                // Se existir a token retorna ela
                if (tokens != null && tokens.Count > 0)
                {
                    IEntity token    = tokens[0];
                    var     tokenKey = token.EntityAttributes.Where(x => x.Name == "Key").FirstOrDefault()
                                       .EntityAttributeValue.Value;

                    return(tokenKey);
                }
                else
                {
                    // Não existe uma key para essa credencial ou ela está desabilitada, vamos criar uma nova token
                    IEntity newToken = new Entity.Model.Entity()
                                       .AddIdSystem(idSystem)
                                       .AddIdOrganization(idOrganization)
                                       .AddCode(RNGKey.New())
                                       .AddName("Token")
                                       .AddAttribute("IdCredential", EntityAttributeType.Integer, credential.Id)
                                       .AddAttribute("Key", EntityAttributeType.TinyString, RNGKey.New())
                                       .AddAttribute("Enabled", EntityAttributeType.Boolean, true)
                                       .AddAttribute("CreatedDate", EntityAttributeType.DateTime, DateTime.Now);

                    // Cria a nova token e retorna ela atualizada com o seu id
                    IEntity token = await this._EntityController.Create(idSystem, idOrganization, newToken);

                    // Se criou a token retorna a key
                    if (token != null)
                    {
                        var tokenKey = token.EntityAttributes.Where(x => x.Name == "Key").FirstOrDefault().EntityAttributeValue.Value;
                        return(tokenKey);
                    }
                }
            }

            return(null);
        }