using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.BL.Enumerations;
using SimpleValidator.Extensions;
using Newtonsoft.Json;
using System.Xml.Serialization;
using Tango.Core.Cryptography;
namespace Tango.BL.Entities
{
public partial class User : UserBase
{
private static IHashGenerator _hashGenerator;
///
/// Determines whether the user has the specified permission.
///
/// The permission.
///
/// true if the user has permission; otherwise, false.
///
public bool HasPermission(Permissions permission)
{
return UsersRoles.Select(x => x.Role).ToList().SelectMany(x => x.RolesPermissions).ToList().Exists(x => x.Permission.Code == permission.ToInt32());
}
public bool HasAnyPermission(IEnumerable permissions)
{
return UsersRoles.Select(x => x.Role).ToList().SelectMany(x => x.RolesPermissions).ToList().Any(x => permissions.Contains((Permissions)x.Permission.Code));
}
public bool HasAnyPermission(params Permissions[] permissions)
{
return HasAnyPermission(permissions.ToList());
}
///
/// Determines whether the user has role.
///
/// The role.
public bool HasRole(Roles role)
{
return UsersRoles.ToList().Exists(x => x.Role.Code == role.ToInt32());
}
///
/// Gets the aggregated user roles.
///
[NotMapped]
[JsonIgnore]
public List Roles
{
get { return UsersRoles.Select(x => x.Role).ToList(); }
}
///
/// Gets the aggregated FSE user roles.
///
[NotMapped]
[JsonIgnore]
public List FSERoles
{
get { return UsersRoles.Select(x => x.Role).Where(x => x.Name.StartsWith("FSE")).ToList(); }
}
///
/// Gets the aggregated user permissions as enumerations.
///
[NotMapped]
[JsonIgnore]
public List Permissions
{
get
{
return UsersRoles.Select(x => x.Role).ToList().SelectMany(x => x.RolesPermissions).Select(x => x.Permission).ToList();
}
}
protected override void RaisePropertyChanged(string propName)
{
base.RaisePropertyChanged(propName);
}
public override bool Validate(ObservablesContext context)
{
return base.Validate(context) && Contact.Validate(context) && Address.Validate(context);
}
protected override void OnValidating(ObservablesContext context)
{
base.OnValidating(context);
var users = context.Users.ToList();
if (users.Exists(x => x.Guid != Guid && x.Email.ToLower() == Email.ToLower()))
{
InsertError(nameof(Email), "The specified email is already taken by another account.");
}
if (!Email.IsEmail())
{
InsertError(nameof(Email), "The specified email address is invalid.");
}
}
///
/// Gets the specified password hash.
///
/// The password.
///
public static String GetPasswordHash(String password)
{
return GetHashGenerator().Encrypt(password);
}
private static IHashGenerator GetHashGenerator()
{
if (_hashGenerator == null)
{
_hashGenerator = new BasicHashGenerator();
}
return _hashGenerator;
}
///
/// Initializes a new instance of the class.
///
public User() : base()
{
}
}
}