DocSpace-client/web/ASC.Web.Api/Controllers/SettingsController.cs

2915 lines
114 KiB
C#
Raw Normal View History

2019-08-12 10:53:12 +00:00
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using System.Net;
2020-07-24 14:01:20 +00:00
using System.Net.Mail;
using System.Security;
2019-08-12 10:53:12 +00:00
using System.ServiceModel.Security;
using System.Text.RegularExpressions;
2019-08-12 10:53:12 +00:00
using System.Web;
2019-08-12 10:53:12 +00:00
using ASC.Api.Collections;
using ASC.Api.Core;
using ASC.Api.Utils;
2020-02-17 08:58:14 +00:00
using ASC.Common;
2020-09-17 13:56:12 +00:00
using ASC.Common.Caching;
2019-08-12 10:53:12 +00:00
using ASC.Common.Logging;
2019-12-03 15:20:21 +00:00
using ASC.Common.Utils;
2019-08-12 10:53:12 +00:00
using ASC.Core;
using ASC.Core.Billing;
using ASC.Core.Common.Configuration;
2020-09-24 14:30:27 +00:00
using ASC.Core.Common.Notify;
2019-10-31 13:54:43 +00:00
using ASC.Core.Common.Settings;
2020-12-28 13:22:08 +00:00
using ASC.Core.Encryption;
2019-08-12 10:53:12 +00:00
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Data.Backup;
2020-09-17 13:56:12 +00:00
using ASC.Data.Backup.Contracts;
2020-09-18 17:57:51 +00:00
using ASC.Data.Backup.Service;
2019-09-13 11:18:27 +00:00
using ASC.Data.Storage;
2019-08-12 10:53:12 +00:00
using ASC.Data.Storage.Configuration;
2020-09-07 15:04:26 +00:00
using ASC.Data.Storage.Encryption;
2019-08-12 10:53:12 +00:00
using ASC.Data.Storage.Migration;
using ASC.FederatedLogin.LoginProviders;
2019-08-12 10:53:12 +00:00
using ASC.IPSecurity;
using ASC.MessagingSystem;
2019-09-17 12:42:32 +00:00
using ASC.Security.Cryptography;
2019-08-12 10:53:12 +00:00
using ASC.Web.Api.Models;
using ASC.Web.Api.Routing;
using ASC.Web.Core;
using ASC.Web.Core.PublicResources;
using ASC.Web.Core.Sms;
2019-09-09 12:56:33 +00:00
using ASC.Web.Core.Users;
2019-08-12 10:53:12 +00:00
using ASC.Web.Core.Utility;
using ASC.Web.Core.Utility.Settings;
using ASC.Web.Core.WebZones;
using ASC.Web.Core.WhiteLabel;
using ASC.Web.Studio.Core;
using ASC.Web.Studio.Core.Notify;
using ASC.Web.Studio.Core.Quota;
using ASC.Web.Studio.Core.SMS;
using ASC.Web.Studio.Core.Statistic;
using ASC.Web.Studio.Core.TFA;
using ASC.Web.Studio.UserControls.CustomNavigation;
2020-07-02 14:11:59 +00:00
using ASC.Web.Studio.UserControls.FirstTime;
using ASC.Web.Studio.UserControls.Management;
2019-09-09 12:56:33 +00:00
using ASC.Web.Studio.UserControls.Statistics;
2019-08-12 10:53:12 +00:00
using ASC.Web.Studio.Utility;
using Google.Authenticator;
2019-08-12 10:53:12 +00:00
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
2020-09-17 13:56:12 +00:00
using Microsoft.AspNetCore.Http;
2019-08-12 10:53:12 +00:00
using Microsoft.AspNetCore.Mvc;
2020-07-24 14:01:20 +00:00
using Microsoft.Extensions.Caching.Memory;
2019-09-23 12:20:08 +00:00
using Microsoft.Extensions.Configuration;
2019-10-17 15:55:35 +00:00
using Microsoft.Extensions.Options;
2019-08-12 10:53:12 +00:00
namespace ASC.Api.Settings
{
2020-10-19 15:53:15 +00:00
[Scope]
2019-11-06 15:03:09 +00:00
[DefaultRoute]
2019-08-12 10:53:12 +00:00
[ApiController]
public partial class SettingsController : ControllerBase
{
2019-10-14 08:23:45 +00:00
//private const int ONE_THREAD = 1;
2019-08-12 10:53:12 +00:00
2019-10-14 08:23:45 +00:00
//private static readonly DistributedTaskQueue quotaTasks = new DistributedTaskQueue("quotaOperations", ONE_THREAD);
//private static DistributedTaskQueue LDAPTasks { get; } = new DistributedTaskQueue("ldapOperations");
//private static DistributedTaskQueue SMTPTasks { get; } = new DistributedTaskQueue("smtpOperations");
2019-08-12 10:53:12 +00:00
public Tenant Tenant { get { return ApiContext.Tenant; } }
public ApiContext ApiContext { get; }
2020-08-12 09:58:08 +00:00
private MessageService MessageService { get; }
private StudioNotifyService StudioNotifyService { get; }
private IWebHostEnvironment WebHostEnvironment { get; }
private IServiceProvider ServiceProvider { get; }
private EmployeeWraperHelper EmployeeWraperHelper { get; }
private ConsumerFactory ConsumerFactory { get; }
private SmsProviderManager SmsProviderManager { get; }
private TimeZoneConverter TimeZoneConverter { get; }
private CustomNamingPeople CustomNamingPeople { get; }
private IPSecurity.IPSecurity IpSecurity { get; }
private IMemoryCache MemoryCache { get; }
private ProviderManager ProviderManager { get; }
private FirstTimeTenantSettings FirstTimeTenantSettings { get; }
2020-08-12 09:58:08 +00:00
private UserManager UserManager { get; }
private TenantManager TenantManager { get; }
private TenantExtra TenantExtra { get; }
private TenantStatisticsProvider TenantStatisticsProvider { get; }
private AuthContext AuthContext { get; }
private CookiesManager CookiesManager { get; }
private WebItemSecurity WebItemSecurity { get; }
private StudioNotifyHelper StudioNotifyHelper { get; }
private LicenseReader LicenseReader { get; }
private PermissionContext PermissionContext { get; }
private SettingsManager SettingsManager { get; }
private TfaManager TfaManager { get; }
private WebItemManager WebItemManager { get; }
private WebItemManagerSecurity WebItemManagerSecurity { get; }
private TenantInfoSettingsHelper TenantInfoSettingsHelper { get; }
private TenantWhiteLabelSettingsHelper TenantWhiteLabelSettingsHelper { get; }
private StorageHelper StorageHelper { get; }
private TenantLogoManager TenantLogoManager { get; }
private TenantUtil TenantUtil { get; }
private CoreBaseSettings CoreBaseSettings { get; }
private CommonLinkUtility CommonLinkUtility { get; }
private ColorThemesSettingsHelper ColorThemesSettingsHelper { get; }
private IConfiguration Configuration { get; }
private SetupInfo SetupInfo { get; }
private BuildVersion BuildVersion { get; }
private DisplayUserSettingsHelper DisplayUserSettingsHelper { get; }
private StatisticManager StatisticManager { get; }
private IPRestrictionsService IPRestrictionsService { get; }
private CoreConfiguration CoreConfiguration { get; }
private MessageTarget MessageTarget { get; }
private StudioSmsNotificationSettingsHelper StudioSmsNotificationSettingsHelper { get; }
private CoreSettings CoreSettings { get; }
private StorageSettingsHelper StorageSettingsHelper { get; }
2020-08-24 06:52:17 +00:00
private ServiceClient ServiceClient { get; }
2020-09-17 12:04:28 +00:00
private StorageFactory StorageFactory { get; }
2020-09-22 14:17:17 +00:00
private UrlShortener UrlShortener { get; }
2020-09-07 15:04:26 +00:00
private EncryptionServiceClient EncryptionServiceClient { get; }
2020-09-17 13:56:12 +00:00
private EncryptionSettingsHelper EncryptionSettingsHelper { get; }
2020-09-18 17:57:51 +00:00
private BackupServiceNotifier BackupServiceNotifier { get; }
2020-09-17 13:56:12 +00:00
private ICacheNotify<DeleteSchedule> CacheDeleteSchedule { get; }
2020-09-18 17:57:51 +00:00
private EncryptionServiceNotifier EncryptionServiceNotifier { get; }
2020-09-29 15:08:54 +00:00
private PasswordHasher PasswordHasher { get; }
2020-09-18 17:57:51 +00:00
private ILog Log { get; set; }
2020-09-24 14:30:27 +00:00
private TelegramHelper TelegramHelper { get; }
private BackupAjaxHandler BackupAjaxHandler { get; }
2020-12-28 13:22:08 +00:00
private PaymentManager PaymentManager { get; }
2019-08-12 10:53:12 +00:00
2019-09-18 12:14:15 +00:00
public SettingsController(
2019-11-06 15:03:09 +00:00
IOptionsMonitor<ILog> option,
2019-08-12 10:53:12 +00:00
MessageService messageService,
StudioNotifyService studioNotifyService,
2019-09-09 12:56:33 +00:00
ApiContext apiContext,
UserManager userManager,
TenantManager tenantManager,
TenantExtra tenantExtra,
TenantStatisticsProvider tenantStatisticsProvider,
AuthContext authContext,
CookiesManager cookiesManager,
WebItemSecurity webItemSecurity,
StudioNotifyHelper studioNotifyHelper,
LicenseReader licenseReader,
2019-09-10 14:29:37 +00:00
PermissionContext permissionContext,
SettingsManager settingsManager,
TfaManager tfaManager,
WebItemManager webItemManager,
2019-09-13 11:18:27 +00:00
WebItemManagerSecurity webItemManagerSecurity,
TenantInfoSettingsHelper tenantInfoSettingsHelper,
TenantWhiteLabelSettingsHelper tenantWhiteLabelSettingsHelper,
2019-09-13 11:18:27 +00:00
StorageHelper storageHelper,
2019-09-17 12:42:32 +00:00
TenantLogoManager tenantLogoManager,
2019-09-18 15:19:30 +00:00
TenantUtil tenantUtil,
2019-09-19 15:55:44 +00:00
CoreBaseSettings coreBaseSettings,
2019-09-20 13:06:10 +00:00
CommonLinkUtility commonLinkUtility,
ColorThemesSettingsHelper colorThemesSettingsHelper,
2019-09-23 12:20:08 +00:00
IConfiguration configuration,
2019-09-24 10:32:12 +00:00
SetupInfo setupInfo,
BuildVersion buildVersion,
DisplayUserSettingsHelper displayUserSettingsHelper,
2019-10-10 08:52:21 +00:00
StatisticManager statisticManager,
2019-10-10 10:59:22 +00:00
IPRestrictionsService iPRestrictionsService,
2019-10-22 11:21:44 +00:00
CoreConfiguration coreConfiguration,
MessageTarget messageTarget,
StudioSmsNotificationSettingsHelper studioSmsNotificationSettingsHelper,
CoreSettings coreSettings,
StorageSettingsHelper storageSettingsHelper,
2019-11-08 15:11:30 +00:00
IWebHostEnvironment webHostEnvironment,
IServiceProvider serviceProvider,
2019-12-03 15:20:21 +00:00
EmployeeWraperHelper employeeWraperHelper,
2019-12-20 11:17:01 +00:00
ConsumerFactory consumerFactory,
SmsProviderManager smsProviderManager,
2020-01-16 15:01:07 +00:00
TimeZoneConverter timeZoneConverter,
2020-07-24 14:01:20 +00:00
CustomNamingPeople customNamingPeople,
IPSecurity.IPSecurity ipSecurity,
IMemoryCache memoryCache,
ProviderManager providerManager,
FirstTimeTenantSettings firstTimeTenantSettings,
2020-09-07 15:04:26 +00:00
ServiceClient serviceClient,
2020-09-24 14:30:27 +00:00
TelegramHelper telegramHelper,
2020-09-18 14:45:59 +00:00
StorageFactory storageFactory,
2020-09-22 14:17:17 +00:00
UrlShortener urlShortener,
2020-09-17 13:56:12 +00:00
EncryptionServiceClient encryptionServiceClient,
EncryptionSettingsHelper encryptionSettingsHelper,
2020-09-18 17:57:51 +00:00
BackupServiceNotifier backupServiceNotifier,
ICacheNotify<DeleteSchedule> cacheDeleteSchedule,
2020-09-29 15:08:54 +00:00
EncryptionServiceNotifier encryptionServiceNotifier,
PasswordHasher passwordHasher,
2020-12-28 13:22:08 +00:00
BackupAjaxHandler backupAjaxHandler,
PaymentManager paymentManager)
2019-08-12 10:53:12 +00:00
{
2019-10-17 15:55:35 +00:00
Log = option.Get("ASC.Api");
WebHostEnvironment = webHostEnvironment;
2019-11-08 15:11:30 +00:00
ServiceProvider = serviceProvider;
EmployeeWraperHelper = employeeWraperHelper;
2019-12-20 11:17:01 +00:00
ConsumerFactory = consumerFactory;
SmsProviderManager = smsProviderManager;
2019-12-03 15:20:21 +00:00
TimeZoneConverter = timeZoneConverter;
2020-01-16 15:01:07 +00:00
CustomNamingPeople = customNamingPeople;
2020-07-24 14:01:20 +00:00
IpSecurity = ipSecurity;
MemoryCache = memoryCache;
ProviderManager = providerManager;
2020-07-02 14:11:59 +00:00
FirstTimeTenantSettings = firstTimeTenantSettings;
2019-08-12 10:53:12 +00:00
MessageService = messageService;
StudioNotifyService = studioNotifyService;
ApiContext = apiContext;
2019-09-09 12:56:33 +00:00
UserManager = userManager;
TenantManager = tenantManager;
TenantExtra = tenantExtra;
TenantStatisticsProvider = tenantStatisticsProvider;
AuthContext = authContext;
CookiesManager = cookiesManager;
WebItemSecurity = webItemSecurity;
StudioNotifyHelper = studioNotifyHelper;
LicenseReader = licenseReader;
PermissionContext = permissionContext;
SettingsManager = settingsManager;
2019-09-10 14:29:37 +00:00
TfaManager = tfaManager;
WebItemManager = webItemManager;
WebItemManagerSecurity = webItemManagerSecurity;
TenantInfoSettingsHelper = tenantInfoSettingsHelper;
TenantWhiteLabelSettingsHelper = tenantWhiteLabelSettingsHelper;
2019-09-13 11:18:27 +00:00
StorageHelper = storageHelper;
2019-09-16 14:51:39 +00:00
TenantLogoManager = tenantLogoManager;
2019-09-17 12:42:32 +00:00
TenantUtil = tenantUtil;
2019-09-18 15:19:30 +00:00
CoreBaseSettings = coreBaseSettings;
2019-09-19 15:55:44 +00:00
CommonLinkUtility = commonLinkUtility;
ColorThemesSettingsHelper = colorThemesSettingsHelper;
2019-09-23 12:20:08 +00:00
Configuration = configuration;
SetupInfo = setupInfo;
2019-09-24 10:32:12 +00:00
BuildVersion = buildVersion;
DisplayUserSettingsHelper = displayUserSettingsHelper;
2019-10-10 08:52:21 +00:00
StatisticManager = statisticManager;
IPRestrictionsService = iPRestrictionsService;
2019-10-10 10:59:22 +00:00
CoreConfiguration = coreConfiguration;
2019-10-22 11:21:44 +00:00
MessageTarget = messageTarget;
StudioSmsNotificationSettingsHelper = studioSmsNotificationSettingsHelper;
CoreSettings = coreSettings;
StorageSettingsHelper = storageSettingsHelper;
2020-08-24 06:52:17 +00:00
ServiceClient = serviceClient;
2020-09-07 15:04:26 +00:00
EncryptionServiceClient = encryptionServiceClient;
2020-09-17 13:56:12 +00:00
EncryptionSettingsHelper = encryptionSettingsHelper;
2020-09-18 17:57:51 +00:00
BackupServiceNotifier = backupServiceNotifier;
2020-09-17 13:56:12 +00:00
CacheDeleteSchedule = cacheDeleteSchedule;
2020-09-18 17:57:51 +00:00
EncryptionServiceNotifier = encryptionServiceNotifier;
2020-09-29 15:08:54 +00:00
PasswordHasher = passwordHasher;
2020-09-17 12:04:28 +00:00
StorageFactory = storageFactory;
2020-09-18 14:45:59 +00:00
UrlShortener = urlShortener;
2020-09-24 14:30:27 +00:00
TelegramHelper = telegramHelper;
BackupAjaxHandler = backupAjaxHandler;
2020-12-28 13:22:08 +00:00
PaymentManager = paymentManager;
2019-08-12 10:53:12 +00:00
}
2020-08-03 15:34:53 +00:00
[Read("", Check = false)]
2019-08-16 12:11:38 +00:00
[AllowAnonymous]
2019-08-12 10:53:12 +00:00
public SettingsWrapper GetSettings()
{
var settings = new SettingsWrapper
{
Culture = Tenant.GetCulture().ToString(),
GreetingSettings = Tenant.Name
2019-08-12 10:53:12 +00:00
};
2019-08-16 12:11:38 +00:00
2019-09-09 12:56:33 +00:00
if (AuthContext.IsAuthenticated)
2019-08-16 12:11:38 +00:00
{
settings.TrustedDomains = Tenant.TrustedDomains;
settings.TrustedDomainsType = Tenant.TrustedDomainsType;
var timeZone = Tenant.TimeZone;
2019-12-03 15:20:21 +00:00
settings.Timezone = timeZone;
settings.UtcOffset = TimeZoneConverter.GetTimeZone(timeZone).GetUtcOffset(DateTime.UtcNow);
2019-08-16 12:11:38 +00:00
settings.UtcHoursOffset = settings.UtcOffset.TotalHours;
settings.OwnerId = Tenant.OwnerId;
2020-01-20 15:29:30 +00:00
settings.NameSchemaId = CustomNamingPeople.Current.Id;
}
else
{
if (!SettingsManager.Load<WizardSettings>().Completed)
{
settings.WizardToken = CommonLinkUtility.GetToken("", ConfirmType.Wizard, userId: Tenant.OwnerId);
}
settings.EnabledJoin =
(Tenant.TrustedDomainsType == TenantTrustedDomainsType.Custom &&
Tenant.TrustedDomains.Count > 0) ||
Tenant.TrustedDomainsType == TenantTrustedDomainsType.All;
if (settings.EnabledJoin.GetValueOrDefault(false))
{
settings.TrustedDomainsType = Tenant.TrustedDomainsType;
settings.TrustedDomains = Tenant.TrustedDomains;
}
var studioAdminMessageSettings = SettingsManager.Load<StudioAdminMessageSettings>();
settings.EnableAdmMess = studioAdminMessageSettings.Enable || TenantExtra.IsNotPaid();
settings.ThirdpartyEnable = SetupInfo.ThirdPartyAuthEnabled && ProviderManager.IsNotEmpty;
2020-09-29 15:08:54 +00:00
settings.PasswordHash = PasswordHasher;
}
2020-01-20 15:29:30 +00:00
return settings;
}
2020-01-16 15:01:07 +00:00
[Create("messagesettings")]
2020-11-06 09:03:49 +00:00
public object EnableAdminMessageSettingsFromBody([FromBody]AdminMessageSettingsModel model)
{
return EnableAdminMessageSettings(model);
}
[Create("messagesettings")]
[Consumes("application/x-www-form-urlencoded")]
public object EnableAdminMessageSettingsFromForm([FromForm] AdminMessageSettingsModel model)
{
return EnableAdminMessageSettings(model);
}
private object EnableAdminMessageSettings(AdminMessageSettingsModel model)
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
SettingsManager.Save(new StudioAdminMessageSettings { Enable = model.TurnOn });
MessageService.Send(MessageAction.AdministratorMessageSettingsUpdated);
2020-10-19 15:53:15 +00:00
return Resource.SuccessfullySaveSettingsMessage;
2020-07-24 14:01:20 +00:00
}
[AllowAnonymous]
[Create("sendadmmail")]
2020-11-06 09:03:49 +00:00
public object SendAdmMailFromBody([FromBody]AdminMessageSettingsModel model)
{
return SendAdmMail(model);
}
[AllowAnonymous]
[Create("sendadmmail")]
[Consumes("application/x-www-form-urlencoded")]
public object SendAdmMailFromForm([FromForm] AdminMessageSettingsModel model)
{
return SendAdmMail(model);
}
private object SendAdmMail(AdminMessageSettingsModel model)
2020-07-24 14:01:20 +00:00
{
var studioAdminMessageSettings = SettingsManager.Load<StudioAdminMessageSettings>();
var enableAdmMess = studioAdminMessageSettings.Enable || TenantExtra.IsNotPaid();
if (!enableAdmMess)
throw new MethodAccessException("Method not available");
if (!model.Email.TestEmailRegex())
throw new Exception(Resource.ErrorNotCorrectEmail);
if (string.IsNullOrEmpty(model.Message))
throw new Exception(Resource.ErrorEmptyMessage);
CheckCache("sendadmmail");
StudioNotifyService.SendMsgToAdminFromNotAuthUser(model.Email, model.Message);
MessageService.Send(MessageAction.ContactAdminMailSent);
2020-10-09 10:05:48 +00:00
return Resource.AdminMessageSent;
}
[Create("maildomainsettings")]
2020-11-06 09:03:49 +00:00
public object SaveMailDomainSettingsFromBody([FromBody] MailDomainSettingsModel model)
{
return SaveMailDomainSettings(model);
}
[Create("maildomainsettings")]
[Consumes("application/x-www-form-urlencoded")]
public object SaveMailDomainSettingsFromForm([FromForm] MailDomainSettingsModel model)
{
return SaveMailDomainSettings(model);
}
private object SaveMailDomainSettings(MailDomainSettingsModel model)
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (model.Type == TenantTrustedDomainsType.Custom)
{
Tenant.TrustedDomains.Clear();
foreach (var d in model.Domains.Select(domain => (domain ?? "").Trim().ToLower()))
{
if (!(!string.IsNullOrEmpty(d) && new Regex("^[a-z0-9]([a-z0-9-.]){1,98}[a-z0-9]$").IsMatch(d)))
2020-10-09 10:05:48 +00:00
return Resource.ErrorNotCorrectTrustedDomain;
Tenant.TrustedDomains.Add(d);
}
if (Tenant.TrustedDomains.Count == 0)
model.Type = TenantTrustedDomainsType.None;
}
Tenant.TrustedDomainsType = model.Type;
SettingsManager.Save(new StudioTrustedDomainSettings { InviteUsersAsVisitors = model.InviteUsersAsVisitors });
TenantManager.SaveTenant(Tenant);
MessageService.Send(MessageAction.TrustedMailDomainSettingsUpdated);
2020-10-09 10:05:48 +00:00
return Resource.SuccessfullySaveSettingsMessage;
2020-07-24 14:01:20 +00:00
}
[AllowAnonymous]
[Create("sendjoininvite")]
2020-11-06 09:03:49 +00:00
public object SendJoinInviteMailFromBody([FromBody]AdminMessageSettingsModel model)
{
return SendJoinInviteMail(model);
}
[AllowAnonymous]
[Create("sendjoininvite")]
[Consumes("application/x-www-form-urlencoded")]
public object SendJoinInviteMailFromForm([FromForm] AdminMessageSettingsModel model)
{
return SendJoinInviteMail(model);
}
private object SendJoinInviteMail(AdminMessageSettingsModel model)
2020-07-24 14:01:20 +00:00
{
try
{
var email = model.Email;
if (!(
(Tenant.TrustedDomainsType == TenantTrustedDomainsType.Custom &&
Tenant.TrustedDomains.Count > 0) ||
Tenant.TrustedDomainsType == TenantTrustedDomainsType.All))
throw new MethodAccessException("Method not available");
if (!email.TestEmailRegex())
throw new Exception(Resource.ErrorNotCorrectEmail);
CheckCache("sendjoininvite");
var user = UserManager.GetUserByEmail(email);
if (!user.ID.Equals(Constants.LostUser.ID))
throw new Exception(CustomNamingPeople.Substitute<Resource>("ErrorEmailAlreadyExists"));
var settings = SettingsManager.Load<IPRestrictionsSettings>();
if (settings.Enable && !IpSecurity.Verify())
throw new Exception(Resource.ErrorAccessRestricted);
var trustedDomainSettings = SettingsManager.Load<StudioTrustedDomainSettings>();
var emplType = trustedDomainSettings.InviteUsersAsVisitors ? EmployeeType.Visitor : EmployeeType.User;
var enableInviteUsers = TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers;
if (!enableInviteUsers)
emplType = EmployeeType.Visitor;
switch (Tenant.TrustedDomainsType)
{
case TenantTrustedDomainsType.Custom:
2020-10-19 15:53:15 +00:00
{
var address = new MailAddress(email);
if (Tenant.TrustedDomains.Any(d => address.Address.EndsWith("@" + d, StringComparison.InvariantCultureIgnoreCase)))
2020-07-24 14:01:20 +00:00
{
StudioNotifyService.SendJoinMsg(email, emplType);
MessageService.Send(MessageInitiator.System, MessageAction.SentInviteInstructions, email);
2020-10-19 15:53:15 +00:00
return Resource.FinishInviteJoinEmailMessage;
2020-07-24 14:01:20 +00:00
}
2020-10-19 15:53:15 +00:00
throw new Exception(Resource.ErrorEmailDomainNotAllowed);
}
case TenantTrustedDomainsType.All:
{
StudioNotifyService.SendJoinMsg(email, emplType);
MessageService.Send(MessageInitiator.System, MessageAction.SentInviteInstructions, email);
return Resource.FinishInviteJoinEmailMessage;
}
2020-07-24 14:01:20 +00:00
default:
throw new Exception(Resource.ErrorNotCorrectEmail);
}
}
catch (FormatException)
{
2020-10-09 10:05:48 +00:00
return Resource.ErrorNotCorrectEmail;
2020-07-24 14:01:20 +00:00
}
catch (Exception e)
{
2020-10-09 10:05:48 +00:00
return e.Message.HtmlEncode();
2020-07-24 14:01:20 +00:00
}
}
2020-01-20 15:29:30 +00:00
[Read("customschemas")]
public List<SchemaModel> PeopleSchemas()
{
return CustomNamingPeople
.GetSchemas()
2020-01-16 15:01:07 +00:00
.Select(r =>
{
var names = CustomNamingPeople.GetPeopleNames(r.Key);
2021-04-13 17:10:14 +00:00
return new SchemaModel
2020-01-16 15:01:07 +00:00
{
Id = names.Id,
2021-04-13 17:10:14 +00:00
Name = names.SchemaName,
2020-01-16 15:01:07 +00:00
UserCaption = names.UserCaption,
UsersCaption = names.UsersCaption,
GroupCaption = names.GroupCaption,
GroupsCaption = names.GroupsCaption,
UserPostCaption = names.UserPostCaption,
RegDateCaption = names.RegDateCaption,
GroupHeadCaption = names.GroupHeadCaption,
GuestCaption = names.GuestCaption,
GuestsCaption = names.GuestsCaption,
};
})
.ToList();
2019-08-12 10:53:12 +00:00
}
2021-04-13 18:11:38 +00:00
[Create("customschemas")]
public SchemaModel SaveNamingSettings(SchemaModel model)
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
CustomNamingPeople.SetPeopleNames(model.Id);
TenantManager.SaveTenant(TenantManager.GetCurrentTenant());
MessageService.Send(MessageAction.TeamTemplateChanged);
return PeopleSchema(model.Id);
}
[Update("customschemas")]
public SchemaModel SaveCustomNamingSettings(SchemaModel model)
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var usrCaption = (model.UserCaption ?? "").Trim();
var usrsCaption = (model.UsersCaption ?? "").Trim();
var grpCaption = (model.GroupCaption ?? "").Trim();
var grpsCaption = (model.GroupsCaption ?? "").Trim();
var usrStatusCaption = (model.UserPostCaption ?? "").Trim();
var regDateCaption = (model.RegDateCaption ?? "").Trim();
var grpHeadCaption = (model.GroupHeadCaption ?? "").Trim();
var guestCaption = (model.GuestCaption ?? "").Trim();
var guestsCaption = (model.GuestsCaption ?? "").Trim();
if (string.IsNullOrEmpty(usrCaption)
|| string.IsNullOrEmpty(usrsCaption)
|| string.IsNullOrEmpty(grpCaption)
|| string.IsNullOrEmpty(grpsCaption)
|| string.IsNullOrEmpty(usrStatusCaption)
|| string.IsNullOrEmpty(regDateCaption)
|| string.IsNullOrEmpty(grpHeadCaption)
|| string.IsNullOrEmpty(guestCaption)
|| string.IsNullOrEmpty(guestsCaption))
{
throw new Exception(Resource.ErrorEmptyFields);
}
var names = new PeopleNamesItem
{
Id = PeopleNamesItem.CustomID,
UserCaption = usrCaption.Substring(0, Math.Min(30, usrCaption.Length)),
UsersCaption = usrsCaption.Substring(0, Math.Min(30, usrsCaption.Length)),
GroupCaption = grpCaption.Substring(0, Math.Min(30, grpCaption.Length)),
GroupsCaption = grpsCaption.Substring(0, Math.Min(30, grpsCaption.Length)),
UserPostCaption = usrStatusCaption.Substring(0, Math.Min(30, usrStatusCaption.Length)),
RegDateCaption = regDateCaption.Substring(0, Math.Min(30, regDateCaption.Length)),
GroupHeadCaption = grpHeadCaption.Substring(0, Math.Min(30, grpHeadCaption.Length)),
GuestCaption = guestCaption.Substring(0, Math.Min(30, guestCaption.Length)),
GuestsCaption = guestsCaption.Substring(0, Math.Min(30, guestsCaption.Length)),
};
CustomNamingPeople.SetPeopleNames(names);
TenantManager.SaveTenant(TenantManager.GetCurrentTenant());
MessageService.Send(MessageAction.TeamTemplateChanged);
return PeopleSchema(PeopleNamesItem.CustomID);
}
[Read("customschemas/{id}")]
2021-04-13 17:10:14 +00:00
public SchemaModel PeopleSchema(string id)
{
var names = CustomNamingPeople.GetPeopleNames(id);
2021-04-13 17:10:14 +00:00
var schemaItem = new SchemaModel
{
Id = names.Id,
2021-04-13 17:10:14 +00:00
Name = names.SchemaName,
UserCaption = names.UserCaption,
UsersCaption = names.UsersCaption,
GroupCaption = names.GroupCaption,
GroupsCaption = names.GroupsCaption,
UserPostCaption = names.UserPostCaption,
RegDateCaption = names.RegDateCaption,
GroupHeadCaption = names.GroupHeadCaption,
GuestCaption = names.GuestCaption,
GuestsCaption = names.GuestsCaption,
};
return schemaItem;
}
2019-08-12 10:53:12 +00:00
[Read("quota")]
public QuotaWrapper GetQuotaUsed()
{
return new QuotaWrapper(Tenant, CoreBaseSettings, CoreConfiguration, TenantExtra, TenantStatisticsProvider, AuthContext, SettingsManager, WebItemManager);
2019-08-12 10:53:12 +00:00
}
2019-09-23 13:19:01 +00:00
[AllowAnonymous]
2020-08-03 14:06:37 +00:00
[Read("cultures", Check = false)]
public IEnumerable<object> GetSupportedCultures()
2019-09-23 13:19:01 +00:00
{
2020-06-03 15:51:01 +00:00
return SetupInfo.EnabledCultures.Select(r => r.Name).ToArray();
2019-09-23 13:19:01 +00:00
}
2020-07-08 08:29:44 +00:00
[Authorize(AuthenticationSchemes = "confirm", Roles = "Wizard,Administrators")]
2020-08-03 14:06:37 +00:00
[Read("timezones", Check = false)]
2020-07-08 08:29:44 +00:00
public List<TimezonesModel> GetTimeZones()
{
2020-07-08 08:29:44 +00:00
ApiContext.AuthByClaim();
2019-10-31 11:28:30 +00:00
var timeZones = TimeZoneInfo.GetSystemTimeZones().ToList();
if (timeZones.All(tz => tz.Id != "UTC"))
{
timeZones.Add(TimeZoneInfo.Utc);
}
2020-07-08 08:29:44 +00:00
var listOfTimezones = new List<TimezonesModel>();
foreach (var tz in timeZones.OrderBy(z => z.BaseUtcOffset))
{
2020-09-03 15:30:14 +00:00
listOfTimezones.Add(new TimezonesModel
{
2020-09-03 15:30:14 +00:00
Id = tz.Id,
DisplayName = TimeZoneConverter.GetTimeZoneDisplayName(tz)
});
}
return listOfTimezones;
}
2020-07-08 08:29:44 +00:00
[Authorize(AuthenticationSchemes = "confirm", Roles = "Wizard")]
2020-08-03 14:06:37 +00:00
[Read("machine", Check = false)]
2020-10-09 10:05:48 +00:00
public object GetMachineName()
2020-07-08 08:29:44 +00:00
{
return Dns.GetHostName().ToLowerInvariant();
}
2020-07-28 11:41:51 +00:00
[Read("greetingsettings")]
public ContentResult GetGreetingSettings()
{
return new ContentResult { Content = Tenant.Name };
}
[Create("greetingsettings")]
2020-11-06 09:03:49 +00:00
public ContentResult SaveGreetingSettingsFromBody([FromBody]GreetingSettingsModel model)
{
return SaveGreetingSettings(model);
}
[Create("greetingsettings")]
[Consumes("application/x-www-form-urlencoded")]
public ContentResult SaveGreetingSettingsFromForm([FromForm]GreetingSettingsModel model)
{
return SaveGreetingSettings(model);
}
private ContentResult SaveGreetingSettings(GreetingSettingsModel model)
{
2020-07-28 11:41:51 +00:00
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2020-07-28 11:41:51 +00:00
Tenant.Name = model.Title;
TenantManager.SaveTenant(Tenant);
2020-07-28 11:41:51 +00:00
MessageService.Send(MessageAction.GreetingSettingsUpdated);
2020-07-28 11:41:51 +00:00
return new ContentResult { Content = Resource.SuccessfullySaveGreetingSettingsMessage };
}
[Create("greetingsettings/restore")]
2020-07-28 11:41:51 +00:00
public ContentResult RestoreGreetingSettings()
{
2020-07-28 11:41:51 +00:00
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2020-07-28 11:41:51 +00:00
TenantInfoSettingsHelper.RestoreDefaultTenantName();
2020-07-28 11:41:51 +00:00
return new ContentResult
{
2020-07-28 11:41:51 +00:00
Content = Tenant.Name
};
}
2019-10-14 08:23:45 +00:00
//[Read("recalculatequota")]
//public void RecalculateQuota()
//{
// SecurityContext.DemandPermissions(Tenant, SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
2019-10-14 08:23:45 +00:00
// var operations = quotaTasks.GetTasks()
// .Where(t => t.GetProperty<int>(QuotaSync.TenantIdKey) == Tenant.TenantId);
2019-08-12 10:53:12 +00:00
2019-10-14 08:23:45 +00:00
// if (operations.Any(o => o.Status <= DistributedTaskStatus.Running))
// {
// throw new InvalidOperationException(Resource.LdapSettingsTooManyOperations);
// }
2019-08-12 10:53:12 +00:00
2019-10-14 08:23:45 +00:00
// var op = new QuotaSync(Tenant.TenantId, ServiceProvider);
2019-08-12 10:53:12 +00:00
2019-10-14 08:23:45 +00:00
// quotaTasks.QueueTask(op.RunJob, op.GetDistributedTask());
//}
2019-08-12 10:53:12 +00:00
2019-10-14 08:23:45 +00:00
//[Read("checkrecalculatequota")]
//public bool CheckRecalculateQuota()
//{
// PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
2019-10-14 08:23:45 +00:00
// var task = quotaTasks.GetTasks().FirstOrDefault(t => t.GetProperty<int>(QuotaSync.TenantIdKey) == Tenant.TenantId);
2019-08-12 10:53:12 +00:00
2019-10-14 08:23:45 +00:00
// if (task != null && task.Status == DistributedTaskStatus.Completed)
// {
// quotaTasks.RemoveTask(task.Id);
// return false;
// }
2019-08-12 10:53:12 +00:00
2019-10-14 08:23:45 +00:00
// return task != null;
//}
2019-08-12 10:53:12 +00:00
[AllowAnonymous]
[Read("version/build", false)]
public BuildVersion GetBuildVersions()
{
return BuildVersion.GetCurrentBuildVersion();
}
[Read("version")]
public TenantVersionWrapper GetVersions()
{
2019-09-09 12:56:33 +00:00
return new TenantVersionWrapper(Tenant.Version, TenantManager.GetTenantVersions());
2019-08-12 10:53:12 +00:00
}
[Update("version")]
2020-11-06 09:03:49 +00:00
public TenantVersionWrapper SetVersionFromBody([FromBody]SettingsModel model)
{
return SetVersion(model);
}
[Update("version")]
[Consumes("application/x-www-form-urlencoded")]
public TenantVersionWrapper SetVersionFromForm([FromForm] SettingsModel model)
{
return SetVersion(model);
}
private TenantVersionWrapper SetVersion(SettingsModel model)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
2019-09-09 12:56:33 +00:00
TenantManager.GetTenantVersions().FirstOrDefault(r => r.Id == model.VersionId).NotFoundIfNull();
TenantManager.SetTenantVersion(Tenant, model.VersionId);
2019-08-12 10:53:12 +00:00
return GetVersions();
}
[Read("security")]
public IEnumerable<SecurityWrapper> GetWebItemSecurityInfo(IEnumerable<string> ids)
{
if (ids == null || !ids.Any())
{
ids = WebItemManager.GetItemsAll().Select(i => i.ID.ToString());
2019-08-12 10:53:12 +00:00
}
var subItemList = WebItemManager.GetItemsAll().Where(item => item.IsSubItem()).Select(i => i.ID.ToString());
2019-08-12 10:53:12 +00:00
return ids.Select(r => WebItemSecurity.GetSecurityInfo(r))
2019-08-12 10:53:12 +00:00
.Select(i => new SecurityWrapper
2019-08-15 12:04:42 +00:00
{
WebItemId = i.WebItemId,
Enabled = i.Enabled,
Users = i.Users.Select(EmployeeWraperHelper.Get),
Groups = i.Groups.Select(g => new GroupWrapperSummary(g, UserManager)),
2019-08-15 12:04:42 +00:00
IsSubItem = subItemList.Contains(i.WebItemId),
}).ToList();
2019-08-12 10:53:12 +00:00
}
[Read("security/{id}")]
public bool GetWebItemSecurityInfo(Guid id)
{
var module = WebItemManager[id];
2019-08-12 10:53:12 +00:00
2019-09-16 14:51:39 +00:00
return module != null && !module.IsDisabled(WebItemSecurity, AuthContext);
2019-08-12 10:53:12 +00:00
}
[Read("security/modules")]
public object GetEnabledModules()
{
2019-09-16 14:51:39 +00:00
var EnabledModules = WebItemManagerSecurity.GetItems(WebZoneType.All, ItemAvailableState.Normal)
2019-08-12 10:53:12 +00:00
.Where(item => !item.IsSubItem() && item.Visible)
.ToList()
.Select(item => new
{
id = item.ProductClassName.HtmlEncode(),
title = item.Name.HtmlEncode()
});
return EnabledModules;
}
[Read("security/password", Check = false)]
[Authorize(AuthenticationSchemes = "confirm", Roles = "Everyone")]
2019-08-12 10:53:12 +00:00
public object GetPasswordSettings()
{
var UserPasswordSettings = SettingsManager.Load<PasswordSettings>();
2019-08-12 10:53:12 +00:00
return UserPasswordSettings;
}
[Update("security")]
2020-11-06 09:03:49 +00:00
public IEnumerable<SecurityWrapper> SetWebItemSecurityFromBody([FromBody]WebItemSecurityModel model)
{
return SetWebItemSecurity(model);
}
[Update("security")]
[Consumes("application/x-www-form-urlencoded")]
public IEnumerable<SecurityWrapper> SetWebItemSecurityFromForm([FromForm] WebItemSecurityModel model)
{
return SetWebItemSecurity(model);
}
private IEnumerable<SecurityWrapper> SetWebItemSecurity(WebItemSecurityModel model)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
WebItemSecurity.SetSecurity(model.Id, model.Enabled, model.Subjects?.ToArray());
var securityInfo = GetWebItemSecurityInfo(new List<string> { model.Id });
if (model.Subjects == null) return securityInfo;
var productName = GetProductName(new Guid(model.Id));
if (!model.Subjects.Any())
{
MessageService.Send(MessageAction.ProductAccessOpened, productName);
}
else
{
foreach (var info in securityInfo)
{
if (info.Groups.Any())
{
MessageService.Send(MessageAction.GroupsOpenedProductAccess, productName, info.Groups.Select(x => x.Name));
}
if (info.Users.Any())
{
MessageService.Send(MessageAction.UsersOpenedProductAccess, productName, info.Users.Select(x => HttpUtility.HtmlDecode(x.DisplayName)));
}
}
}
return securityInfo;
}
[Update("security/access")]
2020-11-06 09:03:49 +00:00
public IEnumerable<SecurityWrapper> SetAccessToWebItemsFromBody([FromBody]WebItemSecurityModel model)
{
return SetAccessToWebItems(model);
}
[Update("security/access")]
[Consumes("application/x-www-form-urlencoded")]
public IEnumerable<SecurityWrapper> SetAccessToWebItemsFromForm([FromForm] WebItemSecurityModel model)
{
return SetAccessToWebItems(model);
}
private IEnumerable<SecurityWrapper> SetAccessToWebItems(WebItemSecurityModel model)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
var itemList = new ItemDictionary<string, bool>();
foreach (var item in model.Items)
{
if (!itemList.ContainsKey(item.Key))
itemList.Add(item.Key, item.Value);
}
var defaultPageSettings = SettingsManager.Load<StudioDefaultPageSettings>();
2019-08-12 10:53:12 +00:00
foreach (var item in itemList)
{
Guid[] subjects = null;
var productId = new Guid(item.Key);
if (item.Value)
{
2020-09-17 12:04:28 +00:00
if (WebItemManager[productId] is IProduct webItem || productId == WebItemManager.MailProductID)
2019-08-12 10:53:12 +00:00
{
var productInfo = WebItemSecurity.GetSecurityInfo(item.Key);
2019-08-12 10:53:12 +00:00
var selectedGroups = productInfo.Groups.Select(group => group.ID).ToList();
var selectedUsers = productInfo.Users.Select(user => user.ID).ToList();
selectedUsers.AddRange(selectedGroups);
if (selectedUsers.Count > 0)
{
subjects = selectedUsers.ToArray();
}
}
}
else if (productId == defaultPageSettings.DefaultProductID)
{
2020-09-17 12:04:28 +00:00
SettingsManager.Save((StudioDefaultPageSettings)defaultPageSettings.GetDefault(ServiceProvider));
2019-08-12 10:53:12 +00:00
}
WebItemSecurity.SetSecurity(item.Key, item.Value, subjects);
}
MessageService.Send(MessageAction.ProductsListUpdated);
return GetWebItemSecurityInfo(itemList.Keys.ToList());
}
[Read("security/administrator/{productid}")]
public IEnumerable<EmployeeWraper> GetProductAdministrators(Guid productid)
{
return WebItemSecurity.GetProductAdministrators(productid)
.Select(EmployeeWraperHelper.Get)
2019-08-12 10:53:12 +00:00
.ToList();
}
[Read("security/administrator")]
public object IsProductAdministrator(Guid productid, Guid userid)
{
var result = WebItemSecurity.IsProductAdministrator(productid, userid);
2020-11-06 10:43:31 +00:00
return new { ProductId = productid, UserId = userid, Administrator = result };
2019-08-12 10:53:12 +00:00
}
[Update("security/administrator")]
2020-11-06 09:03:49 +00:00
public object SetProductAdministratorFromBody([FromBody]SecurityModel model)
2019-08-12 10:53:12 +00:00
{
2020-11-06 09:03:49 +00:00
return SetProductAdministrator(model);
2019-08-12 10:53:12 +00:00
}
[Update("security/administrator")]
2020-11-06 09:03:49 +00:00
[Consumes("application/x-www-form-urlencoded")]
public object SetProductAdministratorFromForm([FromForm] SecurityModel model)
{
return SetProductAdministrator(model);
}
private object SetProductAdministrator(SecurityModel model)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
WebItemSecurity.SetProductAdministrator(model.ProductId, model.UserId, model.Administrator);
2019-08-12 10:53:12 +00:00
2019-09-09 12:56:33 +00:00
var admin = UserManager.GetUsers(model.UserId);
2019-08-12 10:53:12 +00:00
if (model.ProductId == Guid.Empty)
{
var messageAction = model.Administrator ? MessageAction.AdministratorOpenedFullAccess : MessageAction.AdministratorDeleted;
MessageService.Send(messageAction, MessageTarget.Create(admin.ID), admin.DisplayUserName(false, DisplayUserSettingsHelper));
2019-08-12 10:53:12 +00:00
}
else
{
var messageAction = model.Administrator ? MessageAction.ProductAddedAdministrator : MessageAction.ProductDeletedAdministrator;
MessageService.Send(messageAction, MessageTarget.Create(admin.ID), GetProductName(model.ProductId), admin.DisplayUserName(false, DisplayUserSettingsHelper));
2019-08-12 10:53:12 +00:00
}
return new { model.ProductId, model.UserId, model.Administrator };
}
[Read("logo")]
2020-10-09 10:05:48 +00:00
public object GetLogo()
2019-08-12 10:53:12 +00:00
{
return TenantInfoSettingsHelper.GetAbsoluteCompanyLogoPath(SettingsManager.Load<TenantInfoSettings>());
2019-08-12 10:53:12 +00:00
}
///<visible>false</visible>
[Create("whitelabel/save")]
2020-11-06 09:03:49 +00:00
public bool SaveWhiteLabelSettingsFromBody([FromBody] WhiteLabelModel model, [FromQuery] WhiteLabelQuery query)
{
return SaveWhiteLabelSettings(model, query);
}
[Create("whitelabel/save")]
[Consumes("application/x-www-form-urlencoded")]
public bool SaveWhiteLabelSettingsFromForm([FromForm] WhiteLabelModel model, [FromQuery] WhiteLabelQuery query)
{
return SaveWhiteLabelSettings(model, query);
}
private bool SaveWhiteLabelSettings(WhiteLabelModel model, WhiteLabelQuery query)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
if (!TenantLogoManager.WhiteLabelEnabled || !TenantLogoManager.WhiteLabelPaid)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
if (query.IsDefault)
2020-09-17 12:04:28 +00:00
{
DemandRebrandingPermission();
SaveWhiteLabelSettingsForDefaultTenant(model);
}
else
{
SaveWhiteLabelSettingsForCurrentTenant(model);
}
return true;
2020-09-17 12:04:28 +00:00
}
private void SaveWhiteLabelSettingsForCurrentTenant(WhiteLabelModel model)
{
var settings = SettingsManager.Load<TenantWhiteLabelSettings>();
SaveWhiteLabelSettingsForTenant(settings, null, Tenant.TenantId, model);
}
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
private void SaveWhiteLabelSettingsForDefaultTenant(WhiteLabelModel model)
{
var settings = SettingsManager.LoadForDefaultTenant<TenantWhiteLabelSettings>();
var storage = StorageFactory.GetStorage(string.Empty, "static_partnerdata");
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
SaveWhiteLabelSettingsForTenant(settings, storage, Tenant.DEFAULT_TENANT, model);
}
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
private void SaveWhiteLabelSettingsForTenant(TenantWhiteLabelSettings settings, IDataStore storage, int tenantId, WhiteLabelModel model)
{
2019-08-12 10:53:12 +00:00
if (model.Logo != null)
{
var logoDict = new Dictionary<int, string>();
model.Logo.ToList().ForEach(n => logoDict.Add(Int32.Parse(n.Key), n.Value));
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
TenantWhiteLabelSettingsHelper.SetLogo(settings, logoDict, storage);
2019-08-12 10:53:12 +00:00
}
2020-09-17 12:04:28 +00:00
settings.SetLogoText(model.LogoText);
TenantWhiteLabelSettingsHelper.Save(settings, tenantId, TenantLogoManager);
2019-08-12 10:53:12 +00:00
}
///<visible>false</visible>
[Create("whitelabel/savefromfiles")]
2020-11-03 15:16:23 +00:00
public bool SaveWhiteLabelSettingsFromFiles([FromQuery] WhiteLabelQuery query)
2019-08-12 10:53:12 +00:00
{
2020-09-17 12:04:28 +00:00
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!TenantLogoManager.WhiteLabelEnabled || !TenantLogoManager.WhiteLabelPaid)
2019-08-12 10:53:12 +00:00
{
2020-09-17 12:04:28 +00:00
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
2019-08-12 10:53:12 +00:00
2020-11-03 15:16:23 +00:00
if (HttpContext.Request.Form?.Files == null || !HttpContext.Request.Form.Files.Any())
2020-09-17 12:04:28 +00:00
{
throw new InvalidOperationException("No input files");
}
2019-08-12 10:53:12 +00:00
if (query.IsDefault)
2020-09-17 12:04:28 +00:00
{
DemandRebrandingPermission();
2020-11-03 15:16:23 +00:00
SaveWhiteLabelSettingsFromFilesForDefaultTenant();
2019-08-12 10:53:12 +00:00
}
else
{
2020-11-03 15:16:23 +00:00
SaveWhiteLabelSettingsFromFilesForCurrentTenant();
2019-08-12 10:53:12 +00:00
}
return true;
2019-08-12 10:53:12 +00:00
}
2020-11-03 15:16:23 +00:00
private void SaveWhiteLabelSettingsFromFilesForCurrentTenant()
2020-09-17 12:04:28 +00:00
{
var settings = SettingsManager.Load<TenantWhiteLabelSettings>();
2020-11-03 15:16:23 +00:00
SaveWhiteLabelSettingsFromFilesForTenant(settings, null, Tenant.TenantId);
2020-09-17 12:04:28 +00:00
}
2020-11-03 15:16:23 +00:00
private void SaveWhiteLabelSettingsFromFilesForDefaultTenant()
2020-09-17 12:04:28 +00:00
{
var settings = SettingsManager.LoadForDefaultTenant<TenantWhiteLabelSettings>();
var storage = StorageFactory.GetStorage(string.Empty, "static_partnerdata");
2020-11-03 15:16:23 +00:00
SaveWhiteLabelSettingsFromFilesForTenant(settings, storage, Tenant.DEFAULT_TENANT);
2020-09-17 12:04:28 +00:00
}
2020-11-03 15:16:23 +00:00
private void SaveWhiteLabelSettingsFromFilesForTenant(TenantWhiteLabelSettings settings, IDataStore storage, int tenantId)
2020-09-17 12:04:28 +00:00
{
2020-11-03 15:16:23 +00:00
foreach (var f in HttpContext.Request.Form.Files)
2020-09-17 12:04:28 +00:00
{
var parts = f.FileName.Split('.');
var logoType = (WhiteLabelLogoTypeEnum)(Convert.ToInt32(parts[0]));
var fileExt = parts[1];
TenantWhiteLabelSettingsHelper.SetLogoFromStream(settings, logoType, fileExt, f.OpenReadStream(), storage);
2019-08-12 10:53:12 +00:00
}
2020-09-17 12:04:28 +00:00
SettingsManager.SaveForTenant(settings, tenantId);
2019-08-12 10:53:12 +00:00
}
///<visible>false</visible>
[Read("whitelabel/sizes")]
public object GetWhiteLabelSizes()
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
if (!TenantLogoManager.WhiteLabelEnabled)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
return
new[]
{
new {type = (int)WhiteLabelLogoTypeEnum.LightSmall, name = WhiteLabelLogoTypeEnum.LightSmall.ToString(), height = TenantWhiteLabelSettings.logoLightSmallSize.Height, width = TenantWhiteLabelSettings.logoLightSmallSize.Width},
new {type = (int)WhiteLabelLogoTypeEnum.Dark, name = WhiteLabelLogoTypeEnum.Dark.ToString(), height = TenantWhiteLabelSettings.logoDarkSize.Height, width = TenantWhiteLabelSettings.logoDarkSize.Width},
new {type = (int)WhiteLabelLogoTypeEnum.Favicon, name = WhiteLabelLogoTypeEnum.Favicon.ToString(), height = TenantWhiteLabelSettings.logoFaviconSize.Height, width = TenantWhiteLabelSettings.logoFaviconSize.Width},
new {type = (int)WhiteLabelLogoTypeEnum.DocsEditor, name = WhiteLabelLogoTypeEnum.DocsEditor.ToString(), height = TenantWhiteLabelSettings.logoDocsEditorSize.Height, width = TenantWhiteLabelSettings.logoDocsEditorSize.Width}
};
}
///<visible>false</visible>
[Read("whitelabel/logos")]
public Dictionary<string, string> GetWhiteLabelLogos([FromQuery] WhiteLabelQuery query)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
if (!TenantLogoManager.WhiteLabelEnabled)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
Dictionary<string, string> result;
2019-08-12 10:53:12 +00:00
if (query.IsDefault)
2020-09-17 12:04:28 +00:00
{
result = new Dictionary<string, string>
2020-09-17 12:04:28 +00:00
{
{ ((int)WhiteLabelLogoTypeEnum.LightSmall).ToString(), CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettingsHelper.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.LightSmall, !query.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.Dark).ToString(), CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettingsHelper.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.Dark, !query.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.Favicon).ToString(), CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettingsHelper.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.Favicon, !query.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.DocsEditor).ToString(), CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettingsHelper.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.DocsEditor, !query.IsRetina)) }
2020-09-17 12:04:28 +00:00
};
}
else
2019-08-12 10:53:12 +00:00
{
2020-09-17 12:04:28 +00:00
var _tenantWhiteLabelSettings = SettingsManager.Load<TenantWhiteLabelSettings>();
result = new Dictionary<string, string>
2020-09-17 12:04:28 +00:00
{
{ ((int)WhiteLabelLogoTypeEnum.LightSmall).ToString(), CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettingsHelper.GetAbsoluteLogoPath(_tenantWhiteLabelSettings, WhiteLabelLogoTypeEnum.LightSmall, !query.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.Dark).ToString(), CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettingsHelper.GetAbsoluteLogoPath(_tenantWhiteLabelSettings, WhiteLabelLogoTypeEnum.Dark, !query.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.Favicon).ToString(), CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettingsHelper.GetAbsoluteLogoPath(_tenantWhiteLabelSettings, WhiteLabelLogoTypeEnum.Favicon, !query.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.DocsEditor).ToString(), CommonLinkUtility.GetFullAbsolutePath(TenantWhiteLabelSettingsHelper.GetAbsoluteLogoPath(_tenantWhiteLabelSettings, WhiteLabelLogoTypeEnum.DocsEditor, !query.IsRetina)) }
2020-09-17 12:04:28 +00:00
};
}
2019-08-12 10:53:12 +00:00
return result;
}
///<visible>false</visible>
[Read("whitelabel/logotext")]
public object GetWhiteLabelLogoText([FromQuery] WhiteLabelQuery query)
2019-08-12 10:53:12 +00:00
{
if (!TenantLogoManager.WhiteLabelEnabled)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
var settings = query.IsDefault ? SettingsManager.LoadForDefaultTenant<TenantWhiteLabelSettings>() : SettingsManager.Load<TenantWhiteLabelSettings>();
2020-09-17 12:04:28 +00:00
return settings.LogoText ?? TenantWhiteLabelSettings.DefaultLogoText;
2019-08-12 10:53:12 +00:00
}
///<visible>false</visible>
[Update("whitelabel/restore")]
public bool RestoreWhiteLabelOptions(WhiteLabelQuery query)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
if (!TenantLogoManager.WhiteLabelEnabled || !TenantLogoManager.WhiteLabelPaid)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
if (query.IsDefault)
2020-09-17 12:04:28 +00:00
{
DemandRebrandingPermission();
RestoreWhiteLabelOptionsForDefaultTenant();
}
else
{
RestoreWhiteLabelOptionsForCurrentTenant();
}
return true;
2020-09-17 12:04:28 +00:00
}
2019-08-12 10:53:12 +00:00
2020-09-23 10:22:23 +00:00
private void RestoreWhiteLabelOptionsForCurrentTenant()
2020-09-17 12:04:28 +00:00
{
var settings = SettingsManager.Load<TenantWhiteLabelSettings>();
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
RestoreWhiteLabelOptionsForTenant(settings, null, Tenant.TenantId);
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
var tenantInfoSettings = SettingsManager.Load<TenantInfoSettings>();
TenantInfoSettingsHelper.RestoreDefaultLogo(tenantInfoSettings, TenantLogoManager);
SettingsManager.Save(tenantInfoSettings);
2019-08-12 10:53:12 +00:00
}
2020-09-23 10:22:23 +00:00
private void RestoreWhiteLabelOptionsForDefaultTenant()
2020-09-17 12:04:28 +00:00
{
var settings = SettingsManager.LoadForDefaultTenant<TenantWhiteLabelSettings>();
var storage = StorageFactory.GetStorage(string.Empty, "static_partnerdata");
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
RestoreWhiteLabelOptionsForTenant(settings, storage, Tenant.DEFAULT_TENANT);
}
2019-08-12 10:53:12 +00:00
2020-09-23 10:22:23 +00:00
private void RestoreWhiteLabelOptionsForTenant(TenantWhiteLabelSettings settings, IDataStore storage, int tenantId)
2020-09-17 12:04:28 +00:00
{
TenantWhiteLabelSettingsHelper.RestoreDefault(settings, TenantLogoManager, tenantId, storage);
2019-08-12 10:53:12 +00:00
}
2020-09-17 12:04:28 +00:00
2019-08-12 10:53:12 +00:00
[Read("iprestrictions")]
public IEnumerable<IPRestriction> GetIpRestrictions()
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
return IPRestrictionsService.Get(Tenant.TenantId);
}
[Update("iprestrictions")]
2020-11-06 09:03:49 +00:00
public IEnumerable<string> SaveIpRestrictionsFromBody([FromBody]IpRestrictionsModel model)
{
return SaveIpRestrictions(model);
}
[Update("iprestrictions")]
[Consumes("application/x-www-form-urlencoded")]
public IEnumerable<string> SaveIpRestrictionsFromForm([FromForm] IpRestrictionsModel model)
{
return SaveIpRestrictions(model);
}
private IEnumerable<string> SaveIpRestrictions(IpRestrictionsModel model)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
return IPRestrictionsService.Save(model.Ips, Tenant.TenantId);
}
[Update("iprestrictions/settings")]
2020-11-06 09:03:49 +00:00
public IPRestrictionsSettings UpdateIpRestrictionsSettingsFromBody([FromBody]IpRestrictionsModel model)
{
return UpdateIpRestrictionsSettings(model);
}
[Update("iprestrictions/settings")]
[Consumes("application/x-www-form-urlencoded")]
public IPRestrictionsSettings UpdateIpRestrictionsSettingsFromForm([FromForm] IpRestrictionsModel model)
{
return UpdateIpRestrictionsSettings(model);
}
private IPRestrictionsSettings UpdateIpRestrictionsSettings(IpRestrictionsModel model)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
var settings = new IPRestrictionsSettings { Enable = model.Enable };
SettingsManager.Save(settings);
2019-08-12 10:53:12 +00:00
return settings;
}
[Update("tips")]
2020-11-06 09:03:49 +00:00
public TipsSettings UpdateTipsSettingsFromBody([FromBody]SettingsModel model)
{
return UpdateTipsSettings(model);
}
[Update("tips")]
[Consumes("application/x-www-form-urlencoded")]
public TipsSettings UpdateTipsSettingsFromForm([FromForm] SettingsModel model)
{
return UpdateTipsSettings(model);
}
private TipsSettings UpdateTipsSettings(SettingsModel model)
2019-08-12 10:53:12 +00:00
{
var settings = new TipsSettings { Show = model.Show };
SettingsManager.SaveForCurrentUser(settings);
2019-08-12 10:53:12 +00:00
if (!model.Show && !string.IsNullOrEmpty(SetupInfo.TipsAddress))
{
try
{
using var client = new WebClient();
var data = new NameValueCollection
{
2019-09-09 12:56:33 +00:00
["userId"] = AuthContext.CurrentAccount.ID.ToString(),
2019-08-12 10:53:12 +00:00
["tenantId"] = Tenant.TenantId.ToString(CultureInfo.InvariantCulture)
};
client.UploadValues(string.Format("{0}/tips/deletereaded", SetupInfo.TipsAddress), data);
}
catch (Exception e)
{
2019-10-17 15:55:35 +00:00
Log.Error(e.Message, e);
2019-08-12 10:53:12 +00:00
}
}
return settings;
}
[Update("tips/change/subscription")]
public bool UpdateTipsSubscription()
{
return StudioPeriodicNotify.ChangeSubscription(AuthContext.CurrentAccount.ID, StudioNotifyHelper);
2019-08-12 10:53:12 +00:00
}
2020-08-03 14:06:37 +00:00
[Update("wizard/complete", Check = false)]
2020-07-02 14:11:59 +00:00
[Authorize(AuthenticationSchemes = "confirm", Roles = "Wizard")]
2020-11-06 09:03:49 +00:00
public WizardSettings CompleteWizardFromBody([FromBody]WizardModel wizardModel)
{
return CompleteWizard(wizardModel);
}
[Update("wizard/complete", Check = false)]
[Authorize(AuthenticationSchemes = "confirm", Roles = "Wizard")]
[Consumes("application/x-www-form-urlencoded")]
public WizardSettings CompleteWizardFromForm([FromForm] WizardModel wizardModel)
{
return CompleteWizard(wizardModel);
}
private WizardSettings CompleteWizard(WizardModel wizardModel)
2019-08-12 10:53:12 +00:00
{
2020-07-02 14:11:59 +00:00
ApiContext.AuthByClaim();
2019-08-12 10:53:12 +00:00
2020-07-02 14:11:59 +00:00
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
2020-07-02 14:11:59 +00:00
return FirstTimeTenantSettings.SaveData(wizardModel);
2019-08-12 10:53:12 +00:00
}
2021-04-25 15:06:56 +00:00
[Read("tfaapp")]
public IEnumerable<TfaSettings> GetTfaSettings()
{
var result = new List<TfaSettings>();
var SmsVisible = StudioSmsNotificationSettingsHelper.IsVisibleSettings();
var SmsEnable = SmsVisible && SmsProviderManager.Enabled();
var TfaVisible = TfaAppAuthSettings.IsVisibleSettings;
if (SmsVisible)
{
result.Add(new TfaSettings
{
Enabled = StudioSmsNotificationSettingsHelper.Enable,
Id = "sms",
Title = Resource.ButtonSmsEnable,
Avaliable = SmsEnable
});
}
if (TfaVisible)
{
result.Add(new TfaSettings
{
Enabled = SettingsManager.Load<TfaAppAuthSettings>().EnableSetting,
Id = "app",
Title = Resource.ButtonTfaAppEnable,
Avaliable = true
});
}
return result;
}
2020-07-02 14:11:59 +00:00
2021-04-27 10:41:32 +00:00
[Read("tfaapp/confirm")]
public string TfaConfirmUrl()
{
var user = UserManager.GetUsers(AuthContext.CurrentAccount.ID);
if (StudioSmsNotificationSettingsHelper.IsVisibleSettings() && StudioSmsNotificationSettingsHelper.Enable)// && smsConfirm.ToLower() != "true")
{
var confirmType = string.IsNullOrEmpty(user.MobilePhone) ||
user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated
? ConfirmType.PhoneActivation
: ConfirmType.PhoneAuth;
return CommonLinkUtility.GetConfirmationUrl(user.Email, confirmType);
}
if (TfaAppAuthSettings.IsVisibleSettings && SettingsManager.Load<TfaAppAuthSettings>().EnableSetting)
{
var confirmType = TfaAppUserSettings.EnableForUser(SettingsManager, AuthContext.CurrentAccount.ID)
? ConfirmType.TfaAuth
: ConfirmType.TfaActivation;
return CommonLinkUtility.GetConfirmationUrl(user.Email, confirmType);
}
return string.Empty;
}
2019-08-12 10:53:12 +00:00
[Update("tfaapp")]
2020-11-06 09:03:49 +00:00
public bool TfaSettingsFromBody([FromBody]TfaModel model)
{
2021-04-25 15:06:56 +00:00
return TfaSettingsUpdate(model);
2020-11-06 09:03:49 +00:00
}
[Update("tfaapp")]
[Consumes("application/x-www-form-urlencoded")]
public bool TfaSettingsFromForm([FromForm] TfaModel model)
{
2021-04-25 15:06:56 +00:00
return TfaSettingsUpdate(model);
2020-11-06 09:03:49 +00:00
}
2021-04-25 15:06:56 +00:00
private bool TfaSettingsUpdate(TfaModel model)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
var result = false;
MessageAction action;
var settings = SettingsManager.Load<TfaAppAuthSettings>();
2019-08-12 10:53:12 +00:00
switch (model.Type)
{
case "sms":
if (!StudioSmsNotificationSettingsHelper.IsVisibleSettings())
2019-08-12 10:53:12 +00:00
throw new Exception(Resource.SmsNotAvailable);
if (!SmsProviderManager.Enabled())
throw new MethodAccessException();
StudioSmsNotificationSettingsHelper.Enable = true;
2019-08-12 10:53:12 +00:00
action = MessageAction.TwoFactorAuthenticationEnabledBySms;
if (settings.EnableSetting)
2019-08-12 10:53:12 +00:00
{
settings.EnableSetting = false;
SettingsManager.Save(settings);
2019-08-12 10:53:12 +00:00
}
result = true;
break;
case "app":
if (!TfaAppAuthSettings.IsVisibleSettings)
{
throw new Exception(Resource.TfaAppNotAvailable);
}
settings.EnableSetting = true;
SettingsManager.Save(settings);
2019-08-12 10:53:12 +00:00
action = MessageAction.TwoFactorAuthenticationEnabledByTfaApp;
if (StudioSmsNotificationSettingsHelper.IsVisibleSettings() && StudioSmsNotificationSettingsHelper.Enable)
2019-08-12 10:53:12 +00:00
{
StudioSmsNotificationSettingsHelper.Enable = false;
2019-08-12 10:53:12 +00:00
}
result = true;
break;
default:
if (settings.EnableSetting)
2019-08-12 10:53:12 +00:00
{
settings.EnableSetting = false;
SettingsManager.Save(settings);
2019-08-12 10:53:12 +00:00
}
if (StudioSmsNotificationSettingsHelper.IsVisibleSettings() && StudioSmsNotificationSettingsHelper.Enable)
2019-08-12 10:53:12 +00:00
{
StudioSmsNotificationSettingsHelper.Enable = false;
2019-08-12 10:53:12 +00:00
}
action = MessageAction.TwoFactorAuthenticationDisabled;
break;
}
if (result)
{
2019-09-09 12:56:33 +00:00
CookiesManager.ResetTenantCookie();
2019-08-12 10:53:12 +00:00
}
MessageService.Send(action);
return result;
}
[Read("tfaapp/setup")]
[Authorize(AuthenticationSchemes = "confirm", Roles = "TfaActivation")]
public SetupCode TfaAppGenerateSetupCode()
{
ApiContext.AuthByClaim();
var currentUser = UserManager.GetUsers(AuthContext.CurrentAccount.ID);
if (!TfaAppAuthSettings.IsVisibleSettings ||
!SettingsManager.Load<TfaAppAuthSettings>().EnableSetting ||
TfaAppUserSettings.EnableForUser(SettingsManager, currentUser.ID))
throw new Exception(Resource.TfaAppNotAvailable);
if (currentUser.IsVisitor(UserManager) || currentUser.IsOutsider(UserManager))
throw new NotSupportedException("Not available.");
return TfaManager.GenerateSetupCode(currentUser, 300);
}
2019-08-12 10:53:12 +00:00
[Read("tfaappcodes")]
public IEnumerable<object> TfaAppGetCodes()
{
2019-09-09 12:56:33 +00:00
var currentUser = UserManager.GetUsers(AuthContext.CurrentAccount.ID);
2019-08-12 10:53:12 +00:00
if (!TfaAppAuthSettings.IsVisibleSettings || !TfaAppUserSettings.EnableForUser(SettingsManager, currentUser.ID))
2019-08-12 10:53:12 +00:00
throw new Exception(Resource.TfaAppNotAvailable);
if (currentUser.IsVisitor(UserManager) || currentUser.IsOutsider(UserManager))
2019-08-12 10:53:12 +00:00
throw new NotSupportedException("Not available.");
return SettingsManager.LoadForCurrentUser<TfaAppUserSettings>().CodesSetting.Select(r => new { r.IsUsed, r.Code }).ToList();
2019-08-12 10:53:12 +00:00
}
[Update("tfaappnewcodes")]
public IEnumerable<object> TfaAppRequestNewCodes()
{
var currentUser = UserManager.GetUsers(AuthContext.CurrentAccount.ID);
2019-08-12 10:53:12 +00:00
if (!TfaAppAuthSettings.IsVisibleSettings || !TfaAppUserSettings.EnableForUser(SettingsManager, currentUser.ID))
2019-08-12 10:53:12 +00:00
throw new Exception(Resource.TfaAppNotAvailable);
if (currentUser.IsVisitor(UserManager) || currentUser.IsOutsider(UserManager))
2019-08-12 10:53:12 +00:00
throw new NotSupportedException("Not available.");
2020-10-12 13:52:31 +00:00
var codes = TfaManager.GenerateBackupCodes().Select(r => new { r.IsUsed, r.Code }).ToList();
MessageService.Send(MessageAction.UserConnectedTfaApp, MessageTarget.Create(currentUser.ID), currentUser.DisplayUserName(false, DisplayUserSettingsHelper));
2019-08-12 10:53:12 +00:00
return codes;
}
[Update("tfaappnewapp")]
2020-11-06 09:03:49 +00:00
public object TfaAppNewAppFromBody([FromBody]TfaModel model)
{
return TfaAppNewApp(model);
}
[Update("tfaappnewapp")]
[Consumes("application/x-www-form-urlencoded")]
public object TfaAppNewAppFromForm([FromForm] TfaModel model)
{
return TfaAppNewApp(model);
}
private object TfaAppNewApp(TfaModel model)
2019-08-12 10:53:12 +00:00
{
var isMe = model.Id.Equals(Guid.Empty);
2019-09-09 12:56:33 +00:00
var user = UserManager.GetUsers(isMe ? AuthContext.CurrentAccount.ID : model.Id);
2019-08-12 10:53:12 +00:00
if (!isMe && !PermissionContext.CheckPermissions(new UserSecurityProvider(user.ID), Constants.Action_EditUser))
2019-08-12 10:53:12 +00:00
throw new SecurityAccessDeniedException(Resource.ErrorAccessDenied);
if (!TfaAppAuthSettings.IsVisibleSettings || !TfaAppUserSettings.EnableForUser(SettingsManager, user.ID))
2019-08-12 10:53:12 +00:00
throw new Exception(Resource.TfaAppNotAvailable);
if (user.IsVisitor(UserManager) || user.IsOutsider(UserManager))
2019-08-12 10:53:12 +00:00
throw new NotSupportedException("Not available.");
2019-11-08 15:11:30 +00:00
TfaAppUserSettings.DisableForUser(ServiceProvider, SettingsManager, user.ID);
MessageService.Send(MessageAction.UserDisconnectedTfaApp, MessageTarget.Create(user.ID), user.DisplayUserName(false, DisplayUserSettingsHelper));
2019-08-12 10:53:12 +00:00
if (isMe)
{
2019-09-19 15:55:44 +00:00
return CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaActivation);
2019-08-12 10:53:12 +00:00
}
2019-09-17 12:42:32 +00:00
StudioNotifyService.SendMsgTfaReset(user);
2019-08-12 10:53:12 +00:00
return string.Empty;
}
2020-09-17 12:04:28 +00:00
2019-08-12 10:53:12 +00:00
///<visible>false</visible>
[Update("welcome/close")]
public void CloseWelcomePopup()
{
2019-09-09 12:56:33 +00:00
var currentUser = UserManager.GetUsers(AuthContext.CurrentAccount.ID);
2019-08-12 10:53:12 +00:00
var collaboratorPopupSettings = SettingsManager.LoadForCurrentUser<CollaboratorSettings>();
2019-08-12 10:53:12 +00:00
if (!(currentUser.IsVisitor(UserManager) && collaboratorPopupSettings.FirstVisit && !currentUser.IsOutsider(UserManager)))
2019-08-12 10:53:12 +00:00
throw new NotSupportedException("Not available.");
collaboratorPopupSettings.FirstVisit = false;
SettingsManager.SaveForCurrentUser(collaboratorPopupSettings);
2019-08-12 10:53:12 +00:00
}
///<visible>false</visible>
[Update("colortheme")]
2020-11-06 09:03:49 +00:00
public void SaveColorThemeFromBody([FromBody]SettingsModel model)
{
SaveColorTheme(model);
}
[Update("colortheme")]
[Consumes("application/x-www-form-urlencoded")]
public void SaveColorThemeFromForm([FromForm] SettingsModel model)
{
SaveColorTheme(model);
}
private void SaveColorTheme(SettingsModel model)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
ColorThemesSettingsHelper.SaveColorTheme(model.Theme);
2019-08-12 10:53:12 +00:00
MessageService.Send(MessageAction.ColorThemeChanged);
}
///<visible>false</visible>
[Update("timeandlanguage")]
2020-11-06 09:03:49 +00:00
public object TimaAndLanguageFromBody([FromBody]SettingsModel model)
{
return TimaAndLanguage(model);
}
[Update("timeandlanguage")]
[Consumes("application/x-www-form-urlencoded")]
public object TimaAndLanguageFromForm([FromForm] SettingsModel model)
{
return TimaAndLanguage(model);
}
private object TimaAndLanguage(SettingsModel model)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
var culture = CultureInfo.GetCultureInfo(model.Lng);
var changelng = false;
if (SetupInfo.EnabledCultures.Find(c => string.Equals(c.Name, culture.Name, StringComparison.InvariantCultureIgnoreCase)) != null)
{
if (!string.Equals(Tenant.Language, culture.Name, StringComparison.InvariantCultureIgnoreCase))
{
Tenant.Language = culture.Name;
changelng = true;
}
}
var oldTimeZone = Tenant.TimeZone;
var timeZones = TimeZoneInfo.GetSystemTimeZones().ToList();
if (timeZones.All(tz => tz.Id != "UTC"))
{
timeZones.Add(TimeZoneInfo.Utc);
}
2019-12-03 15:20:21 +00:00
Tenant.TimeZone = timeZones.FirstOrDefault(tz => tz.Id == model.TimeZoneID)?.Id ?? TimeZoneInfo.Utc.Id;
2019-08-12 10:53:12 +00:00
2019-09-09 12:56:33 +00:00
TenantManager.SaveTenant(Tenant);
2019-08-12 10:53:12 +00:00
2019-12-03 15:20:21 +00:00
if (!Tenant.TimeZone.Equals(oldTimeZone) || changelng)
2019-08-12 10:53:12 +00:00
{
2019-12-03 15:20:21 +00:00
if (!Tenant.TimeZone.Equals(oldTimeZone))
2019-08-12 10:53:12 +00:00
{
MessageService.Send(MessageAction.TimeZoneSettingsUpdated);
}
if (changelng)
{
MessageService.Send(MessageAction.LanguageSettingsUpdated);
}
}
return Resource.SuccessfullySaveSettingsMessage;
}
[Create("owner")]
2020-11-06 09:03:49 +00:00
public object SendOwnerChangeInstructionsFromBody([FromBody]SettingsModel model)
{
return SendOwnerChangeInstructions(model);
}
[Create("owner")]
[Consumes("application/x-www-form-urlencoded")]
public object SendOwnerChangeInstructionsFromForm([FromForm] SettingsModel model)
{
return SendOwnerChangeInstructions(model);
}
private object SendOwnerChangeInstructions(SettingsModel model)
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var curTenant = TenantManager.GetCurrentTenant();
var owner = UserManager.GetUsers(curTenant.OwnerId);
var newOwner = UserManager.GetUsers(model.OwnerId);
if (newOwner.IsVisitor(UserManager)) throw new System.Security.SecurityException("Collaborator can not be an owner");
if (!owner.ID.Equals(AuthContext.CurrentAccount.ID) || Guid.Empty.Equals(newOwner.ID))
{
return new { Status = 0, Message = Resource.ErrorAccessDenied };
}
var confirmLink = CommonLinkUtility.GetConfirmationUrl(owner.Email, ConfirmType.PortalOwnerChange, newOwner.ID, newOwner.ID);
StudioNotifyService.SendMsgConfirmChangeOwner(owner, newOwner, confirmLink);
MessageService.Send(MessageAction.OwnerSentChangeOwnerInstructions, MessageTarget.Create(owner.ID), owner.DisplayUserName(false, DisplayUserSettingsHelper));
var emailLink = string.Format("<a href=\"mailto:{0}\">{0}</a>", owner.Email);
return new { Status = 1, Message = Resource.ChangePortalOwnerMsg.Replace(":email", emailLink) };
}
[Update("owner")]
[Authorize(AuthenticationSchemes = "confirm", Roles = "PortalOwnerChange")]
2020-11-06 09:03:49 +00:00
public void OwnerFromBody([FromBody]SettingsModel model)
{
Owner(model);
}
[Update("owner")]
[Authorize(AuthenticationSchemes = "confirm", Roles = "PortalOwnerChange")]
[Consumes("application/x-www-form-urlencoded")]
public void OwnerFromForm([FromForm] SettingsModel model)
{
Owner(model);
}
private void Owner(SettingsModel model)
{
var newOwner = Constants.LostUser;
try
{
newOwner = UserManager.GetUsers(model.OwnerId);
}
catch
{
}
if (Constants.LostUser.Equals(newOwner))
{
throw new Exception(Resource.ErrorUserNotFound);
}
if (UserManager.IsUserInGroup(newOwner.ID, Constants.GroupVisitor.ID))
{
throw new Exception(Resource.ErrorUserNotFound);
}
var curTenant = TenantManager.GetCurrentTenant();
curTenant.OwnerId = newOwner.ID;
TenantManager.SaveTenant(curTenant);
MessageService.Send(MessageAction.OwnerUpdated, newOwner.DisplayUserName(false, DisplayUserSettingsHelper));
}
2019-08-12 10:53:12 +00:00
///<visible>false</visible>
[Update("defaultpage")]
2020-11-06 09:03:49 +00:00
public object SaveDefaultPageSettingsFromBody([FromBody]SettingsModel model)
{
return SaveDefaultPageSettings(model);
}
[Update("defaultpage")]
[Consumes("application/x-www-form-urlencoded")]
public object SaveDefaultPageSettingsFromForm([FromForm] SettingsModel model)
{
return SaveDefaultPageSettings(model);
}
private object SaveDefaultPageSettings(SettingsModel model)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
SettingsManager.Save(new StudioDefaultPageSettings { DefaultProductID = model.DefaultProductID });
2019-08-12 10:53:12 +00:00
MessageService.Send(MessageAction.DefaultStartPageSettingsUpdated);
return Resource.SuccessfullySaveSettingsMessage;
}
private string GetProductName(Guid productId)
2019-08-12 10:53:12 +00:00
{
var product = WebItemManager[productId];
2019-08-12 10:53:12 +00:00
return productId == Guid.Empty ? "All" : product != null ? product.Name : productId.ToString();
}
2020-08-11 08:52:39 +00:00
[Read("license/refresh", Check = false)]
2019-08-12 10:53:12 +00:00
public bool RefreshLicense()
{
2019-09-18 15:19:30 +00:00
if (!CoreBaseSettings.Standalone) return false;
2019-08-12 10:53:12 +00:00
LicenseReader.RefreshLicense();
return true;
}
[Create("license/accept", Check = false)]
public object AcceptLicense()
{
if (!CoreBaseSettings.Standalone) return "";
TariffSettings.SetLicenseAccept(SettingsManager);
MessageService.Send(MessageAction.LicenseKeyUploaded);
try
{
LicenseReader.RefreshLicense();
}
catch (BillingNotFoundException)
{
return UserControlsCommonResource.LicenseKeyNotFound;
}
catch (BillingNotConfiguredException)
{
return UserControlsCommonResource.LicenseKeyNotCorrect;
}
catch (BillingException)
{
return UserControlsCommonResource.LicenseException;
}
catch (Exception ex)
{
return ex.Message;
}
return "";
}
2020-12-28 13:22:08 +00:00
///<visible>false</visible>
[Create("license/trial")]
public bool ActivateTrial()
{
if (!CoreBaseSettings.Standalone) throw new NotSupportedException();
if (!UserManager.GetUsers(AuthContext.CurrentAccount.ID).IsAdmin(UserManager)) throw new SecurityException();
var curQuota = TenantExtra.GetTenantQuota();
if (curQuota.Id != Tenant.DEFAULT_TENANT) return false;
if (curQuota.Trial) return false;
var curTariff = TenantExtra.GetCurrentTariff();
if (curTariff.DueDate.Date != DateTime.MaxValue.Date) return false;
var quota = new TenantQuota(-1000)
{
Name = "apirequest",
ActiveUsers = curQuota.ActiveUsers,
MaxFileSize = curQuota.MaxFileSize,
MaxTotalSize = curQuota.MaxTotalSize,
Features = curQuota.Features
};
quota.Trial = true;
TenantManager.SaveTenantQuota(quota);
var DEFAULT_TRIAL_PERIOD = 30;
var tariff = new Tariff
{
QuotaId = quota.Id,
DueDate = DateTime.Today.AddDays(DEFAULT_TRIAL_PERIOD)
};
PaymentManager.SetTariff(-1, tariff);
MessageService.Send(MessageAction.LicenseKeyUploaded);
return true;
}
[AllowAnonymous]
2020-08-03 14:06:37 +00:00
[Read("license/required", Check = false)]
public bool RequestLicense()
{
return FirstTimeTenantSettings.RequestLicense;
}
2020-08-03 14:06:37 +00:00
[Create("license", Check = false)]
[Authorize(AuthenticationSchemes = "confirm", Roles = "Wizard, Administrators")]
2020-08-26 14:34:21 +00:00
public object UploadLicense([FromForm] UploadLicenseModel model)
{
try
{
ApiContext.AuthByClaim();
if (!AuthContext.IsAuthenticated && SettingsManager.Load<WizardSettings>().Completed) throw new SecurityException(Resource.PortalSecurity);
if (!model.Files.Any()) throw new Exception(Resource.ErrorEmptyUploadFileSelected);
var licenseFile = model.Files.First();
var dueDate = LicenseReader.SaveLicenseTemp(licenseFile.OpenReadStream());
return dueDate >= DateTime.UtcNow.Date
? Resource.LicenseUploaded
2020-12-28 13:22:08 +00:00
: string.Format(
(TenantExtra.GetTenantQuota().Update
? Resource.LicenseUploadedOverdueSupport
: Resource.LicenseUploadedOverdue),
"",
"",
dueDate.Date.ToLongDateString());
}
catch (LicenseExpiredException ex)
{
Log.Error("License upload", ex);
throw new Exception(Resource.LicenseErrorExpired);
}
catch (LicenseQuotaException ex)
{
Log.Error("License upload", ex);
throw new Exception(Resource.LicenseErrorQuota);
}
catch (LicensePortalException ex)
{
Log.Error("License upload", ex);
throw new Exception(Resource.LicenseErrorPortal);
}
catch (Exception ex)
{
Log.Error("License upload", ex);
throw new Exception(Resource.LicenseError);
}
}
2019-08-12 10:53:12 +00:00
[Read("customnavigation/getall")]
public List<CustomNavigationItem> GetCustomNavigationItems()
{
return SettingsManager.Load<CustomNavigationSettings>().Items;
2019-08-12 10:53:12 +00:00
}
[Read("customnavigation/getsample")]
public CustomNavigationItem GetCustomNavigationItemSample()
{
return CustomNavigationItem.GetSample();
}
[Read("customnavigation/get/{id}")]
public CustomNavigationItem GetCustomNavigationItem(Guid id)
{
return SettingsManager.Load<CustomNavigationSettings>().Items.FirstOrDefault(item => item.Id == id);
2019-08-12 10:53:12 +00:00
}
[Create("customnavigation/create")]
2020-11-06 09:03:49 +00:00
public CustomNavigationItem CreateCustomNavigationItemFromBody([FromBody]CustomNavigationItem item)
{
return CreateCustomNavigationItem(item);
}
[Create("customnavigation/create")]
[Consumes("application/x-www-form-urlencoded")]
public CustomNavigationItem CreateCustomNavigationItemFromForm([FromForm] CustomNavigationItem item)
{
return CreateCustomNavigationItem(item);
}
private CustomNavigationItem CreateCustomNavigationItem(CustomNavigationItem item)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
var settings = SettingsManager.Load<CustomNavigationSettings>();
2019-08-12 10:53:12 +00:00
var exist = false;
foreach (var existItem in settings.Items)
{
if (existItem.Id != item.Id) continue;
existItem.Label = item.Label;
existItem.Url = item.Url;
existItem.ShowInMenu = item.ShowInMenu;
existItem.ShowOnHomePage = item.ShowOnHomePage;
if (existItem.SmallImg != item.SmallImg)
{
StorageHelper.DeleteLogo(existItem.SmallImg);
2019-09-13 11:18:27 +00:00
existItem.SmallImg = StorageHelper.SaveTmpLogo(item.SmallImg);
2019-08-12 10:53:12 +00:00
}
if (existItem.BigImg != item.BigImg)
{
StorageHelper.DeleteLogo(existItem.BigImg);
2019-09-13 11:18:27 +00:00
existItem.BigImg = StorageHelper.SaveTmpLogo(item.BigImg);
2019-08-12 10:53:12 +00:00
}
exist = true;
break;
}
if (!exist)
{
item.Id = Guid.NewGuid();
2019-09-13 11:18:27 +00:00
item.SmallImg = StorageHelper.SaveTmpLogo(item.SmallImg);
item.BigImg = StorageHelper.SaveTmpLogo(item.BigImg);
2019-08-12 10:53:12 +00:00
settings.Items.Add(item);
}
SettingsManager.Save(settings);
2019-08-12 10:53:12 +00:00
MessageService.Send(MessageAction.CustomNavigationSettingsUpdated);
return item;
}
[Delete("customnavigation/delete/{id}")]
public void DeleteCustomNavigationItem(Guid id)
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
var settings = SettingsManager.Load<CustomNavigationSettings>();
2019-08-12 10:53:12 +00:00
var terget = settings.Items.FirstOrDefault(item => item.Id == id);
if (terget == null) return;
StorageHelper.DeleteLogo(terget.SmallImg);
StorageHelper.DeleteLogo(terget.BigImg);
settings.Items.Remove(terget);
SettingsManager.Save(settings);
2019-08-12 10:53:12 +00:00
MessageService.Send(MessageAction.CustomNavigationSettingsUpdated);
}
[Update("emailactivation")]
2020-11-10 10:41:32 +00:00
public EmailActivationSettings UpdateEmailActivationSettingsFromBody([FromBody]EmailActivationSettings settings)
2019-08-12 10:53:12 +00:00
{
SettingsManager.SaveForCurrentUser(settings);
2020-11-10 10:41:32 +00:00
return settings;
}
2019-08-12 10:53:12 +00:00
2020-11-10 10:41:32 +00:00
[Update("emailactivation")]
[Consumes("application/x-www-form-urlencoded")]
public EmailActivationSettings UpdateEmailActivationSettingsFromForm([FromForm]EmailActivationSettings settings)
2020-11-06 09:03:49 +00:00
{
SettingsManager.SaveForCurrentUser(settings);
2019-08-12 10:53:12 +00:00
return settings;
}
///<visible>false</visible>
[Read("companywhitelabel")]
2020-09-17 12:04:28 +00:00
public List<CompanyWhiteLabelSettings> GetLicensorData()
2019-08-12 10:53:12 +00:00
{
var result = new List<CompanyWhiteLabelSettings>();
var instance = CompanyWhiteLabelSettings.Instance(SettingsManager);
2019-08-12 10:53:12 +00:00
result.Add(instance);
2020-09-18 14:45:59 +00:00
if (!instance.IsDefault(CoreSettings) && !instance.GetIsLicensor(TenantManager, CoreSettings))
2019-08-12 10:53:12 +00:00
{
2019-11-08 15:11:30 +00:00
result.Add(instance.GetDefault(ServiceProvider) as CompanyWhiteLabelSettings);
2019-08-12 10:53:12 +00:00
}
return result;
}
[Read("statistics/spaceusage/{id}")]
public List<UsageSpaceStatItemWrapper> GetSpaceUsageStatistics(Guid id)
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
2019-09-16 14:51:39 +00:00
var webtem = WebItemManagerSecurity.GetItems(WebZoneType.All, ItemAvailableState.All)
2019-08-12 10:53:12 +00:00
.FirstOrDefault(item =>
item != null &&
item.ID == id &&
item.Context != null &&
item.Context.SpaceUsageStatManager != null);
if (webtem == null) return new List<UsageSpaceStatItemWrapper>();
return webtem.Context.SpaceUsageStatManager.GetStatData()
.ConvertAll(it => new UsageSpaceStatItemWrapper
2019-08-15 12:04:42 +00:00
{
Name = it.Name.HtmlEncode(),
Icon = it.ImgUrl,
Disabled = it.Disabled,
Size = FileSizeComment.FilesSizeToString(it.SpaceUsage),
Url = it.Url
});
2019-08-12 10:53:12 +00:00
}
[Read("statistics/visit")]
public List<ChartPointWrapper> GetVisitStatistics(ApiDateTime fromDate, ApiDateTime toDate)
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
var from = TenantUtil.DateTimeFromUtc(fromDate);
var to = TenantUtil.DateTimeFromUtc(toDate);
var points = new List<ChartPointWrapper>();
if (from.CompareTo(to) >= 0) return points;
for (var d = new DateTime(from.Ticks); d.Date.CompareTo(to.Date) <= 0; d = d.AddDays(1))
{
points.Add(new ChartPointWrapper
2019-08-15 12:04:42 +00:00
{
DisplayDate = d.Date.ToShortDateString(),
Date = d.Date,
Hosts = 0,
Hits = 0
});
2019-08-12 10:53:12 +00:00
}
2019-09-02 15:10:27 +00:00
var hits = StatisticManager.GetHitsByPeriod(Tenant.TenantId, from, to);
var hosts = StatisticManager.GetHostsByPeriod(Tenant.TenantId, from, to);
2019-08-12 10:53:12 +00:00
if (hits.Count == 0 || hosts.Count == 0) return points;
hits.Sort((x, y) => x.VisitDate.CompareTo(y.VisitDate));
hosts.Sort((x, y) => x.VisitDate.CompareTo(y.VisitDate));
for (int i = 0, n = points.Count, hitsNum = 0, hostsNum = 0; i < n; i++)
{
while (hitsNum < hits.Count && points[i].Date.CompareTo(hits[hitsNum].VisitDate.Date) == 0)
{
points[i].Hits += hits[hitsNum].VisitCount;
hitsNum++;
}
while (hostsNum < hosts.Count && points[i].Date.CompareTo(hosts[hostsNum].VisitDate.Date) == 0)
{
points[i].Hosts++;
hostsNum++;
}
}
return points;
}
[Read("storage")]
public List<StorageWrapper> GetAllStorages()
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
TenantExtra.DemandControlPanelPermission();
var current = SettingsManager.Load<StorageSettings>();
2019-08-12 10:53:12 +00:00
var consumers = ConsumerFactory.GetAll<DataStoreConsumer>().ToList();
return consumers.Select(consumer => new StorageWrapper(consumer, current)).ToList();
}
[Read("storage/progress", false)]
public double GetStorageProgress()
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-08-12 10:53:12 +00:00
2019-09-18 15:19:30 +00:00
if (!CoreBaseSettings.Standalone) return -1;
2019-08-12 10:53:12 +00:00
2020-08-24 06:52:17 +00:00
return ServiceClient.GetProgress(Tenant.TenantId);
2019-08-12 10:53:12 +00:00
}
2020-09-17 13:56:12 +00:00
public readonly object Locker = new object();
[Create("encryption/start")]
2020-11-06 09:03:49 +00:00
public bool StartStorageEncryptionFromBody([FromBody]StorageEncryptionModel storageEncryption)
{
return StartStorageEncryption(storageEncryption);
}
[Create("encryption/start")]
[Consumes("application/x-www-form-urlencoded")]
public bool StartStorageEncryptionFromForm([FromForm] StorageEncryptionModel storageEncryption)
{
return StartStorageEncryption(storageEncryption);
}
private bool StartStorageEncryption(StorageEncryptionModel storageEncryption)
2020-09-17 13:56:12 +00:00
{
2020-12-28 13:22:08 +00:00
if (CoreBaseSettings.CustomMode)
{
return false;
}
2020-09-17 13:56:12 +00:00
lock (Locker)
{
var activeTenants = TenantManager.GetTenants();
if (activeTenants.Any())
{
StartEncryption(storageEncryption.NotifyUsers);
}
}
return true;
2020-09-17 13:56:12 +00:00
}
private void StartEncryption(bool notifyUsers)
{
if (!SetupInfo.IsVisibleSettings<EncryptionSettings>())
{
throw new NotSupportedException();
}
if (!CoreBaseSettings.Standalone)
{
throw new NotSupportedException();
}
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
TenantExtra.DemandControlPanelPermission();
if (!TenantManager.GetTenantQuota(TenantManager.GetCurrentTenant().TenantId).DiscEncryption)
{
2020-09-18 10:06:32 +00:00
throw new BillingException(Resource.ErrorNotAllowedOption, "DiscEncryption");
2020-09-17 13:56:12 +00:00
}
var storages = GetAllStorages();
if (storages.Any(s => s.Current))
{
throw new NotSupportedException();
}
var cdnStorages = GetAllCdnStorages();
if (cdnStorages.Any(s => s.Current))
{
throw new NotSupportedException();
}
var tenants = TenantManager.GetTenants();
foreach (var tenant in tenants)
{
2020-09-18 17:57:51 +00:00
var progress = BackupServiceNotifier.GetBackupProgress(tenant.TenantId);
2020-09-17 13:56:12 +00:00
if (progress != null && progress.IsCompleted == false)
{
throw new Exception();
}
}
foreach (var tenant in tenants)
{
CacheDeleteSchedule.Publish(new DeleteSchedule() { TenantId = tenant.TenantId }, CacheNotifyAction.Insert);
}
var settings = EncryptionSettingsHelper.Load();
settings.NotifyUsers = notifyUsers;
if (settings.Status == EncryprtionStatus.Decrypted)
{
settings.Status = EncryprtionStatus.EncryptionStarted;
settings.Password = EncryptionSettingsHelper.GeneratePassword(32, 16);
}
else if (settings.Status == EncryprtionStatus.Encrypted)
{
settings.Status = EncryprtionStatus.DecryptionStarted;
}
MessageService.Send(settings.Status == EncryprtionStatus.EncryptionStarted ? MessageAction.StartStorageEncryption : MessageAction.StartStorageDecryption);
var serverRootPath = CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/');
foreach (var tenant in tenants)
{
TenantManager.SetCurrentTenant(tenant);
if (notifyUsers)
{
if (settings.Status == EncryprtionStatus.EncryptionStarted)
{
StudioNotifyService.SendStorageEncryptionStart(serverRootPath);
}
else
{
StudioNotifyService.SendStorageDecryptionStart(serverRootPath);
}
}
tenant.SetStatus(TenantStatus.Encryption);
TenantManager.SaveTenant(tenant);
}
EncryptionSettingsHelper.Save(settings);
2020-09-18 17:57:51 +00:00
var encryptionSettingsProto = new EncryptionSettingsProto
2020-09-17 13:56:12 +00:00
{
NotifyUsers = settings.NotifyUsers,
Password = settings.Password,
Status = settings.Status,
ServerRootPath = serverRootPath
};
EncryptionServiceClient.Start(encryptionSettingsProto);
}
/// <summary>
/// Get storage encryption settings
/// </summary>
/// <returns>EncryptionSettings</returns>
/// <visible>false</visible>
[Read("encryption/settings")]
public EncryptionSettings GetStorageEncryptionSettings()
{
try
{
2020-12-28 13:22:08 +00:00
if (CoreBaseSettings.CustomMode)
{
return null;
}
if (!SetupInfo.IsVisibleSettings<EncryptionSettings>())
{
throw new NotSupportedException();
}
if (!CoreBaseSettings.Standalone)
{
throw new NotSupportedException();
}
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
TenantExtra.DemandControlPanelPermission();
if (!TenantManager.GetTenantQuota(TenantManager.GetCurrentTenant().TenantId).DiscEncryption)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "DiscEncryption");
}
var settings = EncryptionSettingsHelper.Load();
settings.Password = string.Empty; // Don't show password
return settings;
}
catch (Exception e)
{
Log.Error("GetStorageEncryptionSettings", e);
return null;
}
}
[Read("encryption/progress")]
2020-09-18 17:57:51 +00:00
public double? GetStorageEncryptionProgress()
2020-09-07 15:04:26 +00:00
{
2020-12-28 13:22:08 +00:00
if (CoreBaseSettings.CustomMode)
{
return -1;
}
if (!SetupInfo.IsVisibleSettings<EncryptionSettings>())
{
throw new NotSupportedException();
}
if (!CoreBaseSettings.Standalone)
{
throw new NotSupportedException();
}
if (!TenantManager.GetTenantQuota(TenantManager.GetCurrentTenant().TenantId).DiscEncryption)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "DiscEncryption");
}
2020-09-18 17:57:51 +00:00
return EncryptionServiceNotifier.GetEncryptionProgress(Tenant.TenantId)?.Progress;
2020-09-07 15:04:26 +00:00
}
2019-08-12 10:53:12 +00:00
[Update("storage")]
2020-11-06 09:03:49 +00:00
public StorageSettings UpdateStorageFromBody([FromBody]StorageModel model)
{
return UpdateStorage(model);
}
[Update("storage")]
[Consumes("application/x-www-form-urlencoded")]
public StorageSettings UpdateStorageFromForm([FromForm] StorageModel model)
{
return UpdateStorage(model);
}
private StorageSettings UpdateStorage(StorageModel model)
2019-08-12 10:53:12 +00:00
{
2020-01-21 12:44:05 +00:00
try
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!CoreBaseSettings.Standalone) return null;
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
TenantExtra.DemandControlPanelPermission();
2020-01-21 12:44:05 +00:00
var consumer = ConsumerFactory.GetByKey(model.Module);
if (!consumer.IsSet)
throw new ArgumentException("module");
2019-08-12 10:53:12 +00:00
2020-01-21 12:44:05 +00:00
var settings = SettingsManager.Load<StorageSettings>();
if (settings.Module == model.Module) return settings;
2019-08-12 10:53:12 +00:00
2020-01-21 12:44:05 +00:00
settings.Module = model.Module;
settings.Props = model.Props.ToDictionary(r => r.Key, b => b.Value);
2019-08-12 10:53:12 +00:00
StartMigrate(settings);
2020-01-21 12:44:05 +00:00
return settings;
2019-08-12 10:53:12 +00:00
}
catch (Exception e)
{
2019-10-17 15:55:35 +00:00
Log.Error("UpdateStorage", e);
2019-08-12 10:53:12 +00:00
throw;
}
}
[Delete("storage")]
public void ResetStorageToDefault()
{
2020-01-21 12:44:05 +00:00
try
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!CoreBaseSettings.Standalone) return;
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
TenantExtra.DemandControlPanelPermission();
2020-01-21 12:44:05 +00:00
var settings = SettingsManager.Load<StorageSettings>();
settings.Module = null;
settings.Props = null;
2019-08-12 10:53:12 +00:00
StartMigrate(settings);
}
catch (Exception e)
{
2019-10-17 15:55:35 +00:00
Log.Error("ResetStorageToDefault", e);
2019-08-12 10:53:12 +00:00
throw;
}
}
[Read("storage/cdn")]
public List<StorageWrapper> GetAllCdnStorages()
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-09-18 15:19:30 +00:00
if (!CoreBaseSettings.Standalone) return null;
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
TenantExtra.DemandControlPanelPermission();
var current = SettingsManager.Load<CdnStorageSettings>();
2019-08-12 10:53:12 +00:00
var consumers = ConsumerFactory.GetAll<DataStoreConsumer>().Where(r => r.Cdn != null).ToList();
return consumers.Select(consumer => new StorageWrapper(consumer, current)).ToList();
}
[Update("storage/cdn")]
2020-11-06 09:03:49 +00:00
public CdnStorageSettings UpdateCdnFromBody([FromBody]StorageModel model)
{
return UpdateCdn(model);
}
[Update("storage/cdn")]
[Consumes("application/x-www-form-urlencoded")]
public CdnStorageSettings UpdateCdnFromForm([FromForm] StorageModel model)
{
return UpdateCdn(model);
}
private CdnStorageSettings UpdateCdn(StorageModel model)
2019-08-12 10:53:12 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-09-18 15:19:30 +00:00
if (!CoreBaseSettings.Standalone) return null;
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
TenantExtra.DemandControlPanelPermission();
2019-12-20 11:17:01 +00:00
var consumer = ConsumerFactory.GetByKey(model.Module);
2019-08-12 10:53:12 +00:00
if (!consumer.IsSet)
throw new ArgumentException("module");
var settings = SettingsManager.Load<CdnStorageSettings>();
2019-08-12 10:53:12 +00:00
if (settings.Module == model.Module) return settings;
settings.Module = model.Module;
settings.Props = model.Props.ToDictionary(r => r.Key, b => b.Value);
try
{
2020-08-24 06:52:17 +00:00
ServiceClient.UploadCdn(Tenant.TenantId, "/", WebHostEnvironment.ContentRootPath, settings);
2019-08-12 10:53:12 +00:00
}
catch (Exception e)
{
2019-10-17 15:55:35 +00:00
Log.Error("UpdateCdn", e);
2019-08-12 10:53:12 +00:00
throw;
}
return settings;
}
[Delete("storage/cdn")]
public void ResetCdnToDefault()
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2019-09-18 15:19:30 +00:00
if (!CoreBaseSettings.Standalone) return;
2019-08-12 10:53:12 +00:00
2020-09-17 12:04:28 +00:00
TenantExtra.DemandControlPanelPermission();
StorageSettingsHelper.Clear(SettingsManager.Load<CdnStorageSettings>());
2019-08-12 10:53:12 +00:00
}
[Read("storage/backup")]
public List<StorageWrapper> GetAllBackupStorages()
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
2020-11-03 15:16:23 +00:00
if (CoreBaseSettings.Standalone)
{
TenantExtra.DemandControlPanelPermission();
}
var schedule = BackupAjaxHandler.GetSchedule();
var current = new StorageSettings();
2019-08-12 10:53:12 +00:00
if (schedule != null && schedule.StorageType == BackupStorageType.ThirdPartyConsumer)
{
current = new StorageSettings
{
Module = schedule.StorageParams["module"],
Props = schedule.StorageParams.Where(r => r.Key != "module").ToDictionary(r => r.Key, r => r.Value)
};
}
2019-08-12 10:53:12 +00:00
var consumers = ConsumerFactory.GetAll<DataStoreConsumer>().ToList();
return consumers.Select(consumer => new StorageWrapper(consumer, current)).ToList();
}
2019-08-12 10:53:12 +00:00
private void StartMigrate(StorageSettings settings)
{
2020-08-24 06:52:17 +00:00
ServiceClient.Migrate(Tenant.TenantId, settings);
2019-08-12 10:53:12 +00:00
Tenant.SetStatus(TenantStatus.Migrating);
2020-01-21 12:44:05 +00:00
TenantManager.SaveTenant(Tenant);
2019-08-12 10:53:12 +00:00
}
[Read("socket")]
public object GetSocketSettings()
{
2019-09-23 12:20:08 +00:00
var hubUrl = Configuration["web:hub"] ?? string.Empty;
2019-08-12 10:53:12 +00:00
if (hubUrl != string.Empty)
{
if (!hubUrl.EndsWith("/"))
{
hubUrl += "/";
}
}
return new { Url = hubUrl };
}
2020-07-24 14:01:20 +00:00
2020-09-17 12:04:28 +00:00
///<visible>false</visible>
[Read("controlpanel")]
public TenantControlPanelSettings GetTenantControlPanelSettings()
{
return SettingsManager.Load<TenantControlPanelSettings>();
}
///<visible>false</visible>
[Create("rebranding/company")]
2020-11-06 09:03:49 +00:00
public bool SaveCompanyWhiteLabelSettingsFromBody([FromBody] CompanyWhiteLabelSettingsWrapper companyWhiteLabelSettingsWrapper)
{
return SaveCompanyWhiteLabelSettings(companyWhiteLabelSettingsWrapper);
}
[Create("rebranding/company")]
[Consumes("application/x-www-form-urlencoded")]
public bool SaveCompanyWhiteLabelSettingsFromForm([FromForm] CompanyWhiteLabelSettingsWrapper companyWhiteLabelSettingsWrapper)
{
return SaveCompanyWhiteLabelSettings(companyWhiteLabelSettingsWrapper);
}
private bool SaveCompanyWhiteLabelSettings(CompanyWhiteLabelSettingsWrapper companyWhiteLabelSettingsWrapper)
2020-09-17 12:04:28 +00:00
{
if (companyWhiteLabelSettingsWrapper.Settings == null) throw new ArgumentNullException("settings");
2020-09-17 12:04:28 +00:00
DemandRebrandingPermission();
companyWhiteLabelSettingsWrapper.Settings.IsLicensorSetting = false; //TODO: CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Branding && settings.IsLicensor
2020-09-17 12:04:28 +00:00
SettingsManager.SaveForDefaultTenant(companyWhiteLabelSettingsWrapper.Settings);
return true;
2020-09-17 12:04:28 +00:00
}
///<visible>false</visible>
[Read("rebranding/company")]
public CompanyWhiteLabelSettings GetCompanyWhiteLabelSettings()
{
return SettingsManager.LoadForDefaultTenant<CompanyWhiteLabelSettings>();
}
///<visible>false</visible>
[Delete("rebranding/company")]
public CompanyWhiteLabelSettings DeleteCompanyWhiteLabelSettings()
{
DemandRebrandingPermission();
var defaultSettings = (CompanyWhiteLabelSettings)SettingsManager.LoadForDefaultTenant<CompanyWhiteLabelSettings>().GetDefault(CoreSettings);
SettingsManager.SaveForDefaultTenant(defaultSettings);
return defaultSettings;
}
///<visible>false</visible>
[Create("rebranding/additional")]
2020-11-06 09:03:49 +00:00
public bool SaveAdditionalWhiteLabelSettingsFromBody([FromBody]AdditionalWhiteLabelSettingsWrapper wrapper)
{
return SaveAdditionalWhiteLabelSettings(wrapper);
}
[Create("rebranding/additional")]
[Consumes("application/x-www-form-urlencoded")]
public bool SaveAdditionalWhiteLabelSettingsFromForm([FromForm] AdditionalWhiteLabelSettingsWrapper wrapper)
{
return SaveAdditionalWhiteLabelSettings(wrapper);
}
private bool SaveAdditionalWhiteLabelSettings(AdditionalWhiteLabelSettingsWrapper wrapper)
2020-09-17 12:04:28 +00:00
{
if (wrapper.Settings == null) throw new ArgumentNullException("settings");
2020-09-17 12:04:28 +00:00
DemandRebrandingPermission();
SettingsManager.SaveForDefaultTenant(wrapper.Settings);
return true;
2020-09-17 12:04:28 +00:00
}
///<visible>false</visible>
[Read("rebranding/additional")]
public AdditionalWhiteLabelSettings GetAdditionalWhiteLabelSettings()
{
return SettingsManager.LoadForDefaultTenant<AdditionalWhiteLabelSettings>();
}
///<visible>false</visible>
[Delete("rebranding/additional")]
public AdditionalWhiteLabelSettings DeleteAdditionalWhiteLabelSettings()
{
DemandRebrandingPermission();
var defaultSettings = (AdditionalWhiteLabelSettings)SettingsManager.LoadForDefaultTenant<AdditionalWhiteLabelSettings>().GetDefault(Configuration);
SettingsManager.SaveForDefaultTenant(defaultSettings);
return defaultSettings;
}
///<visible>false</visible>
[Create("rebranding/mail")]
2020-11-06 09:03:49 +00:00
public bool SaveMailWhiteLabelSettingsFromBody([FromBody] MailWhiteLabelSettings settings)
{
return SaveMailWhiteLabelSettings(settings);
}
///<visible>false</visible>
[Create("rebranding/mail")]
public bool SaveMailWhiteLabelSettingsFromForm([FromForm] MailWhiteLabelSettings settings)
{
return SaveMailWhiteLabelSettings(settings);
}
private bool SaveMailWhiteLabelSettings(MailWhiteLabelSettings settings)
2020-09-17 12:04:28 +00:00
{
if (settings == null) throw new ArgumentNullException("settings");
DemandRebrandingPermission();
SettingsManager.SaveForDefaultTenant(settings);
return true;
2020-09-17 12:04:28 +00:00
}
///<visible>false</visible>
[Update("rebranding/mail")]
2020-11-10 10:41:32 +00:00
public bool UpdateMailWhiteLabelSettingsFromBody([FromBody]MailWhiteLabelSettingsModel model)
{
return UpdateMailWhiteLabelSettings(model);
}
[Update("rebranding/mail")]
[Consumes("application/x-www-form-urlencoded")]
public bool UpdateMailWhiteLabelSettingsFromForm([FromForm]MailWhiteLabelSettingsModel model)
{
return UpdateMailWhiteLabelSettings(model);
}
private bool UpdateMailWhiteLabelSettings(MailWhiteLabelSettingsModel model)
2020-09-17 12:04:28 +00:00
{
DemandRebrandingPermission();
var settings = SettingsManager.LoadForDefaultTenant<MailWhiteLabelSettings>();
2020-11-10 10:41:32 +00:00
settings.FooterEnabled = model.FooterEnabled;
2020-09-17 12:04:28 +00:00
SettingsManager.SaveForDefaultTenant(settings);
return true;
2020-09-17 12:04:28 +00:00
}
///<visible>false</visible>
[Read("rebranding/mail")]
public MailWhiteLabelSettings GetMailWhiteLabelSettings()
{
return SettingsManager.LoadForDefaultTenant<MailWhiteLabelSettings>();
}
///<visible>false</visible>
[Delete("rebranding/mail")]
public MailWhiteLabelSettings DeleteMailWhiteLabelSettings()
{
DemandRebrandingPermission();
var defaultSettings = (MailWhiteLabelSettings)SettingsManager.LoadForDefaultTenant<MailWhiteLabelSettings>().GetDefault(Configuration);
SettingsManager.SaveForDefaultTenant(defaultSettings);
return defaultSettings;
}
private void DemandRebrandingPermission()
{
TenantExtra.DemandControlPanelPermission();
if (!TenantManager.GetTenantQuota(Tenant.TenantId).SSBranding)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "SSBranding");
}
if (CoreBaseSettings.CustomMode)
{
throw new SecurityException();
}
}
2020-07-24 14:01:20 +00:00
2020-08-26 14:34:21 +00:00
[Read("authservice")]
2020-08-26 16:13:41 +00:00
public IEnumerable<AuthServiceModel> GetAuthServices()
2020-08-26 14:34:21 +00:00
{
return ConsumerFactory.GetAll<Consumer>()
.Where(consumer => consumer.ManagedKeys.Any())
.OrderBy(services => services.Order)
2020-08-26 16:13:41 +00:00
.Select(r => new AuthServiceModel(r))
2020-08-26 14:34:21 +00:00
.ToList();
}
[Create("authservice")]
2020-11-06 09:03:49 +00:00
public bool SaveAuthKeysFromBody([FromBody]AuthServiceModel model)
{
return SaveAuthKeys(model);
}
[Create("authservice")]
[Consumes("application/x-www-form-urlencoded")]
public bool SaveAuthKeysFromForm([FromForm] AuthServiceModel model)
{
return SaveAuthKeys(model);
}
private bool SaveAuthKeys(AuthServiceModel model)
2020-08-26 14:34:21 +00:00
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!SetupInfo.IsVisibleSettings(ManagementType.ThirdPartyAuthorization.ToString()))
throw new BillingException(Resource.ErrorNotAllowedOption, "ThirdPartyAuthorization");
var changed = false;
var consumer = ConsumerFactory.GetByKey<Consumer>(model.Name);
2020-09-23 10:55:39 +00:00
var validateKeyProvider = consumer as IValidateKeysProvider;
2020-08-26 14:34:21 +00:00
if (validateKeyProvider != null)
{
try
{
if (validateKeyProvider is TwilioProvider twilioLoginProvider)
{
twilioLoginProvider.ClearOldNumbers();
}
2020-09-18 14:45:59 +00:00
if (validateKeyProvider is BitlyLoginProvider bitly)
{
UrlShortener.Instance = null;
}
2020-08-26 14:34:21 +00:00
}
catch (Exception e)
{
Log.Error(e);
}
}
if (model.Props.All(r => string.IsNullOrEmpty(r.Value)))
{
consumer.Clear();
changed = true;
}
else
{
foreach (var authKey in model.Props.Where(authKey => consumer[authKey.Name] != authKey.Value))
{
consumer[authKey.Name] = authKey.Value;
changed = true;
}
}
if (validateKeyProvider != null && !validateKeyProvider.ValidateKeys() && !consumer.All(r => string.IsNullOrEmpty(r.Value)))
{
consumer.Clear();
throw new ArgumentException(Resource.ErrorBadKeys);
}
if (changed)
MessageService.Send(MessageAction.AuthorizationKeysSetting);
return changed;
}
[Read("payment", Check = false)]
2020-09-07 13:53:39 +00:00
public object PaymentSettings()
{
var settings = SettingsManager.LoadForDefaultTenant<AdditionalWhiteLabelSettings>();
var currentQuota = TenantExtra.GetTenantQuota();
var currentTariff = TenantExtra.GetCurrentTariff();
return
new
{
settings.SalesEmail,
settings.FeedbackAndSupportUrl,
settings.BuyUrl,
CoreBaseSettings.Standalone,
currentLicense = new
{
currentQuota.Trial,
currentTariff.DueDate.Date
}
};
}
2020-09-24 14:30:27 +00:00
/// <visible>false</visible>
/// <summary>
/// Gets a link that will connect TelegramBot to your account
/// </summary>
/// <returns>url</returns>
///
[Read("telegramlink")]
public object TelegramLink()
{
2020-11-09 11:51:21 +00:00
var currentLink = TelegramHelper.CurrentRegistrationLink(AuthContext.CurrentAccount.ID, Tenant.TenantId);
2020-09-24 14:30:27 +00:00
if (string.IsNullOrEmpty(currentLink))
{
2020-11-09 11:51:21 +00:00
var url = TelegramHelper.RegisterUser(AuthContext.CurrentAccount.ID, Tenant.TenantId);
2020-09-24 14:30:27 +00:00
return url;
}
else
{
return currentLink;
}
}
/// <summary>
/// Checks if user has connected TelegramBot
/// </summary>
/// <returns>0 - not connected, 1 - connected, 2 - awaiting confirmation</returns>
[Read("telegramisconnected")]
public object TelegramIsConnected()
{
2020-11-09 11:51:21 +00:00
return (int)TelegramHelper.UserIsConnected(AuthContext.CurrentAccount.ID, Tenant.TenantId);
2020-09-24 14:30:27 +00:00
}
/// <summary>
/// Unlinks TelegramBot from your account
/// </summary>
[Delete("telegramdisconnect")]
public void TelegramDisconnect()
{
2020-11-09 11:51:21 +00:00
TelegramHelper.Disconnect(AuthContext.CurrentAccount.ID, Tenant.TenantId);
2020-09-24 14:30:27 +00:00
}
2020-07-24 14:01:20 +00:00
private readonly int maxCount = 10;
private readonly int expirationMinutes = 2;
private void CheckCache(string basekey)
{
var key = ApiContext.HttpContextAccessor.HttpContext.Request.GetUserHostAddress() + basekey;
if (MemoryCache.TryGetValue<int>(key, out var count))
{
if (count > maxCount)
throw new Exception(Resource.ErrorRequestLimitExceeded);
}
MemoryCache.Set(key, ++count, TimeSpan.FromMinutes(expirationMinutes));
}
2019-08-12 10:53:12 +00:00
}
}