예제 #1
0
        public void FindTenants()
        {
            var h       = new HostedSolution();
            var tenants = h.FindTenants("76ff727b-f987-4871-9834-e63d4420d6e9");

            Assert.AreNotEqual(0, tenants.Count);
        }
예제 #2
0
        public void FindTenants()
        {
            var h       = new HostedSolution(ConfigurationManager.ConnectionStrings["core"]);
            var tenants = h.FindTenants("76ff727b-f987-4871-9834-e63d4420d6e9");

            Assert.AreNotEqual(0, tenants.Count);
        }
예제 #3
0
        public IActionResult SetTariff(TariffModel model)
        {
            if (!CommonMethods.GetTenant(model, out Tenant tenant))
            {
                Log.Error("Model without tenant");

                return(BadRequest(new
                {
                    error = "portalNameEmpty",
                    message = "PortalName is required"
                }));
            }

            if (tenant == null)
            {
                Log.Error("Tenant not found");

                return(BadRequest(new
                {
                    error = "portalNameNotFound",
                    message = "Portal not found"
                }));
            }

            var quota = new TenantQuota(tenant.TenantId)
            {
                ActiveUsers  = 10000,
                Features     = model.Features ?? "",
                MaxFileSize  = 1024 * 1024 * 1024,
                MaxTotalSize = 1024L * 1024 * 1024 * 1024 - 1,
                Name         = "api",
            };

            if (model.ActiveUsers != default)
            {
                quota.ActiveUsers = model.ActiveUsers;
            }

            if (model.MaxTotalSize != default)
            {
                quota.MaxTotalSize = model.MaxTotalSize;
            }

            if (model.MaxFileSize != default)
            {
                quota.MaxFileSize = model.MaxFileSize;
            }

            HostedSolution.SaveTenantQuota(quota);

            var tariff = new Tariff
            {
                QuotaId = quota.Id,
                DueDate = model.DueDate != default ? model.DueDate : DateTime.MaxValue,
            };

            HostedSolution.SetTariff(tenant.TenantId, tariff);

            return(GetTariff(tenant));
        }
예제 #4
0
        public IActionResult Remove(string portalName)
        {
            if (string.IsNullOrEmpty(portalName))
            {
                return(BadRequest(new
                {
                    errors = "portalName is required."
                }));
            }

            var tenant = HostedSolution.GetTenant(portalName.Trim());

            if (tenant == null)
            {
                return(BadRequest(new
                {
                    errors = "Tenant not found."
                }));
            }

            HostedSolution.RemoveTenant(tenant);

            return(Ok(new
            {
                errors = "",
                tenant = ToTenantWrapper(tenant)
            }));
        }
예제 #5
0
        public IActionResult Remove([FromQuery] TenantModel model)
        {
            if (!CommonMethods.GetTenant(model, out var tenant))
            {
                Log.Error("Model without tenant");

                return BadRequest(new
                {
                    error = "portalNameEmpty",
                    message = "PortalName is required"
                });
            }

            if (tenant == null)
            {
                Log.Error("Tenant not found");

                return BadRequest(new
                {
                    error = "portalNameNotFound",
                    message = "Portal not found"
                });
            }

            HostedSolution.RemoveTenant(tenant);

            return Ok(new
            {
                tenant = CommonMethods.ToTenantWrapper(tenant)
            });
        }
예제 #6
0
        public IActionResult GetTariff(string portalName)
        {
            if (string.IsNullOrEmpty(portalName))
            {
                return(BadRequest(new
                {
                    errors = "portalName is required."
                }));
            }

            var tenant = HostedSolution.GetTenant(portalName.Trim());

            if (tenant == null)
            {
                return(BadRequest(new
                {
                    errors = "Tenant not found."
                }));
            }

            var tariff = HostedSolution.GetTariff(tenant.TenantId, false);

            var quota = HostedSolution.GetTenantQuota(tenant.TenantId);

            return(Ok(new
            {
                errors = "",
                tenant = ToTenantWrapper(tenant),
                tariff = ToTariffWrapper(tariff, quota)
            }));
        }
예제 #7
0
        public void FindTenants()
        {
            var h       = new HostedSolution(null, null, null, null, Configuration.GetConnectionStrings("core"), null, null);
            var tenants = h.FindTenants("76ff727b-f987-4871-9834-e63d4420d6e9");

            Assert.AreNotEqual(0, tenants.Count);
        }
예제 #8
0
        public IActionResult ChangeStatus(TenantModel model, bool active)
        {
            if (model == null)
            {
                return(BadRequest(new
                {
                    errors = "PortalName is required."
                }));
            }

            var tenant = HostedSolution.GetTenant((model.PortalName ?? "").Trim());

            if (tenant == null)
            {
                return(BadRequest(new
                {
                    errors = "Tenant not found."
                }));
            }

            tenant.SetStatus(active ? TenantStatus.Active : TenantStatus.Suspended);

            HostedSolution.SaveTenant(tenant);

            return(Ok(new
            {
                errors = "",
                tenant = ToTenantWrapper(tenant)
            }));
        }
예제 #9
0
        public IActionResult Find(IEnumerable <Guid> userIds)
        {
            var sw = Stopwatch.StartNew();

            userIds = userIds ?? new List <Guid>();

            var users = HostedSolution.FindUsers(userIds);

            var result = users.Select(user => new
            {
                id    = user.ID,
                name  = UserFormatter.GetUserName(user),
                email = user.Email,

                link = GetUserProfileLink(user)
            });

            Log.DebugFormat("People find {0} / {1}; Elapsed {2} ms", result.Count(), userIds.Count(), sw.ElapsedMilliseconds);
            sw.Stop();

            return(Ok(new
            {
                result
            }));
        }
예제 #10
0
        public IActionResult GetPortalsByEmail(string email)
        {
            try
            {
                var tenants = string.IsNullOrEmpty(email)
                                  ? HostedSolution.GetTenants(DateTime.MinValue).OrderBy(t => t.TenantId).ToList()
                                  : HostedSolution.FindTenants(email.Trim()).OrderBy(t => t.TenantId).ToList();


                var refers = tenants.Where(t => t.Status == TenantStatus.Active).ToList()
                             .ConvertAll(t => string.Format("{0}{1}{2}",
                                                            Request.Scheme,
                                                            Uri.SchemeDelimiter,
                                                            t.GetTenantDomain(CoreSettings)));

                return(Ok(new
                {
                    errors = "",
                    message = "",
                    portals = refers
                }));
            }
            catch (Exception ex)
            {
                Log.Error(ex);

                return(StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    errors = new[] { "error" },
                    message = ex.Message,
                    stacktrace = ex.StackTrace
                }));
            }
        }
예제 #11
0
        public void FindTenants()
        {
            var h       = new HostedSolution(ConfigurationManager.ConnectionStrings["core"]);
            var tenants = h.FindTenants("76ff727b-f987-4871-9834-e63d4420d6e9");

            CollectionAssert.IsNotEmpty(tenants);
        }
예제 #12
0
 public PortalController(
     IConfiguration configuration,
     Core.SecurityContext securityContext,
     TenantManager tenantManager,
     SettingsManager settingsManager,
     ApiSystemHelper apiSystemHelper,
     CommonMethods commonMethods,
     HostedSolution hostedSolution,
     CoreSettings coreSettings,
     TenantDomainValidator tenantDomainValidator,
     UserFormatter userFormatter,
     UserManagerWrapper userManagerWrapper,
     CommonConstants commonConstants,
     IOptionsMonitor <ILog> option,
     TimeZonesProvider timeZonesProvider,
     TimeZoneConverter timeZoneConverter)
 {
     Configuration         = configuration;
     SecurityContext       = securityContext;
     TenantManager         = tenantManager;
     SettingsManager       = settingsManager;
     ApiSystemHelper       = apiSystemHelper;
     CommonMethods         = commonMethods;
     HostedSolution        = hostedSolution;
     CoreSettings          = coreSettings;
     TenantDomainValidator = tenantDomainValidator;
     UserFormatter         = userFormatter;
     UserManagerWrapper    = userManagerWrapper;
     CommonConstants       = commonConstants;
     TimeZonesProvider     = timeZonesProvider;
     TimeZoneConverter     = timeZoneConverter;
     Log = option.Get("ASC.ApiSystem");
 }
예제 #13
0
        private IActionResult CheckExistingNamePortal(string portalName)
        {
            if (string.IsNullOrEmpty(portalName))
            {
                return(BadRequest(new
                {
                    error = "portalNameEmpty"
                }));
            }

            try
            {
                if (!string.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl))
                {
                    ValidateDomain(portalName.Trim());
                }
                else
                {
                    HostedSolution.CheckTenantAddress(portalName.Trim());
                }
            }
            catch (TenantAlreadyExistsException ex)
            {
                return(BadRequest(new
                {
                    errors = new[] { "portalNameExist" },
                    variants = ex.ExistsTenants.ToArray()
                }));
            }
            catch (TenantTooShortException)
            {
                return(BadRequest(new
                {
                    errors = new[] { "tooShortError" }
                }));
            }
            catch (TenantIncorrectCharsException)
            {
                return(BadRequest(new
                {
                    errors = new[] { "portalNameIncorrect" }
                }));
            }
            catch (Exception ex)
            {
                Log.Error(ex);

                return(StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    errors = new[] { "error" },
                    message = ex.Message,
                    stacktrace = ex.StackTrace
                }));
            }

            return(null);
        }
예제 #14
0
        private void Setup()
        {
            var tenant = CoreContext.TenantManager.GetCurrentTenant();

            var user = SecurityContext.CurrentAccount;

            _log.Debug("ApiHelper->Setup: Tenant={0} User='******' IsAuthenticated={2} Scheme='{3}' HttpContext is {4}",
                       tenant.TenantId, user.ID, user.IsAuthenticated, Scheme,
                       HttpContext.Current != null
                          ? string.Format("not null and UrlRewriter = {0}, RequestUrl = {1}", HttpContext.Current.Request.GetUrlRewriter(), HttpContext.Current.Request.Url)
                          : "null");

            if (!user.IsAuthenticated)
            {
                throw new AuthenticationException("User not authenticated");
            }

            var hs = new HostedSolution(ConfigurationManager.ConnectionStrings["default"]);

            var authenticationCookie = hs.CreateAuthenticationCookie(tenant.TenantId, user.ID);

            var tempUrl = (WebConfigurationManager.AppSettings["api.url"] ?? "").Trim('~', '/');

            var ubBase = new UriBuilder
            {
                Scheme = Scheme,
                Host   = tenant.GetTenantDomain(false)
            };

            var virtualDir = WebConfigurationManager.AppSettings["api.virtual-dir"];

            if (!string.IsNullOrEmpty(virtualDir))
            {
                tempUrl = string.Format("{0}/{1}", virtualDir.Trim('/'), tempUrl);
            }

            var host = WebConfigurationManager.AppSettings["api.host"];

            if (!string.IsNullOrEmpty(host))
            {
                ubBase.Host = host;
            }

            var port = WebConfigurationManager.AppSettings["api.port"];

            if (!string.IsNullOrEmpty(port))
            {
                ubBase.Port = int.Parse(port);
            }

            ubBase.Path = tempUrl;

            BaseUrl = ubBase;

            _cookie = new Cookie("asc_auth_key", authenticationCookie, "/", BaseUrl.Host);
        }
예제 #15
0
 public TariffController(
     CommonMethods commonMethods,
     HostedSolution hostedSolution,
     IOptionsMonitor <ILog> option
     )
 {
     CommonMethods  = commonMethods;
     HostedSolution = hostedSolution;
     Log            = option.Get("ASC.ApiSystem");
 }
예제 #16
0
        private string GetTenantDomain(int tenantId)
        {
            var domain = Cache.Get <string>(tenantId.ToString());

            if (string.IsNullOrEmpty(domain))
            {
                var tenant = HostedSolution.GetTenant(tenantId);
                domain = tenant.GetTenantDomain(CoreSettings);
                Cache.Insert(tenantId.ToString(), domain, TimeSpan.FromMinutes(10));
            }
            return(domain);
        }
예제 #17
0
        private IActionResult GetTariff(Tenant tenant)
        {
            var tariff = HostedSolution.GetTariff(tenant.TenantId, false);

            var quota = HostedSolution.GetTenantQuota(tenant.TenantId);

            return(Ok(new
            {
                tenant = CommonMethods.ToTenantWrapper(tenant),
                tariff = ToTariffWrapper(tariff, quota),
            }));
        }
예제 #18
0
        public IActionResult GetTariffs()
        {
            var tariffs = HostedSolution.GetTenantQuotas()
                          .Where(q => !q.Trial && !q.Free && !q.Open)
                          .OrderBy(q => q.ActiveUsers)
                          .ThenByDescending(q => q.Id)
                          .Select(q => ToTariffWrapper(null, q));

            return(Ok(new
            {
                tariffs
            }));
        }
예제 #19
0
        public bool GetTenant(IModel model, out Tenant tenant)
        {
            if (model != null && model.TenantId.HasValue)
            {
                tenant = HostedSolution.GetTenant(model.TenantId.Value);
                return(true);
            }

            if (model != null && !string.IsNullOrEmpty((model.PortalName ?? "").Trim()))
            {
                tenant = HostedSolution.GetTenant((model.PortalName ?? "").Trim());
                return(true);
            }

            tenant = null;
            return(false);
        }
예제 #20
0
        private bool CheckExistingNamePortal(string portalName, out object error)
        {
            error = null;
            if (string.IsNullOrEmpty(portalName))
            {
                error = new { error = "portalNameEmpty", message = "PortalName is required" };
                return false;
            }
            try
            {
                if (!string.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl))
                {
                    ValidateDomain(portalName.Trim());
                }
                else
                {
                    HostedSolution.CheckTenantAddress(portalName.Trim());
                }
            }
            catch (TenantAlreadyExistsException ex)
            {
                error = new { error = "portalNameExist", message = "Portal already exists", variants = ex.ExistsTenants.ToArray() };
                return false;
            }
            catch (TenantTooShortException)
            {
                error = new { error = "tooShortError", message = "Portal name is too short" };
                return false;

            }
            catch (TenantIncorrectCharsException)
            {
                error = new { error = "portalNameIncorrect", message = "Unallowable symbols in portalName" };
                return false;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                error = new { error = "error", message = ex.Message, stacktrace = ex.StackTrace };
                return false;
            }

            return true;
        }
예제 #21
0
        private bool CheckRegistrationPayment(out object error)
        {
            error = null;
            if (Configuration["core:base-domain"] == "localhost")
            {
                var tenants = HostedSolution.GetTenants(DateTime.MinValue);
                var firstTenant = tenants.FirstOrDefault();
                if (firstTenant != null)
                {
                    var activePortals = tenants.Count(r => r.Status != TenantStatus.Suspended && r.Status != TenantStatus.RemovePending);

                    var quota = HostedSolution.GetTenantQuota(firstTenant.TenantId);
                    if (quota.CountPortals > 0 && quota.CountPortals <= activePortals)
                    {
                        error = new { error = "portalsCountTooMuch", message = "Too much portals registered already", };
                        return false;
                    }
                }
            }
            return true;
        }
예제 #22
0
        public IActionResult ChangeStatus(TenantModel model)
        {
            if (!CommonMethods.GetTenant(model, out var tenant))
            {
                Log.Error("Model without tenant");

                return BadRequest(new
                {
                    error = "portalNameEmpty",
                    message = "PortalName is required"
                });
            }

            if (tenant == null)
            {
                Log.Error("Tenant not found");

                return BadRequest(new
                {
                    error = "portalNameNotFound",
                    message = "Portal not found"
                });
            }

            var active = model.Status;

            if (active != TenantStatus.Active)
            {
                active = TenantStatus.Suspended;
            }

            tenant.SetStatus(active);

            HostedSolution.SaveTenant(tenant);

            return Ok(new
            {
                tenant = CommonMethods.ToTenantWrapper(tenant)
            });
        }
예제 #23
0
        public object UpdatePortalName(string alias)
        {
            var enabled = SetupInfo.IsVisibleSettings("PortalRename");

            if (!enabled)
            {
                throw new SecurityException(Resource.PortalAccessSettingsTariffException);
            }

            if (CoreContext.Configuration.Personal)
            {
                throw new Exception(Resource.ErrorAccessDenied);
            }

            SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);

            if (String.IsNullOrEmpty(alias))
            {
                throw new ArgumentException();
            }


            var tenant = CoreContext.TenantManager.GetCurrentTenant();
            var user   = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

            var newAlias           = alias.ToLowerInvariant();
            var oldAlias           = tenant.TenantAlias;
            var oldVirtualRootPath = CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/');

            if (!String.Equals(newAlias, oldAlias, StringComparison.InvariantCultureIgnoreCase))
            {
                var hostedSolution = new HostedSolution(ConfigurationManager.ConnectionStrings["default"]);
                if (!String.IsNullOrEmpty(ApiSystemHelper.ApiSystemUrl))
                {
                    ApiSystemHelper.ValidatePortalName(newAlias);
                }
                else
                {
                    hostedSolution.CheckTenantAddress(newAlias.Trim());
                }


                if (!String.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl))
                {
                    ApiSystemHelper.AddTenantToCache(newAlias);
                }

                tenant.TenantAlias = alias;
                tenant             = hostedSolution.SaveTenant(tenant);


                if (!String.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl))
                {
                    ApiSystemHelper.RemoveTenantFromCache(oldAlias);
                }

                var newVirtualRootPath = CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/');
                if (!string.Equals(oldVirtualRootPath, newVirtualRootPath, StringComparison.InvariantCultureIgnoreCase))
                {
                    StudioNotifyService.Instance.PortalRenameNotify(oldVirtualRootPath);
                }
            }
            else
            {
                throw new Exception(ResourceJS.ErrorPortalNameWasNotChanged);
            }

            var reference = CreateReference(Request, tenant.TenantDomain, tenant.TenantId, user.Email);

            return(new {
                message = Resource.SuccessfullyPortalRenameMessage,
                reference = reference
            });
        }
예제 #24
0
        public IActionResult SetTariff(TariffModel model)
        {
            if (model == null)
            {
                return(BadRequest(new
                {
                    errors = "PortalName is required."
                }));
            }

            if (!ModelState.IsValid)
            {
                var errors = new JArray();

                foreach (var k in ModelState.Keys)
                {
                    errors.Add(ModelState[k].Errors.FirstOrDefault().ErrorMessage);
                }

                return(BadRequest(new
                {
                    errors
                }));
            }

            var tenant = HostedSolution.GetTenant((model.PortalName ?? "").Trim());

            if (tenant == null)
            {
                return(BadRequest(new
                {
                    errors = "Tenant not found."
                }));
            }

            var quota = new TenantQuota(tenant.TenantId)
            {
                ActiveUsers  = 10000,
                Features     = model.Features ?? "",
                MaxFileSize  = 1024 * 1024 * 1024,
                MaxTotalSize = 1024L * 1024 * 1024 * 1024 - 1,
                Name         = "api",
            };

            if (model.ActiveUsers != default)
            {
                quota.ActiveUsers = model.ActiveUsers;
            }

            if (model.MaxTotalSize != default)
            {
                quota.MaxTotalSize = model.MaxTotalSize;
            }

            if (model.MaxFileSize != default)
            {
                quota.MaxFileSize = model.MaxFileSize;
            }

            HostedSolution.SaveTenantQuota(quota);

            var tariff = new Tariff
            {
                QuotaId = quota.Id,
                DueDate = model.DueDate != default ? model.DueDate : DateTime.MaxValue,
            };

            HostedSolution.SetTariff(tenant.TenantId, tariff);

            tariff = HostedSolution.GetTariff(tenant.TenantId, false);

            quota = HostedSolution.GetTenantQuota(tenant.TenantId);

            return(Ok(new
            {
                errors = "",
                tenant = ToTenantWrapper(tenant),
                tariff = ToTariffWrapper(tariff, quota)
            }));
        }
예제 #25
0
        public IActionResult Register(TenantModel model)
        {
            if (model == null)
            {
                return BadRequest(new
                {
                    error = "portalNameEmpty",
                    message = "PortalName is required"
                });
            }

            if (!ModelState.IsValid)
            {
                var message = new JArray();

                foreach (var k in ModelState.Keys)
                {
                    message.Add(ModelState[k].Errors.FirstOrDefault().ErrorMessage);
                }

                return BadRequest(new
                {
                    error = "params",
                    message
                });
            }

            var sw = Stopwatch.StartNew();

            if (string.IsNullOrEmpty(model.PasswordHash))
            {
                if (!CheckPasswordPolicy(model.Password, out var error1))
                {
                    sw.Stop();
                    return BadRequest(error1);
                }

                if (!string.IsNullOrEmpty(model.Password))
                {
                    model.PasswordHash = PasswordHasher.GetClientPassword(model.Password);
                }

            }
            model.FirstName = (model.FirstName ?? "").Trim();
            model.LastName = (model.LastName ?? "").Trim();

            if (!CheckValidName(model.FirstName + model.LastName, out var error))
            {
                sw.Stop();

                return BadRequest(error);
            }

            model.PortalName = (model.PortalName ?? "").Trim();

            if (!CheckExistingNamePortal(model.PortalName, out error))
            {
                sw.Stop();

                return BadRequest(error);
            }

            Log.DebugFormat("PortalName = {0}; Elapsed ms. CheckExistingNamePortal: {1}", model.PortalName, sw.ElapsedMilliseconds);

            var clientIP = CommonMethods.GetClientIp();

            if (CommonMethods.CheckMuchRegistration(model, clientIP, sw))
            {
                return BadRequest(new
                {
                    error = "tooMuchAttempts",
                    message = "Too much attempts already"
                });
            }

            if (!CheckRecaptcha(model, clientIP, sw, out error))
            {
                return BadRequest(error);
            }

            if (!CheckRegistrationPayment(out error))
            {
                return BadRequest(error);
            }

            var language = model.Language ?? string.Empty;

            var tz = TimeZonesProvider.GetCurrentTimeZoneInfo(language);

            Log.DebugFormat("PortalName = {0}; Elapsed ms. TimeZonesProvider.GetCurrentTimeZoneInfo: {1}", model.PortalName, sw.ElapsedMilliseconds);

            if (!string.IsNullOrEmpty(model.TimeZoneName))
            {
                tz = TimeZoneConverter.GetTimeZone(model.TimeZoneName.Trim(), false) ?? tz;

                Log.DebugFormat("PortalName = {0}; Elapsed ms. TimeZonesProvider.OlsonTimeZoneToTimeZoneInfo: {1}", model.PortalName, sw.ElapsedMilliseconds);
            }

            var lang = TimeZonesProvider.GetCurrentCulture(language);

            Log.DebugFormat("PortalName = {0}; model.Language = {1}, resultLang.DisplayName = {2}", model.PortalName, language, lang.DisplayName);

            var info = new TenantRegistrationInfo
            {
                Name = Configuration["web:portal-name"] ?? "Cloud Office Applications",
                Address = model.PortalName,
                Culture = lang,
                FirstName = model.FirstName,
                LastName = model.LastName,
                PasswordHash = string.IsNullOrEmpty(model.PasswordHash) ? null : model.PasswordHash,
                Email = (model.Email ?? "").Trim(),
                TimeZoneInfo = tz,
                MobilePhone = string.IsNullOrEmpty(model.Phone) ? null : model.Phone.Trim(),
                Industry = (TenantIndustry)model.Industry,
                Spam = model.Spam,
                Calls = model.Calls,
                Analytics = model.Analytics,
                LimitedControlPanel = model.LimitedControlPanel
            };

            if (!string.IsNullOrEmpty(model.PartnerId))
            {
                if (Guid.TryParse(model.PartnerId, out _))
                {
                    // valid guid
                    info.PartnerId = model.PartnerId;
                }
            }

            if (!string.IsNullOrEmpty(model.AffiliateId))
            {
                info.AffiliateId = model.AffiliateId;
            }

            if (!string.IsNullOrEmpty(model.Campaign))
            {
                info.Campaign = model.Campaign;
            }

            Tenant t;

            try
            {
                /****REGISTRATION!!!*****/
                if (!string.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl))
                {
                    ApiSystemHelper.AddTenantToCache(info.Address, SecurityContext.CurrentAccount.ID);

                    Log.DebugFormat("PortalName = {0}; Elapsed ms. CacheController.AddTenantToCache: {1}", model.PortalName, sw.ElapsedMilliseconds);
                }

                HostedSolution.RegisterTenant(info, out t);

                /*********/

                Log.DebugFormat("PortalName = {0}; Elapsed ms. HostedSolution.RegisterTenant: {1}", model.PortalName, sw.ElapsedMilliseconds);
            }
            catch (Exception e)
            {
                sw.Stop();

                Log.Error(e);

                return StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    error = "registerNewTenantError",
                    message = e.Message,
                    stacktrace = e.StackTrace
                });
            }

            var trialQuota = Configuration["trial-quota"];
            if (!string.IsNullOrEmpty(trialQuota))
            {
                if (int.TryParse(trialQuota, out var trialQuotaId))
                {
                    var dueDate = DateTime.MaxValue;
                    if (int.TryParse(Configuration["trial-due"], out var dueTrial))
                    {
                        dueDate = DateTime.UtcNow.AddDays(dueTrial);
                    }

                    var tariff = new Tariff
                    {
                        QuotaId = trialQuotaId,
                        DueDate = dueDate
                    };
                    HostedSolution.SetTariff(t.TenantId, tariff);
                }
            }


            var isFirst = true;
            string sendCongratulationsAddress = null;

            if (!string.IsNullOrEmpty(model.PasswordHash))
            {
                isFirst = !CommonMethods.SendCongratulations(Request.Scheme, t, model.SkipWelcome, out sendCongratulationsAddress);
            }
            else if (Configuration["core:base-domain"] == "localhost")
            {
                try
                {
                    /* set wizard not completed*/
                    TenantManager.SetCurrentTenant(t);

                    var settings = SettingsManager.Load<WizardSettings>();

                    settings.Completed = false;

                    SettingsManager.Save(settings);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }

            var reference = CommonMethods.CreateReference(Request.Scheme, t.GetTenantDomain(CoreSettings), info.Email, isFirst);

            Log.DebugFormat("PortalName = {0}; Elapsed ms. CreateReferenceByCookie...: {1}", model.PortalName, sw.ElapsedMilliseconds);

            sw.Stop();

            return Ok(new
            {
                reference,
                tenant = CommonMethods.ToTenantWrapper(t),
                referenceWelcome = sendCongratulationsAddress
            });
        }
예제 #26
0
        public IActionResult Register(TenantModel model)
        {
            if (model == null)
            {
                return(BadRequest(new
                {
                    errors = "Tenant data is required."
                }));
            }

            if (!ModelState.IsValid)
            {
                var errors = new JArray();

                foreach (var k in ModelState.Keys)
                {
                    errors.Add(ModelState[k].Errors.FirstOrDefault().ErrorMessage);
                }

                return(Ok(new
                {
                    errors
                }));
            }

            var sw = Stopwatch.StartNew();

            object error;

            if (string.IsNullOrEmpty(model.PasswordHash) && !string.IsNullOrEmpty(model.Password))
            {
                if (!CheckPasswordPolicy(model.Password, out error))
                {
                    sw.Stop();

                    return(BadRequest(error));
                }
                model.PasswordHash = PasswordHasher.GetClientPassword(model.Password);
            }

            if (!CheckValidName(model.FirstName.Trim() + model.LastName.Trim(), out error))
            {
                sw.Stop();

                return(BadRequest(error));
            }

            var checkTenantBusyPesp = CheckExistingNamePortal(model.PortalName.Trim());

            if (checkTenantBusyPesp != null)
            {
                sw.Stop();

                return(checkTenantBusyPesp);
            }

            Log.DebugFormat("PortalName = {0}; Elapsed ms. CheckExistingNamePortal: {1}", model.PortalName, sw.ElapsedMilliseconds);

            var clientIP = CommonMethods.GetClientIp();

            Log.DebugFormat("clientIP = {0}", clientIP);

            if (CommonMethods.CheckMuchRegistration(model, clientIP, sw))
            {
                return(BadRequest(new
                {
                    errors = new[] { "tooMuchAttempts" }
                }));
            }

            if (CommonConstants.RecaptchaRequired && !CommonMethods.IsTestEmail(model.Email))
            {
                /*** validate recaptcha ***/
                if (!CommonMethods.ValidateRecaptcha(model.RecaptchaResponse, clientIP))
                {
                    Log.DebugFormat("PortalName = {0}; Elapsed ms. ValidateRecaptcha: {1}", model.PortalName, sw.ElapsedMilliseconds);

                    sw.Stop();

                    return(BadRequest(new
                    {
                        errors = new[] { "recaptchaInvalid" },
                        message = "Recaptcha is invalid"
                    }));
                }

                Log.DebugFormat("PortalName = {0}; Elapsed ms. ValidateRecaptcha: {1}", model.PortalName, sw.ElapsedMilliseconds);
            }

            //check payment portal count
            if (Configuration["core:base-domain"] == "localhost")
            {
                var tenants     = HostedSolution.GetTenants(DateTime.MinValue);
                var firstTenant = tenants.FirstOrDefault();

                if (firstTenant != null)
                {
                    var activePortals = tenants.Count(r => r.Status != TenantStatus.Suspended && r.Status != TenantStatus.RemovePending);

                    var quota = HostedSolution.GetTenantQuota(firstTenant.TenantId);

                    if (quota.CountPortals > 0 && quota.CountPortals <= activePortals)
                    {
                        return(BadRequest(new
                        {
                            errors = new[] { "portalsCountTooMuch" },
                            message = "Too much portals registered already",
                        }));
                    }
                }
            }

            var language = model.Language ?? string.Empty;

            var tz = TimeZonesProvider.GetCurrentTimeZoneInfo(language);

            Log.DebugFormat("PortalName = {0}; Elapsed ms. TimeZonesProvider.GetCurrentTimeZoneInfo: {1}", model.PortalName, sw.ElapsedMilliseconds);

            if (!string.IsNullOrEmpty(model.TimeZoneName))
            {
                tz = TimeZoneConverter.GetTimeZone(model.TimeZoneName.Trim(), false) ?? tz;

                Log.DebugFormat("PortalName = {0}; Elapsed ms. TimeZonesProvider.OlsonTimeZoneToTimeZoneInfo: {1}", model.PortalName, sw.ElapsedMilliseconds);
            }

            var lang = TimeZonesProvider.GetCurrentCulture(language);

            Log.DebugFormat("PortalName = {0}; model.Language = {1}, resultLang.DisplayName = {2}", model.PortalName, language, lang.DisplayName);

            var info = new TenantRegistrationInfo
            {
                Name                = Configuration["web:portal-name"] ?? "Cloud Office Applications",
                Address             = model.PortalName,
                Culture             = lang,
                FirstName           = model.FirstName.Trim(),
                LastName            = model.LastName.Trim(),
                PasswordHash        = String.IsNullOrEmpty(model.PasswordHash) ? null : model.PasswordHash,
                Email               = model.Email.Trim(),
                TimeZoneInfo        = tz,
                MobilePhone         = string.IsNullOrEmpty(model.Phone) ? null : model.Phone.Trim(),
                Industry            = (TenantIndustry)model.Industry,
                Spam                = model.Spam,
                Calls               = model.Calls,
                Analytics           = model.Analytics,
                LimitedControlPanel = model.LimitedControlPanel
            };

            if (!string.IsNullOrEmpty(model.PartnerId))
            {
                if (Guid.TryParse(model.PartnerId, out Guid guid))
                {
                    // valid guid
                    info.PartnerId = model.PartnerId;
                }
            }

            if (!string.IsNullOrEmpty(model.AffiliateId))
            {
                info.AffiliateId = model.AffiliateId;
            }

            Tenant t;

            try
            {
                /****REGISTRATION!!!*****/
                if (!string.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl))
                {
                    ApiSystemHelper.AddTenantToCache(info.Address, SecurityContext.CurrentAccount.ID);

                    Log.DebugFormat("PortalName = {0}; Elapsed ms. CacheController.AddTenantToCache: {1}", model.PortalName, sw.ElapsedMilliseconds);
                }

                HostedSolution.RegisterTenant(info, out t);

                /*********/

                Log.DebugFormat("PortalName = {0}; Elapsed ms. HostedSolution.RegisterTenant: {1}", model.PortalName, sw.ElapsedMilliseconds);
            }
            catch (Exception e)
            {
                sw.Stop();

                Log.Error(e);

                return(StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    errors = new[] { "registerNewTenantError" },
                    message = e.Message,
                    stacktrace = e.StackTrace
                }));
            }

            var isFirst = true;

            string sendCongratulationsAddress = null;

            if (!String.IsNullOrEmpty(model.PasswordHash))
            {
                isFirst = !CommonMethods.SendCongratulations(Request.Scheme, t, model.SkipWelcome, out sendCongratulationsAddress);
            }
            else if (Configuration["core:base-domain"] == "localhost")
            {
                try
                {
                    /* set wizard not completed*/
                    TenantManager.SetCurrentTenant(t);

                    var settings = SettingsManager.Load <WizardSettings>();

                    settings.Completed = false;

                    SettingsManager.Save(settings);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }

            var reference = CommonMethods.CreateReference(Request.Scheme, t.GetTenantDomain(CoreSettings), info.Email, isFirst, model.Module);

            Log.DebugFormat("PortalName = {0}; Elapsed ms. CreateReferenceByCookie...: {1}", model.PortalName, sw.ElapsedMilliseconds);

            sw.Stop();

            return(Ok(new
            {
                errors = "",
                reference,
                tenant = ToTenantWrapper(t),
                referenceWelcome = sendCongratulationsAddress,
            }));
        }
예제 #27
0
        public IActionResult GetPortals([FromQuery] TenantModel model)
        {
            try
            {
                var tenants = new List<Tenant>();
                var empty = true;

                if (!string.IsNullOrEmpty((model.Email ?? "").Trim()))
                {
                    empty = false;
                    tenants.AddRange(HostedSolution.FindTenants((model.Email ?? "").Trim()));
                }

                if (!string.IsNullOrEmpty((model.PortalName ?? "").Trim()))
                {
                    empty = false;
                    var tenant = HostedSolution.GetTenant((model.PortalName ?? "").Trim());

                    if (tenant != null)
                    {
                        tenants.Add(tenant);
                    }
                }

                if (model.TenantId.HasValue)
                {
                    empty = false;
                    var tenant = HostedSolution.GetTenant(model.TenantId.Value);

                    if (tenant != null)
                    {
                        tenants.Add(tenant);
                    }
                }

                if (empty)
                {
                    tenants.AddRange(HostedSolution.GetTenants(DateTime.MinValue).OrderBy(t => t.TenantId).ToList());
                }

                var tenantsWrapper = tenants
                    .Distinct()
                    .Where(t => t.Status == TenantStatus.Active)
                    .OrderBy(t => t.TenantId)
                    .Select(CommonMethods.ToTenantWrapper);

                return Ok(new
                {
                    tenants = tenantsWrapper
                });
            }
            catch (Exception ex)
            {
                Log.Error(ex);

                return StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    error = "error",
                    message = ex.Message,
                    stacktrace = ex.StackTrace
                });
            }
        }
예제 #28
0
 public void FindTenants()
 {
     var h = new HostedSolution(ConfigurationManager.ConnectionStrings["core"]);
     var tenants = h.FindTenants("76ff727b-f987-4871-9834-e63d4420d6e9");
     Assert.AreNotEqual(0, tenants.Count);
 }