Exemplo n.º 1
0
        private void Encrypt(object model)
        {
            var modelType = model.GetType();

            if (_models.TryGetValue(modelType, out var shouldEncrypt) && !shouldEncrypt)
            {
                return;
            }

            foreach (var property in modelType.GetProperties())
            {
                var attribute = property.GetCustomAttributes(typeof(EncryptedFieldAttribute), false).FirstOrDefault();
                if (attribute == null)
                {
                    continue;
                }

                shouldEncrypt = true;

                var value = property.GetValue(model);
                if (value is null)
                {
                    continue;
                }

                if (value.GetType() != typeof(string))
                {
                    _logger.LogWarning(
                        $"[EncryptedField] should be applied to `string` properties, But type of `{property.DeclaringType}.{property.Name}` is `{property.PropertyType}`.");
                    continue;
                }

                var encryptedValue = _protection.Encrypt(value.ToString());
                property.SetValue(model, encryptedValue);
            }

            _models.TryAdd(modelType, shouldEncrypt);
        }