using System;
using System.Linq;
using xModels.Dtos;
using xCommons.Constants;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using xIdentityModels.Models;
using System.Security.Claims;
using xIdentityModels.Constants;
using System.Collections.Generic;
using xIdentityModels.Configurations;
namespace xIdentityModels.Extensions
{
public static class xIdentityModelsExtensions
{
///
/// Converts a User Entity to Profile Dto ...
///
///
///
///
///
///
///
///
public static XUserProfileDto ToXProfileDto(
this XUser source,
bool isAdmin = false,
bool isSameUser = false,
IEnumerable roles = null,
XFriendshipInfoDto friendship = null,
XIdentityProfile profileConfig = null
)
{
//
XUserProfileDto result = null;
//
if (roles == null)
{
roles = new List();
}
//
// Prepare Dto ...
if (!source.IsNullOrDefault())
{
//
result = new XUserProfileDto
{
Bio = source.Bio,
UserId = source.Id,
Email = source.Email,
Roles = roles.ToList(),
Avatar = source.Avatar,
IsEnable = source.IsEnable,
IsBanned = source.IsBanned,
UserName = source.UserName,
LastName = source.LastName,
FriendshipInfo = friendship,
FirstName = source.FirstName,
LastLogin = source.LastLogin,
CoverImage = source.CoverImage,
PhoneNumber = source.PhoneNumber,
DateOfBirth = source.DateOfBirth,
CreationDate = source.CreationDate,
OpenToSearch = source.OpenToSearch,
Gender = (XGender)(int)source.Gender,
EmailConfirmed = source.EmailConfirmed,
PhoneNumberConfirmed = source.PhoneNumberConfirmed,
Avatars = source.Avatars.Select(pfi =>
{
//
return new XProfileImageDto
{
Id = pfi.Id,
Name = pfi.Name,
Path = pfi.Path,
Thumb = pfi.Thumb,
ThumbPath = pfi.ThumbPath,
CreationDate = pfi.CreationDate
};
}).ToList(),
};
}
//
// Apply Profiling Configuration ...
//
bool isPassed = false;
//
// Handle Friendship ...
isPassed = !isSameUser;
if (!isPassed)
{
result.FriendshipInfo = null;
}
//
// Handle Email Info ...
isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsEmail);
if (!isPassed)
{
result.Email = string.Empty;
result.EmailConfirmed = false;
}
//
// Handle PhoneNumber Info ...
isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsPhoneNumber);
if (!isPassed)
{
source.PhoneNumber = string.Empty;
source.PhoneNumberConfirmed = false;
}
//
// Handle Last Login ...
isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsLastLogin);
if (!isPassed)
{
result.LastLogin = null;
}
//
// Handle Date Of Birth ...
isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsDateOfBirth);
if (!isPassed)
{
result.DateOfBirth = null;
}
//
// Handle Creation Date ...
isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsCreationDate);
if (!isPassed)
{
result.CreationDate = null;
}
//
// Handle Roles ...
isPassed = isAdmin || isSameUser || (!profileConfig.IsNullOrDefault() && profileConfig.ContainsRoles);
if (!isPassed)
{
result.Roles = new List();
}
//
return result;
}
///
/// Check Specified User Has Access to Provided Roles ...
///
///
///
///
public static bool HasAccess(
this XUserClaimsInfoDto source,
string[] roles
)
{
//
var result =
!source.IsNullOrDefault() &&
source.Roles
.Any(r => roles
.Any(ar => r.ToNormalString()
.Contains(ar.ToNormalString())));
//
return result;
}
///
/// Extract Top XApiKey Scope inside an Enumerable ...
///
///
///
public static XApiKeyScope GetTopXApiKeyScope(
this IEnumerable scopes
)
{
//
// Check Scopes Has Child ...
if (!scopes.HasChild())
{
XException.NotFound.Throw();
}
//
var hasAdmin = scopes
.Any(s =>
s.GetStringValue().ToNormalString() == XApiKeyScope.Admin.GetStringValue().ToNormalString());
var hasRead = scopes
.Any(s =>
s.GetStringValue().ToNormalString() == XApiKeyScope.Read.GetStringValue().ToNormalString());
var hasWrite = scopes
.Any(s =>
s.GetStringValue().ToNormalString() == XApiKeyScope.Write.GetStringValue().ToNormalString());
var hasManage =
(hasRead && hasWrite) ||
scopes
.Any(s =>
s.GetStringValue().ToNormalString() == XApiKeyScope.Manage.GetStringValue().ToNormalString());
//
// Admin ...
if (hasAdmin)
{
return XApiKeyScope.Admin;
}
else if (hasManage)
{
return XApiKeyScope.Manage;
}
else if (hasWrite)
{
return XApiKeyScope.Write;
}
else
{
return XApiKeyScope.Read;
}
}
///
/// Check Source ApiKey Scope Has Access to Dest ...
///
///
///
///
public static bool HasAccess(
this XApiKeyScope source,
XApiKeyScope dest
)
{
//
var result = source == dest;
if (result)
{
return result;
}
//
var alls = Enumerable.Empty();
switch (source)
{
//
// Admin ...
case XApiKeyScope.Admin:
//
alls = [
XApiKeyScope.Admin,
XApiKeyScope.Manage,
XApiKeyScope.Write,
XApiKeyScope.Read
];
//
result = alls.Contains(dest);
break;
//
// Manage ...
case XApiKeyScope.Manage:
//
alls = [
XApiKeyScope.Manage,
XApiKeyScope.Write,
XApiKeyScope.Read
];
//
result = alls.Contains(dest);
break;
//
// Write ...
case XApiKeyScope.Write:
//
alls = [XApiKeyScope.Write];
//
result = alls.Contains(dest);
break;
//
// Read ...
case XApiKeyScope.Read:
//
alls = [XApiKeyScope.Read];
//
result = alls.Contains(dest);
break;
}
//
return result;
}
///
/// Check Allowed Scopes passed Based on Required Scopes ...
///
///
///
///
public static bool IsScopePassed(
this IEnumerable allowedScopes,
IEnumerable requiredScopes
)
{
//
// if Allowed Scopes is Empty, this means access to
// All Scopes are Valid ...
var result = !allowedScopes.HasChild();
if (result)
{
return result;
}
//
// Make Sure we Have at least one Required Scope for Validation ...
result = requiredScopes.HasChild();
if (!result)
{
return result;
}
//
// Converts each Allowed or Required Scopes to XApiKeyScope ...
var alloweds = allowedScopes.Select(asc =>
{
//
if (asc.ToNormalString() == XApiKeyScope.Admin.GetStringValue().ToNormalString())
{
return XApiKeyScope.Admin;
}
else if (asc.ToNormalString() == XApiKeyScope.Manage.GetStringValue().ToNormalString())
{
return XApiKeyScope.Manage;
}
else if (asc.ToNormalString() == XApiKeyScope.Write.GetStringValue().ToNormalString())
{
return XApiKeyScope.Write;
}
else
{
return XApiKeyScope.Read;
}
});
var requireds = requiredScopes.Select(asc =>
{
//
if (asc.ToNormalString() == XApiKeyScope.Admin.GetStringValue().ToNormalString())
{
return XApiKeyScope.Admin;
}
else if (asc.ToNormalString() == XApiKeyScope.Manage.GetStringValue().ToNormalString())
{
return XApiKeyScope.Manage;
}
else if (asc.ToNormalString() == XApiKeyScope.Write.GetStringValue().ToNormalString())
{
return XApiKeyScope.Write;
}
else
{
return XApiKeyScope.Read;
}
});
//
// Retrieve top Allowed ApiKey Scope ...
var topAllowed = alloweds.GetTopXApiKeyScope();
var topRequired = requireds.GetTopXApiKeyScope();
//
result = topAllowed.HasAccess(topRequired);
//
return result;
}
///
/// Check Dest Client IP is Exists in Source or not ...
///
///
///
///
public static bool IsClientIpPassed(
this IEnumerable source,
string dest
)
{
//
// if Allowed IPs Empty means all Client IPs is Valid ...
var result =
!source.HasChild();
if (result)
{
return result;
}
//
result = !dest.IsNullOrEmpty();
if (!result)
{
return result;
}
//
result = source.Any(s => s.ToNormalString() == dest.ToNormalString());
if (!result)
{
//
if (dest == "::1")
{
//
result = source.Any(s =>
s.ToNormalString() == "127.0.0.1" ||
s.ToNormalString() == "localhost");
}
}
//
return result;
}
///
/// Check Specified User Contains Specified UserSelectByParam or not ...
///
///
///
///
public static bool ContainsUserSelectByParam(
this XUser source,
string userSelectByParam
)
{
//
var result =
!source.IsNull() &&
!userSelectByParam.IsNullOrEmpty() &&
(source.Id == userSelectByParam ||
source.Email.ToNormalString() == userSelectByParam.ToNormalString() ||
source.UserName.ToNormalString() == userSelectByParam.ToNormalString() ||
source.PhoneNumber.ToNormalString() == userSelectByParam.ToNormalString());
//
return result;
}
///
/// Check Specified Api Key is Revoked or not ...
///
///
///
public static bool IsRevoked(this XApiKey source)
{
//
var result =
!source.IsNullOrDefault() &&
source.RevokedAt.HasValue;
//
return result;
}
///
/// Check Specified Api Key is Expired or not ...
///
///
///
public static bool IsExpired(this XApiKey source)
{
//
var result =
!source.IsNullOrDefault() &&
DateTime.UtcNow >= source.ExpiresAt;
//
return result;
}
///
/// Check Specified Api Key is Active or not ...
///
///
///
public static bool IsActive(this XApiKey source)
{
//
var result =
!source.IsNullOrDefault() &&
!source.IsRevoked() &&
!source.IsExpired();
//
return result;
}
///
/// Extract ApiKey Validated User ...
///
///
///
public static XPersonDto ExtractApiKeyUser(
this ClaimsPrincipal source
)
{
//
XPersonDto result = null;
//
// Validate ...
if (!source.IsNull() &&
source.Claims.HasChild())
{
source.Claims.ExtractApiKeyUser();
}
//
return result;
}
///
/// Extract ApiKey Validated User ...
///
///
///
public static XPersonDto ExtractApiKeyUser(
this IEnumerable source
)
{
//
XPersonDto result = null;
//
// Validate ...
if (source.HasChild())
{
//
result = new XPersonDto
{
UserId = source.FirstOrDefault(c => c.Type == XCustomClaims.UserId)?.Value ?? "",
Avatar = source.FirstOrDefault(c => c.Type == XCustomClaims.Picture)?.Value ?? "",
Username = source.FirstOrDefault(c => c.Type == XCustomClaims.UserName)?.Value ?? "",
Lastname = source.FirstOrDefault(c => c.Type == XCustomClaims.LastName)?.Value ?? "",
Firstname = source.FirstOrDefault(c => c.Type == XCustomClaims.FirstName)?.Value ?? "",
};
}
//
return result;
}
///
/// Extract JWT Validated User ...
///
///
///
public static XPersonDto ExtractAuthenticatedUser(
this ClaimsPrincipal source
)
{
//
XPersonDto result = null;
//
// Validate ...
if (!source.IsNull() &&
source.Claims.HasChild())
{
source.Claims.ExtractAuthenticatedUser();
}
//
return result;
}
///
/// Extract JWT Validated User ...
///
///
///
public static XPersonDto ExtractAuthenticatedUser(
this IEnumerable source
)
{
//
XPersonDto result = null;
//
// Validate ...
if (source.HasChild())
{
//
result = new XPersonDto
{
UserId = source.FirstOrDefault(c => c.Type == XCustomClaims.UserId)?.Value ?? "",
Avatar = source.FirstOrDefault(c => c.Type == XCustomClaims.Picture)?.Value ?? "",
Username = source.FirstOrDefault(c => c.Type == XCustomClaims.UserName)?.Value ?? "",
Lastname = source.FirstOrDefault(c => c.Type == XCustomClaims.LastName)?.Value ?? "",
Firstname = source.FirstOrDefault(c => c.Type == XCustomClaims.FirstName)?.Value ?? "",
};
}
//
return result;
}
}
}