add: unique characters attribute
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
familiarly known as UniqueCharsAttr
This commit is contained in:
parent
4d8c44ce38
commit
345fc8d5e2
|
@ -0,0 +1,46 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace pwt_0x01_ng.Models.Validation
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)]
|
||||
public class UniqueCharsAttr : ValidationAttribute, IClientModelValidator
|
||||
{
|
||||
public UniqueCharsAttr(){
|
||||
}
|
||||
|
||||
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
|
||||
if (value is string phrase) {
|
||||
int count = phrase.Distinct().Count();
|
||||
if(count >= config.min_passwd_unique_chars) {
|
||||
return ValidationResult.Success;
|
||||
} else {
|
||||
return new ValidationResult(GetErrorMessage(count, validationContext.MemberName), new List<string> { validationContext.MemberName });
|
||||
}
|
||||
}
|
||||
throw new NotImplementedException($"Attribute {nameof(UniqueCharsAttr)} not implemented for object {value.GetType()}.");
|
||||
}
|
||||
|
||||
protected string GetErrorMessage(int chars, string member_name) => $"not enough unique characters - provided: {chars}, wanted: {config.min_passwd_unique_chars}, problematic field: {member_name}";
|
||||
protected string GetErrorMessage() => $"not enough unique characters. wanted: {config.min_passwd_unique_chars}";
|
||||
|
||||
public void AddValidation(ClientModelValidationContext ctx){
|
||||
MergeAttribute(ctx.Attributes, "data-val", "true");
|
||||
MergeAttribute(ctx.Attributes, "data-val-uniquechars", GetErrorMessage());
|
||||
}
|
||||
|
||||
private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value){
|
||||
if (attributes.ContainsKey(key)){
|
||||
return false;
|
||||
}
|
||||
|
||||
attributes.Add(key, value);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue