diff --git a/Constants/XApiAccountEndpoint.cs b/Constants/XApiAccountEndpoint.cs index d4ef382..f5914d1 100644 --- a/Constants/XApiAccountEndpoint.cs +++ b/Constants/XApiAccountEndpoint.cs @@ -213,5 +213,95 @@ namespace xIdentityService.Constants [StringValue("Account/Open")] Open, #endregion + + // + #region Applications ... + // + #region Application ... + [StringValue("Applications")] + CreateApplication, + + [StringValue("Applications")] + UpdateApplication, + + [StringValue("Applications/{id}")] + RemoveApplication, + + [StringValue("Applications/{id}")] + GetApplication, + + [StringValue("Applications")] + GetAllApplications, + + [StringValue("Applications/Query")] + QueryApplications, + #endregion + + // + #region ApiKey ... + [StringValue("Applications/ApiKeys/{id}")] + GetApiKey, + + [StringValue("Applications/ApiKeys/{id}")] + RemoveApiKey, + + [StringValue("Applications/ApiKeys/{id}")] + UpdateApiKey, + + [StringValue("Applications/ApiKeys")] + GetAllApiKeys, + + [StringValue("Applications/ApiKeys/Query")] + QueryApiKeys, + #endregion + + // + #region ApiKeyUsage ... + [StringValue("Applications/ApiKeys/Usages")] + AddApiKeyUsage, + + [StringValue("Applications/ApiKeys/Usages/{id}")] + GetApiKeyUsage, + + [StringValue("Applications/ApiKeys/Usages/{id}")] + RemoveApiKeyUsage, + + [StringValue("Applications/ApiKeys/Usages/{id}")] + UpdateApiKeyUsage, + + [StringValue("Applications/Usages")] + GetAllApiKeyUsages, + + [StringValue("Applications/Usages/Query")] + QueryApiKeyUsages, + #endregion + + // + #region Custom ... + [StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}/Show")] + ShowApiKey, + + [StringValue("Applications/{applicationId}/ApiKeys/Create")] + CreateApiKey, + + [StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}")] + RemoveApiKeyCustom, + + [StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}")] + RotateApiKey, + + [StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}/Revoke")] + RevokeApiKey, + + [StringValue("Applications/{applicationId}/ApiKeys")] + GetApiKeys, + + [StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}/Usages")] + GetApiKeyUsages, + + [StringValue("Applications/ApiKeys/Validate")] + ValidateApiKey, + #endregion + #endregion } } \ No newline at end of file diff --git a/Constants/XHeader.cs b/Constants/XHeader.cs index 642f557..004db99 100644 --- a/Constants/XHeader.cs +++ b/Constants/XHeader.cs @@ -18,5 +18,11 @@ namespace xIdentityService.Constants /// [StringValue("X-Api-Key")] ApiKey, + + /// + /// Checksum Digest Header Key ... + /// + [StringValue("X-Check-Sum")] + ChecksumDigest, } } \ No newline at end of file diff --git a/Constants/XParam.cs b/Constants/XParam.cs index 30bf4fc..3643500 100644 --- a/Constants/XParam.cs +++ b/Constants/XParam.cs @@ -55,5 +55,11 @@ namespace xIdentityService.Constants { [StringValue ("scope")] XScope, + + [StringValue("{apiKeyId}")] + XApiKeyId, + + [StringValue("{applicationId}")] + XApplicationId, } } \ No newline at end of file diff --git a/Controllers/XBaseAccountController.cs b/Controllers/XBaseAccountController.cs new file mode 100644 index 0000000..b0401bb --- /dev/null +++ b/Controllers/XBaseAccountController.cs @@ -0,0 +1,1316 @@ +using System; +using xModels.Dtos; +using xCommons.Providers; +using xCommons.Attributes; +using xCommons.Extensions; +using xIdentityModels.Dtos; +using IdentityModel.Client; +using xExceptions.Constants; +using System.Threading.Tasks; +using xIdentityModels.Models; +using xCommons.Configurations; +using Microsoft.AspNetCore.Mvc; +using xIdentityModels.Constants; +using Microsoft.AspNetCore.Http; +using xIdentityModels.Extensions; +using System.Collections.Generic; +using xIdentityService.Interfaces; +using Microsoft.Extensions.Logging; +using Microsoft.AspNetCore.Authorization; + +namespace xIdentityService.Controllers +{ + [AllowAnonymous] + [RequireXPowered(true)] + public abstract class XBaseAccountController : XBaseIdentityController + { + protected XBaseAccountController( + ILogger logger, + XAppConfiguration appConfiguration, + IXIdentityProvider identityProvider, + XValidationProvider validationProvider + ) : base(logger, appConfiguration, identityProvider, validationProvider) + { } + + // + #region Authentication Actions ... + /// + /// Retrieve OAuth Discovery Document + /// + /// an instance of DiscoveryDocumentResponse + [AllowAnonymous] + [RequireXPowered] + [HttpGet("DiscoveryDocument")] + public virtual async Task> GetDiscoveryDocument() + { + // + try + { + // + var result = await IdentityProvider + .RequestDiscoveryDocument(); + + // + // Ceck Response Result ... + if (result.IsError) + { + XException.InvalidConfiguration.Throw(); + } + + // + return Ok(result + .ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Authenticate User + /// + /// + /// Sample request: + /// + /// { + /// "password": "", + /// "userSelectBy": "", + /// } + /// + /// + /// User Login Required Info, an instance of XLoginRequest + /// an instance of XTokenResponse + [AllowAnonymous] + [RequireXPowered] + [HttpPost("Authenticate")] + public virtual async Task> Authenticate( + [FromBody] XLoginRequest model + ) + { + try + { + // + // Validate Args ... + if (!ModelState.IsValid) + { + XException.InvalidArgs.Throw(); + } + await ValidationProvider + .GroupValidationBuilder() + .AddNotNull(model) + .AddNotEmpty( + model.UserSelectBy, + model.Password + ) + .ValidateGroupAsync(); + + // + var result = await IdentityProvider + .Authenticate(model); + + // + return Ok(result + .ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Authenticate User + /// + /// + /// 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" + /// } + /// } + /// + /// + /// User Login Required Info, an instance of XLoginRequest + /// an instance of XLoginResponse + [AllowAnonymous] + [RequireXPowered] + [HttpPost("Login")] + public virtual async Task> Login( + [FromBody] XLoginRequest model + ) + { + 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 IdentityProvider + .Login(model); + + // + return Ok(result + .ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Refresh Expired Tokens + /// + /// + /// in addition to AccessToken, you had to pass RefreshToken due to Headers + /// + /// an instance of XTokenResponse + [AllowAnonymous] + [RequireXPowered] + [HttpPost("RefreshTokens")] + public virtual async Task> RefreshTokens() + { + // + try + { + // + // Retrieve Toke Response ... + var model = await RetrieveTokensAsXTokenResponse(); + + // + // Validate Args ... + ValidationProvider + .GroupValidationBuilder() + .AddNotNull(model) + .AddNotEmpty( + model.AccessToken, + model.RefreshToken) + .ValidateGroup(); + + // + var result = await IdentityProvider + .RefreshTokens(model); + + // + return Ok(result + .ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + #endregion + + // + #region Open Actions ... + /// + /// Retriev User Info Based on Open Actions ... + /// + /// + /// + /// + [AllowAnonymous] + [RequireXPowered] + [HttpGet("GetUserInfo")] + public virtual async Task> GetUserInfo( + [FromHeader] string token, + [FromQuery] string request + ) + { + // + // Do Action ... + try + { + // + // Validate Args ... + await ValidationProvider + .GroupValidationBuilder() + .AddNotEmpty(token) + .AddNotEmpty(request) + .ValidateGroupAsync(); + + // + var result = await IdentityProvider.GetUserInfo( + token: token, + request: request + ); + + // + // Return Result + return Ok(result + .ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + + /// + /// Retriev User Info Based on Open Actions ... + /// + /// + /// + /// + [AllowAnonymous] + [RequireXPowered] + [HttpGet("GetUserInfoByDevice")] + public virtual async Task> GetUserInfoByDevice( + [FromQuery] string userSelectByParam, + [FromBody] XDeviceDto device + ) + { + // + // Do Action ... + try + { + // + // Validate Args ... + await ValidationProvider + .GroupValidationBuilder() + .AddNotEmpty(userSelectByParam) + .AddNotNull(device) + .ValidateGroupAsync(); + + // + var result = await IdentityProvider.GetUserInfo( + userSelectByParam: userSelectByParam, + device: device + ); + + // + // Return Result + return Ok(result + .ToDynamicObject()); + } + catch (Exception ex) + { + // + var result = GetExceptionActionResult(ex); + return result; + } + } + #endregion + + // + #region Registration ... + /// + /// Check a UserName is Available For Registration or not + /// + /// an string value which represent desired username + /// a boolean value + [AllowAnonymous] + [RequireXPowered] + [HttpGet ("CanRegisterUserName/{userName?}")] + public virtual async Task> CanRegisterUserName ( + [FromRoute] string userName + ) { + // + // Do Action ... + try { + // + // Validate Args ... + ValidationProvider.NotEmpty (userName); + + // + // Validate Type ... + var type = userName.GetUserSelectByType (); + if (type != XUserSelectBy.Username) { + XException.InvalidArgs.Throw (); + } + + // + var result = await IdentityProvider + .CanRegister (userName); + + // + // Return Result + return Ok (result); + } catch (Exception ex) { + // + var result = GetExceptionActionResult (ex); + + // + return result; + } + } + + /// + /// Check a Mobile Number is Available For Registration or not + /// + /// an string value which represent desired mobile number + /// a boolean value + [AllowAnonymous] + [RequireXPowered] + [HttpGet ("CanRegisterMobileNumber/{mobileNumber?}")] + public virtual async Task> CanRegisterMobileNumber ( + [FromRoute] string mobileNumber + ) { + // + // Do Action ... + try { + // + // Validate Args ... + ValidationProvider.NotEmpty (mobileNumber); + + // + // Validate Type ... + var type = mobileNumber.GetUserSelectByType (); + if (type != XUserSelectBy.MobileNumber) { + XException.InvalidArgs.Throw (); + } + + // + var result = await IdentityProvider + .CanRegister (mobileNumber); + + // + // Return Result + return Ok (result); + } catch (Exception ex) { + // + var result = GetExceptionActionResult (ex); + + // + return result; + } + } + + /// + /// Check a Email Address is Available For Registration or not + /// + /// an string value which represent desired email address + /// a boolean value + [AllowAnonymous] + [RequireXPowered] + [HttpGet ("CanRegisterEmail/{email?}")] + public virtual async Task> CanRegisterEmail ( + [FromRoute] string email + ) { + // + // Do Action ... + try { + // + // Validate Args ... + ValidationProvider.NotEmpty (email); + + // + // Validate Type ... + var type = email.GetUserSelectByType (); + if (type != XUserSelectBy.Email) { + XException.InvalidArgs.Throw (); + } + + // + var result = await IdentityProvider + .CanRegister (email); + + // + // Return Result + return Ok (result); + } catch (Exception ex) { + // + var result = GetExceptionActionResult (ex); + + // + return result; + } + } + + /// + /// Recieve some Basic Informations and Start Registration Proccess + /// if they Valid + /// + /// Registration Proccess Starts with Invoking this Action + /// + /// + /// for this action you have to provide: + /// - Lang: client device currently used locale, such as: en-US. + /// - FirstName: user's FirstName. + /// - LastName: user's LastName. + /// - DateOfBirth: user's dob date. + /// - MobileNumber: user's MobileNumber optional. + /// - Email: user's Email optional. + /// - ActionToken: user's requested action token for this action (if user invited). + /// - Device: user's client device which is an instance of XDevice. + /// + /// Sample request: + /// + /// { + /// "lang": "fa-IR", + /// "firstName": "", + /// "lastName": "", + /// "dateOfBirth": "", + /// "email": "", + /// "mobileNumber": "", + /// "actionToken": "", + /// "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" + /// } + /// } + /// + /// + /// an instance of XActionRequest class which provider requirement for action + /// an instance of XActionResponse + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("RequestRegistration")] + public virtual async Task> RequestRegistration ( + [FromBody] XActionRequest model + ) { + // + // Do Action ... + try { + // + // Validate Args ... + if (!ModelState.IsValid) { + XException.InvalidArgs.Throw (); + } + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty ( + model.Lang, + model.FirstName, + model.LastName) + .AddNotNull ( + model.Device, + model.DateOfBirth) + .ValidateGroupAsync (); + + // + // Get Request ... + var result = await IdentityProvider + .RequestRegistration ( + model + ); + + // + return Ok (result + .ToDynamicObject ()); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + + // + return exResult; + } + } + + /// + /// Add User Account Informations + /// + /// + /// for this action you have to provide: + /// - Lang: client device currently used locale, such as: en-US. + /// - ActionToken: user's requested action token for this action. + /// - UserName: user name. + /// - Password: assigne password. + /// - Device: user's client device which is an instance of XDevice. + /// + /// Sample request: + /// + /// { + /// "lang": "fa-IR", + /// "userName": "", + /// "password": "", + /// "actionToken": "", + /// "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" + /// } + /// } + /// + /// + /// an instance of XActionRequest class which provider requirement for action + /// an instance of XActionResponse + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("AddAccountInfo")] + public virtual async Task> AddAccountInfo ( + [FromBody] XActionRequest model + ) { + // + // Do Action ... + try { + // + // Validate Args ... + if (!ModelState.IsValid) { + XException.InvalidArgs.Throw (); + } + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty ( + model.Lang, + model.ActionToken, + model.UserName, + model.Password) + .AddNotNull (model.Device) + .ValidateGroupAsync (); + + // + // Get Request ... + var result = await IdentityProvider + .AddAccountInfo ( + model + ); + + // + return Ok (result + .ToDynamicObject ()); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + return exResult; + } + } + + /// + /// Upload and Attach a Profile Image for User. this is an Optional Step + /// + /// user's requested action token + /// an instance of IFormFile for user's Avatar + /// an instance of XActionResponse + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("AttachProfileImage")] + public virtual async Task> AttachProfileImage ( + [FromForm] string actionToken, [FromForm] IFormFile file + ) { + // + // Do Action ... + try { + // + // Validate Args ... + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty (actionToken) + .AddNotNull (file) + .ValidateGroupAsync (); + + // + var result = await IdentityProvider + .AttachProfileImage ( + actionToken, + file + ); + + // + return Ok (result + .ToDynamicObject ()); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + return exResult; + } + } + + /// + /// Finish Registrationn Proccess + /// + /// + /// for this action you have to provide: + /// - a proper User Identifier such as: (UserId, UserName, Email or MobileNumber). + /// - Lang: client device currently used locale, such as: en-US. + /// - ActionToken: user's requested action token for this action. + /// - Password: assigne password. + /// - Device: user's client device which is an instance of XDevice. + /// - ReturnUrl: client application Login URL. + /// + /// Sample request: + /// + /// { + /// "lang": "fa-IR", + /// "userName": "", + /// "password": "", + /// "returnUrl": "", + /// "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" + /// } + /// } + /// + /// + /// an instance of XActionRequest class which provider requirement for action + /// + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("FinishRegistration")] + public virtual async Task FinishRegistration ( + [FromBody] XActionRequest model + ) { + // + // Do Action ... + try { + // + // Validate Args ... + if (!ModelState.IsValid) { + XException.InvalidArgs.Throw (); + } + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty ( + model.Lang, + model.Password, + model.ReturnUrl) + .AddNotNull (model.Device) + .AddUrl (model.ReturnUrl) + .ValidateGroupAsync (); + + // + var userSelectByParam = IdentityProvider + .GetUserSelectByParam (model); + ValidationProvider + .NotEmpty (userSelectByParam); + + // + // Get Request ... + await IdentityProvider + .FinishRegistration (model); + + // + return Ok (); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + + // + return exResult; + } + } + + /// + /// Request Registration Confirm + /// + /// + /// for this action you have to provide: + /// - a UserSelectedBy identifier which represet User. + /// - Lang: client device currently used locale, such as: en-US. + /// - Password: user's current active password. + /// - Device: user's client device which is an instance of XDevice. + /// - ReturnUrl: client application Confirm Registration URL. + /// + /// Sample request: + /// + /// { + /// "lang": "fa-IR", + /// "userId": "" + /// "password": "", + /// "returnUrl": "http://localhost/confirm", + /// "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" + /// } + /// } + /// + /// + /// an instance of XActionRequest class which provider requirement for action + /// + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("RequestConfirmRegistration")] + public virtual async Task RequestConfirmRegistration ( + [FromBody] XActionRequest model + ) { + // + // Do Action ... + try { + // + // Validate Args ... + if (!ModelState.IsValid) { + XException.InvalidArgs.Throw (); + } + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty ( + model.Lang, + model.Password, + model.ReturnUrl) + .AddNotNull (model.Device) + .AddUrl (model.ReturnUrl) + .ValidateGroupAsync (); + + // + // Get UserSelect By Param ... + var userSelectByParam = model.GetUserSelectByParam (); + ValidationProvider.NotEmpty (userSelectByParam); + + // + await IdentityProvider + .RequestConfirmRegistration (model); + + // + return Ok (); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + return exResult; + } + } + + /// + /// Confirm Registration + /// + /// + /// for this action you have to provide: + /// - Lang: client device currently used locale, such as: en-US. + /// - ActionToken: user's requested action token for this action. + /// - Device: user's client device which is an instance of XDevice. + /// - ReturnUrl: client application Login URL. + /// + /// Sample request: + /// + /// { + /// "lang": "fa-IR", + /// "actionToken": "" + /// "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" + /// } + /// } + /// + /// + /// an instance of XActionRequest class which provider requirement for action + /// + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("ConfirmRegistration")] + public virtual async Task ConfirmRegistration ( + [FromBody] XActionRequest model + ) { + // + // Do Action ... + try { + // + // Validate Args ... + if (!ModelState.IsValid) { + XException.InvalidArgs.Throw (); + } + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty ( + model.Lang, + model.ActionToken, + model.ReturnUrl + ) + .AddNotNull (model.Device) + .ValidateGroupAsync (); + + // + // Get Request ... + await IdentityProvider + .ConfirmRegistration (model); + + // + return Ok (); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + return exResult; + } + } + + /// + /// Request For Mobile Number Change/Confirm + /// + /// + /// for this action you have to provide: + /// - Lang: client device currently used locale, such as: en-US. + /// - Password: user's current active password. + /// - MobileNumber: which phone number is going to confirm. + /// - Device: user's client device which is an instance of XDevice. + /// + /// Sample request: + /// + /// { + /// "lang": "fa-IR", + /// "password": "", + /// "mobileNumber": "", + /// "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" + /// } + /// } + /// + /// + /// an instance of XActionRequest class which provider requirement for action + /// an instance of XActionResponse + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("RequestConfirmMobile")] + public virtual async Task> RequestConfirmMobile ( + [FromBody] XActionRequest model + ) { + // + // Do Action ... + try { + // + // Validate Args ... + if (!ModelState.IsValid) { + XException.InvalidArgs.Throw (); + } + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty ( + model.Lang, + model.Password, + model.MobileNumber) + .AddNotNull (model.Device) + .AddMobileNumber (model.MobileNumber) + .ValidateGroupAsync (); + + // + // Get UserSelect By Param ... + var userSelectByParam = GetUserSelectByParam ( + model, + excludes : [ + XUserSelectBy.Email, + XUserSelectBy.MobileNumber + ]); + + // + // Get Request ... + var result = await IdentityProvider + .RequestConfirmMobile (model); + + // + return Ok (result + .ToDynamicObject ()); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + return exResult; + } + } + + /// + /// Confirm Requested Mobile Number + /// + /// + /// for this action you have to provide: + /// - Lang: client device currently used locale, such as: en-US. + /// - ActionToken: user's requested action token for this action. + /// - Device: user's client device which is an instance of XDevice. + /// - MobileVerificationCode: a verification code which produced due Request Action. + /// + /// Sample request: + /// + /// { + /// "lang": "fa-IR", + /// "actionToken": "" + /// "mobileVerificationCode": "", + /// "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" + /// } + /// } + /// + /// + /// an instance of XActionRequest class which provider requirement for action + /// an instance of XActionResponse + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("ConfirmMobileNumber")] + public virtual async Task> ConfirmMobileNumber ( + [FromBody] XActionRequest model + ) { + // + // Do Action ... + try { + // + // Validate Args ... + if (!ModelState.IsValid) { + XException.InvalidArgs.Throw (); + } + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty ( + model.Lang, + model.MobileVerificationCode, + model.ActionToken + ) + .AddNotNull (model.Device) + .ValidateGroupAsync (); + + // + // Get Request ... + var result = await IdentityProvider + .ConfirmMobileNumber (model); + + // + return Ok (result + .ToDynamicObject ()); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + return exResult; + } + } + + /// + /// Request For Email Address Change/Confirm + /// + /// + /// for this action you have to provide: + /// - Lang: client device currently used locale, such as: en-US. + /// - Password: user's current active password. + /// - Email: which email address is going to confirm. + /// - Device: user's client device which is an instance of XDevice. + /// + /// Sample request: + /// + /// { + /// "lang": "fa-IR", + /// "password": "", + /// "email": "", + /// "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" + /// } + /// } + /// + /// + /// an instance of XActionRequest class which provider requirement for action + /// an instance of XActionResponse + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("RequestConfirmEmail")] + public virtual async Task> RequestConfirmEmail ( + [FromBody] XActionRequest model + ) { + // + // Do Action ... + try { + // + // Validate Args ... + if (!ModelState.IsValid) { + XException.InvalidArgs.Throw (); + } + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty ( + model.Lang, + model.Email, + model.Password) + .AddNotNull (model.Device) + .AddEmailAddress (model.Email) + .ValidateGroupAsync (); + + // + // Get UserSelect By Param ... + var userSelectByParam = GetUserSelectByParam ( + model, + excludes : new List { + XUserSelectBy.Email, + XUserSelectBy.MobileNumber + }); + + // + // Get Request ... + var result = await IdentityProvider + .RequestConfirmEmail (model); + + // + return Ok (result + .ToDynamicObject ()); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + return exResult; + } + } + + /// + /// Confirm Requested Email Address + /// + /// + /// for this action you have to provide: + /// - Lang: client device currently used locale, such as: en-US. + /// - ActionToken: user's requested action token for this action. + /// - Device: user's client device which is an instance of XDevice. + /// - EmailVerificationCode: a verification code which produced due Request Action. + /// + /// Sample request: + /// + /// { + /// "lang": "fa-IR", + /// "actionToken": "" + /// "emailVerificationCode": "", + /// "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" + /// } + /// } + /// + /// + /// an instance of XActionRequest class which provider requirement for action + /// an instance of XActionResponse + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("ConfirmEmailAddress")] + public virtual async Task> ConfirmEmailAddress ( + [FromBody] XActionRequest model + ) { + // + // Do Action ... + try { + // + // Validate Args ... + if (!ModelState.IsValid) { + XException.InvalidArgs.Throw (); + } + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty ( + model.Lang, + model.EmailVerificationCode, + model.ActionToken + ) + .AddNotNull (model.Device) + .ValidateGroupAsync (); + + // + // Get Request ... + var result = await IdentityProvider + .ConfirmEmailAddress (model); + + // + return Ok (result + .ToDynamicObject ()); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + return exResult; + } + } + + /// + /// Request Reset Password Action + /// + /// + /// for this action you have to provide: + /// - Lang: client device currently used locale, such as: en-US. + /// - Device: user's client device which is an instance of XDevice. + /// - ReturnUrl: client application ResetPassword URL. + /// + /// Sample request: + /// + /// { + /// "lang": "fa-IR", + /// "returnUrl": "http://localhost/reset-password", + /// "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" + /// } + /// } + /// + /// + /// an instance of XActionRequest class which provider requirement for action + /// an instance of XActionResponse + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("RequestResetPassword")] + public virtual async Task> RequestResetPassword ( + [FromBody] XActionRequest model + ) { + // + // Do Action ... + try { + // + // Validate Args ... + if (!ModelState.IsValid) { + XException.InvalidArgs.Throw (); + } + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty ( + model.Lang, + model.ReturnUrl) + .AddNotNull (model.Device) + .AddUrl (model.ReturnUrl) + .ValidateGroupAsync (); + + // + // Get UserSelect By Param ... + var userSelectByParam = GetUserSelectByParam ( + model, + excludes : new List { + XUserSelectBy.Email, + XUserSelectBy.MobileNumber + }); + + // + // Get Request ... + var result = await IdentityProvider + .RequestResetPassword (model); + + // + return Ok (result + .ToDynamicObject ()); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + return exResult; + } + } + + /// + /// Reset a User's Password + /// + /// + /// for this action you have to provide: + /// - Lang: client device currently used locale, such as: en-US. + /// - ActionToken: user's requested action token for this action. + /// - 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", + /// "actionToken": "", + /// "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" + /// } + /// } + /// + /// + /// an instance of XActionRequest class which provider requirement for action + /// + [AllowAnonymous] + [RequireXPowered] + [HttpPost ("ResetPassword")] + public virtual async Task ResetPassword ( + [FromBody] XActionRequest model + ) { + // + // Do Action ... + try { + // + // Validate Args ... + if (!ModelState.IsValid) { + XException.InvalidArgs.Throw (); + } + await ValidationProvider + .GroupValidationBuilder () + .AddNotEmpty ( + model.Lang, + model.ActionToken, + model.NewPassword, + model.ReturnUrl) + .AddNotNull (model.Device) + .ValidateGroupAsync (); + + // + // Get Request ... + await IdentityProvider + .ResetPassword (model); + + // + return Ok (); + } catch (Exception ex) { + // + var exResult = GetExceptionActionResult (ex); + return exResult; + } + } + #endregion + } +} \ No newline at end of file diff --git a/Controllers/XBaseIdentityController.cs b/Controllers/XBaseIdentityController.cs index 36488d7..81ce817 100644 --- a/Controllers/XBaseIdentityController.cs +++ b/Controllers/XBaseIdentityController.cs @@ -61,6 +61,54 @@ namespace xIdentityService.Controllers return result; } + /// + /// Extract Checksum From Headers ... + /// + /// + [NonAction] + public string GetRequestChecksum() + { + // + var result = string.Empty; + + // + var headerKey = XHeader.ChecksumDigest.GetStringValue(); + + // + // Check if Connection ID is Provided ... + if (Request.Headers.ContainsKey(headerKey)) + { + result = Request.Headers[headerKey]; + } + + // + return result; + } + + /// + /// Extract ApiKey From Headers ... + /// + /// + [NonAction] + public string GetRequestApiKey() + { + // + var result = string.Empty; + + // + var headerKey = XHeader.ApiKey.GetStringValue(); + + // + // Check if Connection ID is Provided ... + if (Request.Headers.ContainsKey(headerKey)) + { + result = Request.Headers[headerKey]; + } + + // + return result; + } + /// /// Retrieve User Identifier Base on XActionRequest /// diff --git a/Interfaces/IXIdentityProvider.cs b/Interfaces/IXIdentityProvider.cs index 916c2fc..da4ff26 100644 --- a/Interfaces/IXIdentityProvider.cs +++ b/Interfaces/IXIdentityProvider.cs @@ -1,5 +1,7 @@ +using System; using RestSharp; using xModels.Dtos; +using System.Threading; using IdentityModel.Client; using xIdentityModels.Dtos; using System.Threading.Tasks; @@ -313,7 +315,7 @@ namespace xIdentityService.Interfaces #region Open Actions ... // XDeviceDto GetDevice(); - + // Task OpenGet( XOpenActionInnerDto model @@ -345,5 +347,351 @@ namespace xIdentityService.Interfaces string request ); #endregion + + // + #region Applications ... + // + #region Application ... + /// + /// Create Application ... + /// + /// + /// + /// + /// + Task CreateApplication( + XTokenResponse tokens, + XApplicationDto item, + CancellationToken cancellationToken = default + ); + + /// + /// Update Specified Application ... + /// + /// + /// + /// + /// + Task UpdateApplication( + XTokenResponse tokens, + XApplicationDto item, + CancellationToken cancellationToken = default + ); + + /// + /// Remove Specified Application ... + /// + /// + /// + /// + /// + Task RemoveApplication( + XTokenResponse tokens, + int id, + CancellationToken cancellationToken = default + ); + + /// + /// Get Specified Application ... + /// + /// + /// + /// + /// + Task GetApplication( + XTokenResponse tokens, + int id, + CancellationToken cancellationToken = default + ); + + /// + /// Query Applications ... + /// + /// + /// + /// + /// + Task> QueryApplications( + XTokenResponse tokens, + XQuery query, + CancellationToken cancellationToken = default + ); + + /// + /// Get All Application ... + /// + /// + /// + /// + Task> GetAllApplications( + XTokenResponse tokens, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region XApiKey ... + /// + /// Get Specified ApiKey ... + /// + /// + /// + /// + /// + Task GetApiKey( + XTokenResponse tokens, + Guid id, + CancellationToken cancellationToken = default + ); + + /// + /// Remove Specified ApiKey ... + /// + /// + /// + /// + /// + Task RemoveApiKey( + XTokenResponse tokens, + Guid id, + CancellationToken cancellationToken = default + ); + + /// + /// Update Specified ApiKey ... + /// + /// + /// + /// + /// + Task UpdateApiKey( + XTokenResponse tokens, + XApiKeyDto item, + CancellationToken cancellationToken = default + ); + + /// + /// Query ApiKeys ... + /// + /// + /// + /// + /// + Task> QueryApiKeys( + XTokenResponse tokens, + XQuery query, + CancellationToken cancellationToken = default + ); + + /// + /// Get All Specified ApiKeys ... + /// + /// + /// + /// + Task> GetAllApiKeys( + XTokenResponse tokens, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region XApiKeyUsage ... + /// + /// Add Api Key Usage ... + /// + /// + /// + /// + /// + Task AddApiKeyUsage( + XTokenResponse tokens, + XApiKeyUsageDto item, + CancellationToken cancellationToken = default + ); + + /// + /// Get Specified Api Key Usage ... + /// + /// + /// + /// + /// + Task GetApiKeyUsage( + XTokenResponse tokens, + long id, + CancellationToken cancellationToken = default + ); + + /// + /// Remove Specified Api Key Usage ... + /// + /// + /// + /// + /// + Task RemoveApiKeyUsage( + XTokenResponse tokens, + long id, + CancellationToken cancellationToken = default + ); + + /// + /// Update Specified Api Key Usage ... + /// + /// + /// + /// + /// + Task UpdateApiKeyUsage( + XTokenResponse tokens, + XApiKeyUsageDto item, + CancellationToken cancellationToken = default + ); + + /// + /// Query Api Key Usages ... + /// + /// + /// + /// + /// + Task> QueryApiKeyUsages( + XTokenResponse tokens, + XQuery query, + CancellationToken cancellationToken = default + ); + + /// + /// Get All Api Key Usages ... + /// + /// + /// + /// + Task> GetAllApiKeyUsages( + XTokenResponse tokens, + CancellationToken cancellationToken = default + ); + #endregion + + // + #region Custom ... + /// + /// Show Api Key ... + /// + /// + /// + /// + /// + /// + Task ShowApiKey( + XTokenResponse tokens, + Guid apiKeyId, + int applicationId, + CancellationToken cancellationToken = default + ); + + /// + /// Create Api Key ... + /// + /// + /// + /// + /// + /// + Task CreateApiKey( + XTokenResponse tokens, + int applicationId, + XCreateApiKeyRequest request, + CancellationToken cancellationToken = default + ); + + /// + /// Remove Specified Api Key ... + /// + /// + /// + /// + /// + /// + Task RemoveApiKey( + XTokenResponse tokens, + int applicationId, + Guid apiKeyId, + CancellationToken cancellationToken = default + ); + + /// + /// Rotate Specified Api Key ... + /// + /// + /// + /// + /// + /// + /// + Task RotateApiKey( + XTokenResponse tokens, + int applicationId, + Guid apiKeyId, + XRotateApiKeyRequest request, + CancellationToken cancellationToken = default + ); + + /// + /// Revoke Specified Api Key ... + /// + /// + /// + /// + /// + /// + Task RevokeApiKey( + XTokenResponse tokens, + int applicationId, + Guid apiKeyId, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieve Specified Application's Api Keys ... + /// + /// + /// + /// + /// + Task> GetApiKeys( + XTokenResponse tokens, + int applicationId, + CancellationToken cancellationToken = default + ); + + /// + /// Retrieve Specified Api Keys Usages ... + /// + /// + /// + /// + /// + /// + Task> GetApiKeyUsages( + XTokenResponse tokens, + int applicationId, + Guid apiKeyId, + CancellationToken cancellationToken = default + ); + + /// + /// Validate Specifed Api Key ... + /// + /// + /// + /// + Task ValidateApiKey( + XApiKeyValidationRequest request, + CancellationToken cancellationToken = default + ); + #endregion + #endregion } } \ No newline at end of file diff --git a/Partial/XIdentityProvider+Application.cs b/Partial/XIdentityProvider+Application.cs new file mode 100644 index 0000000..e62c35c --- /dev/null +++ b/Partial/XIdentityProvider+Application.cs @@ -0,0 +1,1156 @@ +using System; +using xModels.Dtos; +using System.Threading; +using xCommons.Extensions; +using xIdentityModels.Dtos; +using xExceptions.Constants; +using System.Threading.Tasks; +using xIdentityModels.Models; +using xHttpService.Constants; +using System.Collections.Generic; +using xIdentityService.Constants; +using xHttpService.Extensions; +using MongoDB.Bson; + +namespace xIdentityService.Providers +{ + public partial class XIdentityProvider + { + + // + #region Applications ... + // + #region Application ... + /// + /// Create Application ... + /// + /// + /// + /// + /// + public async Task CreateApplication( + XTokenResponse tokens, + XApplicationDto item, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(item) + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet(XApiAccountEndpoint.CreateApplication); + request.AddJsonBody(item); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.POST + ); + return response; + } + + /// + /// Update Specified Application ... + /// + /// + /// + /// + /// + public async Task UpdateApplication( + XTokenResponse tokens, + XApplicationDto item, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(item) + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet(XApiAccountEndpoint.UpdateApplication); + request.AddJsonBody(item); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.PUT + ); + return response; + } + + /// + /// Remove Specified Application ... + /// + /// + /// + /// + /// + public async Task RemoveApplication( + XTokenResponse tokens, + int id, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + if (!id.IsValidIntId()) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.RemoveApplication, + @params: new Dictionary { + { XParam.XId.GetStringValue (), id.ToString() } + } + ); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.DELETE + ); + return response; + } + + /// + /// Get Specified Application ... + /// + /// + /// + /// + /// + public async Task GetApplication( + XTokenResponse tokens, + int id, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + if (!id.IsValidIntId()) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.GetApplication, + @params: new Dictionary { + { XParam.XId.GetStringValue (), id.ToString() } + } + ); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.GET + ); + return response; + } + + /// + /// Query Applications ... + /// + /// + /// + /// + /// + public async Task> QueryApplications( + XTokenResponse tokens, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(query) + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet(XApiAccountEndpoint.QueryApplications); + + // + // Attach XQuery to Request ... + request = request.AttachXQuery (query); + + // + var response = await RunRestRequest>( + client, + request, + XHttpMethod.GET + ); + return response; + } + + /// + /// Get All Application ... + /// + /// + /// + /// + public async Task> GetAllApplications( + XTokenResponse tokens, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet(XApiAccountEndpoint.GetAllApplications); + + // + var response = await RunRestRequest>( + client, + request, + XHttpMethod.GET + ); + return response; + } + #endregion + + // + #region XApiKey ... + /// + /// Get Specified ApiKey ... + /// + /// + /// + /// + /// + public async Task GetApiKey( + XTokenResponse tokens, + Guid id, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.GetApiKey, + @params: new Dictionary { + { XParam.XId.GetStringValue (), id.ToString() } + } + ); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.GET + ); + return response; + } + + /// + /// Remove Specified ApiKey ... + /// + /// + /// + /// + /// + public async Task RemoveApiKey( + XTokenResponse tokens, + Guid id, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddIsGuid(id) + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.RemoveApiKey, + @params: new Dictionary { + { XParam.XId.GetStringValue (), id.ToString() } + } + ); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.DELETE + ); + return response; + } + + /// + /// Update Specified ApiKey ... + /// + /// + /// + /// + /// + public async Task UpdateApiKey( + XTokenResponse tokens, + XApiKeyDto item, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(item) + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.UpdateApiKey, + @params: new Dictionary { + { XParam.XId.GetStringValue (), item.Id.ToString() } + } + ); + request.AddJsonBody(item); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.PUT + ); + return response; + } + + /// + /// Query ApiKeys ... + /// + /// + /// + /// + /// + public async Task> QueryApiKeys( + XTokenResponse tokens, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(query) + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet(XApiAccountEndpoint.QueryApiKeys); + + // + // Attach XQuery to Request ... + request = request.AttachXQuery (query); + + // + var response = await RunRestRequest>( + client, + request, + XHttpMethod.GET + ); + return response; + } + + /// + /// Get All Specified ApiKeys ... + /// + /// + /// + /// + public async Task> GetAllApiKeys( + XTokenResponse tokens, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet(XApiAccountEndpoint.GetAllApiKeys); + + // + var response = await RunRestRequest>( + client, + request, + XHttpMethod.GET + ); + return response; + } + #endregion + + // + #region XApiKeyUsage ... + /// + /// Add Api Key Usage ... + /// + /// + /// + /// + /// + public async Task AddApiKeyUsage( + XTokenResponse tokens, + XApiKeyUsageDto item, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(item) + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet(XApiAccountEndpoint.AddApiKeyUsage); + request.AddJsonBody(item); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.POST + ); + return response; + } + + /// + /// Get Specified Api Key Usage ... + /// + /// + /// + /// + /// + public async Task GetApiKeyUsage( + XTokenResponse tokens, + long id, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + if (id <= 0) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.GetApiKeyUsage, + @params: new Dictionary { + { XParam.XId.GetStringValue (), id.ToString() } + } + ); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.GET + ); + return response; + } + + /// + /// Remove Specified Api Key Usage ... + /// + /// + /// + /// + /// + public async Task RemoveApiKeyUsage( + XTokenResponse tokens, + long id, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + if (id <= 0) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.RemoveApiKeyUsage, + @params: new Dictionary { + { XParam.XId.GetStringValue (), id.ToString() } + } + ); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.DELETE + ); + return response; + } + + /// + /// Update Specified Api Key Usage ... + /// + /// + /// + /// + /// + public async Task UpdateApiKeyUsage( + XTokenResponse tokens, + XApiKeyUsageDto item, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(item) + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.UpdateApiKeyUsage, + @params: new Dictionary + { + { XParam.XId.GetStringValue (), item.Id.ToString() } + } + ); + request.AddJsonBody(item); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.PUT + ); + return response; + } + + /// + /// Query Api Key Usages ... + /// + /// + /// + /// + /// + public async Task> QueryApiKeyUsages( + XTokenResponse tokens, + XQuery query, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(query) + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet(XApiAccountEndpoint.QueryApiKeyUsages); + + // + // Attach XQuery to Request ... + request = request.AttachXQuery (query); + + // + var response = await RunRestRequest>( + client, + request, + XHttpMethod.GET + ); + return response; + } + + /// + /// Get All Api Key Usages ... + /// + /// + /// + /// + public async Task> GetAllApiKeyUsages( + XTokenResponse tokens, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet(XApiAccountEndpoint.GetAllApiKeyUsages); + + // + var response = await RunRestRequest>( + client, + request, + XHttpMethod.GET + ); + return response; + } + #endregion + + // + #region Custom ... + /// + /// Show Api Key ... + /// + /// + /// + /// + /// + /// + public async Task ShowApiKey( + XTokenResponse tokens, + Guid apiKeyId, + int applicationId, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddIsGuid(apiKeyId) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + if (!applicationId.IsValidIntId()) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.ShowApiKey, + @params: new Dictionary { + { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, + { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } + } + ); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.GET + ); + return response; + } + + /// + /// Create Api Key ... + /// + /// + /// + /// + /// + /// + public async Task CreateApiKey( + XTokenResponse tokens, + int applicationId, + XCreateApiKeyRequest createRequest, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddNotNull(createRequest) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + if (!applicationId.IsValidIntId()) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.CreateApiKey, + @params: new Dictionary { + { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } + } + ); + request.AddJsonBody(createRequest); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.POST + ); + return response; + } + + /// + /// Remove Specified Api Key ... + /// + /// + /// + /// + /// + /// + public async Task RemoveApiKey( + XTokenResponse tokens, + int applicationId, + Guid apiKeyId, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddIsGuid(apiKeyId) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + if (!applicationId.IsValidIntId()) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.RemoveApiKey, + @params: new Dictionary { + { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, + { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } + } + ); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.DELETE + ); + return response; + } + + /// + /// Rotate Specified Api Key ... + /// + /// + /// + /// + /// + /// + /// + public async Task RotateApiKey( + XTokenResponse tokens, + int applicationId, + Guid apiKeyId, + XRotateApiKeyRequest rotateRequest, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddIsGuid(apiKeyId) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + if (!applicationId.IsValidIntId()) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.RotateApiKey, + @params: new Dictionary { + { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, + { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } + } + ); + request.AddJsonBody(rotateRequest); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.POST + ); + return response; + } + + /// + /// Revoke Specified Api Key ... + /// + /// + /// + /// + /// + /// + public async Task RevokeApiKey( + XTokenResponse tokens, + int applicationId, + Guid apiKeyId, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddIsGuid(apiKeyId) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + if (!applicationId.IsValidIntId()) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.RevokeApiKey, + @params: new Dictionary { + { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, + { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } + } + ); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.POST + ); + return response; + } + + /// + /// Retrieve Specified Application's Api Keys ... + /// + /// + /// + /// + /// + public async Task> GetApiKeys( + XTokenResponse tokens, + int applicationId, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + if (!applicationId.IsValidIntId()) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.GetApiKeys, + @params: new Dictionary { + { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } + } + ); + + // + var response = await RunRestRequest>( + client, + request, + XHttpMethod.GET + ); + return response; + } + + /// + /// Retrieve Specified Api Keys Usages ... + /// + /// + /// + /// + /// + /// + public async Task> GetApiKeyUsages( + XTokenResponse tokens, + int applicationId, + Guid apiKeyId, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(tokens) + .AddIsGuid(apiKeyId) + .AddNotEmpty( + tokens.AccessToken + ) + .ValidateGroupAsync(); + if (!applicationId.IsValidIntId()) + { + XException.InvalidArgs.Throw(); + } + + // + var client = GetRestClient(tokens); + + // + var request = GetRestRequet( + XApiAccountEndpoint.GetApiKeyUsages, + @params: new Dictionary { + { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, + { XParam.XApplicationId.GetStringValue (), applicationId.ToString() } + } + ); + + // + var response = await RunRestRequest>( + client, + request, + XHttpMethod.GET + ); + return response; + } + + /// + /// Validate Specifed Api Key ... + /// + /// + /// + /// + public async Task ValidateApiKey( + XApiKeyValidationRequest validationRequest, + CancellationToken cancellationToken = default + ) + { + // + // Validate Args ... + await validationProvider + .GroupValidationBuilder() + .AddNotNull(validationRequest) + .ValidateGroupAsync(); + + // + var client = GetRestClient(); + + // + var checksum = SecurityProvider.Encrypt(validationRequest.ToJson()).ToMd5String(); + + // + var request = GetRestRequet( + XApiAccountEndpoint.ValidateApiKey, + headers: new Dictionary{ + { XHeader.ChecksumDigest.GetStringValue(), checksum } + } + ); + + // + var response = await RunRestRequest( + client, + request, + XHttpMethod.POST + ); + return response; + } + #endregion + #endregion + } +} \ No newline at end of file