Exemplo n.º 1
0
 public void Post([FromBody] delSub subscription)
 {
     if (subscription != null)
     {
         Subscription sub = new Subscription
         {
             ID       = subscription.UserID,
             Customer = new Customer
             {
                 Id = subscription.CustomerID
             },
             Notification = subscription.Notification
         };
         subscriptionMediator.CreateSubscription(sub);
     }
 }
Exemplo n.º 2
0
        public IActionResult Subscribe(Subscription subscription)
        {
            var subs = subscriptionService.GetSubscriptions().FirstOrDefault(s => s.Email == subscription.Email);

            if (subs == null)

            {
                subscription.CreatedBy        = User.Identity.Name ?? "username";
                subscription.UpdateBy         = User.Identity.Name ?? "username";
                subscription.SubscriptionDate = DateTime.Now;
                subscription.ConfirmationCode = Guid.NewGuid().ToString();

                subscriptionService.CreateSubscription(subscription);
                subscriptionService.SaveSubscription();
            }
            CategoriesLayout();
            return(RedirectToAction("Index"));
        }
Exemplo n.º 3
0
        public HttpResponseMessage SaveLease([FromBody] LeaseViewModel leaseModel)
        {
            HttpResponseMessage result;

            try
            {
                if (!ModelState.IsValid)
                {
                    result = new HttpResponseMessage(HttpStatusCode.BadRequest);
                    return(result);
                }

                var leaseData = _mapper.Map <LeaseModel>(leaseModel);
                var output    = _subscriptionService.CreateSubscription(leaseData);
                result = output ? new HttpResponseMessage(HttpStatusCode.OK) : new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
            }
            catch (Exception ex)
            {
                //Log exception details,stack trace
                result = new HttpResponseMessage(HttpStatusCode.InternalServerError);
            }

            return(result);
        }
Exemplo n.º 4
0
        public TopicSubscriptionsModule(ISubscriptionService subcriptionService)
        {
            _subscriptionService = subcriptionService;

            //Subscribe to topic
            Post("Subscriptions/{accountId}/Subscribe/{topicId}", async(args, ct) =>
            {
                var accountId     = args.accountId;
                var topicId       = args.topicId;
                var sessionCookie = Request.Headers.Cookie.FirstOrDefault(c => c.Name == _sessionTokenCookieName);
                var sessionToken  = sessionCookie == null ? null : sessionCookie.Value;
                ActionResult <Subscription> result = await _subscriptionService.CreateSubscription(accountId, topicId, sessionToken);
                if (result.statusCode != (System.Net.HttpStatusCode)HttpStatusCode.Created)
                {
                    return(result.statusCode);
                }
                var subscription      = result.resposeObject;
                var confirmationToken = subscription.ConfirmationToken;
                var subId             = subscription.Id;
                var links             = new List <HyperMedia> {
                    new HyperMedia {
                        Href = this.Request.Url,
                        Rel  = "self"
                    },
                    new HyperMedia {
                        Href = $"{this.Request.Url.SiteBase}/Subscriptions/{accountId}/Confirm/{confirmationToken}",
                        Rel  = "confirm"
                    },
                    new HyperMedia {
                        Href = $"{this.Request.Url.SiteBase}/Subscriptions/{accountId}/Subscription/{subId}",
                        Rel  = "delete"
                    }
                };
                var response = Response.AsJson(new { ConfirmationToken = confirmationToken, links = links });
                if (!string.IsNullOrWhiteSpace(result.sessionToken))
                {
                    await response.WithCookie(_sessionTokenCookieName, result.sessionToken);
                }
                return(response);
            });

            //Confirm topic subscription
            Put("Subscriptions/{accountId}/Confirm/{confirmationToken}", async(args, ct) =>
            {
                var confirmationToken = args.confirmationToken;
                var accountId         = args.accountId;
                var sessionCookie     = Request.Headers.Cookie.FirstOrDefault(c => c.Name == _sessionTokenCookieName);
                var sessionToken      = sessionCookie == null ? null : sessionCookie.Value;
                ActionResult <Subscription> result = await _subscriptionService.ConfirmSubscription(confirmationToken, accountId, sessionToken);
                if (result.statusCode != (System.Net.HttpStatusCode)HttpStatusCode.OK)
                {
                    //If status is Precondition failed then there is a concurrency violation.
                    if (result.statusCode == (System.Net.HttpStatusCode)HttpStatusCode.PreconditionFailed)
                    {
                        return("There is an update conflit on this subscription. Please refresh the status of the subscription and try again");
                    }
                    return(result.statusCode);
                }
                var subscription = result.resposeObject;
                var subId        = subscription.Id;
                var links        = new List <HyperMedia> {
                    new HyperMedia {
                        Href = this.Request.Url,
                        Rel  = "self"
                    },
                    new HyperMedia {
                        Href = $"{this.Request.Url.SiteBase}/Subscriptions/{accountId}/Subscription/{subId}",
                        Rel  = "delete"
                    }
                };
                var response = Response.AsJson(links);
                if (!string.IsNullOrWhiteSpace(result.sessionToken))
                {
                    await response.WithCookie(_sessionTokenCookieName, result.sessionToken);
                }
                return(Response.AsJson(links));
            });

            //Delete topic
            Delete("Subscriptions/{accountId}/Subscription/{subscriptionId}", async args => {
                var accountId = args.accountId;
                var subId     = args.subscriptionId;
                var result    = await _subscriptionService.DeleteSubscription(subId, accountId);
                return(result);
            });
        }
 public async Task <ActionResult <SubscriptionDto> > CreateSubscription(SubscriptionDto pSubscriptionDto)
 {
     _SubscriptionService.CreateSubscription(pSubscriptionDto);
     return(Ok());
 }
Exemplo n.º 6
0
        public IActionResult InviteSubmission([FromForm] SubscriptionFormData subscriptionFormData)
        {
            //TODO: Move to service or helper?
            /** Process Plans **/
            //Stop if no plans to subscribe.
            if (subscriptionFormData.Plans == null || subscriptionFormData.Plans.Count <= 0)
            {
                Response.StatusCode = 400;
                var errMessage = "Submission had no plans attached. No transaction or subscription occured. ";
                ViewData["ErrorTitle"]       = "There's a problem with your request";
                ViewData["ErrorDescription"] = errMessage;
                _logger.LogInformation(errMessage);
                return(View("InvitationError"));
            }
            var plans = new List <SubscriptionItem>();

            foreach (var planData in subscriptionFormData.Plans)
            {
                plans.Add(
                    new SubscriptionItem
                {
                    PlanId   = planData.PlanId,
                    Quantity = planData.Quantity
                }
                    );
            }
            Customer customer;

            /** Create Customer. **/
            if (subscriptionFormData.Email == null)
            {
                var errMessage = "New subscription will require a valid client email. No transaction or subscription occured. ";
                Response.StatusCode          = 400;
                ViewData["ErrorTitle"]       = "There's a problem with your request";
                ViewData["ErrorDescription"] = errMessage;
                _logger.LogInformation(errMessage);
                return(View("InvitationError"));
            }
            if (subscriptionFormData.CardToken == null)
            {
                var errMessage = "Subscription requires a valid card token. No transaction or subscription occured. ";
                Response.StatusCode          = 400;
                ViewData["ErrorTitle"]       = "There's a problem with your request";
                ViewData["ErrorDescription"] = errMessage;
                _logger.LogInformation(errMessage);
                return(View("InvitationError"));
            }
            try {
                var customerCreate = new Customer
                {
                    Email         = subscriptionFormData.Email,
                    DefaultSource = subscriptionFormData.CardToken
                };
                if (subscriptionFormData.BusinessName != null)
                {
                    customerCreate.BusinessName = subscriptionFormData.BusinessName;
                }
                if (subscriptionFormData.Name != null)
                {
                    customerCreate.Name = subscriptionFormData.Name;
                }
                if (subscriptionFormData.Abn != null)
                {
                    customerCreate.Abn = subscriptionFormData.Abn;
                }
                customer = _customerService.CreateCustomer(customerCreate);
            }
            catch (StripeException se)
            {
                _logger.LogInformation("Stripe Error: " + se.Message);
                if (se.StripeError.DeclineCode != null)
                {
                    ViewData["ErrorTitle"]       = "There was a problem with your card.";
                    ViewData["ErrorDescription"] = $"{se.Message} Your transaction did not go through. Please check with your card provider and try again later.";
                    return(View("InvitationError"));
                }
                else
                {
                    ViewData["ErrorTitle"] = "There's a problem with your payment request";
                }
                switch (se.StripeError.Code)
                {
                case "token_already_used":
                    ViewData["ErrorDescription"] = "It seems that the card that was used for this transaction has already been used and it's likely that your payment has gone through. " +
                                                   "It is likely that you tried to refresh this page after your payment has been made. If you have any problems, please contact Data Estate.";
                    break;

                default:
                    ViewData["ErrorDescription"] = se.Message;
                    break;
                }

                return(View("InvitationError"));
            }
            catch (Exception e)
            {
                _logger.LogInformation($"Exception: {e.Message}, Source:{e.Source}, StackTrace: {e.StackTrace}");
                ViewData["ErrorTitle"]       = "There's a problem with your request";
                ViewData["ErrorDescription"] = e.Message;
                return(View("InvitationError"));
            }
            /** Create subscription. **/
            if (customer == null)
            {
                Response.StatusCode          = 400;
                ViewData["ErrorTitle"]       = "There's a problem with your request";
                ViewData["ErrorDescription"] = "Client creation failed, and therefore was not able to proceed with subscription. No transaction or subscription occured. ";
                _logger.LogInformation("Request had no customer information");
                return(View("InvitationError"));
            }
            var subscriptionCreate = new Subscription
            {
                CustomerId = customer.Id,
                Items      = plans,
                Tax        = subscriptionFormData.TaxPercent == null ? 10M : (decimal)subscriptionFormData.TaxPercent
            };

            var subscription = _subscriptionService.CreateSubscription(subscriptionCreate);

            _logger.LogInformation($"Subscription success. Customer ID: {customer.Id}, subscription ID: {subscription.Id}");
            return(View("InvitationSubmitted", subscription));
        }
        // GET api/<controller>/5
        public async Task <HttpResponseMessage> Get(string id)
        {
            HttpResponseMessage result = new HttpResponseMessage();

            List <KeyValuePair <string, string> > queryString = Request.GetQueryNameValuePairs().ToList();
            string objectId  = queryString.FirstOrDefault(q => q.Key == "objectId").Value;
            string email     = queryString.FirstOrDefault(q => q.Key == "email").Value;
            string firstName = queryString.FirstOrDefault(q => q.Key == "firstName").Value;
            string lastName  = queryString.FirstOrDefault(q => q.Key == "lastName").Value;

            if (string.IsNullOrEmpty(id) ||
                string.IsNullOrEmpty(objectId) ||
                string.IsNullOrEmpty(email) ||
                string.IsNullOrEmpty(firstName) ||
                string.IsNullOrEmpty(lastName))
            {
                result.StatusCode = HttpStatusCode.BadRequest;
                result.Content    = new StringContent("Please pass an id, objectId, email, firstName, and lastName on the querystring");
            }
            else
            {
                string partitionKey = id.Substring(0, 1).ToLower();
                OrganizationSubscription subscription = await _registrationService.GetOrganizationSubscription(partitionKey, id);

                if (subscription == null)
                {
                    // Create Azure AD Application Registration for the Organization
                    Guid        uniqueId    = Guid.NewGuid();
                    Application application = new Application();
                    application.DisplayName    = $"AAD - {id} Client Application";
                    application.IdentifierUris = new List <string>();
                    application.IdentifierUris.Add($"https://{ConfigurationManager.AppSettings["TENANT"]}/{uniqueId}");
                    application.PasswordCredentials = new List <PasswordCredential>();
                    var    startDate = DateTime.Now;
                    Byte[] bytes     = new Byte[32];
                    using (var rand = System.Security.Cryptography.RandomNumberGenerator.Create())
                    {
                        rand.GetBytes(bytes);
                    }
                    string clientSecret = Convert.ToBase64String(bytes);
                    application.PasswordCredentials.Add(new PasswordCredential()
                    {
                        CustomKeyIdentifier = null,
                        StartDate           = startDate,
                        EndDate             = new DateTime(2299, 12, 31, 5, 0, 0, 0),
                        KeyId = Guid.NewGuid(),
                        Value = clientSecret
                    });
                    application.RequiredResourceAccess = new List <RequiredResourceAccess>();
                    RequiredResourceAccess graphResourceAccess = new RequiredResourceAccess()
                    {
                        ResourceAccess = new List <ResourceAccess>(),
                        ResourceAppId  = "00000003-0000-0000-c000-000000000000"
                    };
                    graphResourceAccess.ResourceAccess.Add(new ResourceAccess()
                    {
                        Id   = new Guid("37f7f235-527c-4136-accd-4a02d197296e"),
                        Type = "Scope"
                    });
                    graphResourceAccess.ResourceAccess.Add(new ResourceAccess()
                    {
                        Id   = new Guid("7427e0e9-2fba-42fe-b0c0-848c9e6a8182"),
                        Type = "Scope"
                    });
                    RequiredResourceAccess apimResourceAccess = new RequiredResourceAccess()
                    {
                        ResourceAccess = new List <ResourceAccess>(),
                        ResourceAppId  = "30fe3279-fbb4-4a13-b1f8-7c5f2ea9e6df"
                    };
                    apimResourceAccess.ResourceAccess.Add(new ResourceAccess()
                    {
                        Id   = new Guid("f9bcce35-145a-4199-bf1b-948467774061"),
                        Type = "Role"
                    });
                    application.RequiredResourceAccess.Add(graphResourceAccess);
                    application.RequiredResourceAccess.Add(apimResourceAccess);
                    application.ReplyUrls = new List <string>();
                    application.ReplyUrls.Add($"msapp://{uniqueId}");
                    string clientId = await _appService.Create(application);

                    // Create APIM subscription key for the organization
                    Guid             primaryKey       = Guid.NewGuid();
                    Guid             secondaryKey     = Guid.NewGuid();
                    APIMSubscription apimSubscription = await _subscriptionService.CreateOrgSubscription($"APIM {id} Subscription", "/products/starter", primaryKey, secondaryKey, $"{id}@{_orgEmailDomain}", id, id);

                    // Store subscription information in Table Storage
                    OrganizationSubscription organizationSubscription = new OrganizationSubscription()
                    {
                        Organization             = id,
                        PrimarySubscriptionKey   = apimSubscription.properties.primaryKey,
                        SecondarySubscriptionKey = apimSubscription.properties.secondaryKey,
                        Scope        = apimSubscription.properties.scope,
                        ClientId     = clientId,
                        ClientSecret = clientSecret
                    };
                    OrganizationEntity organizationEntity = new OrganizationEntity(organizationSubscription);
                    await _registrationService.CreateOrganizationSubscription(organizationEntity);

                    // Create pending APIM subscription for the user
                    APIMSubscription apimUserSubscription = await _subscriptionService.CreateSubscription($"APIM {id} Subscription", "/products/starter", Guid.NewGuid(), Guid.NewGuid(), objectId, email, firstName, lastName);

                    // No user subscriptions have been approved yet so return masked values
                    ResponseContent responseContent = new ResponseContent
                    {
                        version                  = "1.0.0",
                        status                   = (int)HttpStatusCode.OK,
                        organization             = id,
                        primarySubscriptionKey   = MASKED_VALUE,
                        secondarySubscriptionKey = MASKED_VALUE,
                        clientId                 = MASKED_VALUE,
                        clientSecret             = MASKED_VALUE
                    };
                    result.StatusCode = HttpStatusCode.OK;
                    result.Content    = new StringContent(JsonConvert.SerializeObject(responseContent), Encoding.UTF8, "application/json");
                }
                else
                {
                    string            state = string.Empty;
                    bool              userHasSubscription = false;
                    UserSubscriptions userSubscriptions   = await _subscriptionService.GetUserSubscriptions(email);

                    if (userSubscriptions != null && userSubscriptions.count > 0)
                    {
                        foreach (UserSubscription userSubscription in userSubscriptions.value)
                        {
                            if (userSubscription.properties.scope.EndsWith(subscription.Scope, StringComparison.InvariantCultureIgnoreCase))
                            {
                                state = userSubscription.properties.state;
                                userHasSubscription = true;
                                break;
                            }
                        }
                    }

                    if (!userHasSubscription)
                    {
                        APIMSubscription apimSubscription = await _subscriptionService.CreateSubscription($"APIM {id} Subscription", "/products/starter", Guid.NewGuid(), Guid.NewGuid(), objectId, email, firstName, lastName);

                        state = apimSubscription.properties.state;
                    }

                    ResponseContent responseContent = null;
                    if (state == "active") // User has an approved subscription - share the organization values
                    {
                        responseContent = new ResponseContent
                        {
                            version                  = "1.0.0",
                            status                   = (int)HttpStatusCode.OK,
                            organization             = id,
                            primarySubscriptionKey   = subscription.PrimarySubscriptionKey,
                            secondarySubscriptionKey = subscription.SecondarySubscriptionKey,
                            clientId                 = subscription.ClientId,
                            clientSecret             = subscription.ClientSecret
                        };
                    }
                    else // User has a pending subscription - return masked values
                    {
                        responseContent = new ResponseContent
                        {
                            version                  = "1.0.0",
                            status                   = (int)HttpStatusCode.OK,
                            organization             = id,
                            primarySubscriptionKey   = MASKED_VALUE,
                            secondarySubscriptionKey = MASKED_VALUE,
                            clientId                 = MASKED_VALUE,
                            clientSecret             = MASKED_VALUE
                        };
                    }

                    result.StatusCode = HttpStatusCode.OK;
                    result.Content    = new StringContent(JsonConvert.SerializeObject(responseContent), Encoding.UTF8, "application/json");
                }
            }

            return(result);
        }