/// <summary> /// Fetches a User object by its BaseId /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="userId">User BaseId</param> /// <returns></returns> public static async Task<User> GetUserById(AuthorizationToken authToken, Guid userId) { if (!authToken.IsValid) throw new InvalidCredentialException("AuthorizationToken is not valid."); return await TypeProjectionController.GetByBaseId<User>(authToken, userId); }
public static void Initialize(TestContext testContext) { _objectsToCleanup = new List<ConfigurationItem>(); Task<AuthorizationToken> tokenTask = AuthorizationController.GetAuthorizationToken(ConfigurationHelper.PortalUrl, ConfigurationHelper.UserName, ConfigurationHelper.Password, ConfigurationHelper.Domain); tokenTask.Wait(); _authToken = tokenTask.Result; }
/// <summary> /// Creates a new blank PurchaseOrder /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="name">Name of the PurchaseOrder</param> /// <param name="displayName">DisplayName of the PurchaseOrder</param> /// <param name="orderNumber">PurchaseOrder number</param> /// <param name="date">PurchaseOrder date</param> /// <returns></returns> public static async Task<PurchaseOrder> Create(AuthorizationToken authToken, string name, string displayName, string orderNumber, DateTime date) { dynamic extraProps = new { PurchaseOrderNumber = orderNumber, PurchaseOrderDate = date }; return await TypeProjectionController.CreateBlankObject<PurchaseOrder>(authToken, name, displayName, extraProps); }
/// <summary> /// Attempts to commit the configuration item to the portal. Throws an exception if not successful. /// </summary> /// <param name="authToken">AuthorizationToken to use</param> public override Task<bool> Commit(AuthorizationToken authToken) { if (!AllowCommitDeleted && this.IsDeleted) throw new CiresonApiException("Cannot commit a deleted object."); // Any object with a null ObjectStatus is a brand new object and needs to have the status set to Active if (this.ObjectStatus == null) this.ObjectStatus = new Enumeration(EnumerationConstants.ConfigItem.BuiltinValues.ObjectStatus.Active, "Active", "Active", false, false); return base.Commit(authToken); }
public static void Initialize(TestContext testContext) { Task<AuthorizationToken> tokenTask = AuthorizationController.GetAuthorizationToken(ConfigurationHelper.PortalUrl, ConfigurationHelper.UserName, ConfigurationHelper.Password, ConfigurationHelper.Domain); tokenTask.Wait(); _authToken = tokenTask.Result; if (!_authToken.User.CanCreateIncident) { Assert.Fail("Must run Incident tests with an account that can create Incidents."); } }
/// <summary> /// Creates a new HardwareAsset /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="model">Model of the asset</param> /// <param name="manufacturer">Manufacturer of the asset</param> /// <param name="assetTag">Asset tag</param> /// <param name="serialNumber">Asset's serial number</param> /// <returns></returns> public static async Task<HardwareAsset> CreateNewHardwareAsset(AuthorizationToken authToken, string model, string manufacturer, string assetTag, string serialNumber) { dynamic extraProps = new { Model = model, Manufacturer = manufacturer, AssetTag = assetTag, SerialNumber = serialNumber, HardwareAssetID = assetTag }; return await ConfigurationItemController.CreateConfigurationItem<HardwareAsset>(authToken, assetTag, assetTag, extraProps); }
public async Task Initialize_ReturnsActivityDto() { //Arrange var curActivityContext = FixtureData.GetFileListActivityDO(); AuthorizationToken tokenDTO = FixtureData.DropboxAuthorizationToken(); curActivityContext.AuthorizationToken = tokenDTO; //Act await _getFileList_v1.Configure(curActivityContext); // Assert Assert.True(curActivityContext.ActivityPayload.CrateStorage.Count > 0); }
/// <summary> /// Creates a new HardwareAsset with the specified parameters. /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="model">Model of the asset</param> /// <param name="manufacturer">Manufacturer of the asset</param> /// <param name="assetTag">Asset tag</param> /// <param name="serialNumber">Asset's serial number</param> /// <returns></returns> public static async Task <HardwareAsset> Create(AuthorizationToken authToken, string model, string manufacturer, string assetTag, string serialNumber) { dynamic extraProps = new { Model = model, Manufacturer = manufacturer, AssetTag = assetTag, SerialNumber = serialNumber, HardwareAssetID = assetTag }; return(await TypeProjectionController.CreateBlankObject <HardwareAsset>(authToken, assetTag, assetTag, extraProps)); }
private SalesforceAuthToken ToSalesforceToken(AuthorizationToken ourToken) { var startIndexOfInstanceUrl = ourToken.AdditionalAttributes.IndexOf("instance_url", StringComparison.InvariantCulture); var startIndexOfApiVersion = ourToken.AdditionalAttributes.IndexOf("api_version", StringComparison.InvariantCulture); var instanceUrl = ourToken.AdditionalAttributes.Substring(startIndexOfInstanceUrl, (startIndexOfApiVersion - 1 - startIndexOfInstanceUrl)); var apiVersion = ourToken.AdditionalAttributes.Substring(startIndexOfApiVersion, ourToken.AdditionalAttributes.Length - startIndexOfApiVersion); instanceUrl = instanceUrl.Replace("instance_url=", ""); apiVersion = apiVersion.Replace("api_version=", ""); return(new SalesforceAuthToken { ApiVersion = apiVersion, InstanceUrl = instanceUrl, Token = JsonConvert.DeserializeObject <dynamic>(ourToken.Token).AccessToken }); }
public async Task <IActionResult> GetAccountToken() { var c = User.Claims.Where(c => c.Type == ClaimTypes.Name).FirstOrDefault(); if (c != null) { var user = await _userManager.FindByNameAsync(c.Value); AuthorizationToken token = GenerateJSONWebToken(user); return(Ok(token)); } return(Unauthorized()); }
/// <summary> /// Creates a new HardwareAsset with the specified parameters. /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="model">Model of the asset</param> /// <param name="manufacturer">Manufacturer of the asset</param> /// <param name="assetTag">Asset tag</param> /// <param name="serialNumber">Asset's serial number</param> /// <returns></returns> public static async Task<HardwareAsset> Create(AuthorizationToken authToken, string model, string manufacturer, string assetTag, string serialNumber) { dynamic extraProps = new { Model = model, Manufacturer = manufacturer, AssetTag = assetTag, SerialNumber = serialNumber, HardwareAssetID = assetTag }; return await TypeProjectionController.CreateBlankObject<HardwareAsset>(authToken, assetTag, assetTag, extraProps); }
public async Task <IActionResult> Login([FromBody] UserIM userData) { var result = await _signInManager.PasswordSignInAsync(userData.Email, userData.Password, false, false); if (result.Succeeded) { var user = await _userManager.FindByNameAsync(userData.Email); AuthorizationToken token = GenerateJSONWebToken(user); return(Ok(token)); } return(Unauthorized()); }
/// <summary> /// Convenience method that returns a HardwareAsset by its unique HardwareAssetID /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="id">HardwareAssetID</param> /// <returns></returns> public static async Task<HardwareAsset> GetByHardwareAssetID(AuthorizationToken authToken, string id) { QueryCriteria criteria = BuildCriteria(new PropertyPathHelper(ClassConstants.HardwareAsset.Id, "HardwareAssetID"), id); List<HardwareAsset> assetList = await GetByCriteria(authToken, criteria); if (assetList == null) return null; if (assetList.Count == 0) return null; return assetList[0]; }
public ServiceContext CreateServiceContext(AuthorizationToken authToken, IHubCommunicator hubCommunicator) { var tokens = authToken.Token.Split(new[] { Authenticator.TokenSeparator }, StringSplitOptions.None); var accessToken = tokens[0]; var accessTokenSecret = tokens[1]; var companyId = tokens[2]; var expiresAt = tokens[3]; DateTime expiresDate; if (DateTime.TryParse(expiresAt, out expiresDate) == false) { //EventManager.TokenValidationFailed(authToken.Token, "Terminal Quickbooks token is invalid"); throw new ArgumentException("Terminal Quickbooks token is invalid", nameof(expiresAt)); } // Token renew should fit into 151-180 days period, // See https://developer.intuit.com/docs/0100_accounting/0060_authentication_and_authorization/connect_from_within_your_app#/manage // if (DateTime.Now > expiresDate.AddDays(-30) && DateTime.Now <= expiresDate) { authToken = _authenticator.RefreshAuthToken(authToken).Result; var tokenDto = new AuthorizationTokenDTO { Id = authToken.Id.ToString(), ExternalAccountId = authToken.ExternalAccountId, Token = authToken.Token }; hubCommunicator.RenewToken(tokenDto); // After token refresh we need to get new accessToken and accessTokenSecret from it tokens = authToken.Token.Split(new[] { Authenticator.TokenSeparator }, StringSplitOptions.None); accessToken = tokens[0]; accessTokenSecret = tokens[1]; } if (DateTime.Now > expiresDate) { var message = "Quickbooks token is expired. Please, get the new one"; //EventManager.TokenValidationFailed(authToken.Token, message); throw new TerminalQuickbooksTokenExpiredException(message); } var oauthValidator = new OAuthRequestValidator( accessToken, accessTokenSecret, Authenticator.ConsumerKey, Authenticator.ConsumerSecret); return(new ServiceContext(AppToken, companyId, IntuitServicesType.QBO, oauthValidator)); }
private ControlDefinitionDTO CreateStatusDropDownListControl( string key, AuthorizationToken authToken) { return(new DropDownList() { Name = "QueryField_" + key, ListItems = Statuses .Select(x => new ListItem() { Key = x, Value = x }) .ToList() }); }
public async Task AUTH01_GetAuthorizationTokenTest() { // Arrange // Act _authToken = await AuthorizationController.GetAuthorizationToken(ConfigurationHelper.PortalUrl, ConfigurationHelper.UserName, ConfigurationHelper.Password, ConfigurationHelper.Domain); // Assert Assert.IsNotNull(_authToken); Assert.AreEqual(ConfigurationHelper.UserName, _authToken.User.UserName); Assert.AreEqual(ConfigurationHelper.Domain, _authToken.User.Domain); Assert.AreEqual(ConfigurationHelper.PortalUrl, _authToken.PortalUrl); Assert.IsTrue(_authToken.IsValid); }
/// <summary> /// Gets a token. /// </summary> /// <param name="tenantId">The tenant identifier.</param> /// <returns></returns> /// <exception cref="ArgumentNullException">tenantId</exception> private AuthorizationToken GetToken(string tenantId) { if (string.IsNullOrEmpty(tenantId)) { throw new ArgumentNullException("tenantId"); } if (_token == null) { _token = SynchronousExecute(() => GetTokenAsync(tenantId)); } return(_token); }
/// <summary> /// Get access token exchange with refresh token /// </summary> /// <param name="authorizationToken"></param> /// <param name="ct"></param> /// <returns></returns> public async Task <AuthorizationToken> GetTokenExchangeRefreshTokenAsync(AuthorizationToken authorizationToken, CancellationToken ct = default) { CheckAuthorizationToken(authorizationToken); using (var request = PrepareRefreshTokenRequest(authorizationToken)) using (var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead, ct).ConfigureAwait(false)) { return(await _resolverFactory.Create <AuthorizationToken>(Settings, true) .ConfigureStatusResponce(HttpStatusCode.OK) .ConfigureStatusResponce(HttpStatusCode.BadRequest, (message) => throw new BadRefreshTokenException(message, authorizationToken)) .ConfigureDefaultResponce((message) => throw new ServerErrorException(message)) .ExtractDataAsync(response)); } }
public async Task AuthenticateIfTokenExpiredAsync_TokenHasExpired_ReturnsExpectedAuthorizationToken() { // Arrange // Mocks Tikkie Configuration var mockTikkieConfiguration = new Mock <ITikkieConfiguration>(); mockTikkieConfiguration .Setup(m => m.RSAKey) .Returns(new RSACryptoServiceProvider()); mockTikkieConfiguration .Setup(m => m.ApiBaseUrl) .Returns("https://tikkie.unittests"); // Mocks HttpClient var expectedAuthenticationResponse = new AuthenticationResponse { AccessToken = "2334", ExpiresInSeconds = 60, Scope = "tikkie", TokenType = "Bearer" }; var mockHttp = new MockHttpMessageHandler(); mockHttp .When($"{mockTikkieConfiguration.Object.ApiBaseUrl}{UrlProvider.AuthenticationUrlSuffix}") .Respond(HttpStatusCode.OK, "application/json", JsonConvert.SerializeObject(expectedAuthenticationResponse)); var httpClient = mockHttp.ToHttpClient(); // Sets up authorization token var authorizationToken = new AuthorizationToken() { AccessToken = "1234", TokenExpirationDate = DateTime.Now.AddMinutes(-1), Scope = "Tikki", TokenType = "Something" }; var sut = CreateSut(mockTikkieConfiguration.Object, () => httpClient, authorizationToken); // Act await sut.AuthenticateIfTokenExpiredAsync(); // Assert Assert.AreEqual(expectedAuthenticationResponse.AccessToken, authorizationToken.AccessToken); Assert.GreaterOrEqual(DateTime.Now.AddSeconds(expectedAuthenticationResponse.ExpiresInSeconds), authorizationToken.TokenExpirationDate); Assert.AreEqual(expectedAuthenticationResponse.Scope, authorizationToken.Scope); Assert.AreEqual(expectedAuthenticationResponse.TokenType, authorizationToken.TokenType); Assert.IsTrue(httpClient.DefaultRequestHeaders.Contains("API-Key")); }
/// <summary> /// ReconfigurationList algorithm. /// </summary> public async Task ReconfigureActivities(ActivityPayload solution, AuthorizationToken authToken, IReadOnlyList <ConfigurationRequest> items) { var queue = new Queue <ConfigurationRequest>(items); if (solution.ChildrenActivities == null) { solution.ChildrenActivities = new List <ActivityPayload>(); } while (queue.Count > 0) { var item = queue.Dequeue(); var context = new ReconfigurationContext() { SolutionActivity = solution, AuthToken = authToken, Requests = items }; if (!await item.HasActivityMethod(context)) { var childActivityByIndex = solution.ChildrenActivities .SingleOrDefault(x => x.Ordering == item.ChildActivityIndex); if (childActivityByIndex != null) { solution.ChildrenActivities.Remove(childActivityByIndex); } await item.CreateActivityMethod(context); } else { await item.ConfigureActivityMethod(context); } if (context.AdditionalRequests.Count > 0) { foreach (var additionalItem in context.AdditionalRequests) { if (queue.All(x => x.ChildActivityIndex != additionalItem.ChildActivityIndex)) { queue.Enqueue(additionalItem); } } } } }
public ControlDefinitionDTO CreateFolderDropDownListControl(string key, AuthorizationToken authToken) { var conf = _docuSignManager.SetUp(AuthorizationToken); return(new DropDownList() { Name = "QueryField_" + key, ListItems = DocuSignFolders.GetFolders(conf) .Select(x => new ListItem() { Key = x.Key, Value = x.Value }) .ToList() }); }
/// <summary> /// Attempts to commit the configuration item to the portal. Throws an exception if not successful. /// </summary> /// <param name="authToken">AuthorizationToken to use</param> public override Task <bool> Commit(AuthorizationToken authToken) { if (!AllowCommitDeleted && this.IsDeleted) { throw new CiresonApiException("Cannot commit a deleted object."); } // Any object with a null ObjectStatus is a brand new object and needs to have the status set to Active if (this.ObjectStatus == null) { this.ObjectStatus = new Enumeration(EnumerationConstants.ConfigItem.BuiltinValues.ObjectStatus.Active, "Active", "Active", false, false); } return(base.Commit(authToken)); }
/// <summary> /// Get a object instance with the token for requests initialized for the received tenant or the CSP tenant /// (if empty parameter). /// </summary> public AzureADGraphApiHelper(string forCustomerTenant = null) { // If empty, initialize for CSP Tenant authentication if (string.IsNullOrWhiteSpace(forCustomerTenant)) { // Use CSP Tenant context _forCustomerTenant = Constants.CSP_TENANT_NAME; } else { // Initialize for customer tenant authentication _forCustomerTenant = forCustomerTenant; } // Get the AD token for the requests _tokenForRequests = GetADTokenForRequests(_forCustomerTenant).Result; }
/// <summary> /// Cancel offer to sell on secondary market /// </summary> /// <param name="offerId">Secondary market offer Id</param> /// <param name="authorizationToken"></param> /// <param name="ct"></param> /// <returns></returns> public async Task CancelOfferInvestmentOnSecondaryMarketAsync(int offerId, AuthorizationToken authorizationToken, CancellationToken ct = default) { CheckAuthorizationToken(authorizationToken); using (var request = PrepareAuthorizedRequest($"/users/me/traded-investments/{offerId}", HttpMethod.Delete, authorizationToken)) using (var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead, ct).ConfigureAwait(false)) { await _resolverFactory.Create(Settings, true) .ConfigureStatusResponce(HttpStatusCode.OK, (message) => { }) .ConfigureStatusResponce(HttpStatusCode.NoContent, (message) => { }) .ConfigureStatusResponce <SecondaryMarketOfferCancelError>(HttpStatusCode.Gone, (error, message) => throw new CancelSecondartMarketOfferException(offerId, error)) .ConfigureDefaultResponce((message) => throw new ServerErrorException(message)) .ExtractDataAsync(response); } }
public async Task <IActionResult> Login([FromBody] UserIM userData) { var userName = await _userManager.Users.Where(u => u.Email == userData.Email).FirstOrDefaultAsync(); var result = await _signInManager.PasswordSignInAsync(userName.UserName, userData.Password, false, false); if (result.Succeeded) { var user = await _userManager.FindByEmailAsync(userData.Email); AuthorizationToken token = GenerateJSONWebToken(user); return(Ok(token)); } return(Unauthorized()); }
public async Task CreateIssue(IssueInfo issueInfo, AuthorizationToken authToken) { await InterceptJiraExceptions(async() => { var jira = CreateRestClient(authToken.Token); var issueTypes = jira.GetIssueTypes(issueInfo.ProjectKey); var issueType = issueTypes.FirstOrDefault(x => x.Id == issueInfo.IssueTypeKey); if (issueType == null) { throw new ApplicationException("Invalid Jira Issue Type specified."); } var priorities = jira.GetIssuePriorities(); var priority = priorities.FirstOrDefault(x => x.Id == issueInfo.PriorityKey); if (priority == null) { throw new ApplicationException("Invalid Jira Priority specified."); } var jiraCustomFields = jira.GetCustomFields(); var issue = jira.CreateIssue(issueInfo.ProjectKey); issue.Type = issueType; issue.Priority = priority; issue.Summary = issueInfo.Summary; issue.Description = issueInfo.Description; issue.Assignee = issueInfo.Assignee; if (issueInfo.CustomFields != null) { var customFieldsCollection = issue.CustomFields.ForEdit(); foreach (var customField in issueInfo.CustomFields) { var jiraCustomField = jiraCustomFields.FirstOrDefault(x => x.Id == customField.Key); if (jiraCustomField == null) { throw new ApplicationException($"Invalid custom field {customField.Key}"); } customFieldsCollection.Add(jiraCustomField.Name, customField.Value); } } var token = await SaveIssue(jira, issue); issueInfo.Key = token; }); }
public static async Task <AuthorizationToken> RefreshAsync(AuthorizationToken token) { if (token is null) { throw new ArgumentNullException(nameof(token)); } if (string.IsNullOrEmpty(token.ClientSecret)) { throw new ArgumentException("Missing client secret.", nameof(token)); } if (token.RefreshTokenExpires.GetValueOrDefault(DateTime.UtcNow) <= DateTime.UtcNow) { throw new ArgumentException("Refresh token expired.", nameof(token)); } var form = new { client_assertion_type = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", client_assertion = token.ClientSecret, grant_type = "refresh_token", assertion = token.RefreshToken, redirect_uri = await GetCallbackUrl().ConfigureAwait(false) }; var response = await VisualStudioTokenUrl .WithHeader("Accept", "application/json") //.WithHeaders(new MediaTypeWithQualityHeaderValue("application/json")) .AllowAnyHttpStatus() .PostUrlEncodedAsync(form) .ConfigureAwait(false); if (response.IsSuccessStatusCode) { var json = await response.Content .ReadAsStringAsync() .ConfigureAwait(false); JsonConvert.PopulateObject(json, token); } else { throw new Exception(response.ReasonPhrase); } return(token); }
public NewUser GetMe() { AuthorizationToken AuthTok = _userService.AuthorizationTokens.Single( t => t.Uid == Request.Headers["Authorization"] ); User usr = _userService.Users.Find(AuthTok.UserUid); return(new NewUser { Email = usr.Email, Username = usr.Username, FirstName = usr.FirstName, LastName = usr.LastName }); }
public void SignOut(AuthorizationToken authorizationToken) { UserToken token; try { token = context.UserTokens.Single(p => p.Token == authorizationToken.Token); } catch (InvalidOperationException) { throw new SecurityTokenException("User is not signed in."); } context.Delete(token); context.Commit(); }
public async Task <List <UserInfo> > GetUsersAsync(string projectCode, AuthorizationToken token) { if (string.IsNullOrWhiteSpace(projectCode)) { throw new ArgumentException("Project code can't be empty", nameof(projectCode)); } if (token == null) { throw new ArgumentNullException(nameof(token)); } var response = await GetAsync($"user/assignable/search?project={projectCode}&maxResults={MaxResults}", token); var result = JsonConvert.DeserializeObject <List <UserInfo> >(response); return(result); }
public DataService GetDataService(AuthorizationToken authToken, IHubCommunicator hubCommunicator) { var curServiceContext = CreateServiceContext(authToken, hubCommunicator); //Modify required settings for the Service Context curServiceContext.IppConfiguration.BaseUrl.Qbo = "https://sandbox-quickbooks.api.intuit.com/"; curServiceContext.IppConfiguration.MinorVersion.Qbo = "4"; curServiceContext.IppConfiguration.Logger.RequestLog.EnableRequestResponseLogging = true; curServiceContext.IppConfiguration.Logger.CustomLogger = new TraceLogger(); curServiceContext.IppConfiguration.Message.Response.SerializationFormat = SerializationFormat.Json; var curDataService = new DataService(curServiceContext); curServiceContext.UseDataServices(); return(curDataService); }
private async Task <AuthorizationToken> RefreshTokenImpl(AuthorizationToken auth) { AuthorizationToken result; try { result = await RefreshToken(auth); } catch { throw new AuthorizationTokenExpiredOrInvalidException(); } await _hubCommunicator.RenewToken(Mapper.Map <AuthorizationTokenDTO>(result)); return(result); }
internal static IEnumerator InitializeToken(string email, string password) { if (email.Equals("*****@*****.**")) { isAdmin = true; } else { isAdmin = false; } Player player = FindObjectOfType <Player>(); if (string.IsNullOrEmpty(player.Token)) { UnityWebRequest httpClient = new UnityWebRequest(player.HttpServerAddress + "Token", "POST"); // application/x-www-form-urlencoded WWWForm dataToSend = new WWWForm(); dataToSend.AddField("grant_type", "password"); dataToSend.AddField("username", email); dataToSend.AddField("password", password); httpClient.uploadHandler = new UploadHandlerRaw(dataToSend.data); httpClient.downloadHandler = new DownloadHandlerBuffer(); httpClient.SetRequestHeader("Accept", "application/json"); httpClient.certificateHandler = new BypassCertificate(); yield return(httpClient.SendWebRequest()); if (httpClient.isNetworkError || httpClient.isHttpError) { var errorMessage = httpClient.downloadHandler.text; ErrorLoginSerializable error = JsonUtility.FromJson <ErrorLoginSerializable>(errorMessage); Register.MessageError(error.error_description); throw new Exception("Helper > InitToken: " + httpClient.error); } else { string jsonResponse = httpClient.downloadHandler.text; AuthorizationToken authToken = JsonUtility.FromJson <AuthorizationToken>(jsonResponse); player.Token = authToken.access_token; } httpClient.Dispose(); } }
/// <summary> /// Gets file shared link. If file not shared, shares it. /// </summary> /// <param name="authorizationTokenDO"></param> /// <param name="path">Path to file</param> /// <returns></returns> public string GetFileSharedUrl(AuthorizationToken authorizationToken, string path) { var client = new DropboxClient(authorizationToken.Token, CreateDropboxClientConfig(UserAgent)); // Trying to get file links var links = client.Sharing.ListSharedLinksAsync(path).Result.Links; if (links.Count > 0) { return(links[0].Url); } // If file is not shared already, we create a sharing ulr for this file. var createResult = client.Sharing.CreateSharedLinkWithSettingsAsync(path).Result; return(createResult.Url); }
/// <summary> /// Retrieves all user properties for a partial user object. /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <returns></returns> public async Task <bool> FetchFullAttributes(AuthorizationToken authToken) { if (this.IsPartialUser) { // Fetch a full user object and replace the partial data model with the full one User fullUser = await UserController.GetUserById(authToken, this.BaseId); this.CurrentObject = fullUser.CurrentObject; this.IsPartialUser = false; this.ReadOnly = true; return(true); } else { return(false); } }
/// <summary> /// Convenience method that returns a HardwareAsset by its unique HardwareAssetID /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="id">HardwareAssetID</param> /// <returns></returns> public static async Task <HardwareAsset> GetByHardwareAssetID(AuthorizationToken authToken, string id) { QueryCriteria criteria = BuildCriteria(new PropertyPathHelper(ClassConstants.HardwareAsset.Id, "HardwareAssetID"), id); List <HardwareAsset> assetList = await GetByCriteria(authToken, criteria); if (assetList == null) { return(null); } if (assetList.Count == 0) { return(null); } return(assetList[0]); }
public bool Equals(BackblazeB2AuthorizationSession other) { if (EqualsPreamble(other) == false) { return(false); } return (AbsoluteMinimumPartSize == other.AbsoluteMinimumPartSize && AccountID.Equals(other.AccountID, StringComparison.Ordinal) && APIURL.Equals(other.APIURL, StringComparison.Ordinal) && ApplicationKey.Equals(other.ApplicationKey, StringComparison.Ordinal) && AuthorizationToken.Equals(other.AuthorizationToken, StringComparison.Ordinal) && DownloadURL.Equals(other.DownloadURL, StringComparison.Ordinal) && RecommendedPartSize == other.RecommendedPartSize && SessionExpirationDate.Equals(other.SessionExpirationDate)); }
public Task <CommandMessage> Send(CommandMessage commandMessage) { Header authorizationContextHeader = commandMessage.HeaderCollection.GetHeader(CommandMessageHeaderNames.AuthorizationContext); Header routingKeyHeader = commandMessage.HeaderCollection.GetHeader(CommandMessageHeaderNames.RoutingKey); AuthorizationToken authorizationToken = _serializationService.DeserializeFromString <AuthorizationToken>(authorizationContextHeader.Value); bool isAuthorized = authorizationToken.Permissions.Any(p => p.RoutingKey == routingKeyHeader.Value && p.CommandName == commandMessage.CommandMessageBody.CommandName ); commandMessage.HeaderCollection.AddHeader(new Header(CommandMessageHeaderNames.IsAuthorized, isAuthorized.ToString())); if (!isAuthorized) { throw new Exception($"User {authorizationToken.User.Username} is not authorized to execute {commandMessage.CommandMessageBody.CommandName} on {routingKeyHeader.Value}."); } return(Task.FromResult(commandMessage)); }
/// <summary> /// Convenience method that returns an Incident by its ID /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="incidentID">ID of the Incident to retrieve</param> /// <returns>Incident</returns> public static async Task<Incident> GetIncidentByID(AuthorizationToken authToken, string incidentID) { QueryCriteriaExpression expression = new QueryCriteriaExpression(); expression.PropertyName = (new PropertyPathHelper(ClassConstants.Incident, "ID")).ToString(); expression.PropertyType = QueryCriteriaPropertyType.Property; expression.Operator = QueryCriteriaExpressionOperator.Equal; expression.Value = incidentID; QueryCriteria criteria = new QueryCriteria(TypeProjectionConstants.Incident); criteria.GroupingOperator = QueryCriteriaGroupingOperator.SimpleExpression; criteria.Expressions.Add(expression); List<Incident> incidentList = await IncidentController.GetIncidentsByCriteria(authToken, criteria); if (incidentList.Count == 0) return null; return incidentList[0]; }
/// <summary> /// Convenience method that returns a list of Purchase Orders with the specified order type /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="poTypeGuid">Purchase Order Type ID to search for</param> /// <returns></returns> public static async Task<List<PurchaseOrder>> GetByOrderType(AuthorizationToken authToken, Guid poTypeGuid) { QueryCriteriaExpression expression = new QueryCriteriaExpression { PropertyName = (new PropertyPathHelper(ClassConstants.PurchaseOrder.Id, "PurchaseOrderType")).ToString(), PropertyType = QueryCriteriaPropertyType.Property, Operator = QueryCriteriaExpressionOperator.Equal, Value = poTypeGuid.ToString("B") }; QueryCriteria criteria = new QueryCriteria(TypeProjectionConstants.PurchaseOrder.Id); criteria.GroupingOperator = QueryCriteriaGroupingOperator.SimpleExpression; criteria.Expressions.Add(expression); List<PurchaseOrder> purchaseOrderList = await PurchaseOrderController.GetByCriteria(authToken, criteria); if (purchaseOrderList.Count == 0) return null; return purchaseOrderList; }
/// <summary> /// Convenience method that gets a list of all Locations that are active /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <returns></returns> public static async Task<List<Location>> GetAll(AuthorizationToken authToken) { PropertyPathHelper pathHelper = new PropertyPathHelper(); pathHelper.PropertyName = "ObjectStatus"; pathHelper.ObjectClass = ClassConstants.GetClassIdByType<Location>(); QueryCriteriaExpression expr = new QueryCriteriaExpression { PropertyName = pathHelper.ToString(), PropertyType = QueryCriteriaPropertyType.Property, Operator = QueryCriteriaExpressionOperator.Equal, Value = EnumerationConstants.ConfigItem.BuiltinValues.ObjectStatus.Active.ToString("D") }; QueryCriteria criteria = new QueryCriteria(TypeProjectionConstants.Location.Id) { GroupingOperator = QueryCriteriaGroupingOperator.SimpleExpression }; criteria.Expressions.Add(expr); return await GetByCriteria(authToken, criteria); }
/// <summary> /// Returns a list of UserListItems, which contain an ID/Name pair /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="userFilter">Should we filter the query?</param> /// <param name="filterByAnalyst">Should we filter by analysts?</param> /// <param name="groupsOnly">Should we see groups only?</param> /// <param name="maxNumberOfResults">Maximum number of results in this query</param> /// <param name="sort">If true, this list will be sorted before returning it</param> /// <param name="insertNullItem">If true, a null item will be inserted as the first item</param> /// <returns></returns> public static async Task<List<User>> GetUserList(AuthorizationToken authToken, string userFilter = "", bool filterByAnalyst = false, bool groupsOnly = false, int maxNumberOfResults = 10, bool sort = true) { if (!authToken.IsValid) { throw new InvalidCredentialException("AuthorizationToken is not valid."); } string endpoint = USER_LIST_ENDPOINT + "?userFilter=" + userFilter + "&filterByAnalyst=" + filterByAnalyst + "&groupsOnly=" + groupsOnly + "&maxNumberOfResults=" + maxNumberOfResults; try { // Initialize the HTTP helper and get going PortalHttpHelper helper = new PortalHttpHelper(authToken); string result = await helper.GetAsync(endpoint); // Deserialize List<PartialUser> partialList = JsonConvert.DeserializeObject<List<PartialUser>>(result); if (sort) { partialList.Sort(new PartialUserComparer()); } // Convert PartialUsers to Users List<User> returnList = new List<User>(); foreach (PartialUser partialUser in partialList) { returnList.Add(new User(partialUser)); } return returnList; } catch (Exception) { throw; // Rethrow exceptions } }
/// <summary> /// Gets a list of Locations based on the supplied criteria /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="criteria">QueryCriteria to search for</param> /// <returns></returns> public static async Task<List<Location>> GetByCriteria(AuthorizationToken authToken, QueryCriteria criteria) { criteria.ProjectionID = TypeProjectionConstants.Location.Id; return await ConfigurationItemController.GetByCriteria<Location>(authToken, criteria); }
/// <summary> /// Creates a new blank Location /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="name">Name of the Location</param> /// <param name="displayName">DisplayName of the Location</param> /// <returns></returns> public static async Task<Location> Create(AuthorizationToken authToken, string name, string displayName) { return await TypeProjectionController.CreateBlankObject<Location>(authToken, name, displayName); }
/// <summary> /// Gets a list of all Locations that are active /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <returns></returns> public static async Task<List<Location>> GetAllLocations(AuthorizationToken authToken) { QueryCriteria criteria = new QueryCriteria(TypeProjectionConstants.Location); return await TypeProjectionController.GetProjectionByCriteria<Location>(authToken, ConfigurationItemController.ExcludeInactiveItems<Location>(criteria)); }
/// <summary> /// Retrieves all user properties for a partial user object. /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <returns></returns> public async Task<bool> FetchFullAttributes(AuthorizationToken authToken) { if (this.IsPartialUser) { // Fetch a full user object and replace the partial data model with the full one User fullUser = await UserController.GetUserById(authToken, this.BaseId); this.CurrentObject = fullUser.CurrentObject; this.IsPartialUser = false; this.ReadOnly = true; return true; } else return false; }
/// <summary> /// Refreshes this PurchaseOrder from the portal. This will reset any changes made to the object. /// This method must be called before accessing properties of children in relationship collections in order to populate all properties. /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <returns></returns> public override async Task<bool> Refresh(AuthorizationToken authToken) { return await this.RefreshType<PurchaseOrder>(authToken); }
/// <summary> /// Convenience method that returns a list of HardwareAssets with matching serial numbers /// </summary> /// <param name="authToken"></param> /// <param name="serialNumber"></param> /// <returns></returns> public static async Task<List<HardwareAsset>> GetBySerialNumber(AuthorizationToken authToken, string serialNumber) { QueryCriteria criteria = BuildCriteria(new PropertyPathHelper(ClassConstants.HardwareAsset.Id, "SerialNumber"), serialNumber); return await GetByCriteria(authToken, criteria); }
/// <summary> /// Convenience method that returns a list of Purchase Orders with the specified order type /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="purchaseOrderType">Purchase Order Type to search for</param> /// <returns></returns> public static async Task<List<PurchaseOrder>> GetPurchaseOrdersByType(AuthorizationToken authToken, Enumeration purchaseOrderType) { return await GetByOrderType(authToken, purchaseOrderType.Id); }
/// <summary> /// Convenience method that returns a list of HardwareAssets with matching asset tags /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="assetTag">Asset's unique asset tag</param> /// <returns>HardwareAsset</returns> public static async Task<List<HardwareAsset>> GetByAssetTag(AuthorizationToken authToken, string assetTag) { QueryCriteria criteria = BuildCriteria(new PropertyPathHelper(ClassConstants.HardwareAsset.Id, "AssetTag"), assetTag); return await GetByCriteria(authToken, criteria); }
/// <summary> /// Retrieves a list of HardwareAssets that match the given criteria /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="criteria">QueryCriteria to search for</param> /// <param name="includeInactiveItems">If true, override the criteria to exclude inactive items (this will set the grouping operator to AND!)</param> /// <returns></returns> public static async Task<List<HardwareAsset>> GetByCriteria(AuthorizationToken authToken, QueryCriteria criteria, bool includeInactiveItems = false) { criteria.ProjectionID = TypeProjectionConstants.HardwareAsset.Id; return await ConfigurationItemController.GetByCriteria<HardwareAsset>(authToken, criteria); }
/// <summary> /// Marks a Location for deletion /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="item">Location to delete</param> /// <param name="markPending">If true, mark the object as Pending Deletion instead of Deleted.</param> /// <returns></returns> public static async Task<bool> Delete(AuthorizationToken authToken, Location item, bool markPending = true) { return await ConfigurationItemController.DeleteObject(authToken, item, markPending); }
/// <summary> /// Refreshes this Location from the portal. This will reset any changes made to the object. /// This method must be called before accessing properties of children in relationship collections in order to populate all properties. /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <returns></returns> public override async Task<bool> Refresh(AuthorizationToken authToken) { return await this.RefreshType<Location>(authToken); }
/// <summary> /// Convenience method that returns a list of HardwareAssets by asset type. Depending on the size of the asset database, /// this might be a VERY large list, and therefore very time consuming! /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="assetType">HardwareAssetType</param> /// <returns></returns> public static async Task<List<HardwareAsset>> GetHardwareAssetsByType(AuthorizationToken authToken, Enumeration assetType) { QueryCriteria criteria = BuildCriteria(new PropertyPathHelper(ClassConstants.HardwareAsset.Id, "HardwareAssetType"), assetType.Id.ToString()); return await GetByCriteria(authToken, criteria); }
/// <summary> /// Gets a list of Purchase Orders based on the supplied criteria /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="criteria">QueryCriteria to search for</param> /// <returns></returns> public static async Task<List<PurchaseOrder>> GetPurchaseOrdersByCriteria(AuthorizationToken authToken, QueryCriteria criteria) { criteria.ProjectionID = TypeProjectionConstants.PurchaseOrder; return await ConfigurationItemController.GetConfigurationItemsByCriteria<PurchaseOrder>(authToken, criteria); }
/// <summary> /// Gets a list of Incidents based on the supplied criteria /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="criteria">QueryCriteria to search for</param> /// <returns></returns> public static async Task<List<Incident>> GetIncidentsByCriteria(AuthorizationToken authToken, QueryCriteria criteria) { criteria.ProjectionID = TypeProjectionConstants.Incident; return await TypeProjectionController.GetProjectionByCriteria<Incident>(authToken, criteria); }
/// <summary> /// Refreshes this HardwareAsset from the portal. This will reset any changes made to the object. /// This method must be called before accessing properties of children in relationship collections in order to populate all properties. /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <returns></returns> public override async Task<bool> Refresh(AuthorizationToken authToken) { return await this.RefreshType<HardwareAsset>(authToken); }
/// <summary> /// Creates a new Incident based on the supplied Template ID /// </summary> /// <param name="authToken">User AuthorizationToken</param> /// <param name="templateId">TemplateID to use</param> /// <returns></returns> public static async Task<Incident> Create(AuthorizationToken authToken, Guid templateId) { return await Create(authToken, templateId, authToken.User.Id); }
/// <summary> /// Creates a new Incident based on the supplied Template ID /// </summary> /// <param name="authToken">AuthorizationToken to use</param> /// <param name="templateId">TemplateID to use</param> /// <param name="userId">ID of the user creating the Incident</param> /// <returns></returns> public static async Task<Incident> CreateNewIncident(AuthorizationToken authToken, Guid templateId, Guid userId) { TypeProjection projection = await TypeProjectionController.CreateProjectionByTemplate<Incident>(authToken, templateId, userId); return (Incident)projection; }