Пример #1
0
        public async Task <IEnumerable <CustomerUser> > Get(string CustomerId)
        {
            CustomerId.AssertNotEmpty(nameof(CustomerId));

            CustomerPrincipal principal;
            CustomerUser      user;
            Guid              correlationId;
            IPartner          operations;
            IExplorerProvider provider;

            correlationId = Guid.NewGuid();

            operations = await ApplicationDomain.GetUserOperationsAsync(correlationId).ConfigureAwait(false);


            // get customer users collection
            //var customerUsers = ApplicationDomain.userCenterClient.Customers.ById(CustomerId).Users.Get();
            principal = new CustomerPrincipal(ClaimsPrincipal.Current);

            if (
                //principal.CustomerId.Equals(provider.Configuration.PartnerCenterAccountId, StringComparison.InvariantCultureIgnoreCase) ||
                principal.CustomerId.Equals(CustomerId, StringComparison.InvariantCultureIgnoreCase))
            {
                //var customer = await ApplicationDomain.userCenterClient.Customers.ById(CustomerId).Users.GetAsync().ConfigureAwait(false);
                var customer = await operations.Customers.ById(CustomerId).Users.GetAsync().ConfigureAwait(false);
            }
            return(null);
        }
        /// <summary>
        /// Stores an instance of <see cref="CustomerPrincipal"/> in the private bot data associated with the user.
        /// </summary>
        /// <param name="context">The context for the bot.</param>
        /// <param name="principal">An instance of <see cref="CustomerPrincipal"/> associated with the authenticated user.</param>
        public static void StoreCustomerPrincipal(this IBotContext context, CustomerPrincipal principal)
        {
            context.AssertNotNull(nameof(context));
            principal.AssertNotNull(nameof(principal));

            context.PrivateConversationData.SetValue(BotConstants.CustomerPrincipalKey, principal);
        }
Пример #3
0
        /// <summary>
        /// Ensures the given <see cref="CustomerPrincipal"/> has a valid customer context.
        /// </summary>
        /// <param name="principalToValidate">An instance of <see cref="CustomerPrincipal"/> to validate.</param>
        /// <param name="message">The message to report in the exception.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="principalToValidate"/> is null.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// <paramref name="principalToValidate"/> does not contain a valid customer identifier.
        /// </exception>
        public static void AssertValidCustomerContext(this CustomerPrincipal principalToValidate, string message)
        {
            principalToValidate.AssertNotNull(nameof(principalToValidate));

            if (string.IsNullOrEmpty(principalToValidate.Operation.CustomerId))
            {
                throw new InvalidOperationException(message);
            }
        }
        /// <summary>
        /// Gets the specified subscription.
        /// </summary>
        /// <param name="principal">Security principal for the calling user.</param>
        /// <returns>An instance of <see cref="Subscription"/> that represents the specified subscription.</returns>
        /// <exception cref="ArgumentException">
        /// The operation context from <paramref name="principal"/> does not contain a valid customer identifier.
        /// or
        /// The operation context from <paramref name="principal"/> does not contain a valid subscription identifier.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="principal"/> is null.
        /// </exception>
        public async Task <Subscription> GetSubscriptionAsync(CustomerPrincipal principal)
        {
            DateTime startTime;
            Dictionary <string, double> eventMetrics;
            Dictionary <string, string> eventProperties;
            Guid         correlationId;
            IPartner     operations;
            Subscription subscription = null;

            principal.AssertNotNull(nameof(principal));
            principal.Operation.CustomerId.AssertNotEmpty(nameof(principal.Operation.CustomerId));
            principal.Operation.SubscriptionId.AssertNotEmpty(nameof(principal.Operation.SubscriptionId));

            try
            {
                startTime     = DateTime.Now;
                correlationId = Guid.NewGuid();
                operations    = await GetAppOperationsAsync(correlationId).ConfigureAwait(false);

                try
                {
                    subscription = await operations.Customers.ById(principal.Operation.CustomerId)
                                   .Subscriptions.ById(principal.Operation.SubscriptionId).GetAsync().ConfigureAwait(false);
                }
                catch (PartnerException ex)
                {
                    if (ex.ErrorCategory != PartnerErrorCategory.NotFound)
                    {
                        throw;
                    }
                }

                // Track the event measurements for analysis.
                eventMetrics = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds }
                };

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "CustomerId", principal.CustomerId },
                    { "ObjectId", principal.ObjectId },
                    { "ParternCenterCorrelationId", correlationId.ToString() }
                };

                provider.Telemetry.TrackEvent("GetSubscriptionAsync", eventProperties, eventMetrics);

                return(subscription);
            }
            finally
            {
                eventMetrics    = null;
                eventProperties = null;
                operations      = null;
            }
        }
        /// <summary>
        /// Gets the available subscriptions.
        /// </summary>
        /// <param name="principal">Security principal for the calling user.</param>
        /// <returns>A list of available subscriptions.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="principal"/> is null.
        /// </exception>
        public async Task <List <Subscription> > GetSubscriptionsAsync(CustomerPrincipal principal)
        {
            DateTime startTime;
            Dictionary <string, double> eventMetrics;
            Dictionary <string, string> eventProperties;
            Guid     correlationId;
            IPartner operations;
            ResourceCollection <Subscription> subscriptions;

            principal.AssertNotNull(nameof(principal));

            try
            {
                startTime     = DateTime.Now;
                correlationId = Guid.NewGuid();
                operations    = await GetAppOperationsAsync(correlationId).ConfigureAwait(false);

                if (principal.CustomerId.Equals(provider.Configuration.PartnerCenterAccountId))
                {
                    principal.AssertValidCustomerContext(Resources.InvalidCustomerContextException);
                    subscriptions = await operations.Customers
                                    .ById(principal.Operation.CustomerId).Subscriptions.GetAsync().ConfigureAwait(false);
                }
                else
                {
                    subscriptions = await operations.Customers.ById(principal.CustomerId).Subscriptions.GetAsync().ConfigureAwait(false);
                }

                // Track the event measurements for analysis.
                eventMetrics = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds },
                    { "NumberOfSubscriptions", subscriptions.TotalCount }
                };

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "CustomerId", principal.CustomerId },
                    { "Name", principal.Name },
                    { "ParternCenterCorrelationId", correlationId.ToString() }
                };

                provider.Telemetry.TrackEvent("GetCustomersAsync", eventProperties, eventMetrics);

                return(new List <Subscription>(subscriptions.Items));
            }
            finally
            {
                eventMetrics    = null;
                eventProperties = null;
                operations      = null;
                principal       = null;
                subscriptions   = null;
            }
        }
Пример #6
0
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            var             cp  = new CustomerPrincipal <UserLoginVM>();

            if (cp.Identity != null)
            {
                app.Context.User = cp;
            }
        }
        /// <summary>
        /// Gets the specified customer.
        /// </summary>
        /// <param name="principal">Security principal for the calling user.</param>
        /// <param name="customerId">Identifier for the customer.</param>
        /// <returns>An instance of <see cref="Customer"/> that represents the specified customer.</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="customerId"/> is empty or null.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="principal"/> is null.
        /// </exception>
        public async Task <Customer> GetCustomerAsync(CustomerPrincipal principal, string customerId)
        {
            Customer customer;
            DateTime startTime;
            Dictionary <string, double> eventMetrics;
            Dictionary <string, string> eventProperties;
            Guid     correlationId;
            IPartner operations;

            customerId.AssertNotEmpty(nameof(customerId));
            principal.AssertNotNull(nameof(principal));

            try
            {
                startTime     = DateTime.Now;
                correlationId = Guid.NewGuid();
                operations    = await GetAppOperationsAsync(correlationId).ConfigureAwait(false);

                if (principal.CustomerId.Equals(provider.Configuration.PartnerCenterAccountId))
                {
                    customer = await operations.Customers.ById(customerId).GetAsync().ConfigureAwait(false);
                }
                else
                {
                    customer = await operations.Customers.ById(principal.CustomerId).GetAsync().ConfigureAwait(false);
                }

                // Track the event measurements for analysis.
                eventMetrics = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds }
                };

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "CustomerId", principal.CustomerId },
                    { "Name", principal.Name },
                    { "ParternCenterCorrelationId", correlationId.ToString() }
                };

                provider.Telemetry.TrackEvent(nameof(GetCustomerAsync), eventProperties, eventMetrics);

                return(customer);
            }
            finally
            {
                eventMetrics    = null;
                eventProperties = null;
                operations      = null;
                principal       = null;
            }
        }
        /// <summary>
        /// Gets the customer principal from the private bot data associated with the user.
        /// </summary>
        /// <param name="context">The context for the bot.</param>
        /// <param name="provider">Provides access to core application services.</param>
        /// <returns>An instance of <see cref="CustomerPrincipal"/> that represents the authenticated user.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="context"/> is null.
        /// or
        /// <paramref name="provider"/> is null.
        /// </exception>
        public static async Task <CustomerPrincipal> GetCustomerPrincipalAsync(this IBotContext context, IBotProvider provider)
        {
            CustomerPrincipal    principal = null;
            AuthenticationResult authResult;

            context.AssertNotNull(nameof(context));
            provider.AssertNotNull(nameof(provider));

            try
            {
                if (context.PrivateConversationData.TryGetValue(BotConstants.CustomerPrincipalKey, out principal))
                {
                    if (principal.ExpiresOn < DateTime.UtcNow)
                    {
                        authResult = await provider.AccessToken.AcquireTokenSilentAsync(
                            $"{provider.Configuration.ActiveDirectoryEndpoint}/{principal.CustomerId}",
                            provider.Configuration.GraphEndpoint,
                            provider.Configuration.ApplicationId,
                            new UserIdentifier(principal.ObjectId, UserIdentifierType.UniqueId)).ConfigureAwait(false);

                        principal.AccessToken = authResult.AccessToken;
                        principal.ExpiresOn   = authResult.ExpiresOn;

                        context.StoreCustomerPrincipal(principal);
                    }

                    return(principal);
                }

                return(null);
            }
            finally
            {
                authResult = null;
            }
        }
        public async Task <HttpResponseMessage> OAuthCallbackAsync([FromUri] string code, [FromUri] string state, CancellationToken cancellationToken)
        {
            Activity message;
            Address  address;
            ConversationReference conversationReference;
            CustomerPrincipal     principal = null;
            DateTime startTime;
            Dictionary <string, double> eventMeasurements;
            Dictionary <string, string> eventProperties;
            Dictionary <string, string> stateData;
            IBotData            botData;
            HttpResponseMessage response;

            code.AssertNotEmpty(nameof(code));
            state.AssertNotEmpty(nameof(state));

            try
            {
                startTime = DateTime.Now;
                stateData = UrlToken.Decode <Dictionary <string, string> >(state);

                address = new Address(
                    stateData[BotConstants.BotIdKey],
                    stateData[BotConstants.ChannelIdKey],
                    stateData[BotConstants.UserIdKey],
                    stateData[BotConstants.ConversationIdKey],
                    stateData[BotConstants.ServiceUrlKey]);

                conversationReference = address.ToConversationReference();

                message = conversationReference.GetPostToBotMessage();

                using (ILifetimeScope scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
                {
                    botData = scope.Resolve <IBotData>();
                    await botData.LoadAsync(cancellationToken).ConfigureAwait(false);

                    if (!Validate(botData, stateData))
                    {
                        return(Request.CreateErrorResponse(
                                   HttpStatusCode.BadRequest,
                                   new InvalidOperationException(Resources.InvalidAuthenticationException)));
                    }

                    principal = await GetCustomerPrincipalAsync(
                        new Uri($"{Request.RequestUri.Scheme}://{Request.RequestUri.Host}:{Request.RequestUri.Port}/{BotConstants.CallbackPath}"),
                        code).ConfigureAwait(false);

                    if (principal == null)
                    {
                        message.Text = Resources.NoRelationshipException;
                        await Conversation.ResumeAsync(conversationReference, message, cancellationToken).ConfigureAwait(false);

                        return(Request.CreateErrorResponse(
                                   HttpStatusCode.BadRequest,
                                   new InvalidOperationException(Resources.NoRelationshipException)));
                    }

                    botData.PrivateConversationData.SetValue(BotConstants.CustomerPrincipalKey, principal);

                    await botData.FlushAsync(cancellationToken).ConfigureAwait(false);

                    await Conversation.ResumeAsync(conversationReference, message, cancellationToken).ConfigureAwait(false);

                    // Capture the request for the customer summary for analysis.
                    eventProperties = new Dictionary <string, string>
                    {
                        { "CustomerId", principal.CustomerId },
                        { "Name", principal.Name },
                        { "ObjectId", principal.ObjectId }
                    };

                    // Track the event measurements for analysis.
                    eventMeasurements = new Dictionary <string, double>
                    {
                        { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds },
                        { "NumberOfIntents", principal.AvailableIntents.Count },
                        { "NumberOfRoles", principal.Roles.Count }
                    };

                    Provider.Telemetry.TrackEvent("api/OAuthCallback", eventProperties, eventMeasurements);

                    response         = Request.CreateResponse(HttpStatusCode.OK);
                    response.Content = new StringContent(Resources.SuccessfulAuthentication);
                }
            }
            catch (Exception ex)
            {
                Provider.Telemetry.TrackException(ex);
                response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
            finally
            {
                address = null;
                botData = null;
                conversationReference = null;
                eventMeasurements     = null;
                eventProperties       = null;
                message   = null;
                principal = null;
            }

            return(response);
        }
        /// <summary>
        /// Obtain an instance of <see cref="CustomerPrincipal"/> that represents the authenticated user.
        /// </summary>
        /// <param name="redirectUri">Address to return to upon receiving a response from the authority.</param>
        /// <param name="code">The authorization code that was requested.</param>
        /// <returns>An instance of <see cref="CustomerPrincipal"/> that represents the authenticated user.</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="code"/> is empty or null.
        /// </exception>
        private async Task <CustomerPrincipal> GetCustomerPrincipalAsync(Uri redirectUri, string code)
        {
            AuthenticationResult authResult;
            CustomerPrincipal    principal;
            IGraphClient         client;
            List <RoleModel>     roles;

            code.AssertNotEmpty(nameof(code));

            try
            {
                authResult = await Provider.AccessToken.AcquireTokenByAuthorizationCodeAsync(
                    $"{Provider.Configuration.ActiveDirectoryEndpoint}/{BotConstants.AuthorityEndpoint}",
                    code,
                    new ApplicationCredential
                {
                    ApplicationId     = Provider.Configuration.ApplicationId,
                    ApplicationSecret = Provider.Configuration.ApplicationSecret,
                    UseCache          = true
                },
                    redirectUri,
                    Provider.Configuration.GraphEndpoint).ConfigureAwait(false);

                client = new GraphClient(Provider, authResult.TenantId);

                roles = await client.GetDirectoryRolesAsync(authResult.UserInfo.UniqueId).ConfigureAwait(false);

                principal = new CustomerPrincipal
                {
                    AccessToken      = authResult.AccessToken,
                    AvailableIntents = (from intent in Provider.Intent.Intents
                                        let roleList = Permissions.GetRoles(intent.Value.Permissions)
                                                       from r in roleList
                                                       where roles.SingleOrDefault(x => x.DisplayName.Equals(r)) != null
                                                       select intent).Distinct().ToDictionary(intent => intent.Key, intent => intent.Value),
                    CustomerId = authResult.TenantId,
                    ExpiresOn  = authResult.ExpiresOn,
                    Name       = authResult.UserInfo.GivenName,
                    ObjectId   = authResult.UserInfo.UniqueId,
                    Roles      = roles
                };

                if (!Provider.Configuration.ApplicationTenantId.Equals(
                        authResult.TenantId,
                        StringComparison.CurrentCultureIgnoreCase))
                {
                    await Provider.PartnerOperations.GetCustomerAsync(principal, authResult.TenantId).ConfigureAwait(false);
                }

                return(principal);
            }
            catch (PartnerException ex)
            {
                if (ex.ErrorCategory != PartnerErrorCategory.NotFound)
                {
                    throw;
                }

                return(null);
            }
            finally
            {
                authResult = null;
                client     = null;
                roles      = null;
            }
        }
        /// <summary>
        /// Gets the available customers.
        /// </summary>
        /// <param name="principal">Security principal for the calling user.</param>
        /// <returns>A list of available customers.</returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="principal"/> is null.
        /// </exception>
        public async Task <List <Customer> > GetCustomersAsync(CustomerPrincipal principal)
        {
            Customer customer;
            DateTime startTime;
            Dictionary <string, double> eventMetrics;
            Dictionary <string, string> eventProperties;
            Guid     correlationId;
            IPartner operations;
            IResourceCollectionEnumerator <SeekBasedResourceCollection <Customer> > customersEnumerator;
            List <Customer> customers;
            SeekBasedResourceCollection <Customer> seekCustomers;

            principal.AssertNotNull(nameof(principal));

            try
            {
                startTime     = DateTime.Now;
                correlationId = Guid.NewGuid();
                operations    = await GetAppOperationsAsync(correlationId).ConfigureAwait(false);

                customers = new List <Customer>();

                if (principal.CustomerId.Equals(provider.Configuration.PartnerCenterAccountId))
                {
                    seekCustomers = await operations.Customers.GetAsync().ConfigureAwait(false);

                    customersEnumerator = operations.Enumerators.Customers.Create(seekCustomers);

                    while (customersEnumerator.HasValue)
                    {
                        customers.AddRange(customersEnumerator.Current.Items);
                        await customersEnumerator.NextAsync().ConfigureAwait(false);
                    }
                }
                else
                {
                    customer = await operations.Customers.ById(principal.CustomerId).GetAsync().ConfigureAwait(false);

                    customers.Add(customer);
                }

                // Track the event measurements for analysis.
                eventMetrics = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds },
                    { "NumberOfCustomers", customers.Count }
                };

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "CustomerId", principal.CustomerId },
                    { "Name", principal.Name },
                    { "ParternCenterCorrelationId", correlationId.ToString() }
                };

                provider.Telemetry.TrackEvent(nameof(GetCustomersAsync), eventProperties, eventMetrics);

                return(customers);
            }
            finally
            {
                customersEnumerator = null;
                eventMetrics        = null;
                eventProperties     = null;
                operations          = null;
                principal           = null;
                seekCustomers       = null;
            }
        }
 /// <summary>
 /// Gets the customer specified in the operation context.
 /// </summary>
 /// <param name="principal">Security principal for the calling user.</param>
 /// <returns>An instance of <see cref="Customer"/> that represents the specified customer.</returns>
 public async Task <Customer> GetCustomerAsync(CustomerPrincipal principal)
 {
     return(await GetCustomerAsync(principal, principal.Operation.CustomerId).ConfigureAwait(false));
 }