using System;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Text.RegularExpressions;
using System.Threading;
using iiie.Authentication.DBO;
using Newtonsoft.Json;
namespace iiie.Authentication.Business
{
public static class AuthProvider
{
///
/// The registered user dbo, or null if no user is logged
///
public static UserGet UserDbo
{
get
{
var claim = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity).Claims.FirstOrDefault(x => x != null && x.Type == "__userdbo__");
if (claim == null)
return null;
return JsonConvert.DeserializeObject(claim.Value);
}
set
{
var claim = new Claim("__userdbo__", JsonConvert.SerializeObject(value));
((ClaimsIdentity)Thread.CurrentPrincipal.Identity).AddClaim(claim);
}
}
///
/// Check if this is a valid email address
///
/// The email to test
/// True if the email is valid, false otherwise
public static bool IsValidEmail(string email)
{
try
{
return Regex.IsMatch(email,
@"^(?("")("".+?(?
/// Get a int from config file, or return the default value
///
/// The config file key
/// The default value
/// The found int
public static int GetInt(string key, int def)
{
var valueStr = GetString(key, def.ToString());
int value;
if (int.TryParse(valueStr, out value))
return value;
return def;
}
///
/// Get a string from config file, or return the default value
///
/// The config file key
/// The default value
/// The found string
public static string GetString(string key, string def)
{
var value = ConfigurationManager.AppSettings[key];
if (value == null)
return def;
return value;
}
///
/// Const value to compute password hash
///
public static int GetPasswordSaltByteSize()
{
return GetInt("PasswordSaltByteSize", 42);
}
///
/// Const value to compute password hash
///
public static int GetPasswordHashByteSize()
{
return GetInt("PasswordHashByteSize", 42);
}
///
/// Const value to compute password hash
///
public static int GetPasswordIterations()
{
return GetInt("PasswordIterations", 2048);
}
///
/// Returns a string used to validate the token.
/// Must be constant. Default is app setting 'ValidatorString'
///
/// The string
public static string GetValidatorString()
{
return GetString("ValidatorString", "__default__");
}
///
/// Returns a string used to sign the token
/// Must be constant. Default is app setting 'CredentialKey'
///
/// The string
public static string GetCredentialKey()
{
return GetString("CredentialKey", "__default__");
}
}
}