Exemple #1
0
        /// <summary>
        /// Use this API to Remove emails from a user Account
        /// </summary>
        /// <param name="email">user's email</param>
        /// <param name="uid">UID, the unified identifier for each user account</param>
        /// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
        /// <returns>Response containing Definition for Complete profile data</returns>
        /// 18.30

        public ApiResponse <Identity> RemoveEmail(string email, string uid,
                                                  string fields = "")
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(email));
            }
            if (string.IsNullOrWhiteSpace(uid))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
                { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] }
            };

            if (!string.IsNullOrWhiteSpace(fields))
            {
                queryParameters.Add("fields", fields);
            }

            var bodyParameters = new BodyParameters
            {
                { "email", email }
            };

            var resourcePath = $"identity/v2/manage/account/{uid}/email";

            return(ConfigureAndExecute <Identity>(HttpMethod.DELETE, resourcePath, queryParameters, ConvertToJson(bodyParameters)));
        }
Exemple #2
0
        /// <summary>
        /// This API Returns a Forgot Password Token it can also be used to send a Forgot Password email to the customer. Note: If you have the UserName workflow enabled, you may replace the 'email' parameter with 'username' in the body.
        /// </summary>
        /// <param name="email">user's email</param>
        /// <param name="emailTemplate">Email template name</param>
        /// <param name="resetPasswordUrl">Url to which user should get re-directed to for resetting the password</param>
        /// <param name="sendEmail">If set to true, the API will also send a Forgot Password email to the customer, bypassing any Bot Protection challenges that they are faced with.</param>
        /// <returns>Response containing Definition of Complete Forgot Password data</returns>
        /// 18.22

        public ApiResponse <ForgotPasswordResponse> GetForgotPasswordToken(string email, string emailTemplate = null,
                                                                           string resetPasswordUrl            = null, bool?sendEmail = null)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(email));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
                { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] }
            };

            if (!string.IsNullOrWhiteSpace(emailTemplate))
            {
                queryParameters.Add("emailTemplate", emailTemplate);
            }
            if (!string.IsNullOrWhiteSpace(resetPasswordUrl))
            {
                queryParameters.Add("resetPasswordUrl", resetPasswordUrl);
            }
            if (sendEmail != false)
            {
                queryParameters.Add("sendEmail", sendEmail.ToString());
            }

            var bodyParameters = new BodyParameters
            {
                { "email", email }
            };

            var resourcePath = "identity/v2/manage/account/forgot/token";

            return(ConfigureAndExecute <ForgotPasswordResponse>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(bodyParameters)));
        }
Exemple #3
0
        /// <summary>
        /// This API allows you to validate code for a particular dropdown member.
        /// </summary>
        /// <param name="code">Secret Code</param>
        /// <param name="recordId">Selected dropdown item’s record id</param>
        /// <returns>Response containing Definition of Complete Validation data</returns>
        /// 7.2

        public ApiResponse <PostValidationResponse> ValidateRegistrationDataCode(string code, string recordId)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(code));
            }
            if (string.IsNullOrWhiteSpace(recordId))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(recordId));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
            };

            var bodyParameters = new BodyParameters
            {
                { "code", code },
                { "recordId", recordId }
            };

            var resourcePath = "identity/v2/auth/registrationdata/validatecode";

            return(ConfigureAndExecute <PostValidationResponse>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(bodyParameters)));
        }
Exemple #4
0
        /// <summary>
        /// This API is used to send the OTP to reset the account password.
        /// </summary>
        /// <param name="phone">New Phone Number</param>
        /// <param name="smsTemplate">SMS Template name</param>
        /// <returns>Response Containing Validation Data and SMS Data</returns>
        /// 10.4

        public ApiResponse <UserProfilePostResponse <SMSResponseData> > ForgotPasswordByPhoneOTP(string phone, string smsTemplate = null)
        {
            if (string.IsNullOrWhiteSpace(phone))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
            };

            if (!string.IsNullOrWhiteSpace(smsTemplate))
            {
                queryParameters.Add("smsTemplate", smsTemplate);
            }

            var bodyParameters = new BodyParameters
            {
                { "phone", phone }
            };

            var resourcePath = "identity/v2/auth/password/otp";

            return(ConfigureAndExecute <UserProfilePostResponse <SMSResponseData> >(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(bodyParameters)));
        }
 protected override void loadRequest()
 {
     QueryParameters.Clear();
     BodyParameters.Clear();
     if (After != null)
     {
         QueryParameters.Add("after", new List <string>(new string[] { After }));
     }
     if (Before != null)
     {
         QueryParameters.Add("before", new List <string>(new string[] { Before }));
     }
     if (First != 20)
     {
         QueryParameters.Add("first", new List <string>(new string[] { First + "" }));
     }
     if (GameID.Count != 0)
     {
         QueryParameters.Add("game_id", GameID);
     }
     if (Language.Count != 0)
     {
         QueryParameters.Add("language", Language);
     }
     if (UserID.Count != 0)
     {
         QueryParameters.Add("user_id", UserID);
     }
     if (UserLogin.Count != 0)
     {
         QueryParameters.Add("user_login", UserLogin);
     }
 }
Exemple #6
0
        /// <summary>
        /// This API is used to update the PhoneId by using the Uid's. Admin can update the PhoneId's for both the verified and unverified profiles. It will directly replace the PhoneId and bypass the OTP verification process.
        /// </summary>
        /// <param name="phone">Phone number</param>
        /// <param name="uid">UID, the unified identifier for each user account</param>
        /// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
        /// <returns>Response containing Definition for Complete profile data</returns>
        /// 18.16

        public ApiResponse <Identity> UpdatePhoneIDByUid(string phone, string uid,
                                                         string fields = "")
        {
            if (string.IsNullOrWhiteSpace(phone))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
            }
            if (string.IsNullOrWhiteSpace(uid))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
                { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] }
            };

            if (!string.IsNullOrWhiteSpace(fields))
            {
                queryParameters.Add("fields", fields);
            }

            var bodyParameters = new BodyParameters
            {
                { "phone", phone }
            };

            var resourcePath = $"identity/v2/manage/account/{uid}/phoneid";

            return(ConfigureAndExecute <Identity>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(bodyParameters)));
        }
        /// <summary>
        /// This API allows you to query your LoginRadius Cloud Storage and retrieve up to 20 user records.
        /// </summary>
        /// <param name="select"> Fields included in the Query, default all fields, Optional: can be null or empty string</param>
        /// <param name="from">LoginRadius Table that details are being retrieved from, for now users only supported </param>
        /// <param name="where">Filter for data based on condition,Optional: can be null or empty string </param>
        /// <param name="orderBy">Determines ascending order of returned data,Optional: can be null or empty string</param>
        /// <param name="skip">Ignores the specified amount of values used to page through responses, value must be positive and default value is 0, Optional: can be null or empty string</param>
        /// <param name="limit">Determines size of dataset returned. default value is 20 and max value is 20, Optional: can be null or empty string</param>
        /// <returns></returns>
        public ApiResponse <LoginRadiusIdentityUserList> GetUserList(string select  = "", string from = "", string where = "",
                                                                     string orderBy = "", string skip = "",
                                                                     string limit   = "")
        {
            var postRequest = new BodyParameters
            {
                { "From", string.IsNullOrWhiteSpace(from) ? "users" : from }
            };

            if (!string.IsNullOrWhiteSpace(select))
            {
                postRequest.Add("Select", select);
            }
            if (!string.IsNullOrWhiteSpace(where))
            {
                postRequest.Add("Where", where);
            }
            if (!string.IsNullOrWhiteSpace(orderBy))
            {
                postRequest.Add("OrderBy", orderBy);
            }
            if (!string.IsNullOrWhiteSpace(skip))
            {
                postRequest.Add("Skip", skip);
            }
            if (!string.IsNullOrWhiteSpace(limit))
            {
                postRequest.Add("Limit", limit);
            }
            return(ConfigureAndExecute <LoginRadiusIdentityUserList>(RequestType.Cloud, HttpMethod.Post,
                                                                     "identity",
                                                                     postRequest.ConvertToJson()));
        }
        public async Task <BackupRepository> AddBackupRepositoryAsync(BackupRepostioryForCreation newRepository,
                                                                      CancellationToken ct = default)
        {
            var bodyParameters = new BodyParameters()
                                 .AddOptionalParameter("Name", newRepository.Name)
                                 .AddOptionalParameter("ProxyId", newRepository.ProxyId)
                                 .AddOptionalParameter("Path", newRepository.Path)
                                 .AddOptionalParameter("Description", newRepository.Description)
                                 .AddOptionalParameter("RetentionType", newRepository.RetentionType)
                                 .AddOptionalParameter("RetentionPeriodType", newRepository.RetentionPeriodType)
                                 .AddOptionalParameter("DailyRetentionPeriod", newRepository.DailyRetentionPeriod)
                                 .AddOptionalParameter("MonthlyRetentionPeriod", newRepository.MonthlyRetentionPeriod)
                                 .AddOptionalParameter("YearlyRetentionPeriod", newRepository.YearlyRetentionPeriod)
                                 .AddOptionalParameter("RetentionFrequencyType", newRepository.RetentionFrequencyType)
                                 .AddOptionalParameter("DailyTime", newRepository.DailyTime)
                                 .AddOptionalParameter("DailyType", newRepository.DailyType)
                                 .AddOptionalParameter("MonthlyTime", newRepository.MonthlyTime)
                                 .AddOptionalParameter("MonthlyDayNumber", newRepository.MonthlyDayNumber)
                                 .AddOptionalParameter("MonthlyDayOfWeek", newRepository.MonthlyDayOfWeek)
                                 .AddOptionalParameter("AttachUsedRepository", newRepository.AttachUsedRepository)
                                 .AddOptionalParameter("ObjectStorageId", newRepository.ObjectStorageId)
                                 .AddOptionalParameter("ObjectStorageCachePath", newRepository.ObjectStorageCachePath)
                                 .AddOptionalParameter("ObjectStorageEncryptionEnabled", newRepository.ObjectStorageEncryptionEnabled)
                                 .AddOptionalParameter("EncryptionKeyId", newRepository.EncryptionKeyId);

            var url = "backuprepositories";

            return(await _baseClient.PostAsync <BackupRepository>(url, bodyParameters, ct));
        }
Exemple #9
0
        /// <summary>
        /// This API is used to update (if configured) the phone number used for Multi-factor authentication by sending the verification OTP to the provided phone number
        /// </summary>
        /// <param name="phoneNo2FA">Phone Number For 2FA</param>
        /// <param name="secondFactorAuthenticationToken">A Uniquely generated MFA identifier token after successful authentication</param>
        /// <param name="smsTemplate2FA">SMS Template Name</param>
        /// <returns>Response containing Definition for Complete SMS data</returns>
        /// 9.16

        public ApiResponse <SMSResponseData> MFAUpdatePhoneNumber(string phoneNo2FA, string secondFactorAuthenticationToken,
                                                                  string smsTemplate2FA = null)
        {
            if (string.IsNullOrWhiteSpace(phoneNo2FA))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phoneNo2FA));
            }
            if (string.IsNullOrWhiteSpace(secondFactorAuthenticationToken))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(secondFactorAuthenticationToken));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
                { "secondFactorAuthenticationToken", secondFactorAuthenticationToken }
            };

            if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
            {
                queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
            }

            var bodyParameters = new BodyParameters
            {
                { "phoneNo2FA", phoneNo2FA }
            };

            var resourcePath = "identity/v2/auth/login/2fa";

            return(ConfigureAndExecute <SMSResponseData>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(bodyParameters)));
        }
        public async Task SaveOneDriveDocumentToFileAsync(string targetFilePath,
                                                          string restoreSessionId,
                                                          string oneDriveId,
                                                          string oneDriveDocumentId,
                                                          bool?asZip           = null,
                                                          CancellationToken ct = default)
        {
            ParameterValidator.ValidateNotNull(targetFilePath, nameof(targetFilePath));
            ParameterValidator.ValidateNotNull(restoreSessionId, nameof(restoreSessionId));
            ParameterValidator.ValidateNotNull(oneDriveId, nameof(oneDriveId));
            ParameterValidator.ValidateNotNull(oneDriveDocumentId, nameof(oneDriveDocumentId));

            var bodyParameters = new BodyParameters();

            if (asZip != null)
            {
                bodyParameters.AddMandatoryParameter("save", new { asZip = asZip.ToString() });
            }
            else
            {
                bodyParameters.AddNullParameter("save");
            }

            var url = $"restoresessions/{restoreSessionId}/organization/onedrives/{oneDriveId}/documents/{oneDriveDocumentId}/action";
            await _baseClient.DownloadToFilePostAsync(targetFilePath, url, bodyParameters, ct);
        }
Exemple #11
0
        /// <summary>
        /// This API is used to login via Multi-factor-authentication by passing the google authenticator code.
        /// </summary>
        /// <param name="googleAuthenticatorCode">The code generated by google authenticator app after scanning QR code</param>
        /// <param name="secondFactorAuthenticationToken">A Uniquely generated MFA identifier token after successful authentication</param>
        /// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
        /// <param name="smsTemplate2FA">SMS Template Name</param>
        /// <returns>Complete user UserProfile data</returns>
        /// 9.13

        public ApiResponse <AccessToken <Identity> > MFAValidateGoogleAuthCode(string googleAuthenticatorCode, string secondFactorAuthenticationToken,
                                                                               string fields = "", string smsTemplate2FA = null)
        {
            if (string.IsNullOrWhiteSpace(googleAuthenticatorCode))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(googleAuthenticatorCode));
            }
            if (string.IsNullOrWhiteSpace(secondFactorAuthenticationToken))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(secondFactorAuthenticationToken));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
                { "secondFactorAuthenticationToken", secondFactorAuthenticationToken }
            };

            if (!string.IsNullOrWhiteSpace(fields))
            {
                queryParameters.Add("fields", fields);
            }
            if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
            {
                queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
            }

            var bodyParameters = new BodyParameters
            {
                { "googleAuthenticatorCode", googleAuthenticatorCode }
            };

            var resourcePath = "identity/v2/auth/login/2fa/verification/googleauthenticatorcode";

            return(ConfigureAndExecute <AccessToken <Identity> >(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(bodyParameters)));
        }
        TwoFactorAuthUpdatePhoneNumber(string SecondFactorAuthenticationToken, TwoFactorPhoneAuthModel authModel,
                                       LoginRadiusApiOptionalParams optionalParams)
        {
            Validate(new ArrayList {
                SecondFactorAuthenticationToken
            });

            var additionalQueryParams = new QueryParameters
            {
                { "SecondFactorAuthenticationToken", SecondFactorAuthenticationToken }
            };
            var body = new BodyParameters {
                ["PhoneNo2Fa"] = authModel.PhoneNo2Fa
            };

            additionalQueryParams.AddOptionalParamsRange(authModel);
            if (!string.IsNullOrWhiteSpace(optionalParams.SmsTemplate))
            {
                additionalQueryParams.Add("smsTemplate2FA", optionalParams.SmsTemplate2Fa);
            }
            return
                (ConfigureAndExecute
                 <SmsResponseData>(
                     RequestType.Authentication,
                     HttpMethod.Put, _resoucePath.ChildObject("2FA").ToString(), additionalQueryParams,
                     body.ConvertToJson()));
        }
Exemple #13
0
        /// <summary>
        /// This API is used to validate the verification code sent to verify a user's phone number
        /// </summary>
        /// <param name="otp">The Verification Code</param>
        /// <param name="phone">New Phone Number</param>
        /// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
        /// <param name="smsTemplate">SMS Template name</param>
        /// <returns>Response containing User Profile Data and access token</returns>
        /// 11.1.1

        public ApiResponse <AccessToken <Identity> > PhoneVerificationByOTP(string otp, string phone,
                                                                            string fields = "", string smsTemplate = null)
        {
            if (string.IsNullOrWhiteSpace(otp))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(otp));
            }
            if (string.IsNullOrWhiteSpace(phone))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
                { "otp", otp }
            };

            if (!string.IsNullOrWhiteSpace(fields))
            {
                queryParameters.Add("fields", fields);
            }
            if (!string.IsNullOrWhiteSpace(smsTemplate))
            {
                queryParameters.Add("smsTemplate", smsTemplate);
            }

            var bodyParameters = new BodyParameters
            {
                { "phone", phone }
            };

            var resourcePath = "identity/v2/auth/phone/otp";

            return(ConfigureAndExecute <AccessToken <Identity> >(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(bodyParameters)));
        }
Exemple #14
0
        /// <summary>
        /// This API is used to set the password of an account in Cloud Storage.
        /// </summary>
        /// <param name="password">New password</param>
        /// <param name="uid">UID, the unified identifier for each user account</param>
        /// <returns>Response containing Definition for Complete PasswordHash data</returns>
        /// 18.18

        public ApiResponse <UserPasswordHash> SetAccountPasswordByUid(string password, string uid)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(password));
            }
            if (string.IsNullOrWhiteSpace(uid))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
                { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] }
            };

            var bodyParameters = new BodyParameters
            {
                { "password", password }
            };

            var resourcePath = $"identity/v2/manage/account/{uid}/password";

            return(ConfigureAndExecute <UserPasswordHash>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(bodyParameters)));
        }
        public ApiResponse <LoginRadiusPostResponse> ForgotPassword(string email,
                                                                    LoginRadiusApiOptionalParams optionalParams)
        {
            Validate(new ArrayList {
                email
            });
            var additionalQueryParams = new QueryParameters();

            if (!string.IsNullOrWhiteSpace(optionalParams.ResetPasswordUrl))
            {
                additionalQueryParams.Add("resetPasswordUrl", optionalParams.ResetPasswordUrl);
            }
            if (!string.IsNullOrWhiteSpace(optionalParams.EmailTemplate))
            {
                additionalQueryParams.Add("emailTemplate", optionalParams.EmailTemplate);
            }

            var bodyparametre = new BodyParameters {
                ["email"] = email
            };

            return(ConfigureAndExecute <LoginRadiusPostResponse>(RequestType.Authentication, HttpMethod.Post,
                                                                 _resoucePath.ToString(),
                                                                 additionalQueryParams, bodyparametre.ConvertToJson()));
        }
        public async Task <Job> CreateJobForOrganizationAsync(string organizationId,
                                                              string repositoryId,
                                                              string name,
                                                              string description,
                                                              BackupType backupType,
                                                              SchedulePolicy schedulePolicy,
                                                              JobItemCollection selectedItems,
                                                              string proxyId,
                                                              bool runNow,
                                                              CancellationToken ct = default)
        {
            ParameterValidator.ValidateNotNull(organizationId, nameof(organizationId));

            var bodyParameters = new BodyParameters()
                                 .AddOptionalParameter("Name", name)
                                 .AddOptionalParameter("Description", description)
                                 .AddOptionalParameter("BackupType", backupType)
                                 .AddOptionalParameter("SchedulePolicy", schedulePolicy)
                                 .AddOptionalParameter("SelectedItems", selectedItems)
                                 .AddOptionalParameter("ProxyId", proxyId)
                                 .AddMandatoryParameter("RepositoryId", repositoryId)
                                 .AddOptionalParameter("RunNow", runNow);

            var url = $"organizations/{organizationId}/jobs";

            return(await _baseClient.PostAsync <Job>(url, bodyParameters, ct));
        }
Exemple #17
0
        private async Task ProcessApiCallAsync(Uri fullUrl, HttpMethod httpMethod, QueryParameters queryParameters,
                                               BodyParameters bodyParameters, CancellationToken ct)
        {
            var parametersAsDTOs = ConvertToDtoBodyParameters(bodyParameters);
            var apiResponse      = await SendAsync(fullUrl, httpMethod, ct, queryParameters : queryParameters, bodyParameters : parametersAsDTOs);

            EnsureSuccessfullApiResponse(apiResponse);
        }
Exemple #18
0
        private StringBuilder ConvertToJson(BodyParameters parameters)
        {
            var sb = new StringBuilder();
            var sw = new StringWriter(sb);

            using JsonWriter writer = new JsonTextWriter(sw);
            _sut.WriteJson(writer, parameters, _serializer);
            return(sb);
        }
Exemple #19
0
        public async Task StopRestoreSessionAsync(string restoreSessionId, CancellationToken ct = default)
        {
            ParameterValidator.ValidateNotNull(restoreSessionId, nameof(restoreSessionId));

            var bodyParameters = new BodyParameters()
                                 .AddNullParameter("stop");

            var url = $"restoresessions/{restoreSessionId}/action";
            await _baseClient.PostAsync(url, bodyParameters, ct);
        }
        private async Task PostAction(string action, string jobId, CancellationToken ct)
        {
            ParameterValidator.ValidateNotNull(jobId, nameof(jobId));

            var bodyParameters = new BodyParameters()
                                 .AddNullParameter(action);

            var url = $"jobs/{jobId}/action";
            await _baseClient.PostAsync(url, bodyParameters, ct);
        }
        public async Task <RestoreSession> StartJobRestoreSessionAsync(string jobId, RestoreSessionExploreDetails sessionDetails, CancellationToken ct = default)
        {
            ParameterValidator.ValidateNotNull(jobId, nameof(jobId));

            var bodyParameters = new BodyParameters()
                                 .AddMandatoryParameter("explore", sessionDetails);

            var url = $"jobs/{jobId}/action";

            return(await _baseClient.PostAsync <RestoreSession>(url, bodyParameters, ct));
        }
Exemple #22
0
        public ApiResponse <LoginRadiusVerification> EmailVerificationToken(string email)
        {
            Validate(new ArrayList {
                email
            });
            var payload = new BodyParameters {
                ["email"] = email
            };

            return(ConfigureAndExecute <LoginRadiusVerification>(RequestType.Identity, HttpMethod.Post, "verify/token",
                                                                 payload.ConvertToJson()));
        }
        public async Task SaveOneDriveItemToFileAsync(string targetFilePath, string restoreSessionId, string oneDriveId, CancellationToken ct = default)
        {
            ParameterValidator.ValidateNotNull(targetFilePath, nameof(targetFilePath));
            ParameterValidator.ValidateNotNull(restoreSessionId, nameof(restoreSessionId));
            ParameterValidator.ValidateNotNull(oneDriveId, nameof(oneDriveId));

            var bodyParameters = new BodyParameters()
                                 .AddNullParameter("save");

            var url = $"restoresessions/{restoreSessionId}/organization/onedrives/{oneDriveId}/action";
            await _baseClient.DownloadToFilePostAsync(targetFilePath, url, bodyParameters, ct);
        }
    public void AddHeaderParameter(string key, string value)
    {
        var comparison = StringComparison.InvariantCultureIgnoreCase;

        if (key.StartsWith("content-", comparison) &&
            !string.IsNullOrEmpty(value) &&
            !BodyParameters.ContainsKey(key))
        {
            BodyParameters.Add(key, value);
        }
        HeaderParameters[key] = value;
    }
Exemple #25
0
        public ApiResponse <LoginRadiusPassword> GetForgotPasswordToken(string email)
        {
            Validate(new ArrayList {
                email
            });
            var payload = new BodyParameters {
                ["email"] = email
            };

            return(ConfigureAndExecute <LoginRadiusPassword>(RequestType.Identity, HttpMethod.Post, "forgot/token",
                                                             payload.ConvertToJson()));
        }
Exemple #26
0
        /// <summary>
        /// This API can be used to login by Phone on a Multi-factor authentication enabled LoginRadius site.
        /// </summary>
        /// <param name="password">Password for the email</param>
        /// <param name="phone">New Phone Number</param>
        /// <param name="emailTemplate">Email template name</param>
        /// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
        /// <param name="loginUrl">Url where the user is logging from</param>
        /// <param name="smsTemplate">SMS Template name</param>
        /// <param name="smsTemplate2FA">SMS Template Name</param>
        /// <param name="verificationUrl">Email verification url</param>
        /// <returns>Complete user UserProfile data</returns>
        /// 9.8.3

        public ApiResponse <MultiFactorAuthenticationResponse <Identity> > MFALoginByPhone(string password, string phone,
                                                                                           string emailTemplate   = null, string fields = "", string loginUrl = null, string smsTemplate = null, string smsTemplate2FA = null,
                                                                                           string verificationUrl = null)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(password));
            }
            if (string.IsNullOrWhiteSpace(phone))
            {
                throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
            }
            var queryParameters = new QueryParameters
            {
                { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
            };

            if (!string.IsNullOrWhiteSpace(emailTemplate))
            {
                queryParameters.Add("emailTemplate", emailTemplate);
            }
            if (!string.IsNullOrWhiteSpace(fields))
            {
                queryParameters.Add("fields", fields);
            }
            if (!string.IsNullOrWhiteSpace(loginUrl))
            {
                queryParameters.Add("loginUrl", loginUrl);
            }
            if (!string.IsNullOrWhiteSpace(smsTemplate))
            {
                queryParameters.Add("smsTemplate", smsTemplate);
            }
            if (!string.IsNullOrWhiteSpace(smsTemplate2FA))
            {
                queryParameters.Add("smsTemplate2FA", smsTemplate2FA);
            }
            if (!string.IsNullOrWhiteSpace(verificationUrl))
            {
                queryParameters.Add("verificationUrl", verificationUrl);
            }

            var bodyParameters = new BodyParameters
            {
                { "password", password },
                { "phone", phone }
            };

            var resourcePath = "identity/v2/auth/login/2fa";

            return(ConfigureAndExecute <MultiFactorAuthenticationResponse <Identity> >(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(bodyParameters)));
        }
Exemple #27
0
        public void CanWriteNullProperty()
        {
            var parameters = new BodyParameters()
                             .AddNullParameter("param");

            var sb = ConvertToJson(parameters);

            var    expectedJson = @"{""param"":null}";
            JToken expected     = JToken.Parse(expectedJson);
            JToken actual       = JToken.Parse(sb.ToString());

            JToken.DeepEquals(actual, expected).Should().BeTrue();
        }
Exemple #28
0
        public ApiResponse <HashPassword> SetAccountPassword(string uId, string password)
        {
            Validate(new ArrayList {
                uId, password
            });
            var pattern      = new LoginRadiusResoucePath("{0}/password").ToString();
            var resourcePath = SDKUtil.FormatURIPath(pattern, new object[] { uId });
            var passwordbody = new BodyParameters {
                ["password"] = password
            };

            return(ConfigureAndExecute <HashPassword>(RequestType.Identity, HttpMethod.Put, resourcePath,
                                                      passwordbody.ConvertToJson()));
        }
Exemple #29
0
        public ApiResponse <LoginRadiusUserIdentity> ChangeAccountPhone(string uId, string phone)
        {
            Validate(new ArrayList {
                uId
            });
            var pattern      = new LoginRadiusResoucePath("{0}/PhoneId").ToString();
            var resourcePath = SDKUtil.FormatURIPath(pattern, new object[] { uId });
            var payload      = new BodyParameters {
                ["phone"] = phone
            };

            return(ConfigureAndExecute <LoginRadiusUserIdentity>(RequestType.Identity, HttpMethod.Put, resourcePath,
                                                                 payload.ConvertToJson()));
        }
Exemple #30
0
 protected override void loadRequest()
 {
     QueryParameters.Clear();
     BodyParameters.Clear();
     if (UserIDs.Length != 0)
     {
         List <string> ids = new List <string>(UserIDs);
         QueryParameters.Add("id", ids);
     }
     if (LoginNames.Length != 0)
     {
         List <string> names = new List <string>(LoginNames);
         QueryParameters.Add("login", names);
     }
 }
 private void ResetPlugin()
 {
     Cleanup();
     SetRotatingFrameThresholds();
     RemoveBuggyTidalLocking();
     plugin_construction_ = DateTime.Now;
     Dictionary<String, ConfigNode> name_to_gravity_model = null;
     var gravity_model_configs =
     GameDatabase.Instance.GetConfigs(principia_gravity_model_config_name);
     var cartesian_configs =
     GameDatabase.Instance.GetConfigs(principia_initial_state_config_name);
     if (gravity_model_configs.Length == 1) {
       name_to_gravity_model =
       gravity_model_configs[0].config.GetNodes("body").
       ToDictionary(node => node.GetValue("name"));
     } else if (gravity_model_configs.Length > 1) {
       Log.Fatal("too many gravity models (" + gravity_model_configs.Length +
     ")");
     }
     if (cartesian_configs.Length > 0) {
       plugin_source_ = PluginSource.CARTESIAN_CONFIG;
       if (cartesian_configs.Length > 1) {
     Log.Fatal("too many Cartesian configs (" + cartesian_configs.Length +
       ")");
       }
       if (name_to_gravity_model == null) {
     Log.Fatal("Cartesian config without gravity models");
       }
       try {
     ConfigNode initial_states =
     GameDatabase.Instance.GetConfigs(principia_initial_state_config_name)[0].config;
     plugin_ =
     Interface.NewPlugin(initial_states.GetValue("game_epoch"),
                     initial_states.GetValue("solar_system_epoch"),
                     Planetarium.InverseRotAngle);
     var name_to_initial_state =
     initial_states.GetNodes("body").
     ToDictionary(node => node.GetValue("name"));
     BodyProcessor insert_body = body => {
       Log.Info("Inserting " + body.name + "...");
       ConfigNode gravity_model;
       if (!name_to_gravity_model.TryGetValue(body.name,
                                      out gravity_model)) {
      Log.Fatal("missing gravity model for " + body.name);
       }
       ConfigNode initial_state;
       if (!name_to_initial_state.TryGetValue(body.name,
                                      out initial_state)) {
      Log.Fatal("missing Cartesian initial state for " + body.name);
       }
       int? parent_index = body.orbit?.referenceBody.flightGlobalsIndex;
       var body_parameters = new BodyParameters{
       name = body.name,
       gravitational_parameter =
       gravity_model.GetValue("gravitational_parameter"),
       reference_instant       =
       double.Parse(gravity_model.GetValue("reference_instant")),
       mean_radius             = gravity_model.GetValue("mean_radius"),
       axis_right_ascension    =
       gravity_model.GetValue("axis_right_ascension"),
       axis_declination        =
       gravity_model.GetValue("axis_declination"),
       reference_angle         =
       gravity_model.GetValue("reference_angle"),
       angular_frequency       =
       gravity_model.GetValue("angular_frequency"),
       j2                      = gravity_model.GetValue("j2"),
       reference_radius        =
       gravity_model.GetValue("reference_radius")};
       plugin_.InsertCelestialAbsoluteCartesian(
       celestial_index         : body.flightGlobalsIndex,
       parent_index            : parent_index,
       body_parameters         : body_parameters,
       x                       : initial_state.GetValue("x"),
       y                       : initial_state.GetValue("y"),
       z                       : initial_state.GetValue("z"),
       vx                      : initial_state.GetValue("vx"),
       vy                      : initial_state.GetValue("vy"),
       vz                      : initial_state.GetValue("vz"));
     };
     insert_body(Planetarium.fetch.Sun);
     ApplyToBodyTree(insert_body);
     plugin_.EndInitialization();
     plugin_.AdvanceTime(Planetarium.GetUniversalTime(),
                 Planetarium.InverseRotAngle);
       } catch (Exception e) {
     Log.Fatal("Exception while reading initial state: " + e.ToString());
       }
     } else {
       plugin_source_ = PluginSource.ORBITAL_ELEMENTS;
       // We create the plugin at time 0, rather than
       // |Planetarium.GetUniversalTime()|, in order to get a deterministic
       // initial state.
       for(;;) {
     plugin_ = Interface.NewPlugin("0 s", "0 s",
                           Planetarium.InverseRotAngle);
     BodyProcessor insert_body = body => {
       Log.Info("Inserting " + body.name + "...");
       ConfigNode gravity_model = null;
       if (name_to_gravity_model?.TryGetValue(body.name,
                                      out gravity_model) == true) {
     Log.Info("using custom gravity model");
       }
       Orbit orbit = unmodified_orbits_.GetValueOrNull(body);
       var body_parameters = new BodyParameters{
       name = body.name,
       gravitational_parameter =
       (gravity_model?.GetValue("gravitational_parameter")).
           GetValueOrDefault(body.gravParameter + " m^3/s^2"),
       // J2000, because that's when we start non-config games.  We
       // should really parse real-life dates from strings.
       // The origin of rotation in KSP is the x of Barycentric, rather
       // than the y axis as is the case for Earth, so the right
       // ascension is -90 deg.
       reference_instant    = double.Parse(
       (gravity_model?.GetValue("reference_instant")).
           GetValueOrDefault("2451545.0")),
       mean_radius          =
       (gravity_model?.GetValue("mean_radius")).
           GetValueOrDefault(body.Radius + " m"),
       axis_right_ascension =
       (gravity_model?.GetValue("axis_right_ascension")).
           GetValueOrDefault("-90 deg"),
       axis_declination     =
       (gravity_model?.GetValue("axis_declination")).
           GetValueOrDefault("90 deg"),
       reference_angle      =
       (gravity_model?.GetValue("reference_angle")).
           GetValueOrDefault(body.initialRotation.ToString() +
                             " deg"),
       angular_frequency    =
       (gravity_model?.GetValue("angular_frequency")).
           GetValueOrDefault(body.angularV.ToString() + " rad/s"),
       j2                   = gravity_model?.GetValue("j2"),
       reference_radius     =
       gravity_model?.GetValue("reference_radius")};
       plugin_.InsertCelestialJacobiKeplerian(
       celestial_index             : body.flightGlobalsIndex,
       parent_index                :
       orbit?.referenceBody.flightGlobalsIndex,
       body_parameters             : body_parameters,
       keplerian_elements          : orbit?.Elements());
     };
     insert_body(Planetarium.fetch.Sun);
     ApplyToBodyTree(insert_body);
     plugin_.EndInitialization();
     if (plugin_.IsKspStockSystem()) {
       Interface.DeletePlugin(ref plugin_);
       Fix631();
     } else {
       break;
     }
       }
     }
     plotting_frame_selector_.reset(
     new ReferenceFrameSelector(this,
                        plugin_,
                        UpdateRenderingFrame,
                        "Plotting frame"));
     flight_planner_.reset(new FlightPlanner(this, plugin_));
     VesselProcessor insert_vessel = vessel => {
       Log.Info("Inserting " + vessel.name + "...");
       bool inserted =
       plugin_.InsertOrKeepVessel(
       vessel.id.ToString(),
       vessel.orbit.referenceBody.flightGlobalsIndex);
       if (!inserted) {
     Log.Fatal("Plugin initialization: vessel not inserted");
       } else {
     plugin_.SetVesselStateOffset(vessel.id.ToString(),
                          new QP{q = (XYZ)vessel.orbit.pos,
                                 p = (XYZ)vessel.orbit.vel});
       }
     };
     ApplyToVesselsOnRailsOrInInertialPhysicsBubbleInSpace(insert_vessel);
 }