Exemple #1
0
        public async stt::Task GetRequestObjectAsync()
        {
            moq::Mock <UserLicenseService.UserLicenseServiceClient> mockGrpcClient = new moq::Mock <UserLicenseService.UserLicenseServiceClient>(moq::MockBehavior.Strict);
            UserLicenseGetRequest request = new UserLicenseGetRequest
            {
                ApplicationId = "application_ideba4c06b",
                UserId        = "user_idd41a70e8",
            };
            UserLicense expectedResponse = new UserLicense
            {
                Kind    = "kindf7aa39d9",
                Enabled = true,
                State   = "state2e9ed39e",
#pragma warning disable CS0612
                EditionId = "edition_idc7d1accf",
#pragma warning restore CS0612
                CustomerId    = "customer_id3b3724cb",
                ApplicationId = "application_ideba4c06b",
                Id            = "id74b70bb8",
                UserId        = "user_idd41a70e8",
            };

            mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <UserLicense>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            UserLicenseServiceClient client  = new UserLicenseServiceClientImpl(mockGrpcClient.Object, null);
            UserLicense responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));

            xunit::Assert.Same(expectedResponse, responseCallSettings);
            UserLicense responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);

            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
Exemple #2
0
        public async Task <ProfileResponseModel> PostPremium(PremiumRequestModel model)
        {
            var user = await _userService.GetUserByPrincipalAsync(User);

            if (user == null)
            {
                throw new UnauthorizedAccessException();
            }

            var         valid   = model.Validate(_globalSettings);
            UserLicense license = null;

            if (valid && _globalSettings.SelfHosted)
            {
                license = await ApiHelpers.ReadJsonFileFromBody <UserLicense>(HttpContext, model.License);
            }

            if (!valid || (_globalSettings.SelfHosted && license == null))
            {
                throw new BadRequestException("Invalid license.");
            }

            await _userService.SignUpPremiumAsync(user, model.PaymentToken,
                                                  model.AdditionalStorageGb.GetValueOrDefault(0), license);

            return(new ProfileResponseModel(user, null));
        }
Exemple #3
0
        public void GetRequestObject()
        {
            moq::Mock <UserLicenseService.UserLicenseServiceClient> mockGrpcClient = new moq::Mock <UserLicenseService.UserLicenseServiceClient>(moq::MockBehavior.Strict);
            UserLicenseGetRequest request = new UserLicenseGetRequest
            {
                ApplicationId = "application_ideba4c06b",
                UserId        = "user_idd41a70e8",
            };
            UserLicense expectedResponse = new UserLicense
            {
                Kind    = "kindf7aa39d9",
                Enabled = true,
                State   = "state2e9ed39e",
#pragma warning disable CS0612
                EditionId = "edition_idc7d1accf",
#pragma warning restore CS0612
                CustomerId    = "customer_id3b3724cb",
                ApplicationId = "application_ideba4c06b",
                Id            = "id74b70bb8",
                UserId        = "user_idd41a70e8",
            };

            mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse);
            UserLicenseServiceClient client = new UserLicenseServiceClientImpl(mockGrpcClient.Object, null);
            UserLicense response            = client.Get(request);

            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
        public void ApproveOrRejectLicense(List <UserLicenseRequest> licReqList)
        {
            List <UserLicenseRequest> licenseRequestList = new List <UserLicenseRequest>();
            List <UserLicense>        userLicenseList    = new List <UserLicense>();

            foreach (var licReq in licReqList)
            {
                var userlicReq = userLicenseRequestLogic.GetById(licReq.Id);
                userlicReq.Comment    = licReq.Comment;
                userlicReq.ApprovedBy = licReq.ApprovedBy;
                userlicReq.IsApproved = licReq.IsApproved;
                userlicReq.IsRejected = licReq.IsRejected;
                licenseRequestList.Add(userlicReq);
                if (userlicReq.IsApproved)
                {
                    UserLicense lic = new UserLicense();
                    lic.UserId                     = userlicReq.Requested_UserId;
                    lic.TeamId                     = userlicReq.TeamId;
                    lic.License                    = new LicenseData();
                    lic.License.ProductId          = userlicReq.ProductId;
                    lic.License.UserSubscriptionId = userlicReq.UserSubscriptionId;

                    userLicenseList.Add(lic);
                }
            }
            userLicenseRequestLogic.Update(licenseRequestList);
            ErrorMessage = userLicenseRequestLogic.ErrorMessage;
            if (userLicenseList.Count > 0 && String.IsNullOrEmpty(ErrorMessage))
            {
                licLogic.CreataeUserLicense(userLicenseList);
                ErrorMessage = licLogic.ErrorMessage;
            }
        }
        public async Task <PaymentResponseModel> PostPremium(PremiumRequestModel model)
        {
            var user = await _userService.GetUserByPrincipalAsync(User);

            if (user == null)
            {
                throw new UnauthorizedAccessException();
            }

            var         valid   = model.Validate(_globalSettings);
            UserLicense license = null;

            if (valid && _globalSettings.SelfHosted)
            {
                license = await ApiHelpers.ReadJsonFileFromBody <UserLicense>(HttpContext, model.License);
            }

            if (!valid || (_globalSettings.SelfHosted && license == null))
            {
                throw new BadRequestException("Invalid license.");
            }

            var result = await _userService.SignUpPremiumAsync(user, model.PaymentToken,
                                                               model.PaymentMethodType.Value, model.AdditionalStorageGb.GetValueOrDefault(0), license);

            var profile = new ProfileResponseModel(user, null, await _userService.TwoFactorIsEnabledAsync(user));

            return(new PaymentResponseModel
            {
                UserProfile = profile,
                PaymentIntentClientSecret = result.Item2,
                Success = result.Item1
            });
        }
Exemple #6
0
        public async Task <ResponseModel> EditUserLicense(UserLicense userLicense, string token)
        {
            try
            {
                var responseClient = _httpClientFactory.CreateClient("AssetAPI");

                responseClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                var result = await responseClient.PutAsJsonAsync <UserLicense>("api/UserLicense/" + userLicense.LicenseId, userLicense);

                if (result.StatusCode != HttpStatusCode.OK)
                {
                    var faliedResponse = await result.Content.ReadAsJsonAsync <RestException>();

                    return(new ResponseModel()
                    {
                        ResponseMessage = faliedResponse.Errors.ToString(),
                        ResponseCode = result.StatusCode.ToString()
                    });
                }

                return(new ResponseModel()
                {
                    ResponseCode = result.StatusCode.ToString()
                });
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error encountered in UserLicenseService||EditUserLicense ErrorMessage: {ex.Message}");
                throw ex;
            }
        }
Exemple #7
0
        public async Task UpdateLicenseAsync(User user, UserLicense license)
        {
            if (!_globalSettings.SelfHosted)
            {
                throw new InvalidOperationException("Licenses require self hosting.");
            }

            if (license == null || !_licenseService.VerifyLicense(license))
            {
                throw new BadRequestException("Invalid license.");
            }

            if (!license.CanUse(user))
            {
                throw new BadRequestException("This license is not valid for this user.");
            }

            var dir = $"{_globalSettings.LicenseDirectory}/user";

            Directory.CreateDirectory(dir);
            File.WriteAllText($"{dir}/{user.Id}.json", JsonConvert.SerializeObject(license, Formatting.Indented));

            user.Premium               = license.Premium;
            user.RevisionDate          = DateTime.UtcNow;
            user.MaxStorageGb          = _globalSettings.SelfHosted ? 10240 : license.MaxStorageGb; // 10 TB
            user.LicenseKey            = license.LicenseKey;
            user.PremiumExpirationDate = license.Expires;
            await SaveUserAsync(user);
        }
Exemple #8
0
 static void Main()
 {
     UserLicense.Initialize();
     ValidateUsingValidationEngine();
     ValidateUsingValidationEngineAndExpando();
     ValidateUsingProceduralEngine();
 }
Exemple #9
0
        static void Main()
        {
            UserLicense.Initialize();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new EmailForm());
        }
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     UserLicense.Initialize(new MyLicense());
 }
 public BillingResponseModel(User user, UserLicense license)
     : base("billing")
 {
     StorageName  = user.Storage.HasValue ? Utilities.CoreHelpers.ReadableBytesSize(user.Storage.Value) : null;
     StorageGb    = user.Storage.HasValue ? Math.Round(user.Storage.Value / 1073741824D, 2) : 0; // 1 GB
     MaxStorageGb = user.MaxStorageGb;
     License      = license;
     Expiration   = user.PremiumExpirationDate;
 }
Exemple #12
0
        private bool CreateUserLicense(UserLicense lic)
        {
            var obj = AutoMapper.Mapper.Map <UserLicense, Core.Model.UserLicense>(lic);

            obj = Work.UserLicenseRepository.Create(obj);
            Work.UserLicenseRepository.Save();
            LicenseLogic licLogic = new LicenseLogic();

            licLogic.UpdateLicenseStatus(obj.LicenseId, true);
            return(obj.Id > 0);
        }
 public SubscriptionResponseModel(User user, SubscriptionInfo subscription, UserLicense license)
     : base("subscription")
 {
     Subscription    = subscription.Subscription != null ? new BillingSubscription(subscription.Subscription) : null;
     UpcomingInvoice = subscription.UpcomingInvoice != null ?
                       new BillingSubscriptionUpcomingInvoice(subscription.UpcomingInvoice) : null;
     StorageName  = user.Storage.HasValue ? Utilities.CoreHelpers.ReadableBytesSize(user.Storage.Value) : null;
     StorageGb    = user.Storage.HasValue ? Math.Round(user.Storage.Value / 1073741824D, 2) : 0; // 1 GB
     MaxStorageGb = user.MaxStorageGb;
     License      = license;
     Expiration   = License.Expires;
 }
Exemple #14
0
        public SubscriptionResponseModel(User user, UserLicense license = null)
            : base("subscription")
        {
            StorageName  = user.Storage.HasValue ? Utilities.CoreHelpers.ReadableBytesSize(user.Storage.Value) : null;
            StorageGb    = user.Storage.HasValue ? Math.Round(user.Storage.Value / 1073741824D, 2) : 0; // 1 GB
            MaxStorageGb = user.MaxStorageGb;
            Expiration   = user.PremiumExpirationDate;

            if (license != null)
            {
                License = license;
            }
        }
 /// <summary>Snippet for Get</summary>
 /// <remarks>
 /// This snippet has been automatically generated for illustrative purposes only.
 /// It may require modifications to work in your environment.
 /// </remarks>
 public void GetRequestObject()
 {
     // Create client
     UserLicenseServiceClient userLicenseServiceClient = UserLicenseServiceClient.Create();
     // Initialize request argument(s)
     UserLicenseGetRequest request = new UserLicenseGetRequest
     {
         ApplicationId = "",
         UserId        = "",
     };
     // Make the request
     UserLicense response = userLicenseServiceClient.Get(request);
 }
 public BillingResponseModel(User user, BillingInfo billing, UserLicense license)
     : base("billing")
 {
     PaymentSource   = billing.PaymentSource != null ? new BillingSource(billing.PaymentSource) : null;
     Subscription    = billing.Subscription != null ? new BillingSubscription(billing.Subscription) : null;
     Charges         = billing.Charges.Select(c => new BillingCharge(c));
     UpcomingInvoice = billing.UpcomingInvoice != null ? new BillingInvoice(billing.UpcomingInvoice) : null;
     StorageName     = user.Storage.HasValue ? Utilities.CoreHelpers.ReadableBytesSize(user.Storage.Value) : null;
     StorageGb       = user.Storage.HasValue ? Math.Round(user.Storage.Value / 1073741824D, 2) : 0; // 1 GB
     MaxStorageGb    = user.MaxStorageGb;
     License         = license;
     Expiration      = License.Expires;
 }
        /// <summary>Snippet for GetAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetRequestObjectAsync()
        {
            // Create client
            UserLicenseServiceClient userLicenseServiceClient = await UserLicenseServiceClient.CreateAsync();

            // Initialize request argument(s)
            UserLicenseGetRequest request = new UserLicenseGetRequest
            {
                ApplicationId = "",
                UserId        = "",
            };
            // Make the request
            UserLicense response = await userLicenseServiceClient.GetAsync(request);
        }
 public BillingResponseModel(User user, BillingInfo billing, UserLicense license)
     : base("billing")
 {
     CreditAmount    = billing.CreditAmount;
     PaymentSource   = billing.PaymentSource != null ? new BillingSource(billing.PaymentSource) : null;
     Subscription    = billing.Subscription != null ? new BillingSubscription(billing.Subscription) : null;
     Transactions    = billing.Transactions?.Select(t => new BillingTransaction(t));
     Invoices        = billing.Invoices?.Select(i => new BillingInvoice(i));
     UpcomingInvoice = billing.UpcomingInvoice != null ? new BillingInvoiceInfo(billing.UpcomingInvoice) : null;
     StorageName     = user.Storage.HasValue ? Utilities.CoreHelpers.ReadableBytesSize(user.Storage.Value) : null;
     StorageGb       = user.Storage.HasValue ? Math.Round(user.Storage.Value / 1073741824D, 2) : 0; // 1 GB
     MaxStorageGb    = user.MaxStorageGb;
     License         = license;
     Expiration      = License.Expires;
 }
        /// <summary>Snippet for GetAsync</summary>
        public async Task GetRequestObjectAsync()
        {
            // Snippet: GetAsync(UserLicenseGetRequest, CallSettings)
            // Additional: GetAsync(UserLicenseGetRequest, CancellationToken)
            // Create client
            UserLicenseServiceClient userLicenseServiceClient = await UserLicenseServiceClient.CreateAsync();

            // Initialize request argument(s)
            UserLicenseGetRequest request = new UserLicenseGetRequest
            {
                ApplicationId = "",
                UserId        = "",
            };
            // Make the request
            UserLicense response = await userLicenseServiceClient.GetAsync(request);

            // End snippet
        }
Exemple #20
0
        /// <summary>
        /// creating the UserLicense this can be used to update the single user.
        /// </summary>
        /// <param name="licList"></param>
        /// <returns></returns>
        public bool CreataeUserLicense(List <UserLicense> licList)
        {
            LicenseLogic licLogic = new LicenseLogic();

            foreach (var lic in licList)
            {
                var userLicList = Work.UserLicenseRepository.GetData(ul => ul.UserId == lic.UserId).ToList();
                var data        = Work.LicenseDataRepository.GetData(l => l.ProductId == lic.License.ProductId && l.UserSubscriptionId == lic.License.UserSubscriptionId).ToList().Select(l => l.Id);
                var obj         = userLicList.FirstOrDefault(ul => data.Contains(ul.LicenseId));
                if (obj == null)
                {
                    var         licId = licLogic.GetUnassignedLicense(lic.License.UserSubscriptionId, lic.License.ProductId).Id;
                    UserLicense ul    = new UserLicense();
                    ul.UserId    = lic.UserId;
                    ul.LicenseId = licId;
                    ul.TeamId    = lic.TeamId;
                    CreateUserLicense(ul);
                }
                userLicList.Remove(obj);
            }
            return(true);
        }
Exemple #21
0
        public async Task UpdateLicenseAsync_Success(SutProvider <UserService> sutProvider,
                                                     User user, UserLicense userLicense)
        {
            using var tempDir = new TempDirectory();

            var now = DateTime.UtcNow;

            userLicense.Issued  = now.AddDays(-10);
            userLicense.Expires = now.AddDays(10);
            userLicense.Version = 1;
            userLicense.Premium = true;

            user.EmailVerified = true;
            user.Email         = userLicense.Email;

            sutProvider.GetDependency <Settings.IGlobalSettings>().SelfHosted       = true;
            sutProvider.GetDependency <Settings.IGlobalSettings>().LicenseDirectory = tempDir.Directory;
            sutProvider.GetDependency <ILicensingService>()
            .VerifyLicense(userLicense)
            .Returns(true);

            await sutProvider.Sut.UpdateLicenseAsync(user, userLicense);

            var filePath = Path.Combine(tempDir.Directory, "user", $"{user.Id}.json");

            Assert.True(File.Exists(filePath));
            var document = JsonDocument.Parse(File.OpenRead(filePath));
            var root     = document.RootElement;

            Assert.Equal(JsonValueKind.Object, root.ValueKind);
            // Sort of a lazy way to test that it is indented but not sure of a better way
            Assert.Contains('\n', root.GetRawText());
            AssertHelper.AssertJsonProperty(root, "LicenseKey", JsonValueKind.String);
            AssertHelper.AssertJsonProperty(root, "Id", JsonValueKind.String);
            AssertHelper.AssertJsonProperty(root, "Premium", JsonValueKind.True);
            var versionProp = AssertHelper.AssertJsonProperty(root, "Version", JsonValueKind.Number);

            Assert.Equal(1, versionProp.GetInt32());
        }
Exemple #22
0
        public void CreateUserLicense()
        {
            try
            {
                List <UserLicense> userLicList = new List <UserLicense>();
                UserLicense        lic         = new UserLicense();
                lic.UserId    = TeamMember.UserId;
                lic.LicenseId = LicenseList[0].Id;
                lic.License   = licLogic.GetLicenseById(lic.LicenseId);
                userLicList.Add(lic);
                UserLicense lic1 = new UserLicense();
                lic1.UserId    = TeamMember.UserId;
                lic1.LicenseId = LicenseList[1].Id;
                lic1.License   = licLogic.GetLicenseById(lic1.LicenseId);
                userLicList.Add(lic1);
                userLicLogic.CreateMultiUserLicense(userLicList, new List <string>()
                {
                    TeamMember.UserId
                });

                userLicList = new List <UserLicense>();
                UserLicense lic2 = new UserLicense();
                lic2.UserId    = AdminUser.UserId;
                lic2.LicenseId = LicenseList[2].Id;
                lic2.License   = licLogic.GetLicenseById(lic2.LicenseId);
                userLicList.Add(lic2);
                userLicLogic.CreateMultiUserLicense(userLicList, new List <string>()
                {
                    AdminUser.UserId
                });
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Exemple #23
0
 static void Main()
 {
     UserLicense.Initialize();
     ValidatePersonIdentity_StructuredRoutine();
 }
Exemple #24
0
        public override void Initialize(Dictionary <string, Dictionary <string, GameObject> > preloadedObjects)
        {
            instance = this;

            //new Test();
            //return;

            #region VerifyVersion
            Logger.Log("Load Global Json");
            ItemSettings global = SerializeHelper.LoadGlobalSettings <ItemSettings>();
            if (global != null)
            {
                if (global.mod_version > Version)
                {
                    new ErrorPanel($"Require Version:{global.mod_version},BUT you Version:{Version}\n(你的MOD版本该更新了)");
                    throw new FileLoadException("Try To Load an newer json data in an older mod,please update mod");
                }

                ItemData = global;
                Logger.Log("Loaded Json");
            }
            #endregion

            #region Init GameObject
            ObjectLoader.Load(preloadedObjects);
            BehaviourProcessor.RegisterBehaviour <Particle>();
            BehaviourProcessor.RegisterBehaviour <Draw>();
            BehaviourProcessor.RegisterBehaviour <OtherBehaviour>();
            BehaviourProcessor.RegisterBehaviour <AreaBehaviour>();
            BehaviourProcessor.RegisterBehaviour <MovablePlatform>();
            BehaviourProcessor.RegisterBehaviour <ModifyGameItem>();
            BehaviourProcessor.RegisterBehaviour <Mana>();
            BehaviourProcessor.RegisterBehaviour <AudioBehaviours>();
            BehaviourProcessor.RegisterBehaviour <OneShotBehaviour>();
            BehaviourProcessor.RegisterBehaviour <Scope>();
            BehaviourProcessor.RegisterBehaviour <Bench>();
            BehaviourProcessor.RegisterSharedBehaviour <DefaultBehaviour>();
            BehaviourProcessor.RegisterSharedBehaviour <UnVisableBehaviour>();
            BehaviourProcessor.RegisterSharedBehaviour <DelayResizableBehaviour>();
            #endregion

            #region InitGUI
            UIObj = new GameObject();
            UIObj.AddComponent <GUIController>();
            UnityEngine.Object.DontDestroyOnLoad(UIObj);
            GUIController.Instance.BuildMenus();
            #endregion

            #region SetupCallBack
            SelectGetter  = GetKeyPress;
            SelectGetter += PickPanel.SelectFocus;
            UnityEngine.SceneManagement.SceneManager.sceneLoaded += SpawnFromSettings;
            UnityEngine.SceneManagement.SceneManager.sceneLoaded += ShowRespawn;
            UnityEngine.SceneManagement.SceneManager.sceneLoaded += AutoSaveModification;
            On.GameManager.PositionHeroAtSceneEntrance           += HeroOutBoundSave;
            ModHooks.Instance.LanguageGetHook     += DLanguage.MyLanguage;
            ModHooks.Instance.ApplicationQuitHook += SaveJson;
            if (Settings.CreateMode)
            {
                ModHooks.Instance.HeroUpdateHook += OperateItem;
            }
            #endregion

            UserLicense.ShowLicense();
        }
Exemple #25
0
 public IActionResult UpdateUserLicense(UserLicense userLicense)
 {
     userLicense.userId = this.User.GetUserId();
     _uLicenseRepo.UpdateUserLicense(userLicense);
     return(Ok());
 }
Exemple #26
0
        public async Task SignUpPremiumAsync(User user, string paymentToken, PaymentMethodType paymentMethodType,
                                             short additionalStorageGb, UserLicense license)
        {
            if (user.Premium)
            {
                throw new BadRequestException("Already a premium user.");
            }

            if (additionalStorageGb < 0)
            {
                throw new BadRequestException("You can't subtract storage!");
            }

            IPaymentService paymentService = null;

            if (_globalSettings.SelfHosted)
            {
                if (license == null || !_licenseService.VerifyLicense(license))
                {
                    throw new BadRequestException("Invalid license.");
                }

                if (!license.CanUse(user))
                {
                    throw new BadRequestException("This license is not valid for this user.");
                }

                var dir = $"{_globalSettings.LicenseDirectory}/user";
                Directory.CreateDirectory(dir);
                File.WriteAllText($"{dir}/{user.Id}.json", JsonConvert.SerializeObject(license, Formatting.Indented));
            }
            else
            {
                await _paymentService.PurchasePremiumAsync(user, paymentMethodType, paymentToken, additionalStorageGb);
            }

            user.Premium      = true;
            user.RevisionDate = DateTime.UtcNow;

            if (_globalSettings.SelfHosted)
            {
                user.MaxStorageGb          = 10240; // 10 TB
                user.LicenseKey            = license.LicenseKey;
                user.PremiumExpirationDate = license.Expires;
            }
            else
            {
                user.MaxStorageGb = (short)(1 + additionalStorageGb);
                user.LicenseKey   = CoreHelpers.SecureRandomString(20);
            }

            try
            {
                await SaveUserAsync(user);

                await _pushService.PushSyncVaultAsync(user.Id);
            }
            catch when(!_globalSettings.SelfHosted)
            {
                await paymentService.CancelAndRecoverChargesAsync(user);

                throw;
            }
        }
Exemple #27
0
        public async Task SignUpPremiumAsync(User user, string paymentToken, short additionalStorageGb, UserLicense license)
        {
            if (user.Premium)
            {
                throw new BadRequestException("Already a premium user.");
            }

            IPaymentService paymentService = null;

            if (_globalSettings.SelfHosted)
            {
                if (license == null || !_licenseService.VerifyLicense(license))
                {
                    throw new BadRequestException("Invalid license.");
                }

                if (!license.CanUse(user))
                {
                    throw new BadRequestException("This license is not valid for this user.");
                }

                var dir = $"{_globalSettings.LicenseDirectory}/user";
                Directory.CreateDirectory(dir);
                File.WriteAllText($"{dir}/{user.Id}.json", JsonConvert.SerializeObject(license, Formatting.Indented));
            }
            else if (!string.IsNullOrWhiteSpace(paymentToken))
            {
                if (paymentToken.StartsWith("btok_"))
                {
                    throw new BadRequestException("Invalid token.");
                }

                if (paymentToken.StartsWith("tok_"))
                {
                    paymentService = new StripePaymentService();
                }
                else
                {
                    paymentService = new BraintreePaymentService(_globalSettings);
                }

                await paymentService.PurchasePremiumAsync(user, paymentToken, additionalStorageGb);
            }
            else
            {
                throw new InvalidOperationException("License or payment token is required.");
            }

            user.Premium      = true;
            user.RevisionDate = DateTime.UtcNow;

            if (_globalSettings.SelfHosted)
            {
                user.MaxStorageGb          = 10240; // 10 TB
                user.LicenseKey            = license.LicenseKey;
                user.PremiumExpirationDate = license.Expires;
            }
            else
            {
                user.MaxStorageGb = (short)(1 + additionalStorageGb);
                user.LicenseKey   = CoreHelpers.SecureRandomString(20);
            }

            try
            {
                await SaveUserAsync(user);
            }
            catch when(!_globalSettings.SelfHosted)
            {
                await paymentService.CancelAndRecoverChargesAsync(user);

                throw;
            }
        }
Exemple #28
0
 public async Task <User> AssignAsync(string userId, UserLicense UserLicense)
 {
     return(await _call.PostAsync <User, UserLicense>($"users/{userId}/assignLicense", UserLicense).ConfigureAwait(false));
 }
        public async Task <Tuple <bool, string> > SignUpPremiumAsync(User user, string paymentToken,
                                                                     PaymentMethodType paymentMethodType, short additionalStorageGb, UserLicense license,
                                                                     TaxInfo taxInfo)
        {
            if (user.Premium)
            {
                throw new BadRequestException("Already a premium user.");
            }

            if (additionalStorageGb < 0)
            {
                throw new BadRequestException("You can't subtract storage!");
            }

            if ((paymentMethodType == PaymentMethodType.GoogleInApp ||
                 paymentMethodType == PaymentMethodType.AppleInApp) && additionalStorageGb > 0)
            {
                throw new BadRequestException("You cannot add storage with this payment method.");
            }

            string          paymentIntentClientSecret = null;
            IPaymentService paymentService            = null;

            if (_globalSettings.SelfHosted)
            {
                if (license == null || !_licenseService.VerifyLicense(license))
                {
                    throw new BadRequestException("Invalid license.");
                }

                if (!license.CanUse(user))
                {
                    throw new BadRequestException("This license is not valid for this user.");
                }

                var dir = $"{_globalSettings.LicenseDirectory}/user";
                Directory.CreateDirectory(dir);
                File.WriteAllText($"{dir}/{user.Id}.json", JsonConvert.SerializeObject(license, Formatting.Indented));
            }
            else
            {
                paymentIntentClientSecret = await _paymentService.PurchasePremiumAsync(user, paymentMethodType,
                                                                                       paymentToken, additionalStorageGb, taxInfo);
            }

            user.Premium      = true;
            user.RevisionDate = DateTime.UtcNow;

            if (_globalSettings.SelfHosted)
            {
                user.MaxStorageGb          = 10240; // 10 TB
                user.LicenseKey            = license.LicenseKey;
                user.PremiumExpirationDate = license.Expires;
            }
            else
            {
                user.MaxStorageGb = (short)(1 + additionalStorageGb);
                user.LicenseKey   = CoreHelpers.SecureRandomString(20);
            }

            try
            {
                await SaveUserAsync(user);

                await _pushService.PushSyncVaultAsync(user.Id);

                await _referenceEventService.RaiseEventAsync(
                    new ReferenceEvent(ReferenceEventType.UpgradePlan, user)
                {
                    Storage  = user.MaxStorageGb,
                    PlanName = PremiumPlanId,
                });
            }
            catch when(!_globalSettings.SelfHosted)
            {
                await paymentService.CancelAndRecoverChargesAsync(user);

                throw;
            }
            return(new Tuple <bool, string>(string.IsNullOrWhiteSpace(paymentIntentClientSecret),
                                            paymentIntentClientSecret));
        }
 /// <summary>
 /// Assign office license to specific user
 /// </summary>
 /// <param name="userId"></param>
 /// <param name="UserLicense"></param>
 /// <returns></returns>
 public async Task <User> AssignAsync(string userId, UserLicense UserLicense)
 {
     return(await _officeLincenseManager.AssignAsync(userId, UserLicense).ConfigureAwait(false));
 }