Skip to content

Commit

Permalink
Optimize Validation logic
Browse files Browse the repository at this point in the history
  • Loading branch information
tinohager committed Jan 20, 2025
1 parent 85cf1a8 commit d786a4b
Showing 1 changed file with 75 additions and 3 deletions.
78 changes: 75 additions & 3 deletions src/Nager.EmailAuthentication/DkimHeaderParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,15 @@ public static bool TryParse(
{
"v", new MappingHandler
{
Map = value => dataFragment.Version = value
Map = value => dataFragment.Version = value,
Validate = ValidatePositiveNumber
}
},
{
"a", new MappingHandler
{
Map = value => dataFragment.SignatureAlgorithm = value
Map = value => dataFragment.SignatureAlgorithm = value,
Validate = ValidateSignatureAlgorithm
}
},
{
Expand Down Expand Up @@ -102,7 +104,8 @@ public static bool TryParse(
{
"t", new MappingHandler
{
Map = value => dataFragment.Timestamp = value
Map = value => dataFragment.Timestamp = value,
Validate = ValidatePositiveNumber
}
},
{
Expand Down Expand Up @@ -165,5 +168,74 @@ public static bool TryParse(

return mappingFound;
}

private static ParseError[] ValidatePositiveNumber(ValidateRequest validateRequest)
{
var errors = new List<ParseError>();

if (string.IsNullOrEmpty(validateRequest.Value))
{
errors.Add(new ParseError
{
Severity = ErrorSeverity.Error,
ErrorMessage = $"{validateRequest.Field} is empty"
});

return [.. errors];
}

if (!int.TryParse(validateRequest.Value, out var reportInterval))
{
errors.Add(new ParseError
{
Severity = ErrorSeverity.Error,
ErrorMessage = $"{validateRequest.Field} value is not a number"
});

return [.. errors];
}

if (int.IsNegative(reportInterval))
{
errors.Add(new ParseError
{
Severity = ErrorSeverity.Error,
ErrorMessage = $"{validateRequest.Field} number is negative"
});

return [.. errors];
}

return [];
}

private static ParseError[] ValidateSignatureAlgorithm(ValidateRequest validateRequest)
{
var errors = new List<ParseError>();

if (string.IsNullOrEmpty(validateRequest.Value))
{
errors.Add(new ParseError
{
Severity = ErrorSeverity.Error,
ErrorMessage = $"{validateRequest.Field} is empty"
});

return [.. errors];
}

if (!validateRequest.Value.StartsWith("rsa-", StringComparison.OrdinalIgnoreCase))
{
errors.Add(new ParseError
{
Severity = ErrorSeverity.Error,
ErrorMessage = $"{validateRequest.Field} starts not with rsa-"
});

return [.. errors];
}

return [];
}
}
}

0 comments on commit d786a4b

Please sign in to comment.