forked from wanderer/pwt-0x01-ng
45 lines
1.8 KiB
C#
45 lines
1.8 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel.DataAnnotations;
|
|
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
|
|
|
|
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 == null){return new ValidationResult(GetErrorMessage(), new List<string> { validationContext.MemberName });}
|
|
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;
|
|
}
|
|
}
|
|
} |