private TimeZoneInfo GetTimeZone(string zoneId)
        {
            if (defaultTimeZone == null)
            {
                try
                {
                    var tz = TimeZoneInfo.Local;
                    if (Path.DirectorySeparatorChar == '/')
                    {
                        if (tz.StandardName == "UTC" || tz.StandardName == "UCT")
                        {
                            tz = TimeZoneInfo.Utc;
                        }
                        else
                        {
                            var file = File.Exists("/etc/timezone") ? "/etc/timezone" : "/etc/localtime";
                            var id   = File.ReadAllText(file).Trim();
                            tz = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(z => z.Id == id) ?? tz;
                        }
                    }
                    defaultTimeZone = tz;
                }
                catch (Exception)
                {
                    // ignore
                    defaultTimeZone = TimeZoneInfo.Utc;
                }
            }

            return(string.IsNullOrEmpty(zoneId) ? defaultTimeZone : TimeZoneConverter.GetTimeZone(zoneId));
        }
示例#2
0
        public CalendarWrapper UpdateCalendarView(string calendarId, string name, string textColor, string backgroundColor, string timeZone, EventAlertType alertType, bool hideEvents)
        {
            TimeZoneInfo timeZoneInfo = TimeZoneConverter.GetTimeZone(timeZone);

            name = (name ?? "").Trim();
            if (String.IsNullOrEmpty(name))
            {
                throw new Exception(Resources.CalendarApiResource.ErrorEmptyName);
            }

            var settings = new UserViewSettings()
            {
                BackgroundColor = backgroundColor,
                CalendarId      = calendarId,
                IsHideEvents    = hideEvents,
                TextColor       = textColor,
                EventAlertType  = alertType,
                IsAccepted      = true,
                UserId          = SecurityContext.CurrentAccount.ID,
                Name            = name,
                TimeZone        = timeZoneInfo
            };

            _dataProvider.UpdateCalendarUserView(settings);
            return(GetCalendarById(calendarId));
        }
        public static BaseCalendar ConvertCalendar(DDay.iCal.IICalendar calandarObj)
        {
            if (calandarObj == null)
            {
                return(null);
            }

            var result = new BusinessObjects.Calendar();

            result.Name = string.IsNullOrEmpty(calandarObj.Name)
                           ? calandarObj.Properties.ContainsKey("X-WR-CALNAME")
                                 ? calandarObj.Properties["X-WR-CALNAME"].Value.ToString()
                                 : string.Empty
                           : calandarObj.Name;

            result.Description = calandarObj.Properties.ContainsKey("X-WR-CALDESC")
                                     ? calandarObj.Properties["X-WR-CALDESC"].Value.ToString()
                                     : string.Empty;

            var tzids = calandarObj.TimeZones.Select(x => x.TZID).Where(x => !string.IsNullOrEmpty(x)).ToList();

            result.TimeZone = tzids.Any()
                                  ? TimeZoneConverter.GetTimeZone(tzids.First())
                                  : (calandarObj.Properties.ContainsKey("X-WR-TIMEZONE")
                                         ? TimeZoneConverter.GetTimeZone(
                                         calandarObj.Properties["X-WR-TIMEZONE"].Value.ToString())
                                         : CoreContext.TenantManager.GetCurrentTenant().TimeZone);

            return(result);
        }
示例#4
0
 private TimeZoneInfo GetTimeZone(string zoneId)
 {
     if (!string.IsNullOrEmpty(zoneId))
     {
         return(TimeZoneConverter.GetTimeZone(zoneId));
     }
     return(TimeZoneInfo.Utc);
 }
示例#5
0
        private TimeZoneInfo GetTimeZone(string zoneId)
        {
            if (defaultTimeZone == null)
            {
                try
                {
                    var tz = TimeZoneInfo.Local;
                    if (Path.DirectorySeparatorChar == '/')
                    {
                        if (tz.StandardName == "UTC" || tz.StandardName == "UCT")
                        {
                            tz = TimeZoneInfo.Utc;
                        }
                        else
                        {
                            var id = string.Empty;
                            if (File.Exists("/etc/timezone"))
                            {
                                id = File.ReadAllText("/etc/timezone").Trim();
                            }

                            if (string.IsNullOrEmpty(id))
                            {
                                var psi = new ProcessStartInfo
                                {
                                    FileName  = "/bin/bash",
                                    Arguments = "date +%Z",
                                    RedirectStandardOutput = true,
                                    UseShellExecute        = false,
                                };
                                using (var p = Process.Start(psi))
                                {
                                    if (p.WaitForExit(1000))
                                    {
                                        id = p.StandardOutput.ReadToEnd();
                                    }
                                    p.Close();
                                }
                            }
                            if (!string.IsNullOrEmpty(id))
                            {
                                tz = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(z => z.Id == id) ?? tz;
                            }
                        }
                    }
                    defaultTimeZone = tz;
                }
                catch (Exception)
                {
                    // ignore
                    defaultTimeZone = TimeZoneInfo.Utc;
                }
            }

            return(string.IsNullOrEmpty(zoneId) ? defaultTimeZone : TimeZoneConverter.GetTimeZone(zoneId));
        }
示例#6
0
 private static TimeZoneInfo GetTimeZoneInfo(TenantManager tenantManager, TimeZoneConverter timeZoneConverter)
 {
     var timeZone = TimeZoneInfo.Local;
     try
     {
         timeZone = timeZoneConverter.GetTimeZone(tenantManager.GetCurrentTenant().TimeZone);
     }
     catch (Exception)
     {
         //Tenant failed
     }
     return timeZone;
 }
        public static DateTime ToUtc(Ical.Net.Interfaces.DataTypes.IDateTime dateTime)
        {
            if (dateTime.IsUniversalTime || dateTime.TzId.Equals("UTC", StringComparison.InvariantCultureIgnoreCase))
            {
                return(dateTime.Value);
            }

            if (dateTime.AsUtc != dateTime.Value)
            {
                return(dateTime.AsUtc);
            }

            var timeZone = TimeZoneConverter.GetTimeZone(dateTime.TzId);
            var utcOffse = timeZone.GetUtcOffset(dateTime.Value);

            return(dateTime.Value - utcOffse);
        }
示例#8
0
        public DateTime ToUtc(Ical.Net.DataTypes.IDateTime dateTime)
        {
            if (dateTime.IsUtc || string.IsNullOrEmpty(dateTime.TzId) || dateTime.TzId.Equals("UTC", StringComparison.InvariantCultureIgnoreCase))
            {
                return(dateTime.Value);
            }

            if (dateTime.AsUtc != dateTime.Value)
            {
                return(dateTime.AsUtc);
            }

            var timeZone = TimeZoneConverter.GetTimeZone(dateTime.TzId);
            var utcOffse = timeZone.GetOffset();

            return(dateTime.Value - utcOffse);
        }
 private object ToTenantWrapper(Tenant t)
 {
     return(new
     {
         tenantId = t.TenantId,
         tenantAlias = t.TenantAlias,
         tenantDomain = t.GetTenantDomain(CoreSettings),
         hostedRegion = t.HostedRegion,
         name = t.Name,
         ownerId = t.OwnerId,
         status = t.Status,
         partnerId = t.PartnerId,
         paymentId = t.PaymentId,
         language = t.Language,
         industry = t.Industry,
         timeZoneName = TimeZoneConverter.GetTimeZone(t.TimeZone).DisplayName,
         createdDateTime = t.CreatedDateTime
     });
 }
示例#10
0
 public object ToTenantWrapper(Tenant t)
 {
     return(new
     {
         created = t.CreatedDateTime,
         domain = t.GetTenantDomain(CoreSettings),
         hostedRegion = t.HostedRegion,
         industry = t.Industry,
         language = t.Language,
         name = t.Name,
         ownerId = t.OwnerId,
         partnerId = t.PartnerId,
         paymentId = t.PaymentId,
         portalName = t.TenantAlias,
         status = t.Status.ToString(),
         tenantId = t.TenantId,
         timeZoneName = TimeZoneConverter.GetTimeZone(t.TimeZone).DisplayName,
     });
 }
示例#11
0
        /* public BaseCalendar ConvertCalendar(Ical.Net.Calendar calandarObj)
         * {
         *   if (calandarObj == null) return null;
         *
         *   var icalendar = new iCalendar(AuthContext, TimeZoneConverter, TenantManager);
         *   var result = new BusinessObjects.Calendar(AuthContext, TimeZoneConverter, icalendar, DataProvider);
         *
         *   result.Name = string.IsNullOrEmpty(calandarObj.Name)
         *                  ? calandarObj.Properties.ContainsKey("X-WR-CALNAME")
         *                        ? calandarObj.Properties["X-WR-CALNAME"].Value.ToString()
         *                        : string.Empty
         *                  : calandarObj.Name;
         *
         *   result.Description = calandarObj.Properties.ContainsKey("X-WR-CALDESC")
         *                            ? calandarObj.Properties["X-WR-CALDESC"].Value.ToString()
         *                            : string.Empty;
         *
         *   var tzids = calandarObj.TimeZones.Select(x => x.TzId).Where(x => !string.IsNullOrEmpty(x)).ToList();
         *
         *   result.TimeZone = tzids.Any()
         *                         ? TimeZoneConverter.GetTimeZone(tzids.First())
         *                         : (calandarObj.Properties.ContainsKey("X-WR-TIMEZONE")
         *                                ? TimeZoneConverter.GetTimeZone(
         *                                    calandarObj.Properties["X-WR-TIMEZONE"].Value.ToString())
         *                                : TimeZoneConverter.GetTimeZone(TenantManager.GetCurrentTenant().TimeZone));
         *
         *   return result;
         * }*/

        public Ical.Net.Calendar ConvertCalendar(BaseCalendar calandarObj)
        {
            if (calandarObj == null)
            {
                return(null);
            }

            var result = new Ical.Net.Calendar();

            result.Method    = Ical.Net.CalendarMethods.Publish;
            result.Scale     = Ical.Net.CalendarScales.Gregorian;
            result.Version   = Ical.Net.LibraryMetadata.Version;
            result.ProductId = "-//Ascensio System//OnlyOffice Calendar//EN";

            if (!string.IsNullOrEmpty(calandarObj.Name))
            {
                result.AddProperty("X-WR-CALNAME", calandarObj.Name);
            }

            if (!string.IsNullOrEmpty(calandarObj.Description))
            {
                result.AddProperty("X-WR-CALDESC", calandarObj.Description);
            }

            if (calandarObj.TimeZone == null)
            {
                calandarObj.TimeZone = TimeZoneConverter.GetTimeZone(TenantManager.GetCurrentTenant().TimeZone);
            }

            var olsonTzId = TimeZoneConverter.WindowsTzId2OlsonTzId(calandarObj.TimeZone.Id);
            var olsonTz   = olsonTzId == calandarObj.TimeZone.Id
                              ? calandarObj.TimeZone
                              : TimeZoneInfo.CreateCustomTimeZone(olsonTzId,
                                                                  calandarObj.TimeZone.GetOffset(true),
                                                                  calandarObj.TimeZone.DisplayName,
                                                                  calandarObj.TimeZone.StandardName);

            result.AddTimeZone(Ical.Net.CalendarComponents.VTimeZone.FromSystemTimeZone(olsonTz));
            result.AddProperty("X-WR-TIMEZONE", olsonTzId);

            return(result);
        }
示例#12
0
            public T Parse <T>(object[] row)
            {
                if (typeof(T).Equals(typeof(int)))
                {
                    return((T)((object)Convert.ToInt32(row[this.Ind])));
                }

                if (typeof(T).Equals(typeof(Guid)))
                {
                    return((T)((object)new Guid(Convert.ToString(row[this.Ind]))));
                }

                if (typeof(T).Equals(typeof(Boolean)))
                {
                    return((T)((object)(Convert.ToBoolean(row[this.Ind]))));
                }

                if (typeof(T).Equals(typeof(DateTime)))
                {
                    return((T)((object)Convert.ToDateTime(row[this.Ind])));
                }

                if (typeof(T).Equals(typeof(RecurrenceRule)))
                {
                    return((T)((object)RecurrenceRule.Parse(Convert.ToString(row[this.Ind]))));
                }

                if (typeof(T).Equals(typeof(TimeZoneInfo)))
                {
                    if (IsNull(row))
                    {
                        return((T)(object)null);
                    }

                    var timeZoneId = Convert.ToString(row[this.Ind]);

                    return((T)((object)TimeZoneConverter.GetTimeZone(timeZoneId)));
                }

                return((T)(object)(Convert.ToString(row[this.Ind]) ?? ""));
            }
示例#13
0
        public CalendarWrapper CreateCalendar(string name, string description, string textColor, string backgroundColor, string timeZone, EventAlertType alertType, List <SharingParam> sharingOptions)
        {
            var sharingOptionsList = sharingOptions ?? new List <SharingParam>();
            var timeZoneInfo       = TimeZoneConverter.GetTimeZone(timeZone);

            name = (name ?? "").Trim();
            if (String.IsNullOrEmpty(name))
            {
                throw new Exception(Resources.CalendarApiResource.ErrorEmptyName);
            }

            description     = (description ?? "").Trim();
            textColor       = (textColor ?? "").Trim();
            backgroundColor = (backgroundColor ?? "").Trim();

            var cal = _dataProvider.CreateCalendar(
                SecurityContext.CurrentAccount.ID, name, description, textColor, backgroundColor, timeZoneInfo, alertType, null,
                sharingOptionsList.Select(o => o as SharingOptions.PublicItem).ToList(),
                new List <UserViewSettings>());

            if (cal != null)
            {
                foreach (var opt in sharingOptionsList)
                {
                    if (String.Equals(opt.actionId, AccessOption.FullAccessOption.Id, StringComparison.InvariantCultureIgnoreCase))
                    {
                        CoreContext.AuthorizationManager.AddAce(new AzRecord(opt.Id, CalendarAccessRights.FullAccessAction.ID, ASC.Common.Security.Authorizing.AceType.Allow, cal));
                    }
                }

                //notify
                CalendarNotifyClient.NotifyAboutSharingCalendar(cal);

                return(new CalendarWrapper(cal));
            }
            return(null);
        }
示例#14
0
        public void doAttribute(Token key, Token val)
        {
            if (_component.Count <= 0)
            {
                return;
            }

            //event timezone
            if ((_curPropToken.TokenVal == TokenValue.Tdtstart || _curPropToken.TokenVal == TokenValue.Tdtend) && _component.Peek().TokenVal == TokenValue.Tvevent)
            {
                switch (key.TokenText.ToLower())
                {
                case "tzid":

                    var tz = TimeZoneConverter.GetTimeZone(val.TokenText);
                    if (_curPropToken.TokenVal == TokenValue.Tdtstart)
                    {
                        _curEvent.UtcStartDate = _curEvent.OriginalStartDate.AddMinutes((-1) * (int)tz.BaseUtcOffset.TotalMinutes);
                    }

                    else if (_curPropToken.TokenVal == TokenValue.Tdtend)
                    {
                        _curEvent.UtcEndDate = _curEvent.OriginalEndDate.AddMinutes((-1) * (int)tz.BaseUtcOffset.TotalMinutes);
                    }

                    break;
                }
            }

            //event rrule
            if (_curPropToken.TokenVal == TokenValue.Trrule && _component.Peek().TokenVal == TokenValue.Tvevent)
            {
                switch (key.TokenText.ToLower())
                {
                case "freq":
                    _curEvent.RecurrenceRule.Freq = RecurrenceRule.ParseFrequency(val.TokenText);
                    break;

                case "until":
                    bool isDate, isUTC;
                    _curEvent.RecurrenceRule.Until = Token.ParseDateTime(val.TokenText, out isDate, out isUTC);
                    break;

                case "count":
                    _curEvent.RecurrenceRule.Count = Convert.ToInt32(val.TokenText);
                    break;

                case "interval":
                    _curEvent.RecurrenceRule.Interval = Convert.ToInt32(val.TokenText);
                    break;

                case "bysecond":
                    _curEvent.RecurrenceRule.BySecond = val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray();
                    break;

                case "byminute":
                    _curEvent.RecurrenceRule.ByMinute = val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray();
                    break;

                case "byhour":
                    _curEvent.RecurrenceRule.ByHour = val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray();
                    break;

                case "byday":
                    _curEvent.RecurrenceRule.ByDay = val.TokenText.Split(',').Select(v => RecurrenceRule.WeekDay.Parse(v)).ToArray();
                    break;

                case "bymonthday":
                    _curEvent.RecurrenceRule.ByMonthDay = val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray();
                    break;

                case "byyearday":
                    _curEvent.RecurrenceRule.ByYearDay = val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray();
                    break;

                case "byweekno":
                    _curEvent.RecurrenceRule.ByWeekNo = val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray();
                    break;

                case "bymonth":
                    _curEvent.RecurrenceRule.ByMonth = val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray();
                    break;

                case "bysetpos":
                    _curEvent.RecurrenceRule.BySetPos = val.TokenText.Split(',').Select(v => Convert.ToInt32(v)).ToArray();
                    break;

                case "wkst":
                    _curEvent.RecurrenceRule.WKST = RecurrenceRule.WeekDay.Parse(val.TokenText);
                    break;
                }
            }
        }
        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,
            }));
        }
示例#16
0
 public DateTime DateTimeFromUtc(string timeZone, DateTime utc)
 {
     return(DateTimeFromUtc(TimeZoneConverter.GetTimeZone(timeZone), utc));
 }
示例#17
0
 public DateTime DateTimeNow(string timeZone)
 {
     return(DateTimeNow(TimeZoneConverter.GetTimeZone(timeZone)));
 }
示例#18
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
            });
        }
        public WizardSettings SaveData(WizardModel wizardModel)
        {
            try
            {
                var(email, passwordHash, lng, timeZone, promocode, amiid, analytics, subscribeFromSite) = wizardModel;

                var tenant   = TenantManager.GetCurrentTenant();
                var settings = SettingsManager.Load <WizardSettings>();
                if (settings.Completed)
                {
                    throw new Exception("Wizard passed.");
                }

                if (!string.IsNullOrEmpty(SetupInfo.AmiMetaUrl) && IncorrectAmiId(amiid))
                {
                    //throw new Exception(Resource.EmailAndPasswordIncorrectAmiId); TODO
                }

                if (tenant.OwnerId == Guid.Empty)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(6)); // wait cache interval
                    tenant = TenantManager.GetTenant(tenant.TenantId);
                    if (tenant.OwnerId == Guid.Empty)
                    {
                        Log.Error(tenant.TenantId + ": owner id is empty.");
                    }
                }

                var currentUser = UserManager.GetUsers(TenantManager.GetCurrentTenant().OwnerId);

                if (!UserManagerWrapper.ValidateEmail(email))
                {
                    throw new Exception(Resource.EmailAndPasswordIncorrectEmail);
                }

                if (string.IsNullOrEmpty(passwordHash))
                {
                    throw new Exception(Resource.ErrorPasswordEmpty);
                }

                SecurityContext.SetUserPasswordHash(currentUser.ID, passwordHash);

                email = email.Trim();
                if (currentUser.Email != email)
                {
                    currentUser.Email            = email;
                    currentUser.ActivationStatus = EmployeeActivationStatus.NotActivated;
                }
                UserManager.SaveUserInfo(currentUser);

                if (!string.IsNullOrWhiteSpace(promocode))
                {
                    try
                    {
                        PaymentManager.ActivateKey(promocode);
                    }
                    catch (Exception err)
                    {
                        Log.Error("Incorrect Promo: " + promocode, err);
                        throw new Exception(Resource.EmailAndPasswordIncorrectPromocode);
                    }
                }

                if (RequestLicense)
                {
                    TariffSettings.SetLicenseAccept(SettingsManager);
                    MessageService.Send(MessageAction.LicenseKeyUploaded);

                    LicenseReader.RefreshLicense();
                }

                if (TenantExtra.Opensource)
                {
                    settings.Analytics = analytics;
                }
                settings.Completed = true;
                SettingsManager.Save(settings);

                TrySetLanguage(tenant, lng);

                tenant.TimeZone = TimeZoneConverter.GetTimeZone(timeZone).Id;

                TenantManager.SaveTenant(tenant);

                StudioNotifyService.SendCongratulations(currentUser);
                StudioNotifyService.SendRegData(currentUser);

                SendInstallInfo(currentUser);

                if (subscribeFromSite && TenantExtra.Opensource && !CoreBaseSettings.CustomMode)
                {
                    SubscribeFromSite(currentUser);
                }

                return(settings);
            }
            catch (BillingNotFoundException)
            {
                throw new Exception(UserControlsCommonResource.LicenseKeyNotFound);
            }
            catch (BillingNotConfiguredException)
            {
                throw new Exception(UserControlsCommonResource.LicenseKeyNotCorrect);
            }
            catch (BillingException)
            {
                throw new Exception(UserControlsCommonResource.LicenseException);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
        }
示例#20
0
        public CalendarWrapper UpdateCalendar(string calendarId, string name, string description, string textColor, string backgroundColor, string timeZone, EventAlertType alertType, bool hideEvents, List <SharingParam> sharingOptions)
        {
            TimeZoneInfo timeZoneInfo = TimeZoneConverter.GetTimeZone(timeZone);
            int          calId;

            if (int.TryParse(calendarId, out calId))
            {
                var oldCal = _dataProvider.GetCalendarById(calId);
                if (CheckPermissions(oldCal, CalendarAccessRights.FullAccessAction, true))
                {
                    //update calendar and share options
                    var sharingOptionsList = sharingOptions ?? new List <SharingParam>();

                    name = (name ?? "").Trim();
                    if (String.IsNullOrEmpty(name))
                    {
                        throw new Exception(Resources.CalendarApiResource.ErrorEmptyName);
                    }

                    description     = (description ?? "").Trim();
                    textColor       = (textColor ?? "").Trim();
                    backgroundColor = (backgroundColor ?? "").Trim();


                    //view
                    var userOptions = oldCal.ViewSettings;
                    var usrOpt      = userOptions.Find(o => o.UserId.Equals(SecurityContext.CurrentAccount.ID));
                    if (usrOpt == null)
                    {
                        userOptions.Add(new UserViewSettings()
                        {
                            Name            = name,
                            TextColor       = textColor,
                            BackgroundColor = backgroundColor,
                            EventAlertType  = alertType,
                            IsAccepted      = true,
                            UserId          = SecurityContext.CurrentAccount.ID,
                            TimeZone        = timeZoneInfo
                        });
                    }
                    else
                    {
                        usrOpt.Name            = name;
                        usrOpt.TextColor       = textColor;
                        usrOpt.BackgroundColor = backgroundColor;
                        usrOpt.EventAlertType  = alertType;
                        usrOpt.TimeZone        = timeZoneInfo;
                    }

                    userOptions.RemoveAll(o => !o.UserId.Equals(oldCal.OwnerId) & !sharingOptionsList.Exists(opt => (!opt.IsGroup && o.UserId.Equals(opt.Id)) ||
                                                                                                             opt.IsGroup && CoreContext.UserManager.IsUserInGroup(o.UserId, opt.Id)));

                    //check owner
                    if (!oldCal.OwnerId.Equals(SecurityContext.CurrentAccount.ID))
                    {
                        name        = oldCal.Name;
                        description = oldCal.Description;
                    }

                    var cal = _dataProvider.UpdateCalendar(calId, name, description,
                                                           sharingOptionsList.Select(o => o as SharingOptions.PublicItem).ToList(),
                                                           userOptions);
                    if (cal != null)
                    {
                        //clear old rights
                        CoreContext.AuthorizationManager.RemoveAllAces(cal);

                        foreach (var opt in sharingOptionsList)
                        {
                            if (String.Equals(opt.actionId, AccessOption.FullAccessOption.Id, StringComparison.InvariantCultureIgnoreCase))
                            {
                                CoreContext.AuthorizationManager.AddAce(new AzRecord(opt.Id, CalendarAccessRights.FullAccessAction.ID, ASC.Common.Security.Authorizing.AceType.Allow, cal));
                            }
                        }

                        //notify
                        CalendarNotifyClient.NotifyAboutSharingCalendar(cal, oldCal);
                        return(new CalendarWrapper(cal));
                    }
                    return(null);
                }
            }

            //update view
            return(UpdateCalendarView(calendarId, name, textColor, backgroundColor, timeZone, alertType, hideEvents));
        }