Initial ...

This commit is contained in:
2026-03-22 14:08:25 +03:30
commit d3464ef39c
71 changed files with 19087 additions and 0 deletions
@@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using xIdentityHelper;
using xCommons.Attributes;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using static IdentityServer4.IdentityServerConstants;
namespace xIds.Controllers
{
public partial class AccountController
{
//
#region Admin Actions ...
/// <summary>
/// Ban Specific Users
/// </summary>
/// <param name="model">an instance of <see>XUserNameIdRequest</see> which represents user identifier list to Ban</param>
/// <returns>a list of banned users identifiers</returns>
[RequireXPowered]
[HttpPost("Ban")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public async Task<ActionResult<IEnumerable<string>>> Ban(
[FromBody] XUserNameIdRequest model
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
await ValidationProvider
.GroupValidationBuilder()
.AddNotNull(model)
.AddNotZeroChilds(model.Ids)
.ValidateGroupAsync();
//
var result = await IdentityManager
.Ban(
User.Identity.Name,
model
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// UnBann Specific Users
/// </summary>
/// <param name="model">an instance of <see>XUserNameIdRequest</see> which represents user identifier list to Ban</param>
/// <returns>a list of unbanned users identifiers</returns>
[RequireXPowered]
[HttpPost("UnBan")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public async Task<ActionResult<IEnumerable<string>>> UnBan(
[FromBody] XUserNameIdRequest model
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
await ValidationProvider
.GroupValidationBuilder()
.AddNotNull(model)
.AddNotZeroChilds(model.Ids)
.ValidateGroupAsync();
//
var result = await IdentityManager
.UnBan(
User.Identity.Name,
model
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Check Specific User is Banned or not
/// </summary>
/// <param name="userSelectByParam">specified user's identifier</param>
/// <returns>a boolean value which represent user banned or not</returns>
[RequireXPowered]
[Authorize(Policy = LocalApi.PolicyName)]
[HttpGet("IsBanned/{userSelectByParam?}")]
[Authorize(Policy = XPolicies.EnabledAdmin)]
[Authorize(Policy = XPolicies.EnabledAgent)]
public async Task<ActionResult<bool>> IsBanned(
[FromRoute] string userSelectByParam = null
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
if (userSelectByParam.IsNullOrEmpty())
{
userSelectByParam = User.Identity.Name;
}
ValidationProvider.NotEmpty(userSelectByParam);
//
var result = await IdentityManager
.IsBanned(
User.Identity.Name,
userSelectByParam
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
#endregion
}
}
@@ -0,0 +1,392 @@
using System;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using xIdentityHelper;
using xCommons.Attributes;
using xCommons.Extensions;
using xExceptions.Constants;
using xIdentityModels.Extensions;
using xIdentityModels.Models;
using static IdentityServer4.IdentityServerConstants;
using static xIdentityHelper.XApiScopeHelper;
using Microsoft.Extensions.Logging;
namespace xIds.Controllers
{
public partial class AccountController
{
//
#region Authentication Actions ...
/// <summary>
/// Retrieve OAuth Discovery Document
/// </summary>
/// <returns>an instance of <see>DiscoveryDocumentResponse</see></returns>
[AllowAnonymous]
[RequireXPowered]
[HttpGet("DiscoveryDocument")]
public async Task<ActionResult<DiscoveryDocumentResponse>> GetDiscoveryDocument()
{
//
// Do Action ...
try
{
//
var result = await IdentityManager
.RequestDiscoveryDocument();
//
// Ceck Response Result ...
if (result.IsError)
{
XException.InvalidConfiguration.Throw();
}
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Request AccessToken for Specific XApiScope
/// </summary>
/// <param name="scope">a member of <see>XApiScope</see></param>
/// <returns>an instance of <see>XTokenResponse</see></returns>
[AllowAnonymous]
[RequireXPowered]
[HttpPost("RequestScopeAccessToken")]
public async Task<ActionResult<XTokenResponse>> RequestScopeAccessToken(
[FromHeader] XApiScope scope
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
var scopeName = string.Empty;
try
{
scopeName = scope.GetStringValue();
}
catch { }
ValidationProvider.NotEmpty(scopeName);
//
var result = await IdentityManager
.RequestScopeAccessToken(scopeName);
//
// Ceck Response Result ...
if (result.IsError)
{
XException.InvalidConfiguration.Throw();
}
//
return Ok(result
.CreateXTokenResponse()
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Authenticate User
/// </summary>
/// <remarks>
/// Sample request:
///
/// {
/// "password": "",
/// "userSelectBy": "",
/// }
///
/// </remarks>
/// <param name="model">an instance of <see>XLoginRequest</see> class which represent Authentication requirements</param>
/// <returns>an instance of <see>XTokenResponse</see></returns>
[AllowAnonymous]
[RequireXPowered]
[HttpPost("Authenticate")]
public async Task<ActionResult<XTokenResponse>> Authenticate(
[FromBody] XLoginRequest model
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
if (!ModelState.IsValid)
{
XException.InvalidArgs.Throw();
}
await ValidationProvider
.GroupValidationBuilder()
.AddNotNull(model)
.AddNotEmpty(
model.UserSelectBy,
model.Password
)
.ValidateGroupAsync();
//
var result = await IdentityManager
.Authenticate(model);
//
// Check Result ...
if (result.IsError)
{
throw result.GetException();
}
//
// Return Result ...
return Ok(result
.CreateXTokenResponse()
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Authenticate User
/// </summary>
/// <remarks>
/// Sample request:
///
/// {
/// "language": "fa-IR"
/// "password": "",
/// "userSelectBy": "",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
/// </remarks>
/// <param name="model">an instance of <see>XLoginRequest</see> class which represent Authentication requirements</param>
/// <returns>an instance of <see>XLoginResponse</see></returns>
[AllowAnonymous]
[RequireXPowered]
[HttpPost("Login")]
public async Task<ActionResult<XLoginResponse>> Login(
[FromBody] XLoginRequest model
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
if (!ModelState.IsValid)
{
XException.InvalidArgs.Throw();
}
await ValidationProvider
.GroupValidationBuilder()
.AddNotNull(
model,
model.Device)
.AddNotEmpty(
model.Language,
model.UserSelectBy,
model.Password
)
.ValidateGroupAsync();
//
var result = await IdentityManager
.Login(model);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Refresh Expired Tokens
/// </summary>
/// <remarks>
/// in addition to AccessToken, you had to pass RefreshToken due to Headers
/// </remarks>
/// <returns>an instance of <see>XTokenResponse</see></returns>
[AllowAnonymous]
[RequireXPowered]
[HttpPost("RefreshTokens")]
public async Task<ActionResult<XTokenResponse>> RefreshTokens()
{
//
// Do Action ...
try
{
//
// Retrieve Toke Response ...
var model = await RetrieveTokensAsXTokenResponse();
//
// Validate Args ...
ValidationProvider
.GroupValidationBuilder()
.AddNotNull(model)
.AddNotEmpty(
model.AccessToken,
model.RefreshToken)
.ValidateGroup();
//
var result = await IdentityManager
.RefreshTokens(model);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
//
#region Password Actions ...
/// <summary>
/// Change a User's Password ...
/// </summary>
/// <remarks>
/// for this action you have to provide:
/// - Lang: client device currently used locale, such as: en-US.
/// - Password: user's current active password.
/// - NewPassword: user's new password to change.
/// - Device: user's client device which is an instance of XDevice.
/// - ReturnUrl: client application Login URL.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "password": ""
/// "newPassword": "",
/// "returnUrl": "http://localhost/login",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
/// </remarks>
/// <param name="model">an instance of <see>XActionRequest</see> class which provider requirement for action</param>
/// <returns></returns>
[RequireXPowered]
[HttpPost("ChangePassword")]
[Authorize(Policy = XPolicies.User)]
[Authorize(Policy = XPolicies.EnabledUser)]
[Authorize(Policy = LocalApi.PolicyName)]
public async Task<ActionResult> ChangePassword(
[FromBody] XActionRequest model
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
if (!ModelState.IsValid)
{
XException.InvalidArgs.Throw();
}
await ValidationProvider
.GroupValidationBuilder()
.AddNotNull(
model,
model.Device
)
.AddNotEmpty(
model.Lang,
model.Password,
model.NewPassword,
model.ReturnUrl
)
.ValidateGroupAsync();
//
// Get User Select By ...
var userSelectByParam = GetUserSelectByParam(
model,
forceNotNull: false
);
if (userSelectByParam.IsNullOrEmpty())
{
userSelectByParam = User.Identity.Name;
}
ValidationProvider.NotEmpty(userSelectByParam);
//
// Get Request ...
await IdentityManager
.ChangePassword(
model.Lang,
model.Device,
userSelectByParam,
model.Password,
model.NewPassword,
model.ReturnUrl
);
//
return Ok();
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
#endregion
}
}
@@ -0,0 +1,889 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using xCommons.Attributes;
using xCommons.Extensions;
using xExceptions.Constants;
using xIdentityHelper;
using xIdentityModels.Constants;
using xIdentityModels.Dtos;
using xIdentityModels.Navigations;
using xModels.Dtos;
using static IdentityServer4.IdentityServerConstants;
namespace xIds.Controllers
{
public partial class AccountController
{
//
#region Friendship Actions ...
//
#region Actions ...
/// <summary>
/// Follow a User
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>an instance of <see>XFriendshipFollowing</see></returns>
[RequireXPowered]
[HttpPost("Friendship/{destUser}/Follow")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XFriendshipFollowing>> Follow(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.Follow(
User.Identity.Name,
destUser
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Cancel Following
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>a boolean value</returns>
[HttpPost("Friendship/{destUser}/Cancel")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<bool>> Cancel(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.Cancel(
User.Identity.Name,
destUser
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Unfollow a Follower
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns></returns>
[HttpPost("Friendship/{destUser}/UnFollowFollower")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult> UnFollowFollower(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
await IdentityManager
.UnFollowFollower(
User.Identity.Name,
destUser
);
//
return Ok();
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Unfollow Following
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns></returns>
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpPost("Friendship/{destUser}/UnFollowFollowing")]
public async Task<ActionResult> UnFollowFollowing(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
await IdentityManager
.UnFollowFollowing(
User.Identity.Name,
destUser
);
//
return Ok();
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Block a Follower
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>an instance of <see>XFriendshipFollowing</see></returns>
[HttpPost("Friendship/{destUser}/Block")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XFriendshipFollowing>> Block(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.Block(
User.Identity.Name,
destUser
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
//
return exResult;
}
}
/// <summary>
/// Unblock a Blocked User
/// </summary>
/// <param name="destUser">an instance of <see>XFriendshipFollowing</see></param>
/// <returns>an instance of <see>XFriendshipFollowing</see></returns>
[HttpPost("Friendship/{destUser}/UnBlock")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XFriendshipFollowing>> UnBlock(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.UnBlock(
User.Identity.Name,
destUser
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
#endregion
//
#region Request Handlers ...
/// <summary>
/// Accept a Following Request
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>an instance of <see>XFriendshipFollower</see></returns>
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpPost("Friendship/{destUser}/AcceptRequest")]
public async Task<ActionResult<XFriendshipFollower>> AcceptRequest(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.AcceptRequest(
User.Identity.Name,
destUser
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Reject a Following Request
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>an instance of <see>XFriendshipFollower</see></returns>
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpPost("Friendship/{destUser}/RejectRequest")]
public async Task<ActionResult<XFriendshipFollower>> RejectRequest(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.RejectRequest(
User.Identity.Name,
destUser
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
#endregion
//
#region Getters ...
/// <summary>
/// Check a User IsFollower of Requested User
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>a boolean value</returns>
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Friendship/{destUser}/IsFollower")]
public async Task<ActionResult<bool>> IsFollower(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.IsFollower(
User.Identity.Name,
destUser
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Get Follower State of a User
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>an instance of <see>XFriendshipState</see></returns>
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Friendship/{destUser}/FollowerState")]
public async Task<ActionResult<XFriendshipState>> FollowerState(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.GetFollowerState(
User.Identity.Name,
destUser
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Get Specific Follower
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>an instance of <see>XFriendshipFollower</see></returns>
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Friendship/{destUser}/Follower")]
public async Task<ActionResult<XFriendshipFollower>> Follower(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.GetFollower(
User.Identity.Name,
destUser
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Get Followers List Of Current User
/// </summary>
/// <returns>a collection of <see>XFriendshipFollower</see></returns>
[HttpGet("Friendship/Followers")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<IEnumerable<XFriendshipFollower>>> Followers()
{
//
// Do Action ...
try
{
//
var result = await IdentityManager
.GetFollowers(User.Identity.Name);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
//
return exResult;
}
}
/// <summary>
/// Get All Followers List Includes Blocked, Requested and etc
/// of Current User
/// </summary>
/// <returns>a collection of <see>XFriendshipFollower</see></returns>
[HttpGet("Friendship/AllFollowers")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<IEnumerable<XFriendshipFollower>>> AllFollowers()
{
//
// Do Action ...
try
{
//
var result = await IdentityManager
.GetAllFollowers(User.Identity.Name);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Get All Followers List Includes Blocked, Requested and etc
/// of Current User based On Query Model ...
/// </summary>
/// <returns>a Query Result of <see>XFriendDto</see></returns>
[HttpGet("Friendship/QueryFollowers")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XQueryResult<XFriendDto>>> QueryFollowers(
[FromQuery] XQuery query,
[FromQuery] string destUser
)
{
//
// Do Action ...
try
{
//
// Normalizing Dest User ...
var userInfo = await GetUserInfo();
bool isAdmin = userInfo.Roles.Contains(XUserRoles.ADMIN);
if (destUser.IsNullOrEmpty())
{
destUser = userInfo.UserName;
}
bool isDestUserValid = isAdmin || destUser == userInfo.UserId || destUser == userInfo.Email || destUser == userInfo.PhoneNumber || destUser == userInfo.UserName;
if (!isDestUserValid)
{
XException.NotAllowed.Throw();
}
//
var result = await IdentityManager
.QueryFollowers(
query: query,
userSelectByParam: destUser
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Check a User is in Followings of Current User
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>a boolean value</returns>
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Friendship/{destUser}/IsFollowing")]
public async Task<ActionResult<bool>> IsFollowing(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.IsFollowing(
User.Identity.Name,
destUser
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Get Following State Relation between Specific User
/// and Current User
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>an instance of <see>XFriendshipState</see></returns>
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Friendship/{destUser}/FollowingState")]
public async Task<ActionResult<XFriendshipState>> FollowingState(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.GetFollowingState(
User.Identity.Name,
destUser
);
//
return Ok(result);
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Get Specific Following Model
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>an instance of <see>XFriendshipFollowing</see></returns>
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpGet("Friendship/{destUser}/Following")]
public async Task<ActionResult<XFriendshipFollowing>> Following(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotEmpty(destUser);
//
var result = await IdentityManager
.GetFollowing(
User.Identity.Name,
destUser
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Get Followings of Current User
/// </summary>
/// <returns>a collection of <see>XFriendshipFollowing</see></returns>
[HttpGet("Friendship/Followings")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<IEnumerable<XFriendshipFollowing>>> Followings()
{
//
// Do Action ...
try
{
//
var result = await IdentityManager
.GetFollowings(User.Identity.Name);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Get All Following List Includes Blocked, Requested and etc
/// of Current User
/// </summary>
/// <returns>a collection of <see>XFriendshipFollowing</see></returns>
[HttpGet("Friendship/AllFollowings")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<IEnumerable<XFriendshipFollowing>>> AllFollowings()
{
//
// Do Action ...
try
{
//
var result = await IdentityManager
.GetAllFollowings(User.Identity.Name);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Get All Following List Includes Blocked, Requested and etc
/// of Current User based On Query Model ...
/// </summary>
/// <returns>a Query Result of <see>XFriendDto</see></returns>
[HttpGet("Friendship/QueryFollowings")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XQueryResult<XFriendDto>>> QueryFollowings(
[FromQuery] XQuery query,
[FromQuery] string destUser
)
{
//
// Do Action ...
try
{
//
// Normalizing Dest User ...
var userInfo = await GetUserInfo();
bool isAdmin = userInfo.Roles.Contains(XUserRoles.ADMIN);
if (destUser.IsNullOrEmpty())
{
destUser = userInfo.UserName;
}
bool isDestUserValid = isAdmin || destUser == userInfo.UserId || destUser == userInfo.Email || destUser == userInfo.PhoneNumber || destUser == userInfo.UserName;
if (!isDestUserValid)
{
XException.NotAllowed.Throw();
}
//
var result = await IdentityManager
.QueryFollowings(
query: query,
userSelectByParam: destUser
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
#endregion
//
#region Others ...
/// <summary>
/// Return Following UserName's List of Current User
/// </summary>
/// <returns>a collection of UserNames</returns>
[HttpGet("Friendship/FollowingsList")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<IEnumerable<string>>> FollowingsList()
{
//
// Do Action ...
try
{
//
var result = await IdentityManager
.GetFollowingList(User.Identity.Name);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Return Followers UserName's List of Current User
/// </summary>
/// <returns>a collection of UserNames</returns>
[HttpGet("Friendship/FollowersList")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<IEnumerable<string>>> FollowersList()
{
//
// Do Action ...
try
{
//
var result = await IdentityManager
.GetFollowersList(User.Identity.Name);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Get Friendship Info Model between Specific User and Current User
/// </summary>
/// <param name="destUser">a user identifier which represent destination user</param>
/// <returns>an instance of <see>XFriendshipInfoDto</see></returns>
[HttpGet("Friendship/{destUser}/FriendshipInfo")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XFriendshipInfoDto>> FriendshipInfo(
[FromRoute] string destUser
)
{
//
// Do Action ...
try
{
//
var result = await IdentityManager
.GetFriendshipInfo(User.Identity.Name, destUser);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
#endregion
#endregion
}
}
@@ -0,0 +1,68 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using xCommons.Attributes;
using xCommons.Constants;
using xIdentityModels.Dtos;
namespace xIds.Controllers
{
public partial class AccountController
{
//
// Implememnt all Open Actions here ...
//
#region Open Actions ...
[AllowAnonymous]
[RequireXPowered]
[HttpGet("Open")]
public async Task<ActionResult<string>> Get(
[FromHeader] string token,
[FromQuery] string request
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
await ValidationProvider
.GroupValidationBuilder()
.AddNotEmpty(token)
.AddNotEmpty(request)
.ValidateGroupAsync();
//
// Prepare Inner Dto Model ...
var dto = new XOpenActionInnerDto
{
Token = token,
Payload = request
};
//
// Do Action ...
var resultDto = await IdentityManager.OpenGet(dto);
Response.Headers.Add(XAuthentication.TOKEN, resultDto.Token);
//
// Return Result
return Ok(resultDto.Payload);
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
//
#region Private ...
#endregion
}
}
@@ -0,0 +1,511 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using xIdentityHelper;
using xCommons.Attributes;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xIdentityModels.Models;
using xModels.Dtos;
using static IdentityServer4.IdentityServerConstants;
namespace xIds.Controllers
{
public partial class AccountController
{
//
#region Retrieve Actions ...
/// <summary>
/// Retrieve User Names based on UserIds
/// </summary>
/// <param name="ids">a comma seperated list of UserIds</param>
/// <returns>a collection of UserNames</returns>
[HttpGet("Profile/{ids}/GetNames")]
[Authorize(Policy = XPolicies.User)]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<IEnumerable<string>>> GetNames(
[FromRoute] string ids
)
{
//
// Do Action ...
try
{
//
ValidationProvider.NotEmpty(ids);
//
var xIdList = ids.ParseListString<string>();
var result = await IdentityManager.GetUserNamesAsync(
xIdList
);
//
// Return Result
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// get user ids and retrieve corresponding user names
/// </summary>
/// <param name="model">an instance of <see>XUserNameIdRequest</see> which represent required UserIds collection</param>
/// <returns>a collection of <see>XUserNameIdResponse</see> instance</returns>
[HttpPost("Profile/GetNameIds")]
[Authorize(Policy = XPolicies.User)]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<IEnumerable<XUserNameIdResponse>>> GetNameIds(
[FromBody] XUserNameIdRequest model
)
{
//
// Do Action ...
try
{
//
ValidationProvider.NotNull(model);
//
var result = await IdentityManager.GetUserNameIdsAsync(
model
);
//
// Return Result
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Get Profile Object of Specific User
/// </summary>
/// <param name="userSelectByParam">specifies which user profile must be retrieved</param>
/// <returns>an instance of <see>XUserProfileDto</see></returns>
[RequireXPowered]
[Authorize(Policy = XPolicies.User)]
[Authorize(Policy = LocalApi.PolicyName)]
[HttpGet("Profile/{userSelectByParam?}")]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XUserProfileDto>> GetProfile(
[FromRoute] string userSelectByParam = ""
)
{
//
// Do Action ...
try
{
//
if (userSelectByParam.IsNullOrEmpty())
{
userSelectByParam = User.Identity.Name;
}
//
var result = await IdentityManager
.GetUserProfileAsync(
userSelectByParam,
User.Identity.Name
);
//
// Return Result
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Query Users
/// for specifiy users role for query user 'role: string' and 'forceRole: boolean' in header
/// </summary>
/// <param name="query">how to filter results based on <see>XQuery</see> structure</param>
/// <param name="role">an string which represent user role</param>
/// <param name="forceRole">if it's true the user must has exact role, otherwise top level users also listed</param>
/// <returns>an instance of <see>XQueryResult</see> of <see>XUserProfileDto</see></returns>
[RequireXPowered]
[HttpGet("Profile/Query")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledAdmin)]
[Authorize(Policy = XPolicies.EnabledAgent)]
public async Task<ActionResult<XQueryResult<XUserProfileDto>>> QueryProfiles(
[FromQuery] XQuery query, [FromHeader] string role, [FromHeader] bool forceRole = false
)
{
//
// Do Action ...
try
{
//
var userId = User.Identity.Name;
//
var result = new XQueryResult<XUserProfileDto>();
if (role.IsNullOrEmpty())
{
//
result = await IdentityManager.QueryUsers(
userId,
query
);
}
else
{
//
result = await IdentityManager.QueryInRoleUsers(
userId,
role,
query,
forceRole
);
}
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exception = GetExceptionActionResult(ex);
return exception;
}
}
/// <summary>
/// Query Specified User's Profile Images
/// </summary>
/// <param name="userSelectByParam">determine's which user profile must be retrieved</param>
/// <param name="query">how to filter results based on <see>XQuery</see> structure</param>
/// <returns>an instance of <see>XQueryResult</see> of <see>XProfileImage</see></returns>
[RequireXPowered]
[Authorize(Policy = XPolicies.User)]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
[Authorize(Policy = XPolicies.EnabledAdmin)]
[HttpGet("Profile/Avatars/Query/{userSelectByParam?}")]
public async Task<ActionResult<XQueryResult<XProfileImageDto>>> QueryAvatars(
[FromQuery] XQuery query, [FromRoute] string userSelectByParam = null
)
{
//
// Do Action ...
try
{
//
if (userSelectByParam.IsNullOrEmpty())
{
userSelectByParam = User.Identity.Name;
}
//
var result = await IdentityManager.QueryAvatars(
userSelectByParam,
query
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exception = GetExceptionActionResult(ex);
return exception;
}
}
#endregion
//
#region Update Actions ...
/// <summary>
/// Update User Profile based on XProfileUpdateRequest (FirstName/LastName/DateOfBirth)
/// </summary>
/// <param name="model">user update info, an instance of <see>XProfileUpdateRequest</see></param>
/// <param name="userSelectByParam">determine's which user profile must be retrieved</param>
/// <returns>an instance of <see>XUserProfileDto</see></returns>
[RequireXPowered]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
[HttpPost("Profile/Update/{userSelectByParam?}")]
public async Task<ActionResult<XUserProfileDto>> UpdateProfile(
[FromBody] XProfileUpdateRequest model, [FromRoute] string userSelectByParam = null
)
{
//
// Do Action ...
try
{
//
if (userSelectByParam.IsNullOrEmpty())
{
userSelectByParam = User.Identity.Name;
}
//
var result = await IdentityManager.ProfileUpdateAsync(
userSelectByParam,
User.Identity.Name,
model
);
//
// Return Result
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// Update a User Profile based on XProfileUpdateRequest Full
/// </summary>
/// <param name="model">user update info, an instance of <see>XProfileUpdateRequest</see></param>
/// <param name="userSelectByParam">determine's which user profile must be retrieved</param>
/// <returns>an instance of <see>XUserProfileDto</see></returns>
[RequireXPowered]
[Authorize(Policy = LocalApi.PolicyName)]
[HttpPost("Profile/{userSelectByParam?}")]
[Authorize(Policy = XPolicies.EnabledAdminOrAgent)]
public async Task<ActionResult<XUserProfileDto>> FullUpdateProfile(
[FromBody] XProfileUpdateRequest model, [FromRoute] string userSelectByParam = null
)
{
//
// Do Action ...
try
{
//
if (userSelectByParam.IsNullOrEmpty())
{
userSelectByParam = User.Identity.Name;
}
//
var result = await IdentityManager.FullProfileUpdateAsync(
userSelectByParam,
User.Identity.Name,
model
);
//
// Return Result
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
//
#region Avatar Actions ...
/// <summary>
/// Add a New Profile Image
/// </summary>
/// <param name="file">an specific File to upload, <see>IFormFile</see></param>
/// <returns>an instance of <see>XUserProfileDto</see></returns>
[RequireXPowered]
[HttpPost("Profile/Avatar")]
[RequestSizeLimit(966_367_641)]
[Authorize(Policy = XPolicies.User)]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XUserProfileDto>> AddAvatar(
[FromForm] IFormFile file
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotNull(file);
//
// Get Request ...
var result = await IdentityManager
.AddAvatar(
User.Identity.Name,
file
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Add a New Collection of Profile Images
/// </summary>
/// <param name="files">a collection of Files to upload, <see>IFormFileCollection</see></param>
/// <returns>an instance of <see>XUserProfileDto</see></returns>
[RequireXPowered]
[HttpPost("Profile/Avatars")]
[RequestSizeLimit(966_367_641)]
[Authorize(Policy = XPolicies.User)]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XUserProfileDto>> AddAvatars(
[FromForm] IFormFileCollection files
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
ValidationProvider.NotZeroChilds(files);
//
// Get Request ...
var result = await IdentityManager.AddAvatars(
User.Identity.Name,
files
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exResult = GetExceptionActionResult(ex);
return exResult;
}
}
/// <summary>
/// Remove Profile Images
/// </summary>
/// <param name="ids">a comma seperated list of avatarIds to remove</param>
/// <returns>an instance of <see>XUserProfileDto</see></returns>
[RequireXPowered]
[Authorize(Policy = XPolicies.User)]
[HttpDelete("Profile/Avatars/{ids}")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XUserProfileDto>> RemoveAvatars(
[FromRoute] string ids
)
{
//
// Do Action ...
try
{
//
ValidationProvider.NotEmpty(ids);
var idList = ids.Split(",");
var idCollection = new Collection<int>();
//
foreach (var s in idList)
{
idCollection.Add(int.Parse(s));
}
//
// Get Request ...
var result = await IdentityManager
.RemoveAvatar(
User.Identity.Name,
idCollection.ToArray()
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
/// <summary>
/// set Specified Profile Image as Avatar
/// </summary>
/// <param name="id">an integer which reperesent AvatarId to set as current Avatar</param>
/// <returns>an instance of <see>XUserProfileDto</see></returns>
[RequireXPowered]
[HttpPost("Profile/Avatars/{id:int}/Set")]
[Authorize(Policy = XPolicies.User)]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XUserProfileDto>> SetAvatar(
[FromRoute] int id
)
{
//
// Do Action ...
try
{
//
var result = await IdentityManager
.SetAvatar(
User.Identity.Name,
id
);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exception = GetExceptionActionResult(ex);
return exception;
}
}
#endregion
}
}
@@ -0,0 +1,63 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using xCommons.Attributes;
using xCommons.Extensions;
using xIdentityHelper;
using xModels.Dtos;
using static IdentityServer4.IdentityServerConstants;
namespace xIds.Controllers
{
public partial class AccountController
{
/// <summary>
/// Query Users
/// for specifiy users role for query user 'role: string' and 'forceRole: boolean' in header
/// </summary>
/// <param name="query">how to filter results based on <see>XQuery</see> structure</param>
/// <param name="role">an string which represent user role</param>
/// <param name="forceRole">if it's true the user must has exact role, otherwise top level users also listed</param>
/// <returns>an instance of <see>XQueryResult</see> of <see>XUserProfileDto</see></returns>
[RequireXPowered]
[HttpGet("Users/Query")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XQueryResult<string>>> QueryUsers(
[FromQuery] XQuery query,
[FromHeader] string role,
[FromHeader] bool forceRole = false
)
{
//
// Do Actions ...
try
{
//
// Retrieve User Info ...
var userInfo = await GetUserInfo();
//
// Retrieve Result Based on Provided Query ...
var result = await IdentityManager.QueryUsers(
role: role,
query: query,
forceRole: forceRole,
requestedUserSelectByParam: userInfo.UserId
);
//
// Return result ...
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exception = GetExceptionActionResult(ex);
return exception;
}
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using xCommons.Attributes;
using xCommons.Extensions;
using xIdentityHelper;
using xIdentityModels.Dtos;
using xModels.Dtos;
using static IdentityServer4.IdentityServerConstants;
namespace xIds.Controllers
{
/// <summary>
/// Actions which related to Search and Suggest Users for
/// Friendship or Detecting ...
/// </summary>
public partial class AccountController
{
//
#region Actions of Search ...
/// <summary>
/// Query Open To Search Users Profiles ...
/// Query all Users Which their Profiles is Open To Search ...
/// </summary>
/// <param name="query">how to filter results based on <see>XQuery</see> structure</param>
/// <returns>an instance of <see>XQueryResult</see> of <see>XUserProfileDto</see></returns>
[RequireXPowered]
[HttpGet("OpenToSearch/Query")]
[Authorize(Policy = LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public async Task<ActionResult<XQueryResult<XUserProfileDto>>> QueryOpenToSearchProfiles(
[FromQuery] XQuery query)
{
//
// Do Action ...
try
{
//
var userId = User.Identity.Name;
//
var result = await IdentityManager.QueryOpenToSearchUsers(
userId,
query
);
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var exception = GetExceptionActionResult(ex);
return exception;
}
}
#endregion
}
}
@@ -0,0 +1,161 @@
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using xIdentityHelper;
using xCommons.Attributes;
using static IdentityServer4.IdentityServerConstants;
namespace xIds.Controllers
{
public partial class AccountController
{
//
#region Test Actions ...
/// <summary>
/// API Read Scope
/// </summary>
/// <returns>string message</returns>
[RequireXPowered]
[Authorize(LocalApi.PolicyName)]
[HttpGet("Test/PassReadAccess")]
[Authorize(Policy = XPolicies.ReadAccess)]
public ActionResult<string> PassReadAccess()
{
return Ok("Read Access Passed ...");
}
/// <summary>
/// API Write Scope
/// </summary>
/// <returns>string message</returns>
[RequireXPowered]
[Authorize(LocalApi.PolicyName)]
[HttpGet("Test/PassWriteAccess")]
[Authorize(Policy = XPolicies.WriteAccess)]
public ActionResult<string> PassWriteAccess()
{
return Ok("Write Access Passed ...");
}
/// <summary>
/// API Admin Scope
/// </summary>
/// <returns>string message</returns>
[RequireXPowered]
[Authorize(LocalApi.PolicyName)]
[HttpGet("Test/PassAdminAccess")]
[Authorize(Policy = XPolicies.AdminAccess)]
public ActionResult<string> PassAdminAccess()
{
return Ok("Admin Access Passed ...");
}
/// <summary>
/// API Manage Scop
/// </summary>
/// <returns>string message</returns>
[RequireXPowered]
[Authorize(LocalApi.PolicyName)]
[HttpGet("Test/PassManageAccess")]
[Authorize(Policy = XPolicies.ManageAccess)]
public ActionResult<string> PassManageAccess()
{
return Ok("Manage Access Passed ...");
}
/// <summary>
/// a simple Action which returns a List of Authenticated User Claims
/// </summary>
/// <returns>string message which represent current user's claims</returns>
[RequireXPowered]
[HttpGet("Test/HiClaims")]
[Authorize(LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.User)]
public ActionResult<string> HiClaims()
{
//
var result = new
{
name = User.Identity.Name,
claims = User.Claims.Select(c => new
{
c.Type,
c.Value
})
};
//
return Ok(result);
}
/// <summary>
/// a simple Hello User for Checking Authentication and Policy
/// </summary>
/// <returns>string message which contains authenticated user name</returns>
[RequireXPowered]
[HttpGet("Test/HiUser")]
[Authorize(LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.User)]
public ActionResult<string> HiUser()
{
//
var result = $"Hi User: {User.Identity.Name} ...";
//
return Ok(result);
}
/// <summary>
/// a simple Hello User for Checking Authentication and Policy
/// </summary>
/// <returns>string message which contains authenticated user name</returns>
[RequireXPowered]
[HttpGet("Test/HiEnabledUser")]
[Authorize(LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledUser)]
public ActionResult<string> HiEnabledUser()
{
//
var result = $"Hi User: {User.Identity.Name} is Enabled ...";
//
return Ok(result);
}
/// <summary>
/// a simple Hello User for Checking Authentication and Policy
/// </summary>
/// <returns>string message which contains authenticated user name</returns>
[RequireXPowered]
[HttpGet("Test/HiAdmin")]
[Authorize(LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.Admin)]
public ActionResult<string> HiAdmin()
{
//
var result = $"Hi Admin: {User.Identity.Name} ...";
//
return Ok(result);
}
/// <summary>
/// a simple Hello User for Checking Authentication and Policy
/// </summary>
/// <returns>string message which contains authenticated user name</returns>
[RequireXPowered]
[HttpGet("Test/HiEnabledAdmin")]
[Authorize(LocalApi.PolicyName)]
[Authorize(Policy = XPolicies.EnabledAdmin)]
public ActionResult<string> HiEnabledAdmin()
{
//
var result = $"Hi Admin: {User.Identity.Name} is Enabled ...";
//
return Ok(result);
}
#endregion
}
}
+30
View File
@@ -0,0 +1,30 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using xCommons.Configurations;
using xCommons.Providers;
using xIds.Controllers.Base;
using xIds.Interfaces;
namespace xIds.Controllers
{
/// <summary>
/// Provide all available tools for manipulating users and accounts
/// </summary>
[ApiController]
public partial class AccountController : XIBaseController
{
public AccountController(
IXIdentityManager identityManager,
ILogger<AccountController> logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
identityManager,
validationProvider
)
{ }
}
}
+269
View File
@@ -0,0 +1,269 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using xCommons.Configurations;
using xCommons.Constants;
using xCommons.Controllers;
using xCommons.Extensions;
using xCommons.Providers;
using xExceptions.Constants;
using xIdentityModels.Constants;
using xIdentityModels.Models;
using xIds.Interfaces;
namespace xIds.Controllers.Base
{
public abstract class XIBaseController : XBaseController
{
public IXIdentityManager IdentityManager { get; }
protected XIBaseController(
ILogger logger,
XAppConfiguration appConfiguration,
IXIdentityManager identityManager,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
validationProvider
)
{
IdentityManager = identityManager;
}
//
#region User Handlers NonActions ...
/// <summary>
/// Retrieve User Identifier Base on XActionRequest
/// </summary>
/// <param name="model"></param>
/// <param name="forceNotNull"></param>
/// <param name="excludes"></param>
/// <returns></returns>
[NonAction]
public string GetUserSelectByParam(
XActionRequest model,
bool forceNotNull = true,
ICollection<XUserSelectBy> excludes = null)
{
//
// Validate Args ...
ValidationProvider.NotNull(model);
//
var result = IdentityManager.GetUserSelectByParam(
model,
forceNotNull,
excludes);
//
return result;
}
/// <summary>
/// Retrieve Access Token
/// </summary>
/// <returns></returns>
[NonAction]
public async Task<string> GetAccessToken()
{
//
var accessToken = Request.Headers[XAuthorization.Header].ToString();
if (accessToken.IsNullOrEmpty())
{
accessToken = await HttpContext.GetTokenAsync(XAuthorization.AccessToken);
}
//
if (accessToken
.ToNormalString()
.Contains(XAuthorization.TokenIdentifier.ToNormalString()))
{
accessToken = accessToken.Remove(0, XAuthorization.TokenIdentifier.Length);
}
//
Logger.LogInformation($"Token: {accessToken}");
return accessToken;
}
/// <summary>
/// Retrieve Refresh Token
/// </summary>
/// <returns></returns>
[NonAction]
public async Task<string> GetRefreshToken()
{
//
var refreshToken = Request.Headers[XAuthorization.RefreshToken].ToString();
if (refreshToken.IsNullOrEmpty())
{
refreshToken = await HttpContext.GetTokenAsync(XAuthorization.RefreshToken);
}
//
Logger.LogInformation($"Refresh Token: {refreshToken}");
return refreshToken;
}
/// <summary>
/// Retrieve Access Token Expiration Date
/// </summary>
/// <returns></returns>
[NonAction]
public async Task<long> GetTokenExpiresAt()
{
//
var expiresAtStr = Request.Headers[XAuthorization.ExpiresAt].ToString();
if (expiresAtStr.IsNullOrEmpty())
{
expiresAtStr = await HttpContext.GetTokenAsync(XAuthorization.ExpiresAt);
}
//
var expiresAt = expiresAtStr.ConvertTo<long>();
//
Logger.LogInformation($"Token ExpiresAt: {expiresAtStr}");
return expiresAt;
}
/// <summary>
/// Retrieve All Required Tokens
/// </summary>
/// <returns></returns>
[NonAction]
public async Task<XLoginResponse> RetrieveTokensAsXLoginResponse()
{
//
var accessToken = await GetAccessToken();
var refreshToken = await GetRefreshToken();
var expiresAt = await GetTokenExpiresAt();
//
return new XLoginResponse
{
AccessToken = accessToken,
RefreshToken = refreshToken,
ExpiresAt = expiresAt
};
}
/// <summary>
/// Retrieve All Required Tokens
/// </summary>
/// <returns></returns>
[NonAction]
public async Task<XTokenResponse> RetrieveTokensAsXTokenResponse()
{
//
var accessToken = await GetAccessToken();
var refreshToken = await GetRefreshToken();
var expiresAt = await GetTokenExpiresAt();
//
return new XTokenResponse
{
AccessToken = accessToken,
RefreshToken = refreshToken,
ExpiresAt = expiresAt
};
}
/// <summary>
/// Retrive UserInfo
/// </summary>
/// <returns></returns>
[NonAction]
public async Task<XUserClaimsInfoDto> GetUserInfo()
{
//
var claims = User.Claims ?? null;
if (!claims.HasChild())
{
return null;
}
var xTokens = await RetrieveTokensAsXTokenResponse();
var result = new XUserClaimsInfoDto(
xTokens.AccessToken,
xTokens.RefreshToken,
xTokens.ExpiresAt,
User.Claims
);
//
return result;
}
/// <summary>
/// Validate User Authenticated and Retrieve User Info
/// </summary>
/// <returns></returns>
[NonAction]
public async Task<XUserClaimsInfoDto> ValidateAndGetUserInfo()
{
//
if (!User.Identity.IsAuthenticated)
{
XException.NotAuthorized.Throw();
}
//
var result = await GetUserInfo();
if (result.IsNull())
{
XException.NotAuthorized.Throw();
}
//
return result;
}
#endregion
//
#region NonActions ...
/// <summary>
/// Convert an Exception to Propper Error Result
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
[NonAction]
public new ActionResult GetExceptionActionResult(Exception ex)
{
//
var exception = GetExceptionResult(ex);
var error = ex.Message.ToXError();
//
Logger.LogError($"exception: {exception}, error: {error}");
//
try
{
var xError = exception.Message.ToXError();
var xException = (XException)xError.Id;
//
switch (xException)
{
//
case XException.NotFound:
return NotFound(error);
//
case XException.NotAuthorized:
return Unauthorized(error);
}
}
catch { }
//
return BadRequest(error);
}
#endregion
}
}
+44
View File
@@ -0,0 +1,44 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using xCommons.Configurations;
using xCommons.Controllers;
using xCommons.Providers;
namespace xIds.Controllers
{
/// <summary>
/// Startup and Running Controller
/// </summary>
[Route("")]
[AllowAnonymous]
public class StartupController : XBaseController
{
public StartupController(
ILogger<StartupController> logger,
XAppConfiguration appConfiguration,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
validationProvider
)
{ }
/// <summary>
/// Show Configured Welcome Message
/// </summary>
/// <returns>an string message</returns>
[HttpGet("")]
[AllowAnonymous]
public virtual ActionResult<string> Index()
{
//
var controllerName = GetControllerName();
var message = $"{AppConfiguration.WelcomeMessage}";
//
return Ok(message);
}
}
}