Merge branch 'feature/backend-refactor' into feature/builder-extension

This commit is contained in:
Maksim Chegulov 2022-03-15 18:33:58 +03:00
commit 0c61081921
104 changed files with 6344 additions and 6075 deletions

View File

@ -222,9 +222,9 @@ public class EmailValidationKeyModelHelper
};
}
public ValidationResult Validate(EmailValidationKeyModel model)
public ValidationResult Validate(EmailValidationKeyModel inDto)
{
var (key, emplType, email, uiD, type) = model;
var (key, emplType, email, uiD, type) = inDto;
ValidationResult checkKeyResult;

View File

@ -9,7 +9,7 @@
<RazorCompileOnBuild>false</RazorCompileOnBuild>
<GenerateMvcApplicationPartsAssemblyAttributes>false</GenerateMvcApplicationPartsAssemblyAttributes>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<ImplicitUsings>enable</ImplicitUsings>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
@ -17,10 +17,10 @@
<Optimize>true</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Controllers\LdapController.cs" />
<Compile Remove="Controllers\SsoSettingsV2Controller.cs" />
</ItemGroup>
<ItemGroup>
<Compile Remove="Api\LdapController.cs" />
<Compile Remove="Api\SsoSettingsV2Controller.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.2.0" />

View File

@ -0,0 +1,593 @@
using AuthenticationException = System.Security.Authentication.AuthenticationException;
using Constants = ASC.Core.Users.Constants;
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.Web.Api.Controllers;
[Scope]
[DefaultRoute]
[ApiController]
[AllowAnonymous]
public class AuthenticationController : ControllerBase
{
private readonly UserManager _userManager;
private readonly TenantManager _tenantManager;
private readonly SecurityContext _securityContext;
private readonly TenantCookieSettingsHelper _tenantCookieSettingsHelper;
private readonly CookiesManager _cookiesManager;
private readonly PasswordHasher _passwordHasher;
private readonly EmailValidationKeyModelHelper _emailValidationKeyModelHelper;
private readonly ICache _cache;
private readonly SetupInfo _setupInfo;
private readonly MessageService _messageService;
private readonly ProviderManager _providerManager;
private readonly IOptionsSnapshot<AccountLinker> _accountLinker;
private readonly CoreBaseSettings _coreBaseSettings;
private readonly PersonalSettingsHelper _personalSettingsHelper;
private readonly StudioNotifyService _studioNotifyService;
private readonly UserHelpTourHelper _userHelpTourHelper;
private readonly Signature _signature;
private readonly InstanceCrypto _instanceCrypto;
private readonly DisplayUserSettingsHelper _displayUserSettingsHelper;
private readonly MessageTarget _messageTarget;
private readonly StudioSmsNotificationSettingsHelper _studioSmsNotificationSettingsHelper;
private readonly SettingsManager _settingsManager;
private readonly SmsManager _smsManager;
private readonly TfaManager _tfaManager;
private readonly TimeZoneConverter _timeZoneConverter;
private readonly SmsKeyStorage _smsKeyStorage;
private readonly CommonLinkUtility _commonLinkUtility;
private readonly ApiContext _apiContext;
private readonly AuthContext _authContext;
private readonly UserManagerWrapper _userManagerWrapper;
public AuthenticationController(
UserManager userManager,
TenantManager tenantManager,
SecurityContext securityContext,
TenantCookieSettingsHelper tenantCookieSettingsHelper,
CookiesManager cookiesManager,
PasswordHasher passwordHasher,
EmailValidationKeyModelHelper emailValidationKeyModelHelper,
ICache cache,
SetupInfo setupInfo,
MessageService messageService,
ProviderManager providerManager,
IOptionsSnapshot<AccountLinker> accountLinker,
CoreBaseSettings coreBaseSettings,
PersonalSettingsHelper personalSettingsHelper,
StudioNotifyService studioNotifyService,
UserManagerWrapper userManagerWrapper,
UserHelpTourHelper userHelpTourHelper,
Signature signature,
InstanceCrypto instanceCrypto,
DisplayUserSettingsHelper displayUserSettingsHelper,
MessageTarget messageTarget,
StudioSmsNotificationSettingsHelper studioSmsNotificationSettingsHelper,
SettingsManager settingsManager,
SmsManager smsManager,
TfaManager tfaManager,
TimeZoneConverter timeZoneConverter,
SmsKeyStorage smsKeyStorage,
CommonLinkUtility commonLinkUtility,
ApiContext apiContext,
AuthContext authContext)
{
_userManager = userManager;
_tenantManager = tenantManager;
_securityContext = securityContext;
_tenantCookieSettingsHelper = tenantCookieSettingsHelper;
_cookiesManager = cookiesManager;
_passwordHasher = passwordHasher;
_emailValidationKeyModelHelper = emailValidationKeyModelHelper;
_cache = cache;
_setupInfo = setupInfo;
_messageService = messageService;
_providerManager = providerManager;
_accountLinker = accountLinker;
_coreBaseSettings = coreBaseSettings;
_personalSettingsHelper = personalSettingsHelper;
_studioNotifyService = studioNotifyService;
_userHelpTourHelper = userHelpTourHelper;
_signature = signature;
_instanceCrypto = instanceCrypto;
_displayUserSettingsHelper = displayUserSettingsHelper;
_messageTarget = messageTarget;
_studioSmsNotificationSettingsHelper = studioSmsNotificationSettingsHelper;
_settingsManager = settingsManager;
_smsManager = smsManager;
_tfaManager = tfaManager;
_timeZoneConverter = timeZoneConverter;
_smsKeyStorage = smsKeyStorage;
_commonLinkUtility = commonLinkUtility;
_apiContext = apiContext;
_authContext = authContext;
_userManagerWrapper = userManagerWrapper;
}
[Read]
public bool GetIsAuthentificated()
{
return _securityContext.IsAuthenticated;
}
[Create("{code}", false, order: int.MaxValue)]
public AuthenticationTokenDto AuthenticateMeFromBodyWithCode([FromBody] AuthRequestsDto inDto)
{
return AuthenticateMeWithCode(inDto);
}
[Create("{code}", false, order: int.MaxValue)]
[Consumes("application/x-www-form-urlencoded")]
public AuthenticationTokenDto AuthenticateMeFromFormWithCode([FromForm] AuthRequestsDto inDto)
{
return AuthenticateMeWithCode(inDto);
}
[Create(false)]
public Task<AuthenticationTokenDto> AuthenticateMeFromBodyAsync([FromBody] AuthRequestsDto inDto)
{
return AuthenticateMeAsync(inDto);
}
[Create(false)]
[Consumes("application/x-www-form-urlencoded")]
public Task<AuthenticationTokenDto> AuthenticateMeFromFormAsync([FromForm] AuthRequestsDto inDto)
{
return AuthenticateMeAsync(inDto);
}
[Create("logout")]
[Read("logout")]// temp fix
public void Logout()
{
if (_securityContext.IsAuthenticated)
_cookiesManager.ResetUserCookie(_securityContext.CurrentAccount.ID);
_cookiesManager.ClearCookies(CookiesType.AuthKey);
_cookiesManager.ClearCookies(CookiesType.SocketIO);
_securityContext.Logout();
}
[Create("confirm", false)]
public ValidationResult CheckConfirmFromBody([FromBody] EmailValidationKeyModel inDto)
{
return _emailValidationKeyModelHelper.Validate(inDto);
}
[Create("confirm", false)]
[Consumes("application/x-www-form-urlencoded")]
public ValidationResult CheckConfirmFromForm([FromForm] EmailValidationKeyModel inDto)
{
return _emailValidationKeyModelHelper.Validate(inDto);
}
[Authorize(AuthenticationSchemes = "confirm", Roles = "PhoneActivation")]
[Create("setphone", false)]
public Task<AuthenticationTokenDto> SaveMobilePhoneFromBodyAsync([FromBody] MobileRequestsDto inDto)
{
return SaveMobilePhoneAsync(inDto);
}
[Authorize(AuthenticationSchemes = "confirm", Roles = "PhoneActivation")]
[Create("setphone", false)]
[Consumes("application/x-www-form-urlencoded")]
public Task<AuthenticationTokenDto> SaveMobilePhoneFromFormAsync([FromForm] MobileRequestsDto inDto)
{
return SaveMobilePhoneAsync(inDto);
}
private async Task<AuthenticationTokenDto> SaveMobilePhoneAsync(MobileRequestsDto inDto)
{
_apiContext.AuthByClaim();
var user = _userManager.GetUsers(_authContext.CurrentAccount.ID);
inDto.MobilePhone = await _smsManager.SaveMobilePhoneAsync(user, inDto.MobilePhone);
_messageService.Send(MessageAction.UserUpdatedMobileNumber, _messageTarget.Create(user.Id), user.DisplayUserName(false, _displayUserSettingsHelper), inDto.MobilePhone);
return new AuthenticationTokenDto
{
Sms = true,
PhoneNoise = SmsSender.BuildPhoneNoise(inDto.MobilePhone),
Expires = new ApiDateTime(_tenantManager, _timeZoneConverter, DateTime.UtcNow.Add(_smsKeyStorage.StoreInterval))
};
}
[Create(@"sendsms", false)]
public Task<AuthenticationTokenDto> SendSmsCodeFromBodyAsync([FromBody] AuthRequestsDto inDto)
{
return SendSmsCodeAsync(inDto);
}
[Create(@"sendsms", false)]
[Consumes("application/x-www-form-urlencoded")]
public Task<AuthenticationTokenDto> SendSmsCodeFromFormAsync([FromForm] AuthRequestsDto inDto)
{
return SendSmsCodeAsync(inDto);
}
private async Task<AuthenticationTokenDto> SendSmsCodeAsync(AuthRequestsDto inDto)
{
var user = GetUser(inDto, out _);
await _smsManager.PutAuthCodeAsync(user, true);
return new AuthenticationTokenDto
{
Sms = true,
PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
Expires = new ApiDateTime(_tenantManager, _timeZoneConverter, DateTime.UtcNow.Add(_smsKeyStorage.StoreInterval))
};
}
private async Task<AuthenticationTokenDto> AuthenticateMeAsync(AuthRequestsDto inDto)
{
bool viaEmail;
var user = GetUser(inDto, out viaEmail);
if (_studioSmsNotificationSettingsHelper.IsVisibleSettings() && _studioSmsNotificationSettingsHelper.Enable)
{
if (string.IsNullOrEmpty(user.MobilePhone) || user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
return new AuthenticationTokenDto
{
Sms = true,
ConfirmUrl = _commonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PhoneActivation)
};
await _smsManager.PutAuthCodeAsync(user, false);
return new AuthenticationTokenDto
{
Sms = true,
PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
Expires = new ApiDateTime(_tenantManager, _timeZoneConverter, DateTime.UtcNow.Add(_smsKeyStorage.StoreInterval)),
ConfirmUrl = _commonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PhoneAuth)
};
}
if (TfaAppAuthSettings.IsVisibleSettings && _settingsManager.Load<TfaAppAuthSettings>().EnableSetting)
{
if (!TfaAppUserSettings.EnableForUser(_settingsManager, user.Id))
return new AuthenticationTokenDto
{
Tfa = true,
TfaKey = _tfaManager.GenerateSetupCode(user).ManualEntryKey,
ConfirmUrl = _commonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaActivation)
};
return new AuthenticationTokenDto
{
Tfa = true,
ConfirmUrl = _commonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaAuth)
};
}
try
{
var token = _securityContext.AuthenticateMe(user.Id);
_cookiesManager.SetCookies(CookiesType.AuthKey, token, inDto.Session);
_messageService.Send(viaEmail ? MessageAction.LoginSuccessViaApi : MessageAction.LoginSuccessViaApiSocialAccount);
var tenant = _tenantManager.GetCurrentTenant().Id;
var expires = _tenantCookieSettingsHelper.GetExpiresTime(tenant);
return new AuthenticationTokenDto
{
Token = token,
Expires = new ApiDateTime(_tenantManager, _timeZoneConverter, expires)
};
}
catch
{
_messageService.Send(user.DisplayUserName(false, _displayUserSettingsHelper), viaEmail ? MessageAction.LoginFailViaApi : MessageAction.LoginFailViaApiSocialAccount);
throw new AuthenticationException("User authentication failed");
}
finally
{
_securityContext.Logout();
}
}
private AuthenticationTokenDto AuthenticateMeWithCode(AuthRequestsDto inDto)
{
var tenant = _tenantManager.GetCurrentTenant().Id;
var user = GetUser(inDto, out _);
var sms = false;
try
{
if (_studioSmsNotificationSettingsHelper.IsVisibleSettings() && _studioSmsNotificationSettingsHelper.Enable)
{
sms = true;
_smsManager.ValidateSmsCode(user, inDto.Code);
}
else if (TfaAppAuthSettings.IsVisibleSettings && _settingsManager.Load<TfaAppAuthSettings>().EnableSetting)
{
if (_tfaManager.ValidateAuthCode(user, inDto.Code))
{
_messageService.Send(MessageAction.UserConnectedTfaApp, _messageTarget.Create(user.Id));
}
}
else
{
throw new System.Security.SecurityException("Auth code is not available");
}
var token = _securityContext.AuthenticateMe(user.Id);
_messageService.Send(sms ? MessageAction.LoginSuccessViaApiSms : MessageAction.LoginSuccessViaApiTfa);
var expires = _tenantCookieSettingsHelper.GetExpiresTime(tenant);
var result = new AuthenticationTokenDto
{
Token = token,
Expires = new ApiDateTime(_tenantManager, _timeZoneConverter, expires)
};
if (sms)
{
result.Sms = true;
result.PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone);
}
else
{
result.Tfa = true;
}
return result;
}
catch
{
_messageService.Send(user.DisplayUserName(false, _displayUserSettingsHelper), sms
? MessageAction.LoginFailViaApiSms
: MessageAction.LoginFailViaApiTfa,
_messageTarget.Create(user.Id));
throw new AuthenticationException("User authentication failed");
}
finally
{
_securityContext.Logout();
}
}
private UserInfo GetUser(AuthRequestsDto inDto, out bool viaEmail)
{
viaEmail = true;
var action = MessageAction.LoginFailViaApi;
UserInfo user;
try
{
if ((string.IsNullOrEmpty(inDto.Provider) && string.IsNullOrEmpty(inDto.SerializedProfile)) || inDto.Provider == "email")
{
inDto.UserName.ThrowIfNull(new ArgumentException(@"userName empty", "userName"));
if (!string.IsNullOrEmpty(inDto.Password))
{
inDto.Password.ThrowIfNull(new ArgumentException(@"password empty", "password"));
}
else
{
inDto.PasswordHash.ThrowIfNull(new ArgumentException(@"PasswordHash empty", "PasswordHash"));
}
int counter;
int.TryParse(_cache.Get<string>("loginsec/" + inDto.UserName), out counter);
if (++counter > _setupInfo.LoginThreshold && !SetupInfo.IsSecretEmail(inDto.UserName))
{
throw new BruteForceCredentialException();
}
_cache.Insert("loginsec/" + inDto.UserName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
inDto.PasswordHash = (inDto.PasswordHash ?? "").Trim();
if (string.IsNullOrEmpty(inDto.PasswordHash))
{
inDto.Password = (inDto.Password ?? "").Trim();
if (!string.IsNullOrEmpty(inDto.Password))
{
inDto.PasswordHash = _passwordHasher.GetClientPassword(inDto.Password);
}
}
user = _userManager.GetUsersByPasswordHash(
_tenantManager.GetCurrentTenant().Id,
inDto.UserName,
inDto.PasswordHash);
if (user == null || !_userManager.UserExists(user))
{
throw new Exception("user not found");
}
_cache.Insert("loginsec/" + inDto.UserName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
}
else
{
viaEmail = false;
action = MessageAction.LoginFailViaApiSocialAccount;
LoginProfile thirdPartyProfile;
if (!string.IsNullOrEmpty(inDto.SerializedProfile))
{
thirdPartyProfile = new LoginProfile(_signature, _instanceCrypto, inDto.SerializedProfile);
}
else
{
thirdPartyProfile = _providerManager.GetLoginProfile(inDto.Provider, inDto.AccessToken);
}
inDto.UserName = thirdPartyProfile.EMail;
user = GetUserByThirdParty(thirdPartyProfile);
}
}
catch (BruteForceCredentialException)
{
_messageService.Send(!string.IsNullOrEmpty(inDto.UserName) ? inDto.UserName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce);
throw new AuthenticationException("Login Fail. Too many attempts");
}
catch
{
_messageService.Send(!string.IsNullOrEmpty(inDto.UserName) ? inDto.UserName : AuditResource.EmailNotSpecified, action);
throw new AuthenticationException("User authentication failed");
}
return user;
}
private UserInfo GetUserByThirdParty(LoginProfile loginProfile)
{
try
{
if (!string.IsNullOrEmpty(loginProfile.AuthorizationError))
{
// ignore cancellation
if (loginProfile.AuthorizationError != "Canceled at provider")
{
throw new Exception(loginProfile.AuthorizationError);
}
return Constants.LostUser;
}
var userInfo = Constants.LostUser;
Guid userId;
if (TryGetUserByHash(loginProfile.HashId, out userId))
{
userInfo = _userManager.GetUsers(userId);
}
var isNew = false;
if (_coreBaseSettings.Personal)
{
if (_userManager.UserExists(userInfo.Id) && SetupInfo.IsSecretEmail(userInfo.Email))
{
try
{
_securityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem);
_userManager.DeleteUser(userInfo.Id);
userInfo = Constants.LostUser;
}
finally
{
_securityContext.Logout();
}
}
if (!_userManager.UserExists(userInfo.Id))
{
userInfo = JoinByThirdPartyAccount(loginProfile);
isNew = true;
}
}
if (isNew)
{
//TODO:
//var spam = HttpContext.Current.Request["spam"];
//if (spam != "on")
//{
// try
// {
// const string _databaseID = "com";
// using (var db = DbManager.FromHttpContext(_databaseID))
// {
// db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
// .InColumnValue("email", userInfo.Email.ToLowerInvariant())
// .InColumnValue("reason", "personal")
// );
// Log.Debug(string.Format("Write to template_unsubscribe {0}", userInfo.Email.ToLowerInvariant()));
// }
// }
// catch (Exception ex)
// {
// Log.Debug(string.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, userInfo.Email.ToLowerInvariant()));
// }
//}
_studioNotifyService.UserHasJoin();
_userHelpTourHelper.IsNewUser = true;
_personalSettingsHelper.IsNewUser = true;
}
return userInfo;
}
catch (Exception)
{
_cookiesManager.ClearCookies(CookiesType.AuthKey);
_cookiesManager.ClearCookies(CookiesType.SocketIO);
_securityContext.Logout();
throw;
}
}
private UserInfo JoinByThirdPartyAccount(LoginProfile loginProfile)
{
if (string.IsNullOrEmpty(loginProfile.EMail))
{
throw new Exception(Resource.ErrorNotCorrectEmail);
}
var userInfo = _userManager.GetUserByEmail(loginProfile.EMail);
if (!_userManager.UserExists(userInfo.Id))
{
var newUserInfo = ProfileToUserInfo(loginProfile);
try
{
_securityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem);
userInfo = _userManagerWrapper.AddUser(newUserInfo, UserManagerWrapper.GeneratePassword());
}
finally
{
_securityContext.Logout();
}
}
var linker = _accountLinker.Get("webstudio");
linker.AddLink(userInfo.Id.ToString(), loginProfile);
return userInfo;
}
private UserInfo ProfileToUserInfo(LoginProfile loginProfile)
{
if (string.IsNullOrEmpty(loginProfile.EMail)) throw new Exception(Resource.ErrorNotCorrectEmail);
var firstName = loginProfile.FirstName;
if (string.IsNullOrEmpty(firstName)) firstName = loginProfile.DisplayName;
var userInfo = new UserInfo
{
FirstName = string.IsNullOrEmpty(firstName) ? UserControlsCommonResource.UnknownFirstName : firstName,
LastName = string.IsNullOrEmpty(loginProfile.LastName) ? UserControlsCommonResource.UnknownLastName : loginProfile.LastName,
Email = loginProfile.EMail,
Title = string.Empty,
Location = string.Empty,
CultureName = _coreBaseSettings.CustomMode ? "ru-RU" : Thread.CurrentThread.CurrentUICulture.Name,
ActivationStatus = EmployeeActivationStatus.Activated,
};
var gender = loginProfile.Gender;
if (!string.IsNullOrEmpty(gender))
{
userInfo.Sex = gender == "male";
}
return userInfo;
}
private bool TryGetUserByHash(string hashId, out Guid userId)
{
userId = Guid.Empty;
if (string.IsNullOrEmpty(hashId)) return false;
var linkedProfiles = _accountLinker.Get("webstudio").GetLinkedObjectsByHashId(hashId);
var tmp = Guid.Empty;
if (linkedProfiles.Any(profileId => Guid.TryParse(profileId, out tmp) && _userManager.UserExists(tmp)))
userId = tmp;
return true;
}
}

View File

@ -0,0 +1,107 @@
namespace ASC.Web.Api.Controllers;
[DefaultRoute]
[ApiController]
[AllowAnonymous]
public class CapabilitiesController : ControllerBase
{
private readonly CoreBaseSettings _coreBaseSettings;
private readonly TenantManager _tenantManager;
private readonly ProviderManager _providerManager;
private readonly IConfiguration _configuration;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILog _log;
public CapabilitiesController(
CoreBaseSettings coreBaseSettings,
TenantManager tenantManager,
ProviderManager providerManager,
IConfiguration configuration,
IHttpContextAccessor httpContextAccessor,
IOptionsMonitor<ILog> options)
{
_coreBaseSettings = coreBaseSettings;
_tenantManager = tenantManager;
_providerManager = providerManager;
_configuration = configuration;
_httpContextAccessor = httpContextAccessor;
_log = options.CurrentValue;
}
///<summary>
///Returns the information about portal capabilities
///</summary>
///<short>
///Get portal capabilities
///</short>
///<returns>CapabilitiesData</returns>
[Read(Check = false)] //NOTE: this method doesn't requires auth!!! //NOTE: this method doesn't check payment!!!
public CapabilitiesDto GetPortalCapabilities()
{
var result = new CapabilitiesDto
{
LdapEnabled = false,
Providers = null,
SsoLabel = string.Empty,
SsoUrl = string.Empty
};
try
{
if (SetupInfo.IsVisibleSettings(nameof(ManagementType.LdapSettings))
&& (!_coreBaseSettings.Standalone
|| _tenantManager.GetTenantQuota(_tenantManager.GetCurrentTenant().Id).Ldap))
{
//var settings = SettingsManager.Load<LdapSettings>();
//result.LdapEnabled = settings.EnableLdapAuthentication;
result.LdapEnabled = false;
}
}
catch (Exception ex)
{
_log.Error(ex.Message);
}
try
{
result.Providers = ProviderManager.AuthProviders.Where(loginProvider =>
{
var provider = _providerManager.GetLoginProvider(loginProvider);
return provider != null && provider.IsEnabled;
})
.ToList();
}
catch (Exception ex)
{
_log.Error(ex.Message);
}
try
{
if (SetupInfo.IsVisibleSettings(nameof(ManagementType.SingleSignOnSettings))
&& _tenantManager.GetTenantQuota(_tenantManager.GetCurrentTenant().Id).Sso)
{
//var settings = SettingsManager.Load<SsoSettingsV2>();
//if (settings.EnableSso)
//{
var uri = _httpContextAccessor.HttpContext.Request.GetUrlRewriter();
var configUrl = _configuration["web:sso:saml:login:url"] ?? "";
result.SsoUrl = $"{uri.Scheme}://{uri.Host}{((uri.Port == 80 || uri.Port == 443) ? "" : ":" + uri.Port)}{configUrl}";
result.SsoLabel = string.Empty;
// result.SsoLabel = settings.SpLoginLabel;
//}
}
}
catch (Exception ex)
{
_log.Error(ex.Message);
}
return result;
}
}

View File

@ -34,9 +34,9 @@ using ASC.Web.Studio.Core;
using ASC.Web.Studio.Utility;
using Newtonsoft.Json;
using ASC.Notify.Cron;
using ASC.Web.Api.Routing;
using ASC.Web.Core.PublicResources;
using ASC.Web.Api.Routing;
using ASC.Web.Core.PublicResources;
namespace ASC.Api.Settings
{
public partial class SettingsApi

View File

@ -0,0 +1,44 @@
using Module = ASC.Api.Core.Module;
namespace ASC.Web.Api.Controllers;
[Scope]
[DefaultRoute]
[ApiController]
public class ModulesController : ControllerBase
{
private readonly WebItemManagerSecurity _webItemManagerSecurity;
public ModulesController(
WebItemManagerSecurity webItemManagerSecurity)
{
_webItemManagerSecurity = webItemManagerSecurity;
}
[Read]
public IEnumerable<string> GetAll()
{
var result = new List<string>();
foreach (var a in _webItemManagerSecurity.GetItems(WebZoneType.StartProductList))
{
result.Add(a.ApiURL);
}
return result;
}
[Read("info")]
public IEnumerable<Module> GetAllWithInfo()
{
foreach (var a in _webItemManagerSecurity.GetItems(WebZoneType.StartProductList))
{
if(a is Product product)
{
product.Init();
yield return new Module(product);
}
}
}
}

View File

@ -0,0 +1,252 @@
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.Web.Api.Controllers;
[Scope]
[DefaultRoute]
[ApiController]
public class PortalController : ControllerBase
{
private Tenant Tenant { get { return _apiContext.Tenant; } }
private readonly ApiContext _apiContext;
private readonly UserManager _userManager;
private readonly TenantManager _tenantManager;
private readonly PaymentManager _paymentManager;
private readonly CommonLinkUtility _commonLinkUtility;
private readonly UrlShortener _urlShortener;
private readonly AuthContext _authContext;
private readonly WebItemSecurity _webItemSecurity;
private readonly SecurityContext _securityContext;
private readonly SettingsManager _settingsManager;
private readonly IMobileAppInstallRegistrator _mobileAppInstallRegistrator;
private readonly IConfiguration _configuration;
private readonly CoreBaseSettings _coreBaseSettings;
private readonly LicenseReader _licenseReader;
private readonly SetupInfo _setupInfo;
private readonly DocumentServiceLicense _documentServiceLicense;
private readonly TenantExtra _tenantExtra;
private readonly ILog _log;
private readonly IHttpClientFactory _clientFactory;
public PortalController(
IOptionsMonitor<ILog> options,
ApiContext apiContext,
UserManager userManager,
TenantManager tenantManager,
PaymentManager paymentManager,
CommonLinkUtility commonLinkUtility,
UrlShortener urlShortener,
AuthContext authContext,
WebItemSecurity webItemSecurity,
SecurityContext securityContext,
SettingsManager settingsManager,
IMobileAppInstallRegistrator mobileAppInstallRegistrator,
TenantExtra tenantExtra,
IConfiguration configuration,
CoreBaseSettings coreBaseSettings,
LicenseReader licenseReader,
SetupInfo setupInfo,
DocumentServiceLicense documentServiceLicense,
IHttpClientFactory clientFactory
)
{
_log = options.CurrentValue;
_apiContext = apiContext;
_userManager = userManager;
_tenantManager = tenantManager;
_paymentManager = paymentManager;
_commonLinkUtility = commonLinkUtility;
_urlShortener = urlShortener;
_authContext = authContext;
_webItemSecurity = webItemSecurity;
_securityContext = securityContext;
_settingsManager = settingsManager;
_mobileAppInstallRegistrator = mobileAppInstallRegistrator;
_configuration = configuration;
_coreBaseSettings = coreBaseSettings;
_licenseReader = licenseReader;
_setupInfo = setupInfo;
_documentServiceLicense = documentServiceLicense;
_tenantExtra = tenantExtra;
_clientFactory = clientFactory;
}
[Read("")]
public Tenant Get()
{
return Tenant;
}
[Read("users/{userID}")]
public UserInfo GetUser(Guid userID)
{
return _userManager.GetUsers(userID);
}
[Read("users/invite/{employeeType}")]
public object GeInviteLink(EmployeeType employeeType)
{
if (!_webItemSecurity.IsProductAdministrator(WebItemManager.PeopleProductID, _authContext.CurrentAccount.ID))
{
throw new SecurityException("Method not available");
}
return _commonLinkUtility.GetConfirmationUrl(string.Empty, ConfirmType.LinkInvite, (int)employeeType)
+ $"&emplType={employeeType:d}";
}
[Update("getshortenlink")]
public async Task<object> GetShortenLinkAsync(ShortenLinkRequestsDto inDto)
{
try
{
return await _urlShortener.Instance.GetShortenLinkAsync(inDto.Link);
}
catch (Exception ex)
{
_log.Error("getshortenlink", ex);
return inDto.Link;
}
}
[Read("tenantextra")]
public async Task<object> GetTenantExtraAsync()
{
return new
{
customMode = _coreBaseSettings.CustomMode,
opensource = _tenantExtra.Opensource,
enterprise = _tenantExtra.Enterprise,
tariff = _tenantExtra.GetCurrentTariff(),
quota = _tenantExtra.GetTenantQuota(),
notPaid = _tenantExtra.IsNotPaid(),
licenseAccept = _settingsManager.LoadForCurrentUser<TariffSettings>().LicenseAcceptSetting,
enableTariffPage = //TenantExtra.EnableTarrifSettings - think about hide-settings for opensource
(!_coreBaseSettings.Standalone || !string.IsNullOrEmpty(_licenseReader.LicensePath))
&& string.IsNullOrEmpty(_setupInfo.AmiMetaUrl)
&& !_coreBaseSettings.CustomMode,
DocServerUserQuota = await _documentServiceLicense.GetLicenseQuotaAsync(),
DocServerLicense = await _documentServiceLicense.GetLicenseAsync()
};
}
[Read("usedspace")]
public double GetUsedSpace()
{
return Math.Round(
_tenantManager.FindTenantQuotaRows(Tenant.Id)
.Where(q => !string.IsNullOrEmpty(q.Tag) && new Guid(q.Tag) != Guid.Empty)
.Sum(q => q.Counter) / 1024f / 1024f / 1024f, 2);
}
[Read("userscount")]
public long GetUsersCount()
{
return _coreBaseSettings.Personal ? 1 : _userManager.GetUserNames(EmployeeStatus.Active).Length;
}
[Read("tariff")]
public Tariff GetTariff()
{
return _paymentManager.GetTariff(Tenant.Id);
}
[Read("quota")]
public TenantQuota GetQuota()
{
return _tenantManager.GetTenantQuota(Tenant.Id);
}
[Read("quota/right")]
public TenantQuota GetRightQuota()
{
var usedSpace = GetUsedSpace();
var needUsersCount = GetUsersCount();
return _tenantManager.GetTenantQuotas().OrderBy(r => r.Price)
.FirstOrDefault(quota =>
quota.ActiveUsers > needUsersCount
&& quota.MaxTotalSize > usedSpace
&& !quota.Year);
}
[Read("path")]
public object GetFullAbsolutePath(string virtualPath)
{
return _commonLinkUtility.GetFullAbsolutePath(virtualPath);
}
[Read("thumb")]
public FileResult GetThumb(string url)
{
if (!_securityContext.IsAuthenticated || _configuration["bookmarking:thumbnail-url"] == null)
{
return null;
}
url = url.Replace("&amp;", "&");
url = WebUtility.UrlEncode(url);
var request = new HttpRequestMessage();
request.RequestUri = new Uri(string.Format(_configuration["bookmarking:thumbnail-url"], url));
var httpClient = _clientFactory.CreateClient();
using var response = httpClient.Send(request);
using var stream = response.Content.ReadAsStream();
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
string type;
if (response.Headers.TryGetValues("Content-Type", out var values))
{
type = values.First();
}
else
{
type = "image/png";
}
return File(bytes, type);
}
[Create("present/mark")]
public void MarkPresentAsReaded()
{
try
{
var settings = _settingsManager.LoadForCurrentUser<OpensourceGiftSettings>();
settings.Readed = true;
_settingsManager.SaveForCurrentUser(settings);
}
catch (Exception ex)
{
_log.Error("MarkPresentAsReaded", ex);
}
}
[Create("mobile/registration")]
public void RegisterMobileAppInstallFromBody([FromBody] MobileAppRequestsDto inDto)
{
var currentUser = _userManager.GetUsers(_securityContext.CurrentAccount.ID);
_mobileAppInstallRegistrator.RegisterInstall(currentUser.Email, inDto.Type);
}
[Create("mobile/registration")]
[Consumes("application/x-www-form-urlencoded")]
public void RegisterMobileAppInstallFromForm([FromForm] MobileAppRequestsDto inDto)
{
var currentUser = _userManager.GetUsers(_securityContext.CurrentAccount.ID);
_mobileAppInstallRegistrator.RegisterInstall(currentUser.Email, inDto.Type);
}
[Create("mobile/registration")]
public void RegisterMobileAppInstall(MobileAppType type)
{
var currentUser = _userManager.GetUsers(_securityContext.CurrentAccount.ID);
_mobileAppInstallRegistrator.RegisterInstall(currentUser.Email, type);
}
}

View File

@ -0,0 +1,154 @@
namespace ASC.Web.Api.Controllers;
[Scope]
[DefaultRoute]
[ApiController]
public class SecurityController : ControllerBase
{
private readonly PermissionContext _permissionContext;
private readonly TenantExtra _tenantExtra;
private readonly TenantManager _tenantManager;
private readonly MessageService _messageService;
private readonly LoginEventsRepository _loginEventsRepository;
private readonly AuditEventsRepository _auditEventsRepository;
private readonly AuditReportCreator auditReportCreator;
private readonly SettingsManager _settingsManager;
public SecurityController(
PermissionContext permissionContext,
TenantExtra tenantExtra,
TenantManager tenantManager,
MessageService messageService,
LoginEventsRepository loginEventsRepository,
AuditEventsRepository auditEventsRepository,
AuditReportCreator auditReportCreator,
SettingsManager settingsManager)
{
_permissionContext = permissionContext;
_tenantExtra = tenantExtra;
_tenantManager = tenantManager;
_messageService = messageService;
_loginEventsRepository = loginEventsRepository;
_auditEventsRepository = auditEventsRepository;
this.auditReportCreator = auditReportCreator;
_settingsManager = settingsManager;
}
[Read("audit/login/last")]
public IEnumerable<EventDto> GetLastLoginEvents()
{
if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory)))
{
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
}
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
return _loginEventsRepository.GetLast(_tenantManager.GetCurrentTenant().Id, 20).Select(x => new EventDto(x));
}
[Read("audit/events/last")]
public IEnumerable<EventDto> GetLastAuditEvents()
{
if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.AuditTrail)))
{
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
}
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
return _auditEventsRepository.GetLast(_tenantManager.GetCurrentTenant().Id, 20).Select(x => new EventDto(x));
}
[Create("audit/login/report")]
public object CreateLoginHistoryReport()
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var tenantId = _tenantManager.GetCurrentTenant().Id;
if (!_tenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory)))
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
var settings = _settingsManager.LoadForTenant<TenantAuditSettings>(_tenantManager.GetCurrentTenant().Id);
var to = DateTime.UtcNow;
var from = to.Subtract(TimeSpan.FromDays(settings.LoginHistoryLifeTime));
var reportName = string.Format(AuditReportResource.LoginHistoryReportName + ".csv", from.ToShortDateString(), to.ToShortDateString());
var events = _loginEventsRepository.Get(tenantId, from, to);
var result = auditReportCreator.CreateCsvReport(events, reportName);
_messageService.Send(MessageAction.LoginHistoryReportDownloaded);
return result;
}
[Create("audit/events/report")]
public object CreateAuditTrailReport()
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var tenantId = _tenantManager.GetCurrentTenant().Id;
if (!_tenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(nameof(ManagementType.AuditTrail)))
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
var settings = _settingsManager.LoadForTenant<TenantAuditSettings>(_tenantManager.GetCurrentTenant().Id);
var to = DateTime.UtcNow;
var from = to.Subtract(TimeSpan.FromDays(settings.AuditTrailLifeTime));
var reportName = string.Format(AuditReportResource.AuditTrailReportName + ".csv", from.ToString("MM.dd.yyyy"), to.ToString("MM.dd.yyyy"));
var events = _auditEventsRepository.Get(tenantId, from, to);
var result = auditReportCreator.CreateCsvReport(events, reportName);
_messageService.Send(MessageAction.AuditTrailReportDownloaded);
return result;
}
[Read("audit/settings/lifetime")]
public TenantAuditSettings GetAuditSettings()
{
if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory)))
{
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
}
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
return _settingsManager.LoadForTenant<TenantAuditSettings>(_tenantManager.GetCurrentTenant().Id);
}
[Create("audit/settings/lifetime")]
public TenantAuditSettings SetAuditSettingsFromBody([FromBody] TenantAuditSettingsWrapper wrapper)
{
return SetAuditSettings(wrapper);
}
[Create("audit/settings/lifetime")]
[Consumes("application/x-www-form-urlencoded")]
public TenantAuditSettings SetAuditSettingsFromForm([FromForm] TenantAuditSettingsWrapper wrapper)
{
return SetAuditSettings(wrapper);
}
private TenantAuditSettings SetAuditSettings(TenantAuditSettingsWrapper wrapper)
{
if (!_tenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory)))
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (wrapper.settings.LoginHistoryLifeTime <= 0 || wrapper.settings.LoginHistoryLifeTime > TenantAuditSettings.MaxLifeTime)
throw new ArgumentException("LoginHistoryLifeTime");
if (wrapper.settings.AuditTrailLifeTime <= 0 || wrapper.settings.AuditTrailLifeTime > TenantAuditSettings.MaxLifeTime)
throw new ArgumentException("AuditTrailLifeTime");
_settingsManager.SaveForTenant(wrapper.settings, _tenantManager.GetCurrentTenant().Id);
_messageService.Send(MessageAction.AuditSettingsUpdated);
return wrapper.settings;
}
}

View File

@ -0,0 +1,71 @@
/*
*
* (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.
*
*/
namespace ASC.Web.Api.Controllers.Settings;
[Scope]
[DefaultRoute]
[ApiController]
[ControllerName("settings")]
public partial class BaseSettingsController : ControllerBase
{
//private const int ONE_THREAD = 1;
//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");
internal readonly ApiContext _apiContext;
internal readonly IMemoryCache _memoryCache;
internal readonly WebItemManager _webItemManager;
private readonly int _maxCount = 10;
private readonly int _expirationMinutes = 2;
public BaseSettingsController(ApiContext apiContext, IMemoryCache memoryCache, WebItemManager webItemManager)
{
_apiContext = apiContext;
_memoryCache = memoryCache;
_webItemManager = webItemManager;
}
internal 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 + 1, TimeSpan.FromMinutes(_expirationMinutes));
}
internal string GetProductName(Guid productId)
{
var product = _webItemManager[productId];
return productId == Guid.Empty ? "All" : product != null ? product.Name : productId.ToString();
}
}

View File

@ -0,0 +1,124 @@
namespace ASC.Web.Api.Controllers.Settings;
public class CustomNavigationController : BaseSettingsController
{
private readonly MessageService _messageService;
private readonly PermissionContext _permissionContext;
private readonly SettingsManager _settingsManager;
private readonly StorageHelper _storageHelper;
public CustomNavigationController(
MessageService messageService,
ApiContext apiContext,
PermissionContext permissionContext,
SettingsManager settingsManager,
WebItemManager webItemManager,
StorageHelper storageHelper,
IMemoryCache memoryCache) : base(apiContext, memoryCache, webItemManager)
{
_messageService = messageService;
_permissionContext = permissionContext;
_settingsManager = settingsManager;
_storageHelper = storageHelper;
}
[Read("customnavigation/getall")]
public List<CustomNavigationItem> GetCustomNavigationItems()
{
return _settingsManager.Load<CustomNavigationSettings>().Items;
}
[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);
}
[Create("customnavigation/create")]
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)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var settings = _settingsManager.Load<CustomNavigationSettings>();
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);
existItem.SmallImg = _storageHelper.SaveTmpLogo(item.SmallImg);
}
if (existItem.BigImg != item.BigImg)
{
_storageHelper.DeleteLogo(existItem.BigImg);
existItem.BigImg = _storageHelper.SaveTmpLogo(item.BigImg);
}
exist = true;
break;
}
if (!exist)
{
item.Id = Guid.NewGuid();
item.SmallImg = _storageHelper.SaveTmpLogo(item.SmallImg);
item.BigImg = _storageHelper.SaveTmpLogo(item.BigImg);
settings.Items.Add(item);
}
_settingsManager.Save(settings);
_messageService.Send(MessageAction.CustomNavigationSettingsUpdated);
return item;
}
[Delete("customnavigation/delete/{id}")]
public void DeleteCustomNavigationItem(Guid id)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var settings = _settingsManager.Load<CustomNavigationSettings>();
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);
_messageService.Send(MessageAction.CustomNavigationSettingsUpdated);
}
}

View File

@ -0,0 +1,137 @@
namespace ASC.Web.Api.Controllers.Settings;
public class CustomSchemasController : BaseSettingsController
{
private readonly MessageService _messageService;
private readonly CustomNamingPeople _customNamingPeople;
private readonly TenantManager _tenantManager;
private readonly PermissionContext _permissionContext;
public CustomSchemasController(
MessageService messageService,
ApiContext apiContext,
TenantManager tenantManager,
PermissionContext permissionContext,
WebItemManager webItemManager,
CustomNamingPeople customNamingPeople,
IMemoryCache memoryCache) : base(apiContext, memoryCache, webItemManager)
{
_messageService = messageService;
_customNamingPeople = customNamingPeople;
_tenantManager = tenantManager;
_permissionContext = permissionContext;
}
[Read("customschemas")]
public List<SchemaRequestsDto> PeopleSchemas()
{
return _customNamingPeople
.GetSchemas()
.Select(r =>
{
var names = _customNamingPeople.GetPeopleNames(r.Key);
return new SchemaRequestsDto
{
Id = names.Id,
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,
};
})
.ToList();
}
[Create("customschemas")]
public SchemaRequestsDto SaveNamingSettings(SchemaRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
_customNamingPeople.SetPeopleNames(inDto.Id);
_tenantManager.SaveTenant(_tenantManager.GetCurrentTenant());
_messageService.Send(MessageAction.TeamTemplateChanged);
return PeopleSchema(inDto.Id);
}
[Update("customschemas")]
public SchemaRequestsDto SaveCustomNamingSettings(SchemaRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var usrCaption = (inDto.UserCaption ?? "").Trim();
var usrsCaption = (inDto.UsersCaption ?? "").Trim();
var grpCaption = (inDto.GroupCaption ?? "").Trim();
var grpsCaption = (inDto.GroupsCaption ?? "").Trim();
var usrStatusCaption = (inDto.UserPostCaption ?? "").Trim();
var regDateCaption = (inDto.RegDateCaption ?? "").Trim();
var grpHeadCaption = (inDto.GroupHeadCaption ?? "").Trim();
var guestCaption = (inDto.GuestCaption ?? "").Trim();
var guestsCaption = (inDto.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}")]
public SchemaRequestsDto PeopleSchema(string id)
{
var names = _customNamingPeople.GetPeopleNames(id);
var schemaItem = new SchemaRequestsDto
{
Id = names.Id,
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;
}
}

View File

@ -0,0 +1,70 @@
namespace ASC.Web.Api.Controllers.Settings;
public class GreetingSettingsController : BaseSettingsController
{
private Tenant Tenant { get { return _apiContext.Tenant; } }
private readonly MessageService _messageService;
private readonly TenantManager _tenantManager;
private readonly PermissionContext _permissionContext;
private readonly TenantInfoSettingsHelper _tenantInfoSettingsHelper;
public GreetingSettingsController(
TenantInfoSettingsHelper tenantInfoSettingsHelper,
MessageService messageService,
ApiContext apiContext,
TenantManager tenantManager,
PermissionContext permissionContext,
WebItemManager webItemManager,
IMemoryCache memoryCache) : base(apiContext, memoryCache, webItemManager)
{
_tenantInfoSettingsHelper = tenantInfoSettingsHelper;
_messageService = messageService;
_tenantManager = tenantManager;
_permissionContext = permissionContext;
}
[Read("greetingsettings")]
public ContentResult GetGreetingSettings()
{
return new ContentResult { Content = Tenant.Name };
}
[Create("greetingsettings")]
public ContentResult SaveGreetingSettingsFromBody([FromBody] GreetingSettingsRequestsDto inDto)
{
return SaveGreetingSettings(inDto);
}
[Create("greetingsettings")]
[Consumes("application/x-www-form-urlencoded")]
public ContentResult SaveGreetingSettingsFromForm([FromForm] GreetingSettingsRequestsDto inDto)
{
return SaveGreetingSettings(inDto);
}
private ContentResult SaveGreetingSettings(GreetingSettingsRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
Tenant.Name = inDto.Title;
_tenantManager.SaveTenant(Tenant);
_messageService.Send(MessageAction.GreetingSettingsUpdated);
return new ContentResult { Content = Resource.SuccessfullySaveGreetingSettingsMessage };
}
[Create("greetingsettings/restore")]
public ContentResult RestoreGreetingSettings()
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
_tenantInfoSettingsHelper.RestoreDefaultTenantName();
return new ContentResult
{
Content = Tenant.Name
};
}
}

View File

@ -0,0 +1,72 @@
namespace ASC.Web.Api.Controllers.Settings;
public class IpRestrictionsController: BaseSettingsController
{
private Tenant Tenant { get { return _apiContext.Tenant; } }
private readonly PermissionContext _permissionContext;
private readonly SettingsManager _settingsManager;
private readonly IPRestrictionsService _iPRestrictionsService;
public IpRestrictionsController(
ApiContext apiContext,
PermissionContext permissionContext,
SettingsManager settingsManager,
WebItemManager webItemManager,
IPRestrictionsService iPRestrictionsService,
IMemoryCache memoryCache) : base(apiContext, memoryCache, webItemManager)
{
_permissionContext = permissionContext;
_settingsManager = settingsManager;
_iPRestrictionsService = iPRestrictionsService;
}
[Read("iprestrictions")]
public IEnumerable<IPRestriction> GetIpRestrictions()
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
return _iPRestrictionsService.Get(Tenant.Id);
}
[Update("iprestrictions")]
public IEnumerable<string> SaveIpRestrictionsFromBody([FromBody] IpRestrictionsRequestsDto inDto)
{
return SaveIpRestrictions(inDto);
}
[Update("iprestrictions")]
[Consumes("application/x-www-form-urlencoded")]
public IEnumerable<string> SaveIpRestrictionsFromForm([FromForm] IpRestrictionsRequestsDto inDto)
{
return SaveIpRestrictions(inDto);
}
private IEnumerable<string> SaveIpRestrictions(IpRestrictionsRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
return _iPRestrictionsService.Save(inDto.Ips, Tenant.Id);
}
[Update("iprestrictions/settings")]
public IPRestrictionsSettings UpdateIpRestrictionsSettingsFromBody([FromBody] IpRestrictionsRequestsDto inDto)
{
return UpdateIpRestrictionsSettings(inDto);
}
[Update("iprestrictions/settings")]
[Consumes("application/x-www-form-urlencoded")]
public IPRestrictionsSettings UpdateIpRestrictionsSettingsFromForm([FromForm] IpRestrictionsRequestsDto inDto)
{
return UpdateIpRestrictionsSettings(inDto);
}
private IPRestrictionsSettings UpdateIpRestrictionsSettings(IpRestrictionsRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var settings = new IPRestrictionsSettings { Enable = inDto.Enable };
_settingsManager.Save(settings);
return settings;
}
}

View File

@ -0,0 +1,183 @@
namespace ASC.Web.Api.Controllers.Settings;
public class LicenseController: BaseSettingsController
{
private Tenant Tenant { get { return _apiContext.Tenant; } }
private readonly MessageService _messageService;
private readonly FirstTimeTenantSettings _firstTimeTenantSettings;
private readonly UserManager _userManager;
private readonly TenantManager _tenantManager;
private readonly TenantExtra _tenantExtra;
private readonly AuthContext _authContext;
private readonly LicenseReader _licenseReader;
private readonly SettingsManager _settingsManager;
private readonly CoreBaseSettings _coreBaseSettings;
private readonly ILog _log;
private readonly PaymentManager _paymentManager;
public LicenseController(
IOptionsMonitor<ILog> option,
MessageService messageService,
ApiContext apiContext,
UserManager userManager,
TenantManager tenantManager,
TenantExtra tenantExtra,
AuthContext authContext,
LicenseReader licenseReader,
SettingsManager settingsManager,
WebItemManager webItemManager,
CoreBaseSettings coreBaseSettings,
IMemoryCache memoryCache,
FirstTimeTenantSettings firstTimeTenantSettings,
PaymentManager paymentManager) : base(apiContext, memoryCache, webItemManager)
{
_log = option.Get("ASC.Api");
_firstTimeTenantSettings = firstTimeTenantSettings;
_messageService = messageService;
_userManager = userManager;
_tenantManager = tenantManager;
_tenantExtra = tenantExtra;
_authContext = authContext;
_licenseReader = licenseReader;
_settingsManager = settingsManager;
_coreBaseSettings = coreBaseSettings;
_paymentManager = paymentManager;
}
[Read("license/refresh", Check = false)]
public bool RefreshLicense()
{
if (!_coreBaseSettings.Standalone) return false;
_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 "";
}
///<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.Tenant != Tenant.DefaultTenant) 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);
const int DEFAULT_TRIAL_PERIOD = 30;
var tariff = new Tariff
{
QuotaId = quota.Tenant,
DueDate = DateTime.Today.AddDays(DEFAULT_TRIAL_PERIOD)
};
_paymentManager.SetTariff(-1, tariff);
_messageService.Send(MessageAction.LicenseKeyUploaded);
return true;
}
[AllowAnonymous]
[Read("license/required", Check = false)]
public bool RequestLicense()
{
return _firstTimeTenantSettings.RequestLicense;
}
[Create("license", Check = false)]
[Authorize(AuthenticationSchemes = "confirm", Roles = "Wizard, Administrators")]
public object UploadLicense([FromForm] UploadLicenseRequestsDto inDto)
{
try
{
_apiContext.AuthByClaim();
if (!_authContext.IsAuthenticated && _settingsManager.Load<WizardSettings>().Completed) throw new SecurityException(Resource.PortalSecurity);
if (!inDto.Files.Any()) throw new Exception(Resource.ErrorEmptyUploadFileSelected);
var licenseFile = inDto.Files.First();
var dueDate = _licenseReader.SaveLicenseTemp(licenseFile.OpenReadStream());
return dueDate >= DateTime.UtcNow.Date
? Resource.LicenseUploaded
: 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);
}
}
}

View File

@ -0,0 +1,191 @@
using Constants = ASC.Core.Users.Constants;
namespace ASC.Web.Api.Controllers.Settings;
public class MessageSettingsController: BaseSettingsController
{
private Tenant Tenant { get { return _apiContext.Tenant; } }
private readonly MessageService _messageService;
private readonly StudioNotifyService _studioNotifyService;
private readonly CustomNamingPeople _customNamingPeople;
private readonly IPSecurity.IPSecurity _ipSecurity;
private readonly UserManager _userManager;
private readonly TenantExtra _tenantExtra;
private readonly TenantStatisticsProvider _tenantStatisticsProvider;
private readonly PermissionContext _permissionContext;
private readonly SettingsManager _settingsManager;
private readonly CoreBaseSettings _coreBaseSettings;
public MessageSettingsController(
MessageService messageService,
StudioNotifyService studioNotifyService,
ApiContext apiContext,
UserManager userManager,
TenantExtra tenantExtra,
TenantStatisticsProvider tenantStatisticsProvider,
PermissionContext permissionContext,
SettingsManager settingsManager,
WebItemManager webItemManager,
CoreBaseSettings coreBaseSettings,
CustomNamingPeople customNamingPeople,
IPSecurity.IPSecurity ipSecurity,
IMemoryCache memoryCache) : base(apiContext, memoryCache, webItemManager)
{
_customNamingPeople = customNamingPeople;
_ipSecurity = ipSecurity;
_messageService = messageService;
_studioNotifyService = studioNotifyService;
_userManager = userManager;
_tenantExtra = tenantExtra;
_tenantStatisticsProvider = tenantStatisticsProvider;
_permissionContext = permissionContext;
_settingsManager = settingsManager;
_coreBaseSettings = coreBaseSettings;
}
[Create("messagesettings")]
public object EnableAdminMessageSettingsFromBody([FromBody] AdminMessageSettingsRequestsDto inDto)
{
return EnableAdminMessageSettings(inDto);
}
[Create("messagesettings")]
[Consumes("application/x-www-form-urlencoded")]
public object EnableAdminMessageSettingsFromForm([FromForm] AdminMessageSettingsRequestsDto inDto)
{
return EnableAdminMessageSettings(inDto);
}
private object EnableAdminMessageSettings(AdminMessageSettingsRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
_settingsManager.Save(new StudioAdminMessageSettings { Enable = inDto.TurnOn });
_messageService.Send(MessageAction.AdministratorMessageSettingsUpdated);
return Resource.SuccessfullySaveSettingsMessage;
}
[AllowAnonymous]
[Create("sendadmmail")]
public object SendAdmMailFromBody([FromBody] AdminMessageSettingsRequestsDto inDto)
{
return SendAdmMail(inDto);
}
[AllowAnonymous]
[Create("sendadmmail")]
[Consumes("application/x-www-form-urlencoded")]
public object SendAdmMailFromForm([FromForm] AdminMessageSettingsRequestsDto inDto)
{
return SendAdmMail(inDto);
}
private object SendAdmMail(AdminMessageSettingsRequestsDto inDto)
{
var studioAdminMessageSettings = _settingsManager.Load<StudioAdminMessageSettings>();
var enableAdmMess = studioAdminMessageSettings.Enable || _tenantExtra.IsNotPaid();
if (!enableAdmMess)
throw new MethodAccessException("Method not available");
if (!inDto.Email.TestEmailRegex())
throw new Exception(Resource.ErrorNotCorrectEmail);
if (string.IsNullOrEmpty(inDto.Message))
throw new Exception(Resource.ErrorEmptyMessage);
CheckCache("sendadmmail");
_studioNotifyService.SendMsgToAdminFromNotAuthUser(inDto.Email, inDto.Message);
_messageService.Send(MessageAction.ContactAdminMailSent);
return Resource.AdminMessageSent;
}
[AllowAnonymous]
[Create("sendjoininvite")]
public object SendJoinInviteMailFromBody([FromBody] AdminMessageSettingsRequestsDto inDto)
{
return SendJoinInviteMail(inDto);
}
[AllowAnonymous]
[Create("sendjoininvite")]
[Consumes("application/x-www-form-urlencoded")]
public object SendJoinInviteMailFromForm([FromForm] AdminMessageSettingsRequestsDto inDto)
{
return SendJoinInviteMail(inDto);
}
private object SendJoinInviteMail(AdminMessageSettingsRequestsDto inDto)
{
try
{
var email = inDto.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;
if (!_coreBaseSettings.Personal)
{
var enableInviteUsers = _tenantStatisticsProvider.GetUsersCount() < _tenantExtra.GetTenantQuota().ActiveUsers;
if (!enableInviteUsers)
emplType = EmployeeType.Visitor;
}
switch (Tenant.TrustedDomainsType)
{
case TenantTrustedDomainsType.Custom:
{
var address = new MailAddress(email);
if (Tenant.TrustedDomains.Any(d => address.Address.EndsWith("@" + d.Replace("*", ""), StringComparison.InvariantCultureIgnoreCase)))
{
_studioNotifyService.SendJoinMsg(email, emplType);
_messageService.Send(MessageInitiator.System, MessageAction.SentInviteInstructions, email);
return Resource.FinishInviteJoinEmailMessage;
}
throw new Exception(Resource.ErrorEmailDomainNotAllowed);
}
case TenantTrustedDomainsType.All:
{
_studioNotifyService.SendJoinMsg(email, emplType);
_messageService.Send(MessageInitiator.System, MessageAction.SentInviteInstructions, email);
return Resource.FinishInviteJoinEmailMessage;
}
default:
throw new Exception(Resource.ErrorNotCorrectEmail);
}
}
catch (FormatException)
{
return Resource.ErrorNotCorrectEmail;
}
catch (Exception e)
{
return e.Message.HtmlEncode();
}
}
}

View File

@ -0,0 +1,120 @@
using Constants = ASC.Core.Users.Constants;
namespace ASC.Web.Api.Controllers.Settings;
public class OwnerController : BaseSettingsController
{
private readonly MessageService _messageService;
private readonly StudioNotifyService _studioNotifyService;
private readonly UserManager _userManager;
private readonly TenantManager _tenantManager;
private readonly AuthContext _authContext;
private readonly PermissionContext _permissionContext;
private readonly CommonLinkUtility _commonLinkUtility;
private readonly DisplayUserSettingsHelper _displayUserSettingsHelper;
private readonly MessageTarget _messageTarget;
public OwnerController(
MessageService messageService,
CommonLinkUtility commonLinkUtility,
StudioNotifyService studioNotifyService,
ApiContext apiContext,
UserManager userManager,
TenantManager tenantManager,
AuthContext authContext,
PermissionContext permissionContext,
WebItemManager webItemManager,
DisplayUserSettingsHelper displayUserSettingsHelper,
MessageTarget messageTarget,
IMemoryCache memoryCache) : base(apiContext, memoryCache, webItemManager)
{
_messageService = messageService;
_commonLinkUtility = commonLinkUtility;
_studioNotifyService = studioNotifyService;
_userManager = userManager;
_tenantManager = tenantManager;
_authContext = authContext;
_permissionContext = permissionContext;
_displayUserSettingsHelper = displayUserSettingsHelper;
_messageTarget = messageTarget;
}
[Create("owner")]
public object SendOwnerChangeInstructionsFromBody([FromBody] SettingsRequestsDto inDto)
{
return SendOwnerChangeInstructions(inDto);
}
[Create("owner")]
[Consumes("application/x-www-form-urlencoded")]
public object SendOwnerChangeInstructionsFromForm([FromForm] SettingsRequestsDto inDto)
{
return SendOwnerChangeInstructions(inDto);
}
private object SendOwnerChangeInstructions(SettingsRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var curTenant = _tenantManager.GetCurrentTenant();
var owner = _userManager.GetUsers(curTenant.OwnerId);
var newOwner = _userManager.GetUsers(inDto.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 = $"<a href=\"mailto:{owner.Email}\">{owner.Email}</a>";
return new { Status = 1, Message = Resource.ChangePortalOwnerMsg.Replace(":email", emailLink) };
}
[Update("owner")]
[Authorize(AuthenticationSchemes = "confirm", Roles = "PortalOwnerChange")]
public void OwnerFromBody([FromBody] SettingsRequestsDto inDto)
{
Owner(inDto);
}
[Update("owner")]
[Authorize(AuthenticationSchemes = "confirm", Roles = "PortalOwnerChange")]
[Consumes("application/x-www-form-urlencoded")]
public void OwnerFromForm([FromForm] SettingsRequestsDto inDto)
{
Owner(inDto);
}
private void Owner(SettingsRequestsDto inDto)
{
var newOwner = Constants.LostUser;
try
{
newOwner = _userManager.GetUsers(inDto.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));
}
}

View File

@ -0,0 +1,252 @@
namespace ASC.Web.Api.Controllers.Settings;
public class SecurityController : BaseSettingsController
{
private readonly MessageService _messageService;
private readonly IServiceProvider _serviceProvider;
private readonly EmployeeDtoHelper _employeeHelperDto;
private readonly UserManager _userManager;
private readonly AuthContext _authContext;
private readonly WebItemSecurity _webItemSecurity;
private readonly PermissionContext _permissionContext;
private readonly SettingsManager _settingsManager;
private readonly WebItemManagerSecurity _webItemManagerSecurity;
private readonly DisplayUserSettingsHelper _displayUserSettingsHelper;
private readonly MessageTarget _messageTarget;
public SecurityController(
MessageService messageService,
ApiContext apiContext,
UserManager userManager,
AuthContext authContext,
WebItemSecurity webItemSecurity,
PermissionContext permissionContext,
SettingsManager settingsManager,
WebItemManager webItemManager,
WebItemManagerSecurity webItemManagerSecurity,
DisplayUserSettingsHelper displayUserSettingsHelper,
IServiceProvider serviceProvider,
EmployeeDtoHelper employeeWraperHelper,
MessageTarget messageTarget,
IMemoryCache memoryCache) : base(apiContext, memoryCache, webItemManager)
{
_serviceProvider = serviceProvider;
_employeeHelperDto = employeeWraperHelper;
_messageService = messageService;
_userManager = userManager;
_authContext = authContext;
_webItemSecurity = webItemSecurity;
_permissionContext = permissionContext;
_settingsManager = settingsManager;
_webItemManagerSecurity = webItemManagerSecurity;
_displayUserSettingsHelper = displayUserSettingsHelper;
_messageTarget = messageTarget;
}
[Read("security")]
public IEnumerable<SecurityDto> GetWebItemSecurityInfo([FromQuery] IEnumerable<string> ids)
{
if (ids == null || !ids.Any())
{
ids = _webItemManager.GetItemsAll().Select(i => i.ID.ToString());
}
var subItemList = _webItemManager.GetItemsAll().Where(item => item.IsSubItem()).Select(i => i.ID.ToString());
return ids.Select(r => _webItemSecurity.GetSecurityInfo(r))
.Select(i => new SecurityDto
{
WebItemId = i.WebItemId,
Enabled = i.Enabled,
Users = i.Users.Select(_employeeHelperDto.Get),
Groups = i.Groups.Select(g => new GroupSummaryDto(g, _userManager)),
IsSubItem = subItemList.Contains(i.WebItemId),
}).ToList();
}
[Read("security/{id}")]
public bool GetWebItemSecurityInfo(Guid id)
{
var module = _webItemManager[id];
return module != null && !module.IsDisabled(_webItemSecurity, _authContext);
}
[Read("security/modules")]
public object GetEnabledModules()
{
var EnabledModules = _webItemManagerSecurity.GetItems(WebZoneType.All, ItemAvailableState.Normal)
.Where(item => !item.IsSubItem() && item.Visible)
.Select(item => new
{
id = item.ProductClassName.HtmlEncode(),
title = item.Name.HtmlEncode()
});
return EnabledModules;
}
[Read("security/password", Check = false)]
[Authorize(AuthenticationSchemes = "confirm", Roles = "Everyone")]
public object GetPasswordSettings()
{
var UserPasswordSettings = _settingsManager.Load<PasswordSettings>();
return UserPasswordSettings;
}
[Update("security")]
public IEnumerable<SecurityDto> SetWebItemSecurityFromBody([FromBody] WebItemSecurityRequestsDto inDto)
{
return SetWebItemSecurity(inDto);
}
[Update("security")]
[Consumes("application/x-www-form-urlencoded")]
public IEnumerable<SecurityDto> SetWebItemSecurityFromForm([FromForm] WebItemSecurityRequestsDto inDto)
{
return SetWebItemSecurity(inDto);
}
private IEnumerable<SecurityDto> SetWebItemSecurity(WebItemSecurityRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
_webItemSecurity.SetSecurity(inDto.Id, inDto.Enabled, inDto.Subjects?.ToArray());
var securityInfo = GetWebItemSecurityInfo(new List<string> { inDto.Id });
if (inDto.Subjects == null) return securityInfo;
var productName = GetProductName(new Guid(inDto.Id));
if (!inDto.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")]
public IEnumerable<SecurityDto> SetAccessToWebItemsFromBody([FromBody] WebItemSecurityRequestsDto inDto)
{
return SetAccessToWebItems(inDto);
}
[Update("security/access")]
[Consumes("application/x-www-form-urlencoded")]
public IEnumerable<SecurityDto> SetAccessToWebItemsFromForm([FromForm] WebItemSecurityRequestsDto inDto)
{
return SetAccessToWebItems(inDto);
}
private IEnumerable<SecurityDto> SetAccessToWebItems(WebItemSecurityRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var itemList = new ItemDictionary<string, bool>();
foreach (var item in inDto.Items)
{
if (!itemList.ContainsKey(item.Key))
itemList.Add(item.Key, item.Value);
}
var defaultPageSettings = _settingsManager.Load<StudioDefaultPageSettings>();
foreach (var item in itemList)
{
Guid[] subjects = null;
var productId = new Guid(item.Key);
if (item.Value)
{
if (_webItemManager[productId] is IProduct webItem || productId == WebItemManager.MailProductID)
{
var productInfo = _webItemSecurity.GetSecurityInfo(item.Key);
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)
{
_settingsManager.Save((StudioDefaultPageSettings)defaultPageSettings.GetDefault(_serviceProvider));
}
_webItemSecurity.SetSecurity(item.Key, item.Value, subjects);
}
_messageService.Send(MessageAction.ProductsListUpdated);
return GetWebItemSecurityInfo(itemList.Keys.ToList());
}
[Read("security/administrator/{productid}")]
public IEnumerable<EmployeeDto> GetProductAdministrators(Guid productid)
{
return _webItemSecurity.GetProductAdministrators(productid)
.Select(_employeeHelperDto.Get)
.ToList();
}
[Read("security/administrator")]
public object IsProductAdministrator(Guid productid, Guid userid)
{
var result = _webItemSecurity.IsProductAdministrator(productid, userid);
return new { ProductId = productid, UserId = userid, Administrator = result };
}
[Update("security/administrator")]
public object SetProductAdministratorFromBody([FromBody] SecurityRequestsDto inDto)
{
return SetProductAdministrator(inDto);
}
[Update("security/administrator")]
[Consumes("application/x-www-form-urlencoded")]
public object SetProductAdministratorFromForm([FromForm] SecurityRequestsDto inDto)
{
return SetProductAdministrator(inDto);
}
private object SetProductAdministrator(SecurityRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
_webItemSecurity.SetProductAdministrator(inDto.ProductId, inDto.UserId, inDto.Administrator);
var admin = _userManager.GetUsers(inDto.UserId);
if (inDto.ProductId == Guid.Empty)
{
var messageAction = inDto.Administrator ? MessageAction.AdministratorOpenedFullAccess : MessageAction.AdministratorDeleted;
_messageService.Send(messageAction, _messageTarget.Create(admin.Id), admin.DisplayUserName(false, _displayUserSettingsHelper));
}
else
{
var messageAction = inDto.Administrator ? MessageAction.ProductAddedAdministrator : MessageAction.ProductDeletedAdministrator;
_messageService.Send(messageAction, _messageTarget.Create(admin.Id), GetProductName(inDto.ProductId), admin.DisplayUserName(false, _displayUserSettingsHelper));
}
return new { inDto.ProductId, inDto.UserId, inDto.Administrator };
}
}

View File

@ -0,0 +1,710 @@

using Constants = ASC.Core.Users.Constants;
namespace ASC.Web.Api.Controllers.Settings;
public class SettingsController: BaseSettingsController
{
private Tenant Tenant { get { return _apiContext.Tenant; } }
private readonly MessageService _messageService;
private readonly ConsumerFactory _consumerFactory;
private readonly TimeZoneConverter _timeZoneConverter;
private readonly CustomNamingPeople _customNamingPeople;
private readonly ProviderManager _providerManager;
private readonly FirstTimeTenantSettings _firstTimeTenantSettings;
private readonly UserManager _userManager;
private readonly TenantManager _tenantManager;
private readonly TenantExtra _tenantExtra;
private readonly TenantStatisticsProvider _tenantStatisticsProvider;
private readonly AuthContext _authContext;
private readonly PermissionContext _permissionContext;
private readonly SettingsManager _settingsManager;
private readonly WebItemManagerSecurity _webItemManagerSecurity;
private readonly TenantInfoSettingsHelper _tenantInfoSettingsHelper;
private readonly TenantUtil _tenantUtil;
private readonly CoreBaseSettings _coreBaseSettings;
private readonly CommonLinkUtility _commonLinkUtility;
private readonly ColorThemesSettingsHelper _colorThemesSettingsHelper;
private readonly IConfiguration _configuration;
private readonly SetupInfo _setupInfo;
private readonly StatisticManager _statisticManager;
private readonly CoreConfiguration _coreConfiguration;
private readonly UrlShortener _urlShortener;
private readonly PasswordHasher _passwordHasher;
private readonly ILog _log;
private readonly TelegramHelper _telegramHelper;
private readonly Constants _constants;
public SettingsController(
IOptionsMonitor<ILog> option,
MessageService messageService,
ApiContext apiContext,
UserManager userManager,
TenantManager tenantManager,
TenantExtra tenantExtra,
TenantStatisticsProvider tenantStatisticsProvider,
AuthContext authContext,
PermissionContext permissionContext,
SettingsManager settingsManager,
WebItemManager webItemManager,
WebItemManagerSecurity webItemManagerSecurity,
TenantInfoSettingsHelper tenantInfoSettingsHelper,
TenantUtil tenantUtil,
CoreBaseSettings coreBaseSettings,
CommonLinkUtility commonLinkUtility,
ColorThemesSettingsHelper colorThemesSettingsHelper,
IConfiguration configuration,
SetupInfo setupInfo,
StatisticManager statisticManager,
CoreConfiguration coreConfiguration,
ConsumerFactory consumerFactory,
TimeZoneConverter timeZoneConverter,
CustomNamingPeople customNamingPeople,
IMemoryCache memoryCache,
ProviderManager providerManager,
FirstTimeTenantSettings firstTimeTenantSettings,
TelegramHelper telegramHelper,
UrlShortener urlShortener,
PasswordHasher passwordHasher,
Constants constants) : base(apiContext, memoryCache, webItemManager)
{
_log = option.Get("ASC.Api");
_consumerFactory = consumerFactory;
_timeZoneConverter = timeZoneConverter;
_customNamingPeople = customNamingPeople;
_providerManager = providerManager;
_firstTimeTenantSettings = firstTimeTenantSettings;
_messageService = messageService;
_userManager = userManager;
_tenantManager = tenantManager;
_tenantExtra = tenantExtra;
_tenantStatisticsProvider = tenantStatisticsProvider;
_authContext = authContext;
_permissionContext = permissionContext;
_settingsManager = settingsManager;
_webItemManagerSecurity = webItemManagerSecurity;
_tenantInfoSettingsHelper = tenantInfoSettingsHelper;
_tenantUtil = tenantUtil;
_coreBaseSettings = coreBaseSettings;
_commonLinkUtility = commonLinkUtility;
_colorThemesSettingsHelper = colorThemesSettingsHelper;
_configuration = configuration;
_setupInfo = setupInfo;
_statisticManager = statisticManager;
_coreConfiguration = coreConfiguration;
_passwordHasher = passwordHasher;
_urlShortener = urlShortener;
_telegramHelper = telegramHelper;
_constants = constants;
}
[Read("", Check = false)]
[AllowAnonymous]
public SettingsDto GetSettings(bool? withpassword)
{
var settings = new SettingsDto
{
Culture = Tenant.GetCulture().ToString(),
GreetingSettings = Tenant.Name,
Personal = _coreBaseSettings.Personal,
Version = _configuration["version:number"] ?? ""
};
if (_authContext.IsAuthenticated)
{
settings.TrustedDomains = Tenant.TrustedDomains;
settings.TrustedDomainsType = Tenant.TrustedDomainsType;
var timeZone = Tenant.TimeZone;
settings.Timezone = timeZone;
settings.UtcOffset = _timeZoneConverter.GetTimeZone(timeZone).GetUtcOffset(DateTime.UtcNow);
settings.UtcHoursOffset = settings.UtcOffset.TotalHours;
settings.OwnerId = Tenant.OwnerId;
settings.NameSchemaId = _customNamingPeople.Current.Id;
settings.Firebase = new FirebaseDto
{
ApiKey = _configuration["firebase:apiKey"] ?? "",
AuthDomain = _configuration["firebase:authDomain"] ?? "",
ProjectId = _configuration["firebase:projectId"] ?? "",
StorageBucket = _configuration["firebase:storageBucket"] ?? "",
MessagingSenderId = _configuration["firebase:messagingSenderId"] ?? "",
AppId = _configuration["firebase:appId"] ?? "",
MeasurementId = _configuration["firebase:measurementId"] ?? ""
};
bool debugInfo;
if (bool.TryParse(_configuration["debug-info:enabled"], out debugInfo))
{
settings.DebugInfo = debugInfo;
}
}
else
{
if (!_settingsManager.Load<WizardSettings>().Completed)
{
settings.WizardToken = _commonLinkUtility.GetToken(Tenant.Id, "", 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;
settings.RecaptchaPublicKey = _setupInfo.RecaptchaPublicKey;
}
if (!_authContext.IsAuthenticated || (withpassword.HasValue && withpassword.Value))
{
settings.PasswordHash = _passwordHasher;
}
return settings;
}
[Create("maildomainsettings")]
public object SaveMailDomainSettingsFromBody([FromBody] MailDomainSettingsRequestsDto inDto)
{
return SaveMailDomainSettings(inDto);
}
[Create("maildomainsettings")]
[Consumes("application/x-www-form-urlencoded")]
public object SaveMailDomainSettingsFromForm([FromForm] MailDomainSettingsRequestsDto inDto)
{
return SaveMailDomainSettings(inDto);
}
private object SaveMailDomainSettings(MailDomainSettingsRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (inDto.Type == TenantTrustedDomainsType.Custom)
{
Tenant.TrustedDomains.Clear();
foreach (var d in inDto.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)))
return Resource.ErrorNotCorrectTrustedDomain;
Tenant.TrustedDomains.Add(d);
}
if (Tenant.TrustedDomains.Count == 0)
inDto.Type = TenantTrustedDomainsType.None;
}
Tenant.TrustedDomainsType = inDto.Type;
_settingsManager.Save(new StudioTrustedDomainSettings { InviteUsersAsVisitors = inDto.InviteUsersAsVisitors });
_tenantManager.SaveTenant(Tenant);
_messageService.Send(MessageAction.TrustedMailDomainSettingsUpdated);
return Resource.SuccessfullySaveSettingsMessage;
}
[Read("quota")]
public QuotaDto GetQuotaUsed()
{
return new QuotaDto(Tenant, _coreBaseSettings, _coreConfiguration, _tenantExtra, _tenantStatisticsProvider, _authContext, _settingsManager, _webItemManager, _constants);
}
[AllowAnonymous]
[Read("cultures", Check = false)]
public IEnumerable<object> GetSupportedCultures()
{
return _setupInfo.EnabledCultures.Select(r => r.Name).ToArray();
}
[Authorize(AuthenticationSchemes = "confirm", Roles = "Wizard,Administrators")]
[Read("timezones", Check = false)]
public List<TimezonesRequestsDto> GetTimeZones()
{
_apiContext.AuthByClaim();
var timeZones = TimeZoneInfo.GetSystemTimeZones().ToList();
if (timeZones.All(tz => tz.Id != "UTC"))
{
timeZones.Add(TimeZoneInfo.Utc);
}
var listOfTimezones = new List<TimezonesRequestsDto>();
foreach (var tz in timeZones.OrderBy(z => z.BaseUtcOffset))
{
listOfTimezones.Add(new TimezonesRequestsDto
{
Id = tz.Id,
DisplayName = _timeZoneConverter.GetTimeZoneDisplayName(tz)
});
}
return listOfTimezones;
}
[Authorize(AuthenticationSchemes = "confirm", Roles = "Wizard")]
[Read("machine", Check = false)]
public object GetMachineName()
{
return Dns.GetHostName().ToLowerInvariant();
}
//[Read("recalculatequota")]
//public void RecalculateQuota()
//{
// SecurityContext.DemandPermissions(Tenant, SecutiryConstants.EditPortalSettings);
// var operations = quotaTasks.GetTasks()
// .Where(t => t.GetProperty<int>(QuotaSync.IdKey) == Tenant.Id);
// if (operations.Any(o => o.Status <= DistributedTaskStatus.Running))
// {
// throw new InvalidOperationException(Resource.LdapSettingsTooManyOperations);
// }
// var op = new QuotaSync(Tenant.Id, ServiceProvider);
// quotaTasks.QueueTask(op.RunJob, op.GetDistributedTask());
//}
//[Read("checkrecalculatequota")]
//public bool CheckRecalculateQuota()
//{
// PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
// var task = quotaTasks.GetTasks().FirstOrDefault(t => t.GetProperty<int>(QuotaSync.IdKey) == Tenant.Id);
// if (task != null && task.Status == DistributedTaskStatus.Completed)
// {
// quotaTasks.RemoveTask(task.Id);
// return false;
// }
// return task != null;
//}
[Read("logo")]
public object GetLogo()
{
return _tenantInfoSettingsHelper.GetAbsoluteCompanyLogoPath(_settingsManager.Load<TenantInfoSettings>());
}
[Update("wizard/complete", Check = false)]
[Authorize(AuthenticationSchemes = "confirm", Roles = "Wizard")]
public WizardSettings CompleteWizardFromBody([FromBody] WizardRequestsDto inDto)
{
return CompleteWizard(inDto);
}
[Update("wizard/complete", Check = false)]
[Authorize(AuthenticationSchemes = "confirm", Roles = "Wizard")]
[Consumes("application/x-www-form-urlencoded")]
public WizardSettings CompleteWizardFromForm([FromForm] WizardRequestsDto inDto)
{
return CompleteWizard(inDto);
}
private WizardSettings CompleteWizard(WizardRequestsDto wizardModel)
{
_apiContext.AuthByClaim();
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
return _firstTimeTenantSettings.SaveData(wizardModel);
}
///<visible>false</visible>
[Update("welcome/close")]
public void CloseWelcomePopup()
{
var currentUser = _userManager.GetUsers(_authContext.CurrentAccount.ID);
var collaboratorPopupSettings = _settingsManager.LoadForCurrentUser<CollaboratorSettings>();
if (!(currentUser.IsVisitor(_userManager) && collaboratorPopupSettings.FirstVisit && !currentUser.IsOutsider(_userManager)))
throw new NotSupportedException("Not available.");
collaboratorPopupSettings.FirstVisit = false;
_settingsManager.SaveForCurrentUser(collaboratorPopupSettings);
}
///<visible>false</visible>
[Update("colortheme")]
public void SaveColorThemeFromBody([FromBody] SettingsRequestsDto inDto)
{
SaveColorTheme(inDto);
}
[Update("colortheme")]
[Consumes("application/x-www-form-urlencoded")]
public void SaveColorThemeFromForm([FromForm] SettingsRequestsDto inDto)
{
SaveColorTheme(inDto);
}
private void SaveColorTheme(SettingsRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
_colorThemesSettingsHelper.SaveColorTheme(inDto.Theme);
_messageService.Send(MessageAction.ColorThemeChanged);
}
///<visible>false</visible>
[Update("timeandlanguage")]
public object TimaAndLanguageFromBody([FromBody] SettingsRequestsDto inDto)
{
return TimaAndLanguage(inDto);
}
[Update("timeandlanguage")]
[Consumes("application/x-www-form-urlencoded")]
public object TimaAndLanguageFromForm([FromForm] SettingsRequestsDto inDto)
{
return TimaAndLanguage(inDto);
}
private object TimaAndLanguage(SettingsRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var culture = CultureInfo.GetCultureInfo(inDto.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);
}
Tenant.TimeZone = timeZones.FirstOrDefault(tz => tz.Id == inDto.TimeZoneID)?.Id ?? TimeZoneInfo.Utc.Id;
_tenantManager.SaveTenant(Tenant);
if (!Tenant.TimeZone.Equals(oldTimeZone) || changelng)
{
if (!Tenant.TimeZone.Equals(oldTimeZone))
{
_messageService.Send(MessageAction.TimeZoneSettingsUpdated);
}
if (changelng)
{
_messageService.Send(MessageAction.LanguageSettingsUpdated);
}
}
return Resource.SuccessfullySaveSettingsMessage;
}
///<visible>false</visible>
[Update("defaultpage")]
public object SaveDefaultPageSettingsFromBody([FromBody] SettingsRequestsDto inDto)
{
return SaveDefaultPageSettings(inDto);
}
[Update("defaultpage")]
[Consumes("application/x-www-form-urlencoded")]
public object SaveDefaultPageSettingsFromForm([FromForm] SettingsRequestsDto inDto)
{
return SaveDefaultPageSettings(inDto);
}
private object SaveDefaultPageSettings(SettingsRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
_settingsManager.Save(new StudioDefaultPageSettings { DefaultProductID = inDto.DefaultProductID });
_messageService.Send(MessageAction.DefaultStartPageSettingsUpdated);
return Resource.SuccessfullySaveSettingsMessage;
}
[Update("emailactivation")]
public EmailActivationSettings UpdateEmailActivationSettingsFromBody([FromBody] EmailActivationSettings settings)
{
_settingsManager.SaveForCurrentUser(settings);
return settings;
}
[Update("emailactivation")]
[Consumes("application/x-www-form-urlencoded")]
public EmailActivationSettings UpdateEmailActivationSettingsFromForm([FromForm] EmailActivationSettings settings)
{
_settingsManager.SaveForCurrentUser(settings);
return settings;
}
[Read("statistics/spaceusage/{id}")]
public Task<List<UsageSpaceStatItemDto>> GetSpaceUsageStatistics(Guid id)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var webitem = _webItemManagerSecurity.GetItems(WebZoneType.All, ItemAvailableState.All)
.FirstOrDefault(item =>
item != null &&
item.ID == id &&
item.Context != null &&
item.Context.SpaceUsageStatManager != null);
if (webitem == null) return Task.FromResult(new List<UsageSpaceStatItemDto>());
return InternalGetSpaceUsageStatistics(webitem);
}
private async Task<List<UsageSpaceStatItemDto>> InternalGetSpaceUsageStatistics(IWebItem webitem)
{
var statData = await webitem.Context.SpaceUsageStatManager.GetStatDataAsync();
return statData.ConvertAll(it => new UsageSpaceStatItemDto
{
Name = it.Name.HtmlEncode(),
Icon = it.ImgUrl,
Disabled = it.Disabled,
Size = FileSizeComment.FilesSizeToString(it.SpaceUsage),
Url = it.Url
});
}
[Read("statistics/visit")]
public List<ChartPointDto> GetVisitStatistics(ApiDateTime fromDate, ApiDateTime toDate)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var from = _tenantUtil.DateTimeFromUtc(fromDate);
var to = _tenantUtil.DateTimeFromUtc(toDate);
var points = new List<ChartPointDto>();
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 ChartPointDto
{
DisplayDate = d.Date.ToShortDateString(),
Date = d.Date,
Hosts = 0,
Hits = 0
});
}
var hits = _statisticManager.GetHitsByPeriod(Tenant.Id, from, to);
var hosts = _statisticManager.GetHostsByPeriod(Tenant.Id, from, to);
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("socket")]
public object GetSocketSettings()
{
var hubUrl = _configuration["web:hub"] ?? string.Empty;
if (hubUrl.Length != 0)
{
if (!hubUrl.EndsWith('/'))
{
hubUrl += "/";
}
}
return new { Url = hubUrl };
}
///<visible>false</visible>
[Read("controlpanel")]
public TenantControlPanelSettings GetTenantControlPanelSettings()
{
return _settingsManager.Load<TenantControlPanelSettings>();
}
[Read("authservice")]
public IEnumerable<AuthServiceRequestsDto> GetAuthServices()
{
return _consumerFactory.GetAll<Consumer>()
.Where(consumer => consumer.ManagedKeys.Any())
.OrderBy(services => services.Order)
.Select(r => new AuthServiceRequestsDto(r))
.ToList();
}
[Create("authservice")]
public bool SaveAuthKeysFromBody([FromBody] AuthServiceRequestsDto inDto)
{
return SaveAuthKeys(inDto);
}
[Create("authservice")]
[Consumes("application/x-www-form-urlencoded")]
public bool SaveAuthKeysFromForm([FromForm] AuthServiceRequestsDto inDto)
{
return SaveAuthKeys(inDto);
}
private bool SaveAuthKeys(AuthServiceRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var saveAvailable = _coreBaseSettings.Standalone || _tenantManager.GetTenantQuota(_tenantManager.GetCurrentTenant().Id).ThirdParty;
if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.ThirdPartyAuthorization))
|| !saveAvailable)
throw new BillingException(Resource.ErrorNotAllowedOption, "ThirdPartyAuthorization");
var changed = false;
var consumer = _consumerFactory.GetByKey<Consumer>(inDto.Name);
var validateKeyProvider = consumer as IValidateKeysProvider;
if (validateKeyProvider != null)
{
try
{
if (validateKeyProvider is TwilioProvider twilioLoginProvider)
{
twilioLoginProvider.ClearOldNumbers();
}
if (validateKeyProvider is BitlyLoginProvider bitly)
{
_urlShortener.Instance = null;
}
}
catch (Exception e)
{
_log.Error(e);
}
}
if (inDto.Props.All(r => string.IsNullOrEmpty(r.Value)))
{
consumer.Clear();
changed = true;
}
else
{
foreach (var authKey in inDto.Props.Where(authKey => consumer[authKey.Name] != authKey.Value))
{
consumer[authKey.Name] = authKey.Value;
changed = true;
}
}
//TODO: Consumer implementation required (Bug 50606)
var allPropsIsEmpty = consumer.GetType() == typeof(SmscProvider)
? consumer.ManagedKeys.All(key => string.IsNullOrEmpty(consumer[key]))
: consumer.All(r => string.IsNullOrEmpty(r.Value));
if (validateKeyProvider != null && !validateKeyProvider.ValidateKeys() && !allPropsIsEmpty)
{
consumer.Clear();
throw new ArgumentException(Resource.ErrorBadKeys);
}
if (changed)
_messageService.Send(MessageAction.AuthorizationKeysSetting);
return changed;
}
[Read("payment", Check = false)]
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
}
};
}
/// <visible>false</visible>
/// <summary>
/// Gets a link that will connect TelegramBot to your account
/// </summary>
/// <returns>url</returns>
///
[Read("telegramlink")]
public object TelegramLink()
{
var currentLink = _telegramHelper.CurrentRegistrationLink(_authContext.CurrentAccount.ID, Tenant.Id);
if (string.IsNullOrEmpty(currentLink))
{
var url = _telegramHelper.RegisterUser(_authContext.CurrentAccount.ID, Tenant.Id);
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()
{
return (int)_telegramHelper.UserIsConnected(_authContext.CurrentAccount.ID, Tenant.Id);
}
/// <summary>
/// Unlinks TelegramBot from your account
/// </summary>
[Delete("telegramdisconnect")]
public void TelegramDisconnect()
{
_telegramHelper.Disconnect(_authContext.CurrentAccount.ID, Tenant.Id);
}
}

View File

@ -0,0 +1,464 @@
namespace ASC.Web.Api.Controllers.Settings;
public class StorageController : BaseSettingsController
{
private Tenant Tenant { get { return _apiContext.Tenant; } }
private readonly MessageService _messageService;
private readonly StudioNotifyService _studioNotifyService;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly ConsumerFactory _consumerFactory;
private readonly TenantManager _tenantManager;
private readonly TenantExtra _tenantExtra;
private readonly PermissionContext _permissionContext;
private readonly SettingsManager _settingsManager;
private readonly CoreBaseSettings _coreBaseSettings;
private readonly CommonLinkUtility _commonLinkUtility;
private readonly StorageSettingsHelper _storageSettingsHelper;
private readonly ServiceClient _serviceClient;
private readonly EncryptionServiceClient _encryptionServiceClient;
private readonly EncryptionSettingsHelper _encryptionSettingsHelper;
private readonly BackupAjaxHandler _backupAjaxHandler;
private readonly ICacheNotify<DeleteSchedule> _cacheDeleteSchedule;
private readonly EncryptionWorker _encryptionWorker;
private readonly ILog _log;
public StorageController(
IOptionsMonitor<ILog> option,
ServiceClient serviceClient,
MessageService messageService,
StudioNotifyService studioNotifyService,
ApiContext apiContext,
TenantManager tenantManager,
TenantExtra tenantExtra,
PermissionContext permissionContext,
SettingsManager settingsManager,
WebItemManager webItemManager,
CoreBaseSettings coreBaseSettings,
CommonLinkUtility commonLinkUtility,
StorageSettingsHelper storageSettingsHelper,
IWebHostEnvironment webHostEnvironment,
ConsumerFactory consumerFactory,
IMemoryCache memoryCache,
EncryptionServiceClient encryptionServiceClient,
EncryptionSettingsHelper encryptionSettingsHelper,
BackupAjaxHandler backupAjaxHandler,
ICacheNotify<DeleteSchedule> cacheDeleteSchedule,
EncryptionWorker encryptionWorker) : base(apiContext, memoryCache, webItemManager)
{
_log = option.Get("ASC.Api");
_serviceClient = serviceClient;
_webHostEnvironment = webHostEnvironment;
_consumerFactory = consumerFactory;
_messageService = messageService;
_studioNotifyService = studioNotifyService;
_tenantManager = tenantManager;
_tenantExtra = tenantExtra;
_permissionContext = permissionContext;
_settingsManager = settingsManager;
_coreBaseSettings = coreBaseSettings;
_commonLinkUtility = commonLinkUtility;
_storageSettingsHelper = storageSettingsHelper;
_encryptionServiceClient = encryptionServiceClient;
_encryptionSettingsHelper = encryptionSettingsHelper;
_backupAjaxHandler = backupAjaxHandler;
_cacheDeleteSchedule = cacheDeleteSchedule;
_encryptionWorker = encryptionWorker;
}
[Read("storage")]
public List<StorageDto> GetAllStorages()
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
_tenantExtra.DemandControlPanelPermission();
var current = _settingsManager.Load<StorageSettings>();
var consumers = _consumerFactory.GetAll<DataStoreConsumer>();
return consumers.Select(consumer => new StorageDto(consumer, current)).ToList();
}
[Read("storage/progress", false)]
public double GetStorageProgress()
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!_coreBaseSettings.Standalone) return -1;
return _serviceClient.GetProgress(Tenant.Id);
}
public readonly object Locker = new object();
[Create("encryption/start")]
public bool StartStorageEncryptionFromBody([FromBody] StorageEncryptionRequestsDto inDto)
{
return StartStorageEncryption(inDto);
}
[Create("encryption/start")]
[Consumes("application/x-www-form-urlencoded")]
public bool StartStorageEncryptionFromForm([FromForm] StorageEncryptionRequestsDto inDto)
{
return StartStorageEncryption(inDto);
}
private bool StartStorageEncryption(StorageEncryptionRequestsDto inDto)
{
if (_coreBaseSettings.CustomMode)
{
return false;
}
lock (Locker)
{
var activeTenants = _tenantManager.GetTenants();
if (activeTenants.Count > 0)
{
StartEncryption(inDto.NotifyUsers);
}
}
return true;
}
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().Id).DiscEncryption)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "DiscEncryption");
}
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)
{
var progress = _backupAjaxHandler.GetBackupProgress(tenant.Id);
if (progress != null && !progress.IsCompleted)
{
throw new Exception();
}
}
foreach (var tenant in tenants)
{
_cacheDeleteSchedule.Publish(new DeleteSchedule() { TenantId = tenant.Id }, Common.Caching.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);
var encryptionSettingsProto = new EncryptionSettingsProto
{
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
{
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().Id).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")]
public double? GetStorageEncryptionProgress()
{
if (_coreBaseSettings.CustomMode)
{
return -1;
}
if (!SetupInfo.IsVisibleSettings<EncryptionSettings>())
{
throw new NotSupportedException();
}
if (!_coreBaseSettings.Standalone)
{
throw new NotSupportedException();
}
if (!_tenantManager.GetTenantQuota(_tenantManager.GetCurrentTenant().Id).DiscEncryption)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "DiscEncryption");
}
return _encryptionWorker.GetEncryptionProgress();
}
[Update("storage")]
public StorageSettings UpdateStorageFromBody([FromBody] StorageRequestsDto inDto)
{
return UpdateStorage(inDto);
}
[Update("storage")]
[Consumes("application/x-www-form-urlencoded")]
public StorageSettings UpdateStorageFromForm([FromForm] StorageRequestsDto inDto)
{
return UpdateStorage(inDto);
}
private StorageSettings UpdateStorage(StorageRequestsDto inDto)
{
try
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!_coreBaseSettings.Standalone) return null;
_tenantExtra.DemandControlPanelPermission();
var consumer = _consumerFactory.GetByKey(inDto.Module);
if (!consumer.IsSet)
throw new ArgumentException("module");
var settings = _settingsManager.Load<StorageSettings>();
if (settings.Module == inDto.Module) return settings;
settings.Module = inDto.Module;
settings.Props = inDto.Props.ToDictionary(r => r.Key, b => b.Value);
StartMigrate(settings);
return settings;
}
catch (Exception e)
{
_log.Error("UpdateStorage", e);
throw;
}
}
[Delete("storage")]
public void ResetStorageToDefault()
{
try
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!_coreBaseSettings.Standalone) return;
_tenantExtra.DemandControlPanelPermission();
var settings = _settingsManager.Load<StorageSettings>();
settings.Module = null;
settings.Props = null;
StartMigrate(settings);
}
catch (Exception e)
{
_log.Error("ResetStorageToDefault", e);
throw;
}
}
[Read("storage/cdn")]
public List<StorageDto> GetAllCdnStorages()
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!_coreBaseSettings.Standalone) return null;
_tenantExtra.DemandControlPanelPermission();
var current = _settingsManager.Load<CdnStorageSettings>();
var consumers = _consumerFactory.GetAll<DataStoreConsumer>().Where(r => r.Cdn != null);
return consumers.Select(consumer => new StorageDto(consumer, current)).ToList();
}
[Update("storage/cdn")]
public CdnStorageSettings UpdateCdnFromBody([FromBody] StorageRequestsDto inDto)
{
return UpdateCdn(inDto);
}
[Update("storage/cdn")]
[Consumes("application/x-www-form-urlencoded")]
public CdnStorageSettings UpdateCdnFromForm([FromForm] StorageRequestsDto inDto)
{
return UpdateCdn(inDto);
}
private CdnStorageSettings UpdateCdn(StorageRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!_coreBaseSettings.Standalone) return null;
_tenantExtra.DemandControlPanelPermission();
var consumer = _consumerFactory.GetByKey(inDto.Module);
if (!consumer.IsSet)
throw new ArgumentException("module");
var settings = _settingsManager.Load<CdnStorageSettings>();
if (settings.Module == inDto.Module) return settings;
settings.Module = inDto.Module;
settings.Props = inDto.Props.ToDictionary(r => r.Key, b => b.Value);
try
{
_serviceClient.UploadCdn(Tenant.Id, "/", _webHostEnvironment.ContentRootPath, settings);
}
catch (Exception e)
{
_log.Error("UpdateCdn", e);
throw;
}
return settings;
}
[Delete("storage/cdn")]
public void ResetCdnToDefault()
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!_coreBaseSettings.Standalone) return;
_tenantExtra.DemandControlPanelPermission();
_storageSettingsHelper.Clear(_settingsManager.Load<CdnStorageSettings>());
}
[Read("storage/backup")]
public List<StorageDto> GetAllBackupStorages()
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (_coreBaseSettings.Standalone)
{
_tenantExtra.DemandControlPanelPermission();
}
var schedule = _backupAjaxHandler.GetSchedule();
var current = new StorageSettings();
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)
};
}
var consumers = _consumerFactory.GetAll<DataStoreConsumer>();
return consumers.Select(consumer => new StorageDto(consumer, current)).ToList();
}
private void StartMigrate(StorageSettings settings)
{
_serviceClient.Migrate(Tenant.Id, settings);
Tenant.SetStatus(TenantStatus.Migrating);
_tenantManager.SaveTenant(Tenant);
}
}

View File

@ -0,0 +1,309 @@
using Constants = ASC.Core.Users.Constants;
namespace ASC.Web.Api.Controllers.Settings;
public class TfaappController : BaseSettingsController
{
private readonly MessageService _messageService;
private readonly StudioNotifyService _studioNotifyService;
private readonly IServiceProvider _serviceProvider;
private readonly SmsProviderManager _smsProviderManager;
private readonly UserManager _userManager;
private readonly AuthContext _authContext;
private readonly CookiesManager _cookiesManager;
private readonly PermissionContext _permissionContext;
private readonly SettingsManager _settingsManager;
private readonly TfaManager _tfaManager;
private readonly CommonLinkUtility _commonLinkUtility;
private readonly DisplayUserSettingsHelper _displayUserSettingsHelper;
private readonly MessageTarget _messageTarget;
private readonly StudioSmsNotificationSettingsHelper _studioSmsNotificationSettingsHelper;
private readonly InstanceCrypto _instanceCrypto;
private readonly Signature _signature;
public TfaappController(
MessageService messageService,
StudioNotifyService studioNotifyService,
ApiContext apiContext,
UserManager userManager,
AuthContext authContext,
CookiesManager cookiesManager,
PermissionContext permissionContext,
SettingsManager settingsManager,
TfaManager tfaManager,
WebItemManager webItemManager,
CommonLinkUtility commonLinkUtility,
DisplayUserSettingsHelper displayUserSettingsHelper,
MessageTarget messageTarget,
StudioSmsNotificationSettingsHelper studioSmsNotificationSettingsHelper,
IServiceProvider serviceProvider,
SmsProviderManager smsProviderManager,
IMemoryCache memoryCache,
InstanceCrypto instanceCrypto,
Signature signature) : base(apiContext, memoryCache, webItemManager)
{
_serviceProvider = serviceProvider;
_smsProviderManager = smsProviderManager;
_messageService = messageService;
_studioNotifyService = studioNotifyService;
_userManager = userManager;
_authContext = authContext;
_cookiesManager = cookiesManager;
_permissionContext = permissionContext;
_settingsManager = settingsManager;
_tfaManager = tfaManager;
_commonLinkUtility = commonLinkUtility;
_displayUserSettingsHelper = displayUserSettingsHelper;
_messageTarget = messageTarget;
_studioSmsNotificationSettingsHelper = studioSmsNotificationSettingsHelper;
_instanceCrypto = instanceCrypto;
_signature = signature;
}
[Read("tfaapp")]
public IEnumerable<TfaSettingsRequestsDto> GetTfaSettings()
{
var result = new List<TfaSettingsRequestsDto>();
var SmsVisible = _studioSmsNotificationSettingsHelper.IsVisibleSettings();
var SmsEnable = SmsVisible && _smsProviderManager.Enabled();
var TfaVisible = TfaAppAuthSettings.IsVisibleSettings;
if (SmsVisible)
{
result.Add(new TfaSettingsRequestsDto
{
Enabled = _studioSmsNotificationSettingsHelper.Enable,
Id = "sms",
Title = Resource.ButtonSmsEnable,
Avaliable = SmsEnable
});
}
if (TfaVisible)
{
result.Add(new TfaSettingsRequestsDto
{
Enabled = _settingsManager.Load<TfaAppAuthSettings>().EnableSetting,
Id = "app",
Title = Resource.ButtonTfaAppEnable,
Avaliable = true
});
}
return result;
}
[Create("tfaapp/validate")]
[Authorize(AuthenticationSchemes = "confirm", Roles = "TfaActivation,Everyone")]
public bool TfaValidateAuthCode(TfaValidateRequestsDto inDto)
{
_apiContext.AuthByClaim();
var user = _userManager.GetUsers(_authContext.CurrentAccount.ID);
return _tfaManager.ValidateAuthCode(user, inDto.Code);
}
[Read("tfaapp/confirm")]
public object 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;
}
[Update("tfaapp")]
public bool TfaSettingsFromBody([FromBody] TfaRequestsDto inDto)
{
return TfaSettingsUpdate(inDto);
}
[Update("tfaapp")]
[Consumes("application/x-www-form-urlencoded")]
public bool TfaSettingsFromForm([FromForm] TfaRequestsDto inDto)
{
return TfaSettingsUpdate(inDto);
}
private bool TfaSettingsUpdate(TfaRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var result = false;
MessageAction action;
var settings = _settingsManager.Load<TfaAppAuthSettings>();
switch (inDto.Type)
{
case "sms":
if (!_studioSmsNotificationSettingsHelper.IsVisibleSettings())
throw new Exception(Resource.SmsNotAvailable);
if (!_smsProviderManager.Enabled())
throw new MethodAccessException();
_studioSmsNotificationSettingsHelper.Enable = true;
action = MessageAction.TwoFactorAuthenticationEnabledBySms;
if (settings.EnableSetting)
{
settings.EnableSetting = false;
_settingsManager.Save(settings);
}
result = true;
break;
case "app":
if (!TfaAppAuthSettings.IsVisibleSettings)
{
throw new Exception(Resource.TfaAppNotAvailable);
}
settings.EnableSetting = true;
_settingsManager.Save(settings);
action = MessageAction.TwoFactorAuthenticationEnabledByTfaApp;
if (_studioSmsNotificationSettingsHelper.IsVisibleSettings() && _studioSmsNotificationSettingsHelper.Enable)
{
_studioSmsNotificationSettingsHelper.Enable = false;
}
result = true;
break;
default:
if (settings.EnableSetting)
{
settings.EnableSetting = false;
_settingsManager.Save(settings);
}
if (_studioSmsNotificationSettingsHelper.IsVisibleSettings() && _studioSmsNotificationSettingsHelper.Enable)
{
_studioSmsNotificationSettingsHelper.Enable = false;
}
action = MessageAction.TwoFactorAuthenticationDisabled;
break;
}
if (result)
{
_cookiesManager.ResetTenantCookie();
}
_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);
}
[Read("tfaappcodes")]
public IEnumerable<object> TfaAppGetCodes()
{
var currentUser = _userManager.GetUsers(_authContext.CurrentAccount.ID);
if (!TfaAppAuthSettings.IsVisibleSettings || !TfaAppUserSettings.EnableForUser(_settingsManager, currentUser.Id))
throw new Exception(Resource.TfaAppNotAvailable);
if (currentUser.IsVisitor(_userManager) || currentUser.IsOutsider(_userManager))
throw new NotSupportedException("Not available.");
return _settingsManager.LoadForCurrentUser<TfaAppUserSettings>().CodesSetting.Select(r => new { r.IsUsed, Code = r.GetEncryptedCode(_instanceCrypto, _signature) }).ToList();
}
[Update("tfaappnewcodes")]
public IEnumerable<object> TfaAppRequestNewCodes()
{
var currentUser = _userManager.GetUsers(_authContext.CurrentAccount.ID);
if (!TfaAppAuthSettings.IsVisibleSettings || !TfaAppUserSettings.EnableForUser(_settingsManager, currentUser.Id))
throw new Exception(Resource.TfaAppNotAvailable);
if (currentUser.IsVisitor(_userManager) || currentUser.IsOutsider(_userManager))
throw new NotSupportedException("Not available.");
var codes = _tfaManager.GenerateBackupCodes().Select(r => new { r.IsUsed, Code = r.GetEncryptedCode(_instanceCrypto, _signature) }).ToList();
_messageService.Send(MessageAction.UserConnectedTfaApp, _messageTarget.Create(currentUser.Id), currentUser.DisplayUserName(false, _displayUserSettingsHelper));
return codes;
}
[Update("tfaappnewapp")]
public object TfaAppNewAppFromBody([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] TfaRequestsDto inDto)
{
return TfaAppNewApp(inDto);
}
[Update("tfaappnewapp")]
[Consumes("application/x-www-form-urlencoded")]
public object TfaAppNewAppFromForm([FromForm] TfaRequestsDto inDto)
{
return TfaAppNewApp(inDto);
}
private object TfaAppNewApp(TfaRequestsDto inDto)
{
var id = inDto?.Id ?? Guid.Empty;
var isMe = id.Equals(Guid.Empty);
var user = _userManager.GetUsers(isMe ? _authContext.CurrentAccount.ID : id);
if (!isMe && !_permissionContext.CheckPermissions(new UserSecurityProvider(user.Id), Constants.Action_EditUser))
throw new SecurityAccessDeniedException(Resource.ErrorAccessDenied);
if (!TfaAppAuthSettings.IsVisibleSettings || !TfaAppUserSettings.EnableForUser(_settingsManager, user.Id))
throw new Exception(Resource.TfaAppNotAvailable);
if (user.IsVisitor(_userManager) || user.IsOutsider(_userManager))
throw new NotSupportedException("Not available.");
TfaAppUserSettings.DisableForUser(_serviceProvider, _settingsManager, user.Id);
_messageService.Send(MessageAction.UserDisconnectedTfaApp, _messageTarget.Create(user.Id), user.DisplayUserName(false, _displayUserSettingsHelper));
if (isMe)
{
return _commonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaActivation);
}
_studioNotifyService.SendMsgTfaReset(user);
return string.Empty;
}
}

View File

@ -0,0 +1,84 @@
namespace ASC.Web.Api.Controllers.Settings;
public class TipsController: BaseSettingsController
{
private Tenant Tenant { get { return _apiContext.Tenant; } }
private readonly AuthContext _authContext;
private readonly StudioNotifyHelper _studioNotifyHelper;
private readonly SettingsManager _settingsManager;
private readonly SetupInfo _setupInfo;
private readonly ILog _log;
private readonly IHttpClientFactory _clientFactory;
public TipsController(
IOptionsMonitor<ILog> option,
ApiContext apiContext,
AuthContext authContext,
StudioNotifyHelper studioNotifyHelper,
SettingsManager settingsManager,
WebItemManager webItemManager,
SetupInfo setupInfo,
IMemoryCache memoryCache,
IHttpClientFactory clientFactory) : base(apiContext, memoryCache, webItemManager)
{
_log = option.Get("ASC.Api");
_authContext = authContext;
_studioNotifyHelper = studioNotifyHelper;
_settingsManager = settingsManager;
_setupInfo = setupInfo;
_clientFactory = clientFactory;
}
[Update("tips")]
public TipsSettings UpdateTipsSettingsFromBody([FromBody] SettingsRequestsDto inDto)
{
return UpdateTipsSettings(inDto);
}
[Update("tips")]
[Consumes("application/x-www-form-urlencoded")]
public TipsSettings UpdateTipsSettingsFromForm([FromForm] SettingsRequestsDto inDto)
{
return UpdateTipsSettings(inDto);
}
private TipsSettings UpdateTipsSettings(SettingsRequestsDto inDto)
{
var settings = new TipsSettings { Show = inDto.Show };
_settingsManager.SaveForCurrentUser(settings);
if (!inDto.Show && !string.IsNullOrEmpty(_setupInfo.TipsAddress))
{
try
{
var request = new HttpRequestMessage();
request.RequestUri = new Uri($"{_setupInfo.TipsAddress}/tips/deletereaded");
var data = new NameValueCollection
{
["userId"] = _authContext.CurrentAccount.ID.ToString(),
["tenantId"] = Tenant.Id.ToString(CultureInfo.InvariantCulture)
};
var body = JsonSerializer.Serialize(data);//todo check
request.Content = new StringContent(body);
var httpClient = _clientFactory.CreateClient();
using var response = httpClient.Send(request);
}
catch (Exception e)
{
_log.Error(e.Message, e);
}
}
return settings;
}
[Update("tips/change/subscription")]
public bool UpdateTipsSubscription()
{
return StudioPeriodicNotify.ChangeSubscription(_authContext.CurrentAccount.ID, _studioNotifyHelper);
}
}

View File

@ -0,0 +1,59 @@
namespace ASC.Web.Api.Controllers.Settings;
public class VersionController : BaseSettingsController
{
private Tenant Tenant { get { return _apiContext.Tenant; } }
private readonly TenantManager _tenantManager;
private readonly PermissionContext _permissionContext;
private readonly BuildVersion _buildVersion;
public VersionController(
PermissionContext permissionContext,
ApiContext apiContext,
TenantManager tenantManager,
WebItemManager webItemManager,
BuildVersion buildVersion,
IMemoryCache memoryCache) : base(apiContext, memoryCache, webItemManager)
{
_permissionContext = permissionContext;
_tenantManager = tenantManager;
_buildVersion = buildVersion;
}
[AllowAnonymous]
[Read("version/build", false)]
public Task<BuildVersion> GetBuildVersionsAsync()
{
return _buildVersion.GetCurrentBuildVersionAsync();
}
[Read("version")]
public TenantVersionDto GetVersions()
{
return new TenantVersionDto(Tenant.Version, _tenantManager.GetTenantVersions());
}
[Update("version")]
public TenantVersionDto SetVersionFromBody([FromBody] SettingsRequestsDto inDto)
{
return SetVersion(inDto);
}
[Update("version")]
[Consumes("application/x-www-form-urlencoded")]
public TenantVersionDto SetVersionFromForm([FromForm] SettingsRequestsDto inDto)
{
return SetVersion(inDto);
}
private TenantVersionDto SetVersion(SettingsRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
_tenantManager.GetTenantVersions().FirstOrDefault(r => r.Id == inDto.VersionId).NotFoundIfNull();
_tenantManager.SetTenantVersion(Tenant, inDto.VersionId);
return GetVersions();
}
}

View File

@ -0,0 +1,57 @@
namespace ASC.Web.Api.Controllers.Settings;
public class WebhooksController: BaseSettingsController
{
private readonly DbWorker _webhookDbWorker;
public WebhooksController(
ApiContext apiContext,
WebItemManager webItemManager,
IMemoryCache memoryCache,
DbWorker dbWorker) : base(apiContext, memoryCache, webItemManager)
{
_webhookDbWorker = dbWorker;
}
/// <summary>
/// Add new config for webhooks
/// </summary>
[Create("webhook")]
public void CreateWebhook(WebhooksConfig model)
{
if (model.Uri == null) throw new ArgumentNullException("Uri");
if (model.SecretKey == null) throw new ArgumentNullException("SecretKey");
_webhookDbWorker.AddWebhookConfig(model);
}
/// <summary>
/// Update config for webhooks
/// </summary>
[Update("webhook")]
public void UpdateWebhook(WebhooksConfig model)
{
if (model.Uri == null) throw new ArgumentNullException("Uri");
if (model.SecretKey == null) throw new ArgumentNullException("SecretKey");
_webhookDbWorker.UpdateWebhookConfig(model);
}
/// <summary>
/// Remove config for webhooks
/// </summary>
[Delete("webhook")]
public void RemoveWebhook(WebhooksConfig model)
{
if (model.Uri == null) throw new ArgumentNullException("Uri");
if (model.SecretKey == null) throw new ArgumentNullException("SecretKey");
_webhookDbWorker.RemoveWebhookConfig(model);
}
/// <summary>
/// Read Webhooks history for actual tenant
/// </summary>
[Read("webhooks")]
public List<WebhooksLog> TenantWebhooks()
{
return _webhookDbWorker.GetTenantWebhooks();
}
}

View File

@ -0,0 +1,499 @@
namespace ASC.Web.Api.Controllers.Settings;
public class WhitelabelController: BaseSettingsController
{
private Tenant Tenant { get { return _apiContext.Tenant; } }
private readonly IServiceProvider _serviceProvider;
private readonly TenantManager _tenantManager;
private readonly TenantExtra _tenantExtra;
private readonly PermissionContext _permissionContext;
private readonly SettingsManager _settingsManager;
private readonly TenantInfoSettingsHelper _tenantInfoSettingsHelper;
private readonly TenantWhiteLabelSettingsHelper _tenantWhiteLabelSettingsHelper;
private readonly TenantLogoManager _tenantLogoManager;
private readonly CoreBaseSettings _coreBaseSettings;
private readonly CommonLinkUtility _commonLinkUtility;
private readonly IConfiguration _configuration;
private readonly CoreSettings _coreSettings;
private readonly StorageFactory _storageFactory;
public WhitelabelController(
ApiContext apiContext,
TenantManager tenantManager,
TenantExtra tenantExtra,
PermissionContext permissionContext,
SettingsManager settingsManager,
WebItemManager webItemManager,
TenantInfoSettingsHelper tenantInfoSettingsHelper,
TenantWhiteLabelSettingsHelper tenantWhiteLabelSettingsHelper,
TenantLogoManager tenantLogoManager,
CoreBaseSettings coreBaseSettings,
CommonLinkUtility commonLinkUtility,
IConfiguration configuration,
CoreSettings coreSettings,
IServiceProvider serviceProvider,
IMemoryCache memoryCache,
StorageFactory storageFactory) : base(apiContext, memoryCache, webItemManager)
{
_serviceProvider = serviceProvider;
_tenantManager = tenantManager;
_tenantExtra = tenantExtra;
_permissionContext = permissionContext;
_settingsManager = settingsManager;
_tenantInfoSettingsHelper = tenantInfoSettingsHelper;
_tenantWhiteLabelSettingsHelper = tenantWhiteLabelSettingsHelper;
_tenantLogoManager = tenantLogoManager;
_coreBaseSettings = coreBaseSettings;
_commonLinkUtility = commonLinkUtility;
_configuration = configuration;
_coreSettings = coreSettings;
_storageFactory = storageFactory;
}
///<visible>false</visible>
[Create("whitelabel/save")]
public bool SaveWhiteLabelSettingsFromBody([FromBody] WhiteLabelRequestsDto inDto, [FromQuery] WhiteLabelQueryRequestsDto inQueryDto)
{
return SaveWhiteLabelSettings(inDto, inQueryDto);
}
[Create("whitelabel/save")]
[Consumes("application/x-www-form-urlencoded")]
public bool SaveWhiteLabelSettingsFromForm([FromForm] WhiteLabelRequestsDto inDto, [FromQuery] WhiteLabelQueryRequestsDto inQueryDto)
{
return SaveWhiteLabelSettings(inDto, inQueryDto);
}
private bool SaveWhiteLabelSettings(WhiteLabelRequestsDto inDto, WhiteLabelQueryRequestsDto inQueryDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!_tenantLogoManager.WhiteLabelEnabled || !_tenantLogoManager.WhiteLabelPaid)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
if (inQueryDto.IsDefault)
{
DemandRebrandingPermission();
SaveWhiteLabelSettingsForDefaultTenant(inDto);
}
else
{
SaveWhiteLabelSettingsForCurrentTenant(inDto);
}
return true;
}
private void SaveWhiteLabelSettingsForCurrentTenant(WhiteLabelRequestsDto inDto)
{
var settings = _settingsManager.Load<TenantWhiteLabelSettings>();
SaveWhiteLabelSettingsForTenant(settings, null, Tenant.Id, inDto);
}
private void SaveWhiteLabelSettingsForDefaultTenant(WhiteLabelRequestsDto inDto)
{
var settings = _settingsManager.LoadForDefaultTenant<TenantWhiteLabelSettings>();
var storage = _storageFactory.GetStorage(string.Empty, "static_partnerdata");
SaveWhiteLabelSettingsForTenant(settings, storage, Tenant.DefaultTenant, inDto);
}
private void SaveWhiteLabelSettingsForTenant(TenantWhiteLabelSettings settings, IDataStore storage, int tenantId, WhiteLabelRequestsDto inDto)
{
if (inDto.Logo != null)
{
var logoDict = new Dictionary<int, string>();
foreach (var l in inDto.Logo)
{
logoDict.Add(Int32.Parse(l.Key), l.Value);
}
_tenantWhiteLabelSettingsHelper.SetLogo(settings, logoDict, storage);
}
settings.SetLogoText(inDto.LogoText);
_tenantWhiteLabelSettingsHelper.Save(settings, tenantId, _tenantLogoManager);
}
///<visible>false</visible>
[Create("whitelabel/savefromfiles")]
public bool SaveWhiteLabelSettingsFromFiles([FromQuery] WhiteLabelQueryRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!_tenantLogoManager.WhiteLabelEnabled || !_tenantLogoManager.WhiteLabelPaid)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
if (HttpContext.Request.Form?.Files == null || HttpContext.Request.Form.Files.Count == 0)
{
throw new InvalidOperationException("No input files");
}
if (inDto.IsDefault)
{
DemandRebrandingPermission();
SaveWhiteLabelSettingsFromFilesForDefaultTenant();
}
else
{
SaveWhiteLabelSettingsFromFilesForCurrentTenant();
}
return true;
}
private void SaveWhiteLabelSettingsFromFilesForCurrentTenant()
{
var settings = _settingsManager.Load<TenantWhiteLabelSettings>();
SaveWhiteLabelSettingsFromFilesForTenant(settings, null, Tenant.Id);
}
private void SaveWhiteLabelSettingsFromFilesForDefaultTenant()
{
var settings = _settingsManager.LoadForDefaultTenant<TenantWhiteLabelSettings>();
var storage = _storageFactory.GetStorage(string.Empty, "static_partnerdata");
SaveWhiteLabelSettingsFromFilesForTenant(settings, storage, Tenant.DefaultTenant);
}
private void SaveWhiteLabelSettingsFromFilesForTenant(TenantWhiteLabelSettings settings, IDataStore storage, int tenantId)
{
foreach (var f in HttpContext.Request.Form.Files)
{
var parts = f.FileName.Split('.');
var logoType = (WhiteLabelLogoTypeEnum)Convert.ToInt32(parts[0]);
var fileExt = parts[1];
_tenantWhiteLabelSettingsHelper.SetLogoFromStream(settings, logoType, fileExt, f.OpenReadStream(), storage);
}
_settingsManager.SaveForTenant(settings, tenantId);
}
///<visible>false</visible>
[Read("whitelabel/sizes")]
public object GetWhiteLabelSizes()
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!_tenantLogoManager.WhiteLabelEnabled)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
return
new[]
{
new {type = (int)WhiteLabelLogoTypeEnum.LightSmall, name = nameof(WhiteLabelLogoTypeEnum.LightSmall), height = TenantWhiteLabelSettings.logoLightSmallSize.Height, width = TenantWhiteLabelSettings.logoLightSmallSize.Width},
new {type = (int)WhiteLabelLogoTypeEnum.Dark, name = nameof(WhiteLabelLogoTypeEnum.Dark), height = TenantWhiteLabelSettings.logoDarkSize.Height, width = TenantWhiteLabelSettings.logoDarkSize.Width},
new {type = (int)WhiteLabelLogoTypeEnum.Favicon, name = nameof(WhiteLabelLogoTypeEnum.Favicon), height = TenantWhiteLabelSettings.logoFaviconSize.Height, width = TenantWhiteLabelSettings.logoFaviconSize.Width},
new {type = (int)WhiteLabelLogoTypeEnum.DocsEditor, name = nameof(WhiteLabelLogoTypeEnum.DocsEditor), height = TenantWhiteLabelSettings.logoDocsEditorSize.Height, width = TenantWhiteLabelSettings.logoDocsEditorSize.Width},
new {type = (int)WhiteLabelLogoTypeEnum.DocsEditorEmbed, name = nameof(WhiteLabelLogoTypeEnum.DocsEditorEmbed), height = TenantWhiteLabelSettings.logoDocsEditorEmbedSize.Height, width = TenantWhiteLabelSettings.logoDocsEditorEmbedSize.Width}
};
}
///<visible>false</visible>
[Read("whitelabel/logos")]
public Dictionary<string, string> GetWhiteLabelLogos([FromQuery] WhiteLabelQueryRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!_tenantLogoManager.WhiteLabelEnabled)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
Dictionary<string, string> result;
if (inDto.IsDefault)
{
result = new Dictionary<string, string>
{
{ ((int)WhiteLabelLogoTypeEnum.LightSmall).ToString(), _commonLinkUtility.GetFullAbsolutePath(_tenantWhiteLabelSettingsHelper.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.LightSmall, !inDto.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.Dark).ToString(), _commonLinkUtility.GetFullAbsolutePath(_tenantWhiteLabelSettingsHelper.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.Dark, !inDto.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.Favicon).ToString(), _commonLinkUtility.GetFullAbsolutePath(_tenantWhiteLabelSettingsHelper.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.Favicon, !inDto.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.DocsEditor).ToString(), _commonLinkUtility.GetFullAbsolutePath(_tenantWhiteLabelSettingsHelper.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.DocsEditor, !inDto.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.DocsEditorEmbed).ToString(), _commonLinkUtility.GetFullAbsolutePath(_tenantWhiteLabelSettingsHelper.GetAbsoluteDefaultLogoPath(WhiteLabelLogoTypeEnum.DocsEditorEmbed, !inDto.IsRetina)) }
};
}
else
{
var _tenantWhiteLabelSettings = _settingsManager.Load<TenantWhiteLabelSettings>();
result = new Dictionary<string, string>
{
{ ((int)WhiteLabelLogoTypeEnum.LightSmall).ToString(), _commonLinkUtility.GetFullAbsolutePath(_tenantWhiteLabelSettingsHelper.GetAbsoluteLogoPath(_tenantWhiteLabelSettings, WhiteLabelLogoTypeEnum.LightSmall, !inDto.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.Dark).ToString(), _commonLinkUtility.GetFullAbsolutePath(_tenantWhiteLabelSettingsHelper.GetAbsoluteLogoPath(_tenantWhiteLabelSettings, WhiteLabelLogoTypeEnum.Dark, !inDto.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.Favicon).ToString(), _commonLinkUtility.GetFullAbsolutePath(_tenantWhiteLabelSettingsHelper.GetAbsoluteLogoPath(_tenantWhiteLabelSettings, WhiteLabelLogoTypeEnum.Favicon, !inDto.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.DocsEditor).ToString(), _commonLinkUtility.GetFullAbsolutePath(_tenantWhiteLabelSettingsHelper.GetAbsoluteLogoPath(_tenantWhiteLabelSettings, WhiteLabelLogoTypeEnum.DocsEditor, !inDto.IsRetina)) },
{ ((int)WhiteLabelLogoTypeEnum.DocsEditorEmbed).ToString(), _commonLinkUtility.GetFullAbsolutePath(_tenantWhiteLabelSettingsHelper.GetAbsoluteLogoPath(_tenantWhiteLabelSettings,WhiteLabelLogoTypeEnum.DocsEditorEmbed, !inDto.IsRetina)) }
};
}
return result;
}
///<visible>false</visible>
[Read("whitelabel/logotext")]
public object GetWhiteLabelLogoText([FromQuery] WhiteLabelQueryRequestsDto inDto)
{
if (!_tenantLogoManager.WhiteLabelEnabled)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
var settings = inDto.IsDefault ? _settingsManager.LoadForDefaultTenant<TenantWhiteLabelSettings>() : _settingsManager.Load<TenantWhiteLabelSettings>();
return settings.LogoText ?? TenantWhiteLabelSettings.DefaultLogoText;
}
///<visible>false</visible>
[Update("whitelabel/restore")]
public bool RestoreWhiteLabelOptions(WhiteLabelQueryRequestsDto inDto)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (!_tenantLogoManager.WhiteLabelEnabled || !_tenantLogoManager.WhiteLabelPaid)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "WhiteLabel");
}
if (inDto.IsDefault)
{
DemandRebrandingPermission();
RestoreWhiteLabelOptionsForDefaultTenant();
}
else
{
RestoreWhiteLabelOptionsForCurrentTenant();
}
return true;
}
private void RestoreWhiteLabelOptionsForCurrentTenant()
{
var settings = _settingsManager.Load<TenantWhiteLabelSettings>();
RestoreWhiteLabelOptionsForTenant(settings, null, Tenant.Id);
var tenantInfoSettings = _settingsManager.Load<TenantInfoSettings>();
_tenantInfoSettingsHelper.RestoreDefaultLogo(tenantInfoSettings, _tenantLogoManager);
_settingsManager.Save(tenantInfoSettings);
}
private void RestoreWhiteLabelOptionsForDefaultTenant()
{
var settings = _settingsManager.LoadForDefaultTenant<TenantWhiteLabelSettings>();
var storage = _storageFactory.GetStorage(string.Empty, "static_partnerdata");
RestoreWhiteLabelOptionsForTenant(settings, storage, Tenant.DefaultTenant);
}
private void RestoreWhiteLabelOptionsForTenant(TenantWhiteLabelSettings settings, IDataStore storage, int tenantId)
{
_tenantWhiteLabelSettingsHelper.RestoreDefault(settings, _tenantLogoManager, tenantId, storage);
}
///<visible>false</visible>
[Read("companywhitelabel")]
public List<CompanyWhiteLabelSettings> GetLicensorData()
{
var result = new List<CompanyWhiteLabelSettings>();
var instance = CompanyWhiteLabelSettings.Instance(_settingsManager);
result.Add(instance);
if (!instance.IsDefault(_coreSettings) && !instance.IsLicensor)
{
result.Add(instance.GetDefault(_serviceProvider) as CompanyWhiteLabelSettings);
}
return result;
}
///<visible>false</visible>
[Create("rebranding/company")]
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)
{
if (companyWhiteLabelSettingsWrapper.Settings == null) throw new ArgumentNullException("settings");
DemandRebrandingPermission();
companyWhiteLabelSettingsWrapper.Settings.IsLicensor = false; //TODO: CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Branding && settings.IsLicensor
_settingsManager.SaveForDefaultTenant(companyWhiteLabelSettingsWrapper.Settings);
return true;
}
///<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")]
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)
{
if (wrapper.Settings == null) throw new ArgumentNullException("settings");
DemandRebrandingPermission();
_settingsManager.SaveForDefaultTenant(wrapper.Settings);
return true;
}
///<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")]
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)
{
ArgumentNullException.ThrowIfNull(settings);
DemandRebrandingPermission();
_settingsManager.SaveForDefaultTenant(settings);
return true;
}
///<visible>false</visible>
[Update("rebranding/mail")]
public bool UpdateMailWhiteLabelSettingsFromBody([FromBody] MailWhiteLabelSettingsRequestsDto inDto)
{
return UpdateMailWhiteLabelSettings(inDto);
}
[Update("rebranding/mail")]
[Consumes("application/x-www-form-urlencoded")]
public bool UpdateMailWhiteLabelSettingsFromForm([FromForm] MailWhiteLabelSettingsRequestsDto inDto)
{
return UpdateMailWhiteLabelSettings(inDto);
}
private bool UpdateMailWhiteLabelSettings(MailWhiteLabelSettingsRequestsDto inDto)
{
DemandRebrandingPermission();
var settings = _settingsManager.LoadForDefaultTenant<MailWhiteLabelSettings>();
settings.FooterEnabled = inDto.FooterEnabled;
_settingsManager.SaveForDefaultTenant(settings);
return true;
}
///<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.Id).SSBranding)
{
throw new BillingException(Resource.ErrorNotAllowedOption, "SSBranding");
}
if (_coreBaseSettings.CustomMode)
{
throw new SecurityException();
}
}
}

View File

@ -0,0 +1,206 @@
/*
*
* (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.
*
*/
namespace ASC.Api.Settings;
[Scope]
[DefaultRoute]
[ApiController]
public class SmtpSettingsController : ControllerBase
{
private readonly PermissionContext _permissionContext;
private readonly CoreConfiguration _coreConfiguration;
private readonly CoreBaseSettings _coreBaseSettings;
private readonly IMapper _mapper;
public SmtpSettingsController(
PermissionContext permissionContext,
CoreConfiguration coreConfiguration,
CoreBaseSettings coreBaseSettings,
IMapper mapper)
{
_permissionContext = permissionContext;
_coreConfiguration = coreConfiguration;
_coreBaseSettings = coreBaseSettings;
_mapper = mapper;
}
[Read("smtp")]
public SmtpSettingsDto GetSmtpSettings()
{
CheckSmtpPermissions();
var settings = _mapper.Map<SmtpSettings, SmtpSettingsDto>(_coreConfiguration.SmtpSettings);
settings.CredentialsUserPassword = "";
return settings;
}
[Create("smtp")]
public SmtpSettingsDto SaveSmtpSettingsFromBody([FromBody] SmtpSettingsDto inDto)
{
return SaveSmtpSettings(inDto);
}
[Create("smtp")]
[Consumes("application/x-www-form-urlencoded")]
public SmtpSettingsDto SaveSmtpSettingsFromForm([FromForm] SmtpSettingsDto inDto)
{
return SaveSmtpSettings(inDto);
}
private SmtpSettingsDto SaveSmtpSettings(SmtpSettingsDto inDto)
{
CheckSmtpPermissions();
//TODO: Add validation check
ArgumentNullException.ThrowIfNull(inDto);
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var settingConfig = ToSmtpSettingsConfig(inDto);
_coreConfiguration.SmtpSettings = settingConfig;
var settings = _mapper.Map<SmtpSettings, SmtpSettingsDto>(settingConfig);
settings.CredentialsUserPassword = "";
return settings;
}
[Delete("smtp")]
public SmtpSettingsDto ResetSmtpSettings()
{
CheckSmtpPermissions();
if (!_coreConfiguration.SmtpSettings.IsDefaultSettings)
{
_permissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
_coreConfiguration.SmtpSettings = null;
}
var current = _coreBaseSettings.Standalone ? _coreConfiguration.SmtpSettings : SmtpSettings.Empty;
var settings = _mapper.Map<SmtpSettings, SmtpSettingsDto>(current);
settings.CredentialsUserPassword = "";
return settings;
}
//[Read("smtp/test")]
//public SmtpOperationStatus TestSmtpSettings()
//{
// CheckSmtpPermissions();
// var settings = ToSmtpSettings(CoreConfiguration.SmtpSettings);
// //add resolve
// var smtpTestOp = new SmtpOperation(settings, Tenant.Id, SecurityContext.CurrentAccount.ID, UserManager, SecurityContext, TenantManager, Configuration);
// SMTPTasks.QueueTask(smtpTestOp.RunJob, smtpTestOp.GetDistributedTask());
// return ToSmtpOperationStatus();
//}
//[Read("smtp/test/status")]
//public SmtpOperationStatus GetSmtpOperationStatus()
//{
// CheckSmtpPermissions();
// return ToSmtpOperationStatus();
//}
//private SmtpOperationStatus ToSmtpOperationStatus()
//{
// var operations = SMTPTasks.GetTasks().ToList();
// foreach (var o in operations)
// {
// if (!string.IsNullOrEmpty(o.InstanseId) &&
// Process.GetProcesses().Any(p => p.Id == int.Parse(o.InstanseId)))
// continue;
// o.SetProperty(SmtpOperation.PROGRESS, 100);
// SMTPTasks.RemoveTask(o.Id);
// }
// var operation =
// operations
// .FirstOrDefault(t => t.GetProperty<int>(SmtpOperation.OWNER) == Tenant.Id);
// if (operation == null)
// {
// return null;
// }
// if (DistributedTaskStatus.Running < operation.Status)
// {
// operation.SetProperty(SmtpOperation.PROGRESS, 100);
// SMTPTasks.RemoveTask(operation.Id);
// }
// var result = new SmtpOperationStatus
// {
// Id = operation.Id,
// Completed = operation.GetProperty<bool>(SmtpOperation.FINISHED),
// Percents = operation.GetProperty<int>(SmtpOperation.PROGRESS),
// Status = operation.GetProperty<string>(SmtpOperation.RESULT),
// Error = operation.GetProperty<string>(SmtpOperation.ERROR),
// Source = operation.GetProperty<string>(SmtpOperation.SOURCE)
// };
// return result;
//}
public static SmtpSettings ToSmtpSettingsConfig(SmtpSettingsDto inDto)
{
var settingsConfig = new SmtpSettings(
inDto.Host,
inDto.Port ?? SmtpSettings.DefaultSmtpPort,
inDto.SenderAddress,
inDto.SenderDisplayName)
{
EnableSSL = inDto.EnableSSL,
EnableAuth = inDto.EnableAuth
};
if (inDto.EnableAuth)
{
settingsConfig.SetCredentials(inDto.CredentialsUserName, inDto.CredentialsUserPassword);
}
return settingsConfig;
}
private static void CheckSmtpPermissions()
{
if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.SmtpSettings)))
{
throw new BillingException(Resource.ErrorNotAllowedOption, "Smtp");
}
}
}

View File

@ -30,8 +30,8 @@ using ASC.Core;
using ASC.Core.Billing;
using ASC.Core.Users;
using ASC.MessagingSystem;
using ASC.Web.Api.Routing;
using ASC.Web.Core.PublicResources;
using ASC.Web.Api.Routing;
using ASC.Web.Core.PublicResources;
using ASC.Web.Studio.Core;
using ASC.Web.Studio.Utility;
using Newtonsoft.Json;

View File

@ -0,0 +1,139 @@
/*
*
* (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.
*
*/
namespace ASC.Web.Api.Controllers;
[Scope(Additional = typeof(BaseLoginProviderExtension))]
[DefaultRoute]
[ApiController]
public class ThirdPartyController : ControllerBase
{
private readonly OAuth20TokenHelper _oAuth20TokenHelper;
public ThirdPartyController(OAuth20TokenHelper oAuth20TokenHelper)
{
_oAuth20TokenHelper = oAuth20TokenHelper;
}
[Read("{provider}")]
public object Get(LoginProviderEnum provider)
{
var desktop = HttpContext.Request.Query["desktop"] == "true";
var additionals = new Dictionary<string, string>();
if (desktop)
{
additionals = HttpContext.Request.Query.ToDictionary(r => r.Key, r => r.Value.FirstOrDefault());
}
switch (provider)
{
case LoginProviderEnum.Google:
return _oAuth20TokenHelper.RequestCode<GoogleLoginProvider>(
GoogleLoginProvider.GoogleScopeDrive,
new Dictionary<string, string>
{
{ "access_type", "offline" },
{ "prompt", "consent" }
}, additionalStateArgs: additionals);
case LoginProviderEnum.Dropbox:
return _oAuth20TokenHelper.RequestCode<DropboxLoginProvider>(
additionalArgs: new Dictionary<string, string>
{
{ "force_reauthentication", "true" }
}, additionalStateArgs: additionals);
case LoginProviderEnum.Docusign:
return _oAuth20TokenHelper.RequestCode<DocuSignLoginProvider>(
DocuSignLoginProvider.DocuSignLoginProviderScopes,
new Dictionary<string, string>
{
{ "prompt", "login" }
}, additionalStateArgs: additionals);
case LoginProviderEnum.Box:
return _oAuth20TokenHelper.RequestCode<BoxLoginProvider>(additionalStateArgs: additionals);
case LoginProviderEnum.OneDrive:
return _oAuth20TokenHelper.RequestCode<OneDriveLoginProvider>(OneDriveLoginProvider.OneDriveLoginProviderScopes, additionalStateArgs: additionals);
case LoginProviderEnum.Wordpress:
return _oAuth20TokenHelper.RequestCode<WordpressLoginProvider>(additionalStateArgs: additionals);
}
return null;
}
[Read("{provider}/code")]
public object GetCode(string redirect, string code, string error)
{
try
{
if (!string.IsNullOrEmpty(error))
{
if (error == "access_denied")
{
error = "Canceled at provider";
}
throw new Exception(error);
}
if (!string.IsNullOrEmpty(redirect))
{
return AppendCode(redirect, code);
}
return code;
}
catch (ThreadAbortException)
{
}
catch (Exception ex)
{
if (!string.IsNullOrEmpty(redirect))
{
return AppendCode(redirect, error: ex.Message);
}
return ex.Message;
}
return null;
}
private static string AppendCode(string url, string code = null, string error = null)
{
url += (url.Contains('#') ? "&" : "#")
+ (string.IsNullOrEmpty(error)
? (string.IsNullOrEmpty(code)
? string.Empty
: "code=" + HttpUtility.UrlEncode(code))
: ("error/" + HttpUtility.UrlEncode(error)));
return url;
}
}

View File

@ -0,0 +1,18 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class AuthRequestsDto
{
public string UserName { get; set; }
public string Password { get; set; }
public string PasswordHash { get; set; }
public string Provider { get; set; }
public string AccessToken { get; set; }
public string SerializedProfile { get; set; }
public string Code { get; set; }
public bool Session { get; set; }
}
public class MobileRequestsDto
{
public string MobilePhone { get; set; }
}

View File

@ -0,0 +1,33 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class AuthServiceRequestsDto
{
public string Name { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Instruction { get; set; }
public bool CanSet { get; set; }
public List<AuthKey> Props { get; set; }
public AuthServiceRequestsDto()
{
}
public AuthServiceRequestsDto(Consumer consumer)
{
var authService = new AuthService(consumer);
Name = authService.Name;
Title = authService.Title;
Description = authService.Description;
Instruction = authService.Instruction;
CanSet = authService.CanSet;
if (consumer.CanSet)
{
Props = authService.Props;
CanSet = authService.CanSet;
}
}
}

View File

@ -0,0 +1,9 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class EncryptionSettingsRequestsDto
{
public string Password { get; set; }
public EncryprtionStatus Status { get; set; }
public bool NotifyUsers { get; set; }
public string ServerRootPath { get; set; }
}

View File

@ -0,0 +1,6 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class GreetingSettingsRequestsDto
{
public string Title { get; set; }
}

View File

@ -1,33 +1,32 @@
/*
*
* (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.
*
*/
namespace ASC.Web.Api.Models
{
public class IpRestrictionsModel
{
public IEnumerable<string> Ips { get; set; }
public bool Enable { get; set; }
}
}
/*
*
* (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.
*
*/
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class IpRestrictionsRequestsDto
{
public IEnumerable<string> Ips { get; set; }
public bool Enable { get; set; }
}

View File

@ -0,0 +1,15 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class MailDomainSettingsRequestsDto
{
public TenantTrustedDomainsType Type { get; set; }
public List<string> Domains { get; set; }
public bool InviteUsersAsVisitors { get; set; }
}
public class AdminMessageSettingsRequestsDto
{
public string Email { get; set; }
public string Message { get; set; }
public bool TurnOn { get; set; }
}

View File

@ -0,0 +1,6 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class MailWhiteLabelSettingsRequestsDto
{
public bool FooterEnabled { get; set; }
}

View File

@ -0,0 +1,6 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class MobileAppRequestsDto
{
public MobileAppType Type { get; set; }
}

View File

@ -0,0 +1,16 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class SchemaRequestsDto
{
public string Id { get; set; }
public string Name { get; set; }
public string UserCaption { get; set; }
public string UsersCaption { get; set; }
public string GroupCaption { get; set; }
public string GroupsCaption { get; set; }
public string UserPostCaption { get; set; }
public string RegDateCaption { get; set; }
public string GroupHeadCaption { get; set; }
public string GuestCaption { get; set; }
public string GuestsCaption { get; set; }
}

View File

@ -0,0 +1,8 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class SecurityRequestsDto
{
public Guid ProductId { get; set; }
public Guid UserId { get; set; }
public bool Administrator { get; set; }
}

View File

@ -0,0 +1,12 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class SettingsRequestsDto
{
public Guid DefaultProductID { get; set; }
public string Lng { get; set; }
public string TimeZoneID { get; set; }
public string Theme { get; set; }
public bool Show { get; set; } //tips
public int VersionId { get; set; }
public Guid OwnerId { get; set; }
}

View File

@ -0,0 +1,6 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class ShortenLinkRequestsDto
{
public string Link { get; set; }
}

View File

@ -23,33 +23,27 @@
*
*/
namespace ASC.Api.Settings.Smtp
namespace ASC.Api.Settings.Smtp;
public class SmtpOperationStatusRequestsDto
{
public class SmtpOperationStatus
public bool Completed { get; set; }
public string Id { get; set; }
public string Status { get; set; }
public string Error { get; set; }
public int Percents { get; set; }
public string Source { get; set; }
public static SmtpOperationStatusRequestsDto GetSample()
{
public bool Completed { get; set; }
public string Id { get; set; }
public string Status { get; set; }
public string Error { get; set; }
public int Percents { get; set; }
public string Source { get; set; }
public static SmtpOperationStatus GetSample()
return new SmtpOperationStatusRequestsDto
{
return new SmtpOperationStatus
{
Id = "{some-random-guid}",
Error = "",
Percents = 0,
Completed = true,
Status = "",
Source = ""
};
}
Id = "{some-random-guid}",
Error = "",
Percents = 0,
Completed = true,
Status = "",
Source = ""
};
}
}

View File

@ -0,0 +1,6 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class StorageEncryptionRequestsDto
{
public bool NotifyUsers { get; set; }
}

View File

@ -0,0 +1,7 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class StorageRequestsDto
{
public string Module { get; set; }
public IEnumerable<ItemKeyValuePair<string, string>> Props { get; set; }
}

View File

@ -0,0 +1,12 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class TfaRequestsDto
{
public string Type { get; set; }
public Guid? Id { get; set; }
}
public class TfaValidateRequestsDto
{
public string Code { get; set; }
}

View File

@ -0,0 +1,9 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class TfaSettingsRequestsDto
{
public string Id { get; set; }
public string Title { get; set; }
public bool Enabled { get; set; }
public bool Avaliable { get; set; }
}

View File

@ -0,0 +1,7 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class ThirdpartyRequestsDto
{
public string Code { get; set; }
public string Redirect { get; set; }
}

View File

@ -0,0 +1,7 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class TimezonesRequestsDto
{
public string Id { get; set; }
public string DisplayName { get; set; }
}

View File

@ -0,0 +1,6 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class UploadLicenseRequestsDto
{
public IEnumerable<IFormFile> Files { get; set; }
}

View File

@ -0,0 +1,9 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class WebItemSecurityRequestsDto
{
public string Id { get; set; }
public bool Enabled { get; set; }
public IEnumerable<Guid> Subjects { get; set; }
public IEnumerable<ItemKeyValuePair<string, bool>> Items { get; set; }
}

View File

@ -0,0 +1,13 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class WhiteLabelRequestsDto
{
public string LogoText { get; set; }
public IEnumerable<ItemKeyValuePair<string, string>> Logo { get; set; }
}
public class WhiteLabelQueryRequestsDto
{
public bool IsDefault { get; set; }
public bool IsRetina { get; set; }
}

View File

@ -0,0 +1,17 @@
namespace ASC.Web.Api.ApiModel.RequestsDto;
public class WizardRequestsDto
{
public string Email { get; set; }
public string PasswordHash { get; set; }
public string Lng { get; set; }
public string TimeZone { get; set; }
public string Promocode { get; set; }
public string AmiId { get; set; }
public bool SubscribeFromSite { get; set; }
public void Deconstruct(out string email, out string passwordHash, out string lng, out string timeZone, out string promocode, out string amiid, out bool subscribeFromSite)
{
(email, passwordHash, lng, timeZone, promocode, amiid, subscribeFromSite) = (Email, PasswordHash, Lng, TimeZone, Promocode, AmiId, SubscribeFromSite);
}
}

View File

@ -0,0 +1,25 @@
namespace ASC.Web.Api.ApiModel.ResponseDto;
public class AuthenticationTokenDto
{
public string Token { get; set; }
public DateTime Expires { get; set; }
public bool Sms { get; set; }
public string PhoneNoise { get; set; }
public bool Tfa { get; set; }
public string TfaKey { get; set; }
public string ConfirmUrl { get; set; }
public static AuthenticationTokenDto GetSample()
{
return new AuthenticationTokenDto
{
Expires = DateTime.UtcNow,
Token = "abcde12345",
Sms = false,
PhoneNoise = null,
Tfa = false,
TfaKey = null
};
}
}

View File

@ -0,0 +1,24 @@
namespace ASC.Web.Api.ApiModel.ResponseDto;
public class CapabilitiesDto
{
public bool LdapEnabled { get; set; }
public List<string> Providers { get; set; }
public string SsoLabel { get; set; }
/// <summary>
/// if empty sso is disabled
/// </summary>
public string SsoUrl { get; set; }
public static CapabilitiesDto GetSample()
{
return new CapabilitiesDto
{
LdapEnabled = false,
// Providers = AccountLinkControl.AuthProviders,
SsoLabel = string.Empty,
SsoUrl = string.Empty,
};
}
}

View File

@ -23,24 +23,20 @@
*
*/
namespace ASC.Api.Security
namespace ASC.Web.Api.ApiModel.ResponseDto;
public class EventDto
{
public class EventWrapper
public EventDto(BaseEvent auditEvent)
{
public EventWrapper(BaseEvent auditEvent)
{
Id = auditEvent.Id;
Date = new ApiDateTime(auditEvent.Date, TimeSpan.Zero);
User = auditEvent.UserName;
Action = auditEvent.ActionText;
}
public int Id { get; private set; }
public ApiDateTime Date { get; private set; }
public string User { get; private set; }
public string Action { get; private set; }
Id = auditEvent.Id;
Date = new ApiDateTime(auditEvent.Date, TimeSpan.Zero);
User = auditEvent.UserName;
Action = auditEvent.ActionText;
}
public int Id { get; private set; }
public ApiDateTime Date { get; private set; }
public string User { get; private set; }
public string Action { get; private set; }
}

View File

@ -0,0 +1,14 @@

namespace ASC.Web.Api.ApiModel.ResponseDto;
public class FirebaseDto
{
public string ApiKey { get; set; }
public string AuthDomain { get; set; }
public string ProjectId { get; set; }
public string StorageBucket { get; set; }
public string MessagingSenderId { get; set; }
public string AppId { get; set; }
public string MeasurementId { get; set; }
}

View File

@ -0,0 +1,126 @@
/*
*
* (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 Constants = ASC.Core.Users.Constants;
namespace ASC.Web.Api.ApiModel.ResponseDto;
public class QuotaDto
{
public ulong StorageSize { get; set; }
public ulong MaxFileSize { get; set; }
public ulong UsedSize { get; set; }
public int MaxUsersCount { get; set; }
public int UsersCount { get; set; }
public ulong AvailableSize
{
get { return Math.Max(0, StorageSize > UsedSize ? StorageSize - UsedSize : 0); }
set { throw new NotImplementedException(); }
}
public int AvailableUsersCount
{
get { return Math.Max(0, MaxUsersCount - UsersCount); }
set { throw new NotImplementedException(); }
}
public IList<QuotaUsage> StorageUsage { get; set; }
public long UserStorageSize { get; set; }
public long UserUsedSize { get; set; }
public long UserAvailableSize
{
get { return Math.Max(0, UserStorageSize - UserUsedSize); }
set { throw new NotImplementedException(); }
}
public long MaxVisitors { get; set; }
public long VisitorsCount { get; set; }
public QuotaDto()
{
}
public QuotaDto(
Tenant tenant,
CoreBaseSettings coreBaseSettings,
CoreConfiguration configuration,
TenantExtra tenantExtra,
TenantStatisticsProvider tenantStatisticsProvider,
AuthContext authContext,
SettingsManager settingsManager,
WebItemManager webItemManager,
Constants constants)
{
var quota = tenantExtra.GetTenantQuota();
var quotaRows = tenantStatisticsProvider.GetQuotaRows(tenant.Id).ToList();
StorageSize = (ulong)Math.Max(0, quota.MaxTotalSize);
UsedSize = (ulong)Math.Max(0, quotaRows.Sum(r => r.Counter));
MaxUsersCount = quota.ActiveUsers;
UsersCount = coreBaseSettings.Personal ? 1 : tenantStatisticsProvider.GetUsersCount();
MaxVisitors = coreBaseSettings.Standalone ? -1 : constants.CoefficientOfVisitors * quota.ActiveUsers;
VisitorsCount = coreBaseSettings.Personal ? 0 : tenantStatisticsProvider.GetVisitorsCount();
StorageUsage = quotaRows
.Select(x => new QuotaUsage { Path = x.Path.TrimStart('/').TrimEnd('/'), Size = x.Counter, })
.ToList();
if (coreBaseSettings.Personal && SetupInfo.IsVisibleSettings("PersonalMaxSpace"))
{
UserStorageSize = configuration.PersonalMaxSpace(settingsManager);
var webItem = webItemManager[WebItemManager.DocumentsProductID];
if (webItem.Context.SpaceUsageStatManager is IUserSpaceUsage spaceUsageManager)
{
UserUsedSize = spaceUsageManager.GetUserSpaceUsageAsync(authContext.CurrentAccount.ID).Result;
}
}
MaxFileSize = Math.Min(AvailableSize, (ulong)quota.MaxFileSize);
}
public static QuotaDto GetSample()
{
return new QuotaDto
{
MaxFileSize = 25 * 1024 * 1024,
StorageSize = 1024 * 1024 * 1024,
UsedSize = 250 * 1024 * 1024,
StorageUsage = new List<QuotaUsage>
{
new QuotaUsage { Size = 100*1024*1024, Path = "crm" },
new QuotaUsage { Size = 150*1024*1024, Path = "files" }
}
};
}
public class QuotaUsage
{
public string Path { get; set; }
public long Size { get; set; }
}
}

View File

@ -1,58 +1,53 @@
/*
*
* (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.
*
*/
namespace ASC.Api.Settings
{
public class SecurityWrapper
{
public string WebItemId { get; set; }
public IEnumerable<EmployeeDto> Users { get; set; }
public IEnumerable<GroupSummaryDto> Groups { get; set; }
public bool Enabled { get; set; }
public bool IsSubItem { get; set; }
public static SecurityWrapper GetSample()
{
return new SecurityWrapper
{
WebItemId = Guid.Empty.ToString(),
Enabled = true,
IsSubItem = false,
Groups = new List<GroupSummaryDto>
{
GroupSummaryDto.GetSample()
},
Users = new List<EmployeeDto>
{
EmployeeDto.GetSample()
}
};
}
}
/*
*
* (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.
*
*/
namespace ASC.Web.Api.ApiModel.ResponseDto;
public class SecurityDto
{
public string WebItemId { get; set; }
public IEnumerable<EmployeeDto> Users { get; set; }
public IEnumerable<GroupSummaryDto> Groups { get; set; }
public bool Enabled { get; set; }
public bool IsSubItem { get; set; }
public static SecurityDto GetSample()
{
return new SecurityDto
{
WebItemId = Guid.Empty.ToString(),
Enabled = true,
IsSubItem = false,
Groups = new List<GroupSummaryDto>
{
GroupSummaryDto.GetSample()
},
Users = new List<EmployeeDto>
{
EmployeeDto.GetSample()
}
};
}
}

View File

@ -0,0 +1,63 @@
/*
*
* (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.
*
*/
namespace ASC.Web.Api.ApiModel.ResponseDto;
public class SettingsDto
{
public string Timezone { get; set; }
public List<string> TrustedDomains { get; set; }
public TenantTrustedDomainsType TrustedDomainsType { get; set; }
public string Culture { get; set; }
public TimeSpan UtcOffset { get; set; }
public double UtcHoursOffset { get; set; }
public string GreetingSettings { get; set; }
public Guid OwnerId { get; set; }
public string NameSchemaId { get; set; }
public bool? EnabledJoin { get; set; }
public bool? EnableAdmMess { get; set; }
public bool? ThirdpartyEnable { get; set; }
public bool Personal { get; set; }
public string WizardToken { get; set; }
public PasswordHasher PasswordHash { get; set; }
public FirebaseDto Firebase { get; set; }
public string Version { get; set; }
public string RecaptchaPublicKey { get; set; }
public bool DebugInfo { get; set; }
public static SettingsDto GetSample()
{
return new SettingsDto
{
Culture = "en-US",
Timezone = TimeZoneInfo.Utc.ToString(),
TrustedDomains = new List<string> { "mydomain.com" },
UtcHoursOffset = -8.5,
UtcOffset = TimeSpan.FromHours(-8.5),
GreetingSettings = "Web Office Applications",
OwnerId = new Guid()
};
}
}

View File

@ -0,0 +1,58 @@
/*
*
* (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.
*
*/
namespace ASC.Web.Api.ApiModel.ResponseDto;
public class SmtpSettingsDto : IMapFrom<SmtpSettings>
{
public string Host { get; set; }
public int? Port { get; set; }
public string SenderAddress { get; set; }
public string SenderDisplayName { get; set; }
public string CredentialsUserName { get; set; }
public string CredentialsUserPassword { get; set; }
public bool EnableSSL { get; set; }
public bool EnableAuth { get; set; }
public static SmtpSettingsDto GetSample()
{
return new SmtpSettingsDto
{
Host = "mail.example.com",
Port = 25,
CredentialsUserName = "notify@example.com",
CredentialsUserPassword = "{password}",
EnableAuth = true,
EnableSSL = false,
SenderAddress = "notify@example.com",
SenderDisplayName = "Postman"
};
}
public void Mapping(Profile profile)
{
profile.CreateMap<SmtpSettings, SmtpSettingsDto>();
}
}

View File

@ -23,52 +23,43 @@
*
*/
namespace ASC.Api.Settings
namespace ASC.Web.Api.ApiModel.ResponseDto;
public class StorageDto
{
public class UsageSpaceStatItemWrapper
public string Id { get; set; }
public string Title { get; set; }
public List<AuthKey> Properties { get; set; }
public bool Current { get; set; }
public bool IsSet { get; set; }
public StorageDto(DataStoreConsumer consumer, StorageSettings current)
{
public string Name { get; set; }
public string Icon { get; set; }
public bool Disabled { get; set; }
public string Size { get; set; }
public string Url { get; set; }
public static UsageSpaceStatItemWrapper GetSample()
{
return new UsageSpaceStatItemWrapper
{
Name = "Item name",
Icon = "Item icon path",
Disabled = false,
Size = "0 Byte",
Url = "Item url"
};
}
StorageWrapperInit(consumer, current);
}
public class ChartPointWrapper
public StorageDto(DataStoreConsumer consumer, CdnStorageSettings current)
{
public string DisplayDate { get; set; }
StorageWrapperInit(consumer, current);
}
public DateTime Date { get; set; }
private void StorageWrapperInit<T>(DataStoreConsumer consumer, BaseStorageSettings<T> current) where T : class, ISettings, new()
{
Id = consumer.Name;
Title = ConsumerExtension.GetResourceString(consumer.Name) ?? consumer.Name;
Current = consumer.Name == current.Module;
IsSet = consumer.IsSet;
public int Hosts { get; set; }
var props = Current
? current.Props
: current.Switch(consumer).AdditionalKeys.ToDictionary(r => r, a => consumer[a]);
public int Hits { get; set; }
public static ChartPointWrapper GetSample()
{
return new ChartPointWrapper
{
DisplayDate = DateTime.Now.ToShortDateString(),
Date = DateTime.Now,
Hosts = 0,
Hits = 0
};
}
Properties = props.Select(
r => new AuthKey
{
Name = r.Key,
Value = r.Value,
Title = ConsumerExtension.GetResourceString(consumer.Name + r.Key) ?? r.Key
}).ToList();
}
}

View File

@ -1,39 +1,38 @@
/*
*
* (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.
*
*/
namespace ASC.Api.Settings
{
public class TenantVersionWrapper
{
public int Current { get; set; }
public IEnumerable<TenantVersion> Versions { get; set; }
public TenantVersionWrapper(int version, IEnumerable<TenantVersion> tenantVersions)
{
Current = version;
Versions = tenantVersions;
}
}
/*
*
* (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.
*
*/
namespace ASC.Web.Api.ApiModel.ResponseDto;
public class TenantVersionDto
{
public int Current { get; set; }
public IEnumerable<TenantVersion> Versions { get; set; }
public TenantVersionDto(int version, IEnumerable<TenantVersion> tenantVersions)
{
Current = version;
Versions = tenantVersions;
}
}

View File

@ -23,39 +23,44 @@
*
*/
namespace ASC.Api.Settings.Smtp
namespace ASC.Web.Api.ApiModel.ResponseDto;
public class UsageSpaceStatItemDto
{
public class SmtpSettingsWrapper
public string Name { get; set; }
public string Icon { get; set; }
public bool Disabled { get; set; }
public string Size { get; set; }
public string Url { get; set; }
public static UsageSpaceStatItemDto GetSample()
{
public string Host { get; set; }
public int? Port { get; set; }
public string SenderAddress { get; set; }
public string SenderDisplayName { get; set; }
public string CredentialsUserName { get; set; }
public string CredentialsUserPassword { get; set; }
public bool EnableSSL { get; set; }
public bool EnableAuth { get; set; }
public static SmtpSettingsWrapper GetSample()
return new UsageSpaceStatItemDto
{
return new SmtpSettingsWrapper
{
Host = "mail.example.com",
Port = 25,
CredentialsUserName = "notify@example.com",
CredentialsUserPassword = "{password}",
EnableAuth = true,
EnableSSL = false,
SenderAddress = "notify@example.com",
SenderDisplayName = "Postman"
};
}
Name = "Item name",
Icon = "Item icon path",
Disabled = false,
Size = "0 Byte",
Url = "Item url"
};
}
}
public class ChartPointDto
{
public string DisplayDate { get; set; }
public DateTime Date { get; set; }
public int Hosts { get; set; }
public int Hits { get; set; }
public static ChartPointDto GetSample()
{
return new ChartPointDto
{
DisplayDate = DateTime.Now.ToShortDateString(),
Date = DateTime.Now,
Hosts = 0,
Hits = 0
};
}
}

View File

@ -1,625 +0,0 @@
using AuthenticationException = System.Security.Authentication.AuthenticationException;
using Constants = ASC.Core.Users.Constants;
using SecurityContext = ASC.Core.SecurityContext;
using System.Threading.Tasks;
namespace ASC.Web.Api.Controllers
{
[Scope]
[DefaultRoute]
[ApiController]
[AllowAnonymous]
public class AuthenticationController : ControllerBase
{
private UserManager UserManager { get; }
private TenantManager TenantManager { get; }
private SecurityContext SecurityContext { get; }
private TenantCookieSettingsHelper TenantCookieSettingsHelper { get; }
private CookiesManager CookiesManager { get; }
private PasswordHasher PasswordHasher { get; }
private EmailValidationKeyModelHelper EmailValidationKeyModelHelper { get; }
private ICache Cache { get; }
private SetupInfo SetupInfo { get; }
private MessageService MessageService { get; }
private ProviderManager ProviderManager { get; }
private IOptionsSnapshot<AccountLinker> AccountLinker { get; }
private CoreBaseSettings CoreBaseSettings { get; }
private PersonalSettingsHelper PersonalSettingsHelper { get; }
private StudioNotifyService StudioNotifyService { get; }
private UserHelpTourHelper UserHelpTourHelper { get; }
private Signature Signature { get; }
private InstanceCrypto InstanceCrypto { get; }
private DisplayUserSettingsHelper DisplayUserSettingsHelper { get; }
private MessageTarget MessageTarget { get; }
private StudioSmsNotificationSettingsHelper StudioSmsNotificationSettingsHelper { get; }
private SettingsManager SettingsManager { get; }
private SmsManager SmsManager { get; }
private TfaManager TfaManager { get; }
private TimeZoneConverter TimeZoneConverter { get; }
private SmsKeyStorage SmsKeyStorage { get; }
private CommonLinkUtility CommonLinkUtility { get; }
private ApiContext ApiContext { get; }
private AuthContext AuthContext { get; }
private UserManagerWrapper UserManagerWrapper { get; }
public AuthenticationController(
UserManager userManager,
TenantManager tenantManager,
SecurityContext securityContext,
TenantCookieSettingsHelper tenantCookieSettingsHelper,
CookiesManager cookiesManager,
PasswordHasher passwordHasher,
EmailValidationKeyModelHelper emailValidationKeyModelHelper,
ICache cache,
SetupInfo setupInfo,
MessageService messageService,
ProviderManager providerManager,
IOptionsSnapshot<AccountLinker> accountLinker,
CoreBaseSettings coreBaseSettings,
PersonalSettingsHelper personalSettingsHelper,
StudioNotifyService studioNotifyService,
UserManagerWrapper userManagerWrapper,
UserHelpTourHelper userHelpTourHelper,
Signature signature,
InstanceCrypto instanceCrypto,
DisplayUserSettingsHelper displayUserSettingsHelper,
MessageTarget messageTarget,
StudioSmsNotificationSettingsHelper studioSmsNotificationSettingsHelper,
SettingsManager settingsManager,
SmsManager smsManager,
TfaManager tfaManager,
TimeZoneConverter timeZoneConverter,
SmsKeyStorage smsKeyStorage,
CommonLinkUtility commonLinkUtility,
ApiContext apiContext,
AuthContext authContext)
{
UserManager = userManager;
TenantManager = tenantManager;
SecurityContext = securityContext;
TenantCookieSettingsHelper = tenantCookieSettingsHelper;
CookiesManager = cookiesManager;
PasswordHasher = passwordHasher;
EmailValidationKeyModelHelper = emailValidationKeyModelHelper;
Cache = cache;
SetupInfo = setupInfo;
MessageService = messageService;
ProviderManager = providerManager;
AccountLinker = accountLinker;
CoreBaseSettings = coreBaseSettings;
PersonalSettingsHelper = personalSettingsHelper;
StudioNotifyService = studioNotifyService;
UserHelpTourHelper = userHelpTourHelper;
Signature = signature;
InstanceCrypto = instanceCrypto;
DisplayUserSettingsHelper = displayUserSettingsHelper;
MessageTarget = messageTarget;
StudioSmsNotificationSettingsHelper = studioSmsNotificationSettingsHelper;
SettingsManager = settingsManager;
SmsManager = smsManager;
TfaManager = tfaManager;
TimeZoneConverter = timeZoneConverter;
SmsKeyStorage = smsKeyStorage;
CommonLinkUtility = commonLinkUtility;
ApiContext = apiContext;
AuthContext = authContext;
UserManagerWrapper = userManagerWrapper;
}
[Read]
public bool GetIsAuthentificated()
{
return SecurityContext.IsAuthenticated;
}
[Create("{code}", false, order: int.MaxValue)]
public AuthenticationTokenData AuthenticateMeFromBodyWithCode([FromBody] AuthModel auth)
{
return AuthenticateMeWithCode(auth);
}
[Create("{code}", false, order: int.MaxValue)]
[Consumes("application/x-www-form-urlencoded")]
public AuthenticationTokenData AuthenticateMeFromFormWithCode([FromForm] AuthModel auth)
{
return AuthenticateMeWithCode(auth);
}
[Create(false)]
public Task<AuthenticationTokenData> AuthenticateMeFromBodyAsync([FromBody] AuthModel auth)
{
return AuthenticateMeAsync(auth);
}
[Create(false)]
[Consumes("application/x-www-form-urlencoded")]
public Task<AuthenticationTokenData> AuthenticateMeFromFormAsync([FromForm] AuthModel auth)
{
return AuthenticateMeAsync(auth);
}
[Create("logout")]
[Read("logout")]// temp fix
public void Logout()
{
if (SecurityContext.IsAuthenticated)
CookiesManager.ResetUserCookie(SecurityContext.CurrentAccount.ID);
CookiesManager.ClearCookies(CookiesType.AuthKey);
CookiesManager.ClearCookies(CookiesType.SocketIO);
SecurityContext.Logout();
}
[Create("confirm", false)]
public ValidationResult CheckConfirmFromBody([FromBody] EmailValidationKeyModel model)
{
return EmailValidationKeyModelHelper.Validate(model);
}
[Create("confirm", false)]
[Consumes("application/x-www-form-urlencoded")]
public ValidationResult CheckConfirmFromForm([FromForm] EmailValidationKeyModel model)
{
return EmailValidationKeyModelHelper.Validate(model);
}
[Authorize(AuthenticationSchemes = "confirm", Roles = "PhoneActivation")]
[Create("setphone", false)]
public Task<AuthenticationTokenData> SaveMobilePhoneFromBodyAsync([FromBody] MobileModel model)
{
return SaveMobilePhoneAsync(model);
}
[Authorize(AuthenticationSchemes = "confirm", Roles = "PhoneActivation")]
[Create("setphone", false)]
[Consumes("application/x-www-form-urlencoded")]
public Task<AuthenticationTokenData> SaveMobilePhoneFromFormAsync([FromForm] MobileModel model)
{
return SaveMobilePhoneAsync(model);
}
private async Task<AuthenticationTokenData> SaveMobilePhoneAsync(MobileModel model)
{
ApiContext.AuthByClaim();
var user = UserManager.GetUsers(AuthContext.CurrentAccount.ID);
model.MobilePhone = await SmsManager.SaveMobilePhoneAsync(user, model.MobilePhone);
MessageService.Send(MessageAction.UserUpdatedMobileNumber, MessageTarget.Create(user.Id), user.DisplayUserName(false, DisplayUserSettingsHelper), model.MobilePhone);
return new AuthenticationTokenData
{
Sms = true,
PhoneNoise = SmsSender.BuildPhoneNoise(model.MobilePhone),
Expires = new ApiDateTime(TenantManager, TimeZoneConverter, DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval))
};
}
[Create(@"sendsms", false)]
public Task<AuthenticationTokenData> SendSmsCodeFromBodyAsync([FromBody] AuthModel model)
{
return SendSmsCodeAsync(model);
}
[Create(@"sendsms", false)]
[Consumes("application/x-www-form-urlencoded")]
public Task<AuthenticationTokenData> SendSmsCodeFromFormAsync([FromForm] AuthModel model)
{
return SendSmsCodeAsync(model);
}
private async Task<AuthenticationTokenData> SendSmsCodeAsync(AuthModel model)
{
var user = GetUser(model, out _);
await SmsManager.PutAuthCodeAsync(user, true);
return new AuthenticationTokenData
{
Sms = true,
PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
Expires = new ApiDateTime(TenantManager, TimeZoneConverter, DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval))
};
}
private async Task<AuthenticationTokenData> AuthenticateMeAsync(AuthModel auth)
{
bool viaEmail;
var user = GetUser(auth, out viaEmail);
if (StudioSmsNotificationSettingsHelper.IsVisibleSettings() && StudioSmsNotificationSettingsHelper.Enable)
{
if (string.IsNullOrEmpty(user.MobilePhone) || user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
return new AuthenticationTokenData
{
Sms = true,
ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PhoneActivation)
};
await SmsManager.PutAuthCodeAsync(user, false);
return new AuthenticationTokenData
{
Sms = true,
PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
Expires = new ApiDateTime(TenantManager, TimeZoneConverter, DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval)),
ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.PhoneAuth)
};
}
if (TfaAppAuthSettings.IsVisibleSettings && SettingsManager.Load<TfaAppAuthSettings>().EnableSetting)
{
if (!TfaAppUserSettings.EnableForUser(SettingsManager, user.Id))
return new AuthenticationTokenData
{
Tfa = true,
TfaKey = TfaManager.GenerateSetupCode(user).ManualEntryKey,
ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaActivation)
};
return new AuthenticationTokenData
{
Tfa = true,
ConfirmUrl = CommonLinkUtility.GetConfirmationUrl(user.Email, ConfirmType.TfaAuth)
};
}
try
{
var token = SecurityContext.AuthenticateMe(user.Id);
CookiesManager.SetCookies(CookiesType.AuthKey, token, auth.Session);
MessageService.Send(viaEmail ? MessageAction.LoginSuccessViaApi : MessageAction.LoginSuccessViaApiSocialAccount);
var tenant = TenantManager.GetCurrentTenant().Id;
var expires = TenantCookieSettingsHelper.GetExpiresTime(tenant);
return new AuthenticationTokenData
{
Token = token,
Expires = new ApiDateTime(TenantManager, TimeZoneConverter, expires)
};
}
catch
{
MessageService.Send(user.DisplayUserName(false, DisplayUserSettingsHelper), viaEmail ? MessageAction.LoginFailViaApi : MessageAction.LoginFailViaApiSocialAccount);
throw new AuthenticationException("User authentication failed");
}
finally
{
SecurityContext.Logout();
}
}
private AuthenticationTokenData AuthenticateMeWithCode(AuthModel auth)
{
var tenant = TenantManager.GetCurrentTenant().Id;
var user = GetUser(auth, out _);
var sms = false;
try
{
if (StudioSmsNotificationSettingsHelper.IsVisibleSettings() && StudioSmsNotificationSettingsHelper.Enable)
{
sms = true;
SmsManager.ValidateSmsCode(user, auth.Code);
}
else if (TfaAppAuthSettings.IsVisibleSettings && SettingsManager.Load<TfaAppAuthSettings>().EnableSetting)
{
if (TfaManager.ValidateAuthCode(user, auth.Code))
{
MessageService.Send(MessageAction.UserConnectedTfaApp, MessageTarget.Create(user.Id));
}
}
else
{
throw new System.Security.SecurityException("Auth code is not available");
}
var token = SecurityContext.AuthenticateMe(user.Id);
MessageService.Send(sms ? MessageAction.LoginSuccessViaApiSms : MessageAction.LoginSuccessViaApiTfa);
var expires = TenantCookieSettingsHelper.GetExpiresTime(tenant);
var result = new AuthenticationTokenData
{
Token = token,
Expires = new ApiDateTime(TenantManager, TimeZoneConverter, expires)
};
if (sms)
{
result.Sms = true;
result.PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone);
}
else
{
result.Tfa = true;
}
return result;
}
catch
{
MessageService.Send(user.DisplayUserName(false, DisplayUserSettingsHelper), sms
? MessageAction.LoginFailViaApiSms
: MessageAction.LoginFailViaApiTfa,
MessageTarget.Create(user.Id));
throw new AuthenticationException("User authentication failed");
}
finally
{
SecurityContext.Logout();
}
}
private UserInfo GetUser(AuthModel memberModel, out bool viaEmail)
{
viaEmail = true;
var action = MessageAction.LoginFailViaApi;
UserInfo user;
try
{
if ((string.IsNullOrEmpty(memberModel.Provider) && string.IsNullOrEmpty(memberModel.SerializedProfile)) || memberModel.Provider == "email")
{
memberModel.UserName.ThrowIfNull(new ArgumentException(@"userName empty", "userName"));
if (!string.IsNullOrEmpty(memberModel.Password))
{
memberModel.Password.ThrowIfNull(new ArgumentException(@"password empty", "password"));
}
else
{
memberModel.PasswordHash.ThrowIfNull(new ArgumentException(@"PasswordHash empty", "PasswordHash"));
}
int counter;
int.TryParse(Cache.Get<string>("loginsec/" + memberModel.UserName), out counter);
if (++counter > SetupInfo.LoginThreshold && !SetupInfo.IsSecretEmail(memberModel.UserName))
{
throw new BruteForceCredentialException();
}
Cache.Insert("loginsec/" + memberModel.UserName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
memberModel.PasswordHash = (memberModel.PasswordHash ?? "").Trim();
if (string.IsNullOrEmpty(memberModel.PasswordHash))
{
memberModel.Password = (memberModel.Password ?? "").Trim();
if (!string.IsNullOrEmpty(memberModel.Password))
{
memberModel.PasswordHash = PasswordHasher.GetClientPassword(memberModel.Password);
}
}
user = UserManager.GetUsersByPasswordHash(
TenantManager.GetCurrentTenant().Id,
memberModel.UserName,
memberModel.PasswordHash);
if (user == null || !UserManager.UserExists(user))
{
throw new Exception("user not found");
}
Cache.Insert("loginsec/" + memberModel.UserName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
}
else
{
viaEmail = false;
action = MessageAction.LoginFailViaApiSocialAccount;
LoginProfile thirdPartyProfile;
if (!string.IsNullOrEmpty(memberModel.SerializedProfile))
{
thirdPartyProfile = new LoginProfile(Signature, InstanceCrypto, memberModel.SerializedProfile);
}
else
{
thirdPartyProfile = ProviderManager.GetLoginProfile(memberModel.Provider, memberModel.AccessToken);
}
memberModel.UserName = thirdPartyProfile.EMail;
user = GetUserByThirdParty(thirdPartyProfile);
}
}
catch (BruteForceCredentialException)
{
MessageService.Send(!string.IsNullOrEmpty(memberModel.UserName) ? memberModel.UserName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce);
throw new AuthenticationException("Login Fail. Too many attempts");
}
catch
{
MessageService.Send(!string.IsNullOrEmpty(memberModel.UserName) ? memberModel.UserName : AuditResource.EmailNotSpecified, action);
throw new AuthenticationException("User authentication failed");
}
return user;
}
private UserInfo GetUserByThirdParty(LoginProfile loginProfile)
{
try
{
if (!string.IsNullOrEmpty(loginProfile.AuthorizationError))
{
// ignore cancellation
if (loginProfile.AuthorizationError != "Canceled at provider")
{
throw new Exception(loginProfile.AuthorizationError);
}
return Constants.LostUser;
}
var userInfo = Constants.LostUser;
Guid userId;
if (TryGetUserByHash(loginProfile.HashId, out userId))
{
userInfo = UserManager.GetUsers(userId);
}
var isNew = false;
if (CoreBaseSettings.Personal)
{
if (UserManager.UserExists(userInfo.Id) && SetupInfo.IsSecretEmail(userInfo.Email))
{
try
{
SecurityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem);
UserManager.DeleteUser(userInfo.Id);
userInfo = Constants.LostUser;
}
finally
{
SecurityContext.Logout();
}
}
if (!UserManager.UserExists(userInfo.Id))
{
userInfo = JoinByThirdPartyAccount(loginProfile);
isNew = true;
}
}
if (isNew)
{
//TODO:
//var spam = HttpContext.Current.Request["spam"];
//if (spam != "on")
//{
// try
// {
// const string _databaseID = "com";
// using (var db = DbManager.FromHttpContext(_databaseID))
// {
// db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
// .InColumnValue("email", userInfo.Email.ToLowerInvariant())
// .InColumnValue("reason", "personal")
// );
// Log.Debug(string.Format("Write to template_unsubscribe {0}", userInfo.Email.ToLowerInvariant()));
// }
// }
// catch (Exception ex)
// {
// Log.Debug(string.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, userInfo.Email.ToLowerInvariant()));
// }
//}
StudioNotifyService.UserHasJoin();
UserHelpTourHelper.IsNewUser = true;
PersonalSettingsHelper.IsNewUser = true;
}
return userInfo;
}
catch (Exception)
{
CookiesManager.ClearCookies(CookiesType.AuthKey);
CookiesManager.ClearCookies(CookiesType.SocketIO);
SecurityContext.Logout();
throw;
}
}
private UserInfo JoinByThirdPartyAccount(LoginProfile loginProfile)
{
if (string.IsNullOrEmpty(loginProfile.EMail))
{
throw new Exception(Resource.ErrorNotCorrectEmail);
}
var userInfo = UserManager.GetUserByEmail(loginProfile.EMail);
if (!UserManager.UserExists(userInfo.Id))
{
var newUserInfo = ProfileToUserInfo(loginProfile);
try
{
SecurityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem);
userInfo = UserManagerWrapper.AddUser(newUserInfo, UserManagerWrapper.GeneratePassword());
}
finally
{
SecurityContext.Logout();
}
}
var linker = AccountLinker.Get("webstudio");
linker.AddLink(userInfo.Id.ToString(), loginProfile);
return userInfo;
}
private UserInfo ProfileToUserInfo(LoginProfile loginProfile)
{
if (string.IsNullOrEmpty(loginProfile.EMail)) throw new Exception(Resource.ErrorNotCorrectEmail);
var firstName = loginProfile.FirstName;
if (string.IsNullOrEmpty(firstName)) firstName = loginProfile.DisplayName;
var userInfo = new UserInfo
{
FirstName = string.IsNullOrEmpty(firstName) ? UserControlsCommonResource.UnknownFirstName : firstName,
LastName = string.IsNullOrEmpty(loginProfile.LastName) ? UserControlsCommonResource.UnknownLastName : loginProfile.LastName,
Email = loginProfile.EMail,
Title = string.Empty,
Location = string.Empty,
CultureName = CoreBaseSettings.CustomMode ? "ru-RU" : Thread.CurrentThread.CurrentUICulture.Name,
ActivationStatus = EmployeeActivationStatus.Activated,
};
var gender = loginProfile.Gender;
if (!string.IsNullOrEmpty(gender))
{
userInfo.Sex = gender == "male";
}
return userInfo;
}
private bool TryGetUserByHash(string hashId, out Guid userId)
{
userId = Guid.Empty;
if (string.IsNullOrEmpty(hashId)) return false;
var linkedProfiles = AccountLinker.Get("webstudio").GetLinkedObjectsByHashId(hashId);
var tmp = Guid.Empty;
if (linkedProfiles.Any(profileId => Guid.TryParse(profileId, out tmp) && UserManager.UserExists(tmp)))
userId = tmp;
return true;
}
}
public class AuthenticationTokenData
{
public string Token { get; set; }
public DateTime Expires { get; set; }
public bool Sms { get; set; }
public string PhoneNoise { get; set; }
public bool Tfa { get; set; }
public string TfaKey { get; set; }
public string ConfirmUrl { get; set; }
public static AuthenticationTokenData GetSample()
{
return new AuthenticationTokenData
{
Expires = DateTime.UtcNow,
Token = "abcde12345",
Sms = false,
PhoneNoise = null,
Tfa = false,
TfaKey = null
};
}
}
}

View File

@ -1,114 +0,0 @@
namespace ASC.Web.Api.Controllers
{
[DefaultRoute]
[ApiController]
[AllowAnonymous]
public class CapabilitiesController : ControllerBase
{
private SetupInfo SetupInfo { get; }
private CoreBaseSettings CoreBaseSettings { get; }
private TenantManager TenantManager { get; }
private SettingsManager SettingsManager { get; }
private ProviderManager ProviderManager { get; }
private IConfiguration Configuration { get; }
private IHttpContextAccessor HttpContextAccessor { get; }
private ILog Log { get; }
public CapabilitiesController(
SetupInfo setupInfo,
CoreBaseSettings coreBaseSettings,
TenantManager tenantManager,
SettingsManager settingsManager,
ProviderManager providerManager,
IConfiguration configuration,
IHttpContextAccessor httpContextAccessor,
IOptionsMonitor<ILog> options)
{
SetupInfo = setupInfo;
CoreBaseSettings = coreBaseSettings;
TenantManager = tenantManager;
SettingsManager = settingsManager;
ProviderManager = providerManager;
Configuration = configuration;
HttpContextAccessor = httpContextAccessor;
Log = options.CurrentValue;
}
///<summary>
///Returns the information about portal capabilities
///</summary>
///<short>
///Get portal capabilities
///</short>
///<returns>CapabilitiesData</returns>
[Read(Check = false)] //NOTE: this method doesn't requires auth!!! //NOTE: this method doesn't check payment!!!
public CapabilitiesData GetPortalCapabilities()
{
var result = new CapabilitiesData
{
LdapEnabled = false,
Providers = null,
SsoLabel = string.Empty,
SsoUrl = string.Empty
};
try
{
if (SetupInfo.IsVisibleSettings(nameof(ManagementType.LdapSettings))
&& (!CoreBaseSettings.Standalone
|| TenantManager.GetTenantQuota(TenantManager.GetCurrentTenant().Id).Ldap))
{
//var settings = SettingsManager.Load<LdapSettings>();
//result.LdapEnabled = settings.EnableLdapAuthentication;
result.LdapEnabled = false;
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
try
{
result.Providers = ProviderManager.AuthProviders.Where(loginProvider =>
{
var provider = ProviderManager.GetLoginProvider(loginProvider);
return provider != null && provider.IsEnabled;
})
.ToList();
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
try
{
if (SetupInfo.IsVisibleSettings(nameof(ManagementType.SingleSignOnSettings))
&& TenantManager.GetTenantQuota(TenantManager.GetCurrentTenant().Id).Sso)
{
//var settings = SettingsManager.Load<SsoSettingsV2>();
//if (settings.EnableSso)
//{
var uri = HttpContextAccessor.HttpContext.Request.GetUrlRewriter();
var configUrl = Configuration["web:sso:saml:login:url"] ?? "";
result.SsoUrl = $"{uri.Scheme}://{uri.Host}{((uri.Port == 80 || uri.Port == 443) ? "" : ":" + uri.Port)}{configUrl}";
result.SsoLabel = string.Empty;
// result.SsoLabel = settings.SpLoginLabel;
//}
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
return result;
}
}
}

View File

@ -1,45 +0,0 @@
using Module = ASC.Api.Core.Module;
namespace ASC.Web.Api.Controllers
{
[Scope]
[DefaultRoute]
[ApiController]
public class ModulesController : ControllerBase
{
private WebItemManagerSecurity WebItemManagerSecurity { get; }
public ModulesController(
WebItemManagerSecurity webItemManagerSecurity)
{
WebItemManagerSecurity = webItemManagerSecurity;
}
[Read]
public IEnumerable<string> GetAll()
{
var result = new List<string>();
foreach (var a in WebItemManagerSecurity.GetItems(WebZoneType.StartProductList))
{
result.Add(a.ApiURL);
}
return result;
}
[Read("info")]
public IEnumerable<Module> GetAllWithInfo()
{
foreach (var a in WebItemManagerSecurity.GetItems(WebZoneType.StartProductList))
{
if(a is Product product)
{
product.Init();
yield return new Module(product);
}
}
}
}
}

View File

@ -1,254 +0,0 @@
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.Web.Api.Controllers
{
[Scope]
[DefaultRoute]
[ApiController]
public class PortalController : ControllerBase
{
private Tenant Tenant { get { return ApiContext.Tenant; } }
private ApiContext ApiContext { get; }
private UserManager UserManager { get; }
private TenantManager TenantManager { get; }
private PaymentManager PaymentManager { get; }
private CommonLinkUtility CommonLinkUtility { get; }
private UrlShortener UrlShortener { get; }
private AuthContext AuthContext { get; }
private WebItemSecurity WebItemSecurity { get; }
private SecurityContext SecurityContext { get; }
private SettingsManager SettingsManager { get; }
private IMobileAppInstallRegistrator MobileAppInstallRegistrator { get; }
private IConfiguration Configuration { get; set; }
private CoreBaseSettings CoreBaseSettings { get; }
private LicenseReader LicenseReader { get; }
private SetupInfo SetupInfo { get; }
private DocumentServiceLicense DocumentServiceLicense { get; }
private TenantExtra TenantExtra { get; set; }
public ILog Log { get; }
public IHttpClientFactory ClientFactory { get; }
public PortalController(
IOptionsMonitor<ILog> options,
ApiContext apiContext,
UserManager userManager,
TenantManager tenantManager,
PaymentManager paymentManager,
CommonLinkUtility commonLinkUtility,
UrlShortener urlShortener,
AuthContext authContext,
WebItemSecurity webItemSecurity,
SecurityContext securityContext,
SettingsManager settingsManager,
IMobileAppInstallRegistrator mobileAppInstallRegistrator,
TenantExtra tenantExtra,
IConfiguration configuration,
CoreBaseSettings coreBaseSettings,
LicenseReader licenseReader,
SetupInfo setupInfo,
DocumentServiceLicense documentServiceLicense,
IHttpClientFactory clientFactory
)
{
Log = options.CurrentValue;
ApiContext = apiContext;
UserManager = userManager;
TenantManager = tenantManager;
PaymentManager = paymentManager;
CommonLinkUtility = commonLinkUtility;
UrlShortener = urlShortener;
AuthContext = authContext;
WebItemSecurity = webItemSecurity;
SecurityContext = securityContext;
SettingsManager = settingsManager;
MobileAppInstallRegistrator = mobileAppInstallRegistrator;
Configuration = configuration;
CoreBaseSettings = coreBaseSettings;
LicenseReader = licenseReader;
SetupInfo = setupInfo;
DocumentServiceLicense = documentServiceLicense;
TenantExtra = tenantExtra;
ClientFactory = clientFactory;
}
[Read("")]
public Tenant Get()
{
return Tenant;
}
[Read("users/{userID}")]
public UserInfo GetUser(Guid userID)
{
return UserManager.GetUsers(userID);
}
[Read("users/invite/{employeeType}")]
public object GeInviteLink(EmployeeType employeeType)
{
if (!WebItemSecurity.IsProductAdministrator(WebItemManager.PeopleProductID, AuthContext.CurrentAccount.ID))
{
throw new SecurityException("Method not available");
}
return CommonLinkUtility.GetConfirmationUrl(string.Empty, ConfirmType.LinkInvite, (int)employeeType)
+ $"&emplType={employeeType:d}";
}
[Update("getshortenlink")]
public async Task<object> GetShortenLinkAsync(ShortenLinkModel model)
{
try
{
return await UrlShortener.Instance.GetShortenLinkAsync(model.Link);
}
catch (Exception ex)
{
Log.Error("getshortenlink", ex);
return model.Link;
}
}
[Read("tenantextra")]
public async Task<object> GetTenantExtraAsync()
{
return new
{
customMode = CoreBaseSettings.CustomMode,
opensource = TenantExtra.Opensource,
enterprise = TenantExtra.Enterprise,
tariff = TenantExtra.GetCurrentTariff(),
quota = TenantExtra.GetTenantQuota(),
notPaid = TenantExtra.IsNotPaid(),
licenseAccept = SettingsManager.LoadForCurrentUser<TariffSettings>().LicenseAcceptSetting,
enableTariffPage = //TenantExtra.EnableTarrifSettings - think about hide-settings for opensource
(!CoreBaseSettings.Standalone || !string.IsNullOrEmpty(LicenseReader.LicensePath))
&& string.IsNullOrEmpty(SetupInfo.AmiMetaUrl)
&& !CoreBaseSettings.CustomMode,
DocServerUserQuota = await DocumentServiceLicense.GetLicenseQuotaAsync(),
DocServerLicense = await DocumentServiceLicense.GetLicenseAsync()
};
}
[Read("usedspace")]
public double GetUsedSpace()
{
return Math.Round(
TenantManager.FindTenantQuotaRows(Tenant.Id)
.Where(q => !string.IsNullOrEmpty(q.Tag) && new Guid(q.Tag) != Guid.Empty)
.Sum(q => q.Counter) / 1024f / 1024f / 1024f, 2);
}
[Read("userscount")]
public long GetUsersCount()
{
return CoreBaseSettings.Personal ? 1 : UserManager.GetUserNames(EmployeeStatus.Active).Length;
}
[Read("tariff")]
public Tariff GetTariff()
{
return PaymentManager.GetTariff(Tenant.Id);
}
[Read("quota")]
public TenantQuota GetQuota()
{
return TenantManager.GetTenantQuota(Tenant.Id);
}
[Read("quota/right")]
public TenantQuota GetRightQuota()
{
var usedSpace = GetUsedSpace();
var needUsersCount = GetUsersCount();
return TenantManager.GetTenantQuotas().OrderBy(r => r.Price)
.FirstOrDefault(quota =>
quota.ActiveUsers > needUsersCount
&& quota.MaxTotalSize > usedSpace
&& !quota.Year);
}
[Read("path")]
public object GetFullAbsolutePath(string virtualPath)
{
return CommonLinkUtility.GetFullAbsolutePath(virtualPath);
}
[Read("thumb")]
public FileResult GetThumb(string url)
{
if (!SecurityContext.IsAuthenticated || Configuration["bookmarking:thumbnail-url"] == null)
{
return null;
}
url = url.Replace("&amp;", "&");
url = WebUtility.UrlEncode(url);
var request = new HttpRequestMessage();
request.RequestUri = new Uri(string.Format(Configuration["bookmarking:thumbnail-url"], url));
var httpClient = ClientFactory.CreateClient();
using var response = httpClient.Send(request);
using var stream = response.Content.ReadAsStream();
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
string type;
if (response.Headers.TryGetValues("Content-Type", out var values))
{
type = values.First();
}
else
{
type = "image/png";
}
return File(bytes, type);
}
[Create("present/mark")]
public void MarkPresentAsReaded()
{
try
{
var settings = SettingsManager.LoadForCurrentUser<OpensourceGiftSettings>();
settings.Readed = true;
SettingsManager.SaveForCurrentUser(settings);
}
catch (Exception ex)
{
Log.Error("MarkPresentAsReaded", ex);
}
}
[Create("mobile/registration")]
public void RegisterMobileAppInstallFromBody([FromBody] MobileAppModel model)
{
var currentUser = UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
MobileAppInstallRegistrator.RegisterInstall(currentUser.Email, model.Type);
}
[Create("mobile/registration")]
[Consumes("application/x-www-form-urlencoded")]
public void RegisterMobileAppInstallFromForm([FromForm] MobileAppModel model)
{
var currentUser = UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
MobileAppInstallRegistrator.RegisterInstall(currentUser.Email, model.Type);
}
[Create("mobile/registration")]
public void RegisterMobileAppInstall(MobileAppType type)
{
var currentUser = UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
MobileAppInstallRegistrator.RegisterInstall(currentUser.Email, type);
}
}
}

View File

@ -1,158 +0,0 @@
namespace ASC.Web.Api.Controllers
{
[Scope]
[DefaultRoute]
[ApiController]
public class SecurityController : ControllerBase
{
private PermissionContext PermissionContext { get; }
private CoreBaseSettings CoreBaseSettings { get; }
private TenantExtra TenantExtra { get; }
private TenantManager TenantManager { get; }
private MessageService MessageService { get; }
private LoginEventsRepository LoginEventsRepository { get; }
private AuditEventsRepository AuditEventsRepository { get; }
private AuditReportCreator AuditReportCreator { get; }
private SettingsManager SettingsManager { get; }
public SecurityController(
PermissionContext permissionContext,
CoreBaseSettings coreBaseSettings,
TenantExtra tenantExtra,
TenantManager tenantManager,
MessageService messageService,
LoginEventsRepository loginEventsRepository,
AuditEventsRepository auditEventsRepository,
AuditReportCreator auditReportCreator,
SettingsManager settingsManager)
{
PermissionContext = permissionContext;
CoreBaseSettings = coreBaseSettings;
TenantExtra = tenantExtra;
TenantManager = tenantManager;
MessageService = messageService;
LoginEventsRepository = loginEventsRepository;
AuditEventsRepository = auditEventsRepository;
AuditReportCreator = auditReportCreator;
SettingsManager = settingsManager;
}
[Read("audit/login/last")]
public IEnumerable<EventWrapper> GetLastLoginEvents()
{
if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory)))
{
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
}
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
return LoginEventsRepository.GetLast(TenantManager.GetCurrentTenant().Id, 20).Select(x => new EventWrapper(x));
}
[Read("audit/events/last")]
public IEnumerable<EventWrapper> GetLastAuditEvents()
{
if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.AuditTrail)))
{
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
}
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
return AuditEventsRepository.GetLast(TenantManager.GetCurrentTenant().Id, 20).Select(x => new EventWrapper(x));
}
[Create("audit/login/report")]
public object CreateLoginHistoryReport()
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var tenantId = TenantManager.GetCurrentTenant().Id;
if (!TenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory)))
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
var settings = SettingsManager.LoadForTenant<TenantAuditSettings>(TenantManager.GetCurrentTenant().Id);
var to = DateTime.UtcNow;
var from = to.Subtract(TimeSpan.FromDays(settings.LoginHistoryLifeTime));
var reportName = string.Format(AuditReportResource.LoginHistoryReportName + ".csv", from.ToShortDateString(), to.ToShortDateString());
var events = LoginEventsRepository.Get(tenantId, from, to);
var result = AuditReportCreator.CreateCsvReport(events, reportName);
MessageService.Send(MessageAction.LoginHistoryReportDownloaded);
return result;
}
[Create("audit/events/report")]
public object CreateAuditTrailReport()
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var tenantId = TenantManager.GetCurrentTenant().Id;
if (!TenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(nameof(ManagementType.AuditTrail)))
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
var settings = SettingsManager.LoadForTenant<TenantAuditSettings>(TenantManager.GetCurrentTenant().Id);
var to = DateTime.UtcNow;
var from = to.Subtract(TimeSpan.FromDays(settings.AuditTrailLifeTime));
var reportName = string.Format(AuditReportResource.AuditTrailReportName + ".csv", from.ToString("MM.dd.yyyy"), to.ToString("MM.dd.yyyy"));
var events = AuditEventsRepository.Get(tenantId, from, to);
var result = AuditReportCreator.CreateCsvReport(events, reportName);
MessageService.Send(MessageAction.AuditTrailReportDownloaded);
return result;
}
[Read("audit/settings/lifetime")]
public TenantAuditSettings GetAuditSettings()
{
if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory)))
{
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
}
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
return SettingsManager.LoadForTenant<TenantAuditSettings>(TenantManager.GetCurrentTenant().Id);
}
[Create("audit/settings/lifetime")]
public TenantAuditSettings SetAuditSettingsFromBody([FromBody] TenantAuditSettingsWrapper wrapper)
{
return SetAuditSettings(wrapper);
}
[Create("audit/settings/lifetime")]
[Consumes("application/x-www-form-urlencoded")]
public TenantAuditSettings SetAuditSettingsFromForm([FromForm] TenantAuditSettingsWrapper wrapper)
{
return SetAuditSettings(wrapper);
}
private TenantAuditSettings SetAuditSettings(TenantAuditSettingsWrapper wrapper)
{
if (!TenantExtra.GetTenantQuota().Audit || !SetupInfo.IsVisibleSettings(nameof(ManagementType.LoginHistory)))
throw new BillingException(Resource.ErrorNotAllowedOption, "Audit");
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
if (wrapper.settings.LoginHistoryLifeTime <= 0 || wrapper.settings.LoginHistoryLifeTime > TenantAuditSettings.MaxLifeTime)
throw new ArgumentException("LoginHistoryLifeTime");
if (wrapper.settings.AuditTrailLifeTime <= 0 || wrapper.settings.AuditTrailLifeTime > TenantAuditSettings.MaxLifeTime)
throw new ArgumentException("AuditTrailLifeTime");
SettingsManager.SaveForTenant(wrapper.settings, TenantManager.GetCurrentTenant().Id);
MessageService.Send(MessageAction.AuditSettingsUpdated);
return wrapper.settings;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,222 +0,0 @@
/*
*
* (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.
*
*/
namespace ASC.Api.Settings
{
[Scope]
[DefaultRoute]
[ApiController]
public class SmtpSettingsController : ControllerBase
{
//private static DistributedTaskQueue SMTPTasks { get; } = new DistributedTaskQueue("smtpOperations");
public Tenant Tenant { get { return ApiContext.Tenant; } }
private ApiContext ApiContext { get; }
private PermissionContext PermissionContext { get; }
private CoreConfiguration CoreConfiguration { get; }
private CoreBaseSettings CoreBaseSettings { get; }
public SmtpSettingsController(
ApiContext apiContext,
PermissionContext permissionContext,
CoreConfiguration coreConfiguration,
CoreBaseSettings coreBaseSettings)
{
ApiContext = apiContext;
PermissionContext = permissionContext;
CoreConfiguration = coreConfiguration;
CoreBaseSettings = coreBaseSettings;
}
[Read("smtp")]
public SmtpSettingsWrapper GetSmtpSettings()
{
CheckSmtpPermissions();
var settings = ToSmtpSettings(CoreConfiguration.SmtpSettings, true);
return settings;
}
[Create("smtp")]
public SmtpSettingsWrapper SaveSmtpSettingsFromBody([FromBody] SmtpSettingsWrapper smtpSettings)
{
return SaveSmtpSettings(smtpSettings);
}
[Create("smtp")]
[Consumes("application/x-www-form-urlencoded")]
public SmtpSettingsWrapper SaveSmtpSettingsFromForm([FromForm] SmtpSettingsWrapper smtpSettings)
{
return SaveSmtpSettings(smtpSettings);
}
private SmtpSettingsWrapper SaveSmtpSettings(SmtpSettingsWrapper smtpSettings)
{
CheckSmtpPermissions();
//TODO: Add validation check
ArgumentNullException.ThrowIfNull(smtpSettings);
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var settingConfig = ToSmtpSettingsConfig(smtpSettings);
CoreConfiguration.SmtpSettings = settingConfig;
var settings = ToSmtpSettings(settingConfig, true);
return settings;
}
[Delete("smtp")]
public SmtpSettingsWrapper ResetSmtpSettings()
{
CheckSmtpPermissions();
if (!CoreConfiguration.SmtpSettings.IsDefaultSettings)
{
PermissionContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
CoreConfiguration.SmtpSettings = null;
}
var current = CoreBaseSettings.Standalone ? CoreConfiguration.SmtpSettings : SmtpSettings.Empty;
return ToSmtpSettings(current, true);
}
//[Read("smtp/test")]
//public SmtpOperationStatus TestSmtpSettings()
//{
// CheckSmtpPermissions();
// var settings = ToSmtpSettings(CoreConfiguration.SmtpSettings);
// //add resolve
// var smtpTestOp = new SmtpOperation(settings, Tenant.TenantId, SecurityContext.CurrentAccount.ID, UserManager, SecurityContext, TenantManager, Configuration);
// SMTPTasks.QueueTask(smtpTestOp.RunJob, smtpTestOp.GetDistributedTask());
// return ToSmtpOperationStatus();
//}
//[Read("smtp/test/status")]
//public SmtpOperationStatus GetSmtpOperationStatus()
//{
// CheckSmtpPermissions();
// return ToSmtpOperationStatus();
//}
//private SmtpOperationStatus ToSmtpOperationStatus()
//{
// var operations = SMTPTasks.GetTasks().ToList();
// foreach (var o in operations)
// {
// if (!string.IsNullOrEmpty(o.InstanseId) &&
// Process.GetProcesses().Any(p => p.Id == int.Parse(o.InstanseId)))
// continue;
// o.SetProperty(SmtpOperation.PROGRESS, 100);
// SMTPTasks.RemoveTask(o.Id);
// }
// var operation =
// operations
// .FirstOrDefault(t => t.GetProperty<int>(SmtpOperation.OWNER) == Tenant.TenantId);
// if (operation == null)
// {
// return null;
// }
// if (DistributedTaskStatus.Running < operation.Status)
// {
// operation.SetProperty(SmtpOperation.PROGRESS, 100);
// SMTPTasks.RemoveTask(operation.Id);
// }
// var result = new SmtpOperationStatus
// {
// Id = operation.Id,
// Completed = operation.GetProperty<bool>(SmtpOperation.FINISHED),
// Percents = operation.GetProperty<int>(SmtpOperation.PROGRESS),
// Status = operation.GetProperty<string>(SmtpOperation.RESULT),
// Error = operation.GetProperty<string>(SmtpOperation.ERROR),
// Source = operation.GetProperty<string>(SmtpOperation.SOURCE)
// };
// return result;
//}
public static SmtpSettings ToSmtpSettingsConfig(SmtpSettingsWrapper settingsWrapper)
{
var settingsConfig = new SmtpSettings(
settingsWrapper.Host,
settingsWrapper.Port ?? SmtpSettings.DefaultSmtpPort,
settingsWrapper.SenderAddress,
settingsWrapper.SenderDisplayName)
{
EnableSSL = settingsWrapper.EnableSSL,
EnableAuth = settingsWrapper.EnableAuth
};
if (settingsWrapper.EnableAuth)
{
settingsConfig.SetCredentials(settingsWrapper.CredentialsUserName, settingsWrapper.CredentialsUserPassword);
}
return settingsConfig;
}
private static SmtpSettingsWrapper ToSmtpSettings(SmtpSettings settingsConfig, bool hidePassword = false)
{
return new SmtpSettingsWrapper
{
Host = settingsConfig.Host,
Port = settingsConfig.Port,
SenderAddress = settingsConfig.SenderAddress,
SenderDisplayName = settingsConfig.SenderDisplayName,
CredentialsUserName = settingsConfig.CredentialsUserName,
CredentialsUserPassword = hidePassword ? "" : settingsConfig.CredentialsUserPassword,
EnableSSL = settingsConfig.EnableSSL,
EnableAuth = settingsConfig.EnableAuth
};
}
private static void CheckSmtpPermissions()
{
if (!SetupInfo.IsVisibleSettings(nameof(ManagementType.SmtpSettings)))
{
throw new BillingException(Resource.ErrorNotAllowedOption, "Smtp");
}
}
}
}

View File

@ -1,140 +0,0 @@
/*
*
* (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.
*
*/
namespace ASC.Web.Api.Controllers
{
[Scope(Additional = typeof(BaseLoginProviderExtension))]
[DefaultRoute]
[ApiController]
public class ThirdPartyController : ControllerBase
{
private OAuth20TokenHelper OAuth20TokenHelper { get; }
public ThirdPartyController(OAuth20TokenHelper oAuth20TokenHelper)
{
OAuth20TokenHelper = oAuth20TokenHelper;
}
[Read("{provider}")]
public object Get(LoginProviderEnum provider)
{
var desktop = HttpContext.Request.Query["desktop"] == "true";
var additionals = new Dictionary<string, string>();
if (desktop)
{
additionals = HttpContext.Request.Query.ToDictionary(r => r.Key, r => r.Value.FirstOrDefault());
}
switch (provider)
{
case LoginProviderEnum.Google:
return OAuth20TokenHelper.RequestCode<GoogleLoginProvider>(
GoogleLoginProvider.GoogleScopeDrive,
new Dictionary<string, string>
{
{ "access_type", "offline" },
{ "prompt", "consent" }
}, additionalStateArgs: additionals);
case LoginProviderEnum.Dropbox:
return OAuth20TokenHelper.RequestCode<DropboxLoginProvider>(
additionalArgs: new Dictionary<string, string>
{
{ "force_reauthentication", "true" }
}, additionalStateArgs: additionals);
case LoginProviderEnum.Docusign:
return OAuth20TokenHelper.RequestCode<DocuSignLoginProvider>(
DocuSignLoginProvider.DocuSignLoginProviderScopes,
new Dictionary<string, string>
{
{ "prompt", "login" }
}, additionalStateArgs: additionals);
case LoginProviderEnum.Box:
return OAuth20TokenHelper.RequestCode<BoxLoginProvider>(additionalStateArgs: additionals);
case LoginProviderEnum.OneDrive:
return OAuth20TokenHelper.RequestCode<OneDriveLoginProvider>(OneDriveLoginProvider.OneDriveLoginProviderScopes, additionalStateArgs: additionals);
case LoginProviderEnum.Wordpress:
return OAuth20TokenHelper.RequestCode<WordpressLoginProvider>(additionalStateArgs: additionals);
}
return null;
}
[Read("{provider}/code")]
public object GetCode(string redirect, string code, string error)
{
try
{
if (!string.IsNullOrEmpty(error))
{
if (error == "access_denied")
{
error = "Canceled at provider";
}
throw new Exception(error);
}
if (!string.IsNullOrEmpty(redirect))
{
return AppendCode(redirect, code);
}
return code;
}
catch (ThreadAbortException)
{
}
catch (Exception ex)
{
if (!string.IsNullOrEmpty(redirect))
{
return AppendCode(redirect, error: ex.Message);
}
return ex.Message;
}
return null;
}
private static string AppendCode(string url, string code = null, string error = null)
{
url += (url.Contains('#') ? "&" : "#")
+ (string.IsNullOrEmpty(error)
? (string.IsNullOrEmpty(code)
? string.Empty
: "code=" + HttpUtility.UrlEncode(code))
: ("error/" + HttpUtility.UrlEncode(error)));
return url;
}
}
}

View File

@ -0,0 +1,119 @@
/*
*
* (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.
*
*/
namespace ASC.Api.Settings;
[Scope]
public class BuildVersion
{
public string CommunityServer { get; set; }
public string DocumentServer { get; set; }
public string MailServer { get; set; }
public string XmppServer { get; set; }
[JsonIgnore]
private readonly IConfiguration _configuration;
[JsonIgnore]
private readonly FilesLinkUtility _filesLinkUtility;
[JsonIgnore]
private readonly DocumentServiceConnector _documentServiceConnector;
public BuildVersion(IConfiguration configuration, FilesLinkUtility filesLinkUtility, DocumentServiceConnector documentServiceConnector)
{
_configuration = configuration;
_filesLinkUtility = filesLinkUtility;
_documentServiceConnector = documentServiceConnector;
}
public async Task<BuildVersion> GetCurrentBuildVersionAsync()
{
CommunityServer = GetCommunityVersion();
DocumentServer = await GetDocumentVersionAsync();
MailServer = GetMailServerVersion();
XmppServer = GetXmppServerVersion();
return this;
}
private string GetCommunityVersion()
{
return _configuration["version:number"] ?? "8.5.0";
}
private Task<string> GetDocumentVersionAsync()
{
if (string.IsNullOrEmpty(_filesLinkUtility.DocServiceApiUrl))
return null;
return _documentServiceConnector.GetVersionAsync();
}
private static string GetMailServerVersion()
{
//TODO
return "";
/*
try
{
var engineFactory = new EngineFactory(
CoreContext.TenantManager.GetCurrentTenant().Id,
SecurityContext.CurrentAccount.ID.ToString());
var version = engineFactory.ServerEngine.GetServerVersion();
return version;
}
catch (Exception e)
{
LogManager.GetLogger("ASC").Warn(e.Message, e);
}
return null;*/
}
private static string GetXmppServerVersion()
{
//try
//{
// if (ConfigurationManagerExtension.AppSettings["web.talk"] != "true")
// return null;
// return new JabberServiceClient().GetVersion();
//}
//catch (Exception e)
//{
// LogManager.GetLogger("ASC").Warn(e.Message, e);
//}
return null;
}
}

View File

@ -25,253 +25,252 @@
using SecurityContext = ASC.Core.SecurityContext;
namespace ASC.Web.Studio.UserControls.FirstTime
namespace ASC.Web.Studio.UserControls.FirstTime;
[Transient]
public class FirstTimeTenantSettings
{
[Transient]
public class FirstTimeTenantSettings
private readonly ILog _log;
private readonly TenantManager _tenantManager;
private readonly TenantExtra _tenantExtra;
private readonly SettingsManager _settingsManager;
private readonly UserManager _userManager;
private readonly SetupInfo _setupInfo;
private readonly SecurityContext _securityContext;
private readonly PaymentManager _paymentManager;
private readonly MessageService _messageService;
private readonly LicenseReader _licenseReader;
private readonly StudioNotifyService _studioNotifyService;
private readonly TimeZoneConverter _timeZoneConverter;
private readonly CoreBaseSettings _coreBaseSettings;
private readonly IHttpClientFactory _clientFactory;
public FirstTimeTenantSettings(
IOptionsMonitor<ILog> options,
TenantManager tenantManager,
TenantExtra tenantExtra,
SettingsManager settingsManager,
UserManager userManager,
SetupInfo setupInfo,
SecurityContext securityContext,
PaymentManager paymentManager,
MessageService messageService,
LicenseReader licenseReader,
StudioNotifyService studioNotifyService,
TimeZoneConverter timeZoneConverter,
CoreBaseSettings coreBaseSettings,
IHttpClientFactory clientFactory)
{
private ILog Log { get; }
private TenantManager TenantManager { get; }
private TenantExtra TenantExtra { get; }
private SettingsManager SettingsManager { get; }
private UserManager UserManager { get; }
private SetupInfo SetupInfo { get; }
private SecurityContext SecurityContext { get; }
private PaymentManager PaymentManager { get; }
private MessageService MessageService { get; }
private LicenseReader LicenseReader { get; }
private StudioNotifyService StudioNotifyService { get; }
private TimeZoneConverter TimeZoneConverter { get; }
public CoreBaseSettings CoreBaseSettings { get; }
public IHttpClientFactory ClientFactory { get; }
_log = options.CurrentValue;
_tenantManager = tenantManager;
_tenantExtra = tenantExtra;
_settingsManager = settingsManager;
_userManager = userManager;
_setupInfo = setupInfo;
_securityContext = securityContext;
_paymentManager = paymentManager;
_messageService = messageService;
_licenseReader = licenseReader;
_studioNotifyService = studioNotifyService;
_timeZoneConverter = timeZoneConverter;
_coreBaseSettings = coreBaseSettings;
_clientFactory = clientFactory;
}
public FirstTimeTenantSettings(
IOptionsMonitor<ILog> options,
TenantManager tenantManager,
TenantExtra tenantExtra,
SettingsManager settingsManager,
UserManager userManager,
SetupInfo setupInfo,
SecurityContext securityContext,
PaymentManager paymentManager,
MessageService messageService,
LicenseReader licenseReader,
StudioNotifyService studioNotifyService,
TimeZoneConverter timeZoneConverter,
CoreBaseSettings coreBaseSettings,
IHttpClientFactory clientFactory)
public WizardSettings SaveData(WizardRequestsDto inDto)
{
try
{
Log = options.CurrentValue;
TenantManager = tenantManager;
TenantExtra = tenantExtra;
SettingsManager = settingsManager;
UserManager = userManager;
SetupInfo = setupInfo;
SecurityContext = securityContext;
PaymentManager = paymentManager;
MessageService = messageService;
LicenseReader = licenseReader;
StudioNotifyService = studioNotifyService;
TimeZoneConverter = timeZoneConverter;
CoreBaseSettings = coreBaseSettings;
ClientFactory = clientFactory;
}
var (email, passwordHash, lng, timeZone, promocode, amiid, subscribeFromSite) = inDto;
public WizardSettings SaveData(WizardModel wizardModel)
{
try
var tenant = _tenantManager.GetCurrentTenant();
var settings = _settingsManager.Load<WizardSettings>();
if (settings.Completed)
{
var (email, passwordHash, lng, timeZone, promocode, amiid, subscribeFromSite) = wizardModel;
throw new Exception("Wizard passed.");
}
var tenant = TenantManager.GetCurrentTenant();
var settings = SettingsManager.Load<WizardSettings>();
if (settings.Completed)
{
throw new Exception("Wizard passed.");
}
if (!string.IsNullOrEmpty(SetupInfo.AmiMetaUrl) && IncorrectAmiId(amiid))
{
//throw new Exception(Resource.EmailAndPasswordIncorrectAmiId); TODO
}
if (!string.IsNullOrEmpty(_setupInfo.AmiMetaUrl) && IncorrectAmiId(amiid))
{
//throw new Exception(Resource.EmailAndPasswordIncorrectAmiId); TODO
}
if (tenant.OwnerId == Guid.Empty)
{
Thread.Sleep(TimeSpan.FromSeconds(6)); // wait cache interval
tenant = _tenantManager.GetTenant(tenant.Id);
if (tenant.OwnerId == Guid.Empty)
{
Thread.Sleep(TimeSpan.FromSeconds(6)); // wait cache interval
tenant = TenantManager.GetTenant(tenant.Id);
if (tenant.OwnerId == Guid.Empty)
{
Log.Error(tenant.Id + ": owner id is empty.");
}
_log.Error(tenant.Id + ": owner id is empty.");
}
var currentUser = UserManager.GetUsers(TenantManager.GetCurrentTenant().OwnerId);
if (!UserManagerWrapper.ValidateEmail(email))
{
throw new Exception(Resource.EmailAndPasswordIncorrectEmail);
}
if (string.IsNullOrEmpty(passwordHash))
throw new Exception(Resource.ErrorPasswordEmpty);
SecurityContext.SetUserPasswordHash(currentUser.Id, passwordHash);
email = email.Trim();
if (currentUser.Email != email)
{
currentUser.Email = email;
currentUser.ActivationStatus = EmployeeActivationStatus.NotActivated;
}
UserManager.SaveUserInfo(currentUser);
if (!string.IsNullOrWhiteSpace(promocode))
{
try
{
PaymentManager.ActivateKey(promocode);
}
catch (Exception err)
{
Log.Error("Incorrect Promo: " + promocode, err);
throw new Exception(Resource.EmailAndPasswordIncorrectPromocode);
}
}
if (RequestLicense)
{
TariffSettings.SetLicenseAccept(SettingsManager);
MessageService.Send(MessageAction.LicenseKeyUploaded);
LicenseReader.RefreshLicense();
}
settings.Completed = true;
SettingsManager.Save(settings);
TrySetLanguage(tenant, lng);
tenant.TimeZone = TimeZoneConverter.GetTimeZone(timeZone).Id;
TenantManager.SaveTenant(tenant);
StudioNotifyService.SendCongratulations(currentUser);
StudioNotifyService.SendRegData(currentUser);
if (subscribeFromSite && TenantExtra.Opensource && !CoreBaseSettings.CustomMode)
{
SubscribeFromSite(currentUser);
}
return settings;
}
catch (BillingNotFoundException)
{
throw new Exception(UserControlsCommonResource.LicenseKeyNotFound);
}
catch (BillingNotConfiguredException)
{
throw new Exception(UserControlsCommonResource.LicenseKeyNotCorrect);
}
catch (BillingException)
{
throw new Exception(UserControlsCommonResource.LicenseException);
}
catch (Exception ex)
{
Log.Error(ex);
throw;
}
}
public bool RequestLicense
{
get
var currentUser = _userManager.GetUsers(_tenantManager.GetCurrentTenant().OwnerId);
if (!UserManagerWrapper.ValidateEmail(email))
{
return TenantExtra.EnableTariffSettings && TenantExtra.Enterprise
&& !File.Exists(LicenseReader.LicensePath);
throw new Exception(Resource.EmailAndPasswordIncorrectEmail);
}
}
private void TrySetLanguage(Tenant tenant, string lng)
{
if (string.IsNullOrEmpty(lng)) return;
if (string.IsNullOrEmpty(passwordHash))
throw new Exception(Resource.ErrorPasswordEmpty);
try
_securityContext.SetUserPasswordHash(currentUser.Id, passwordHash);
email = email.Trim();
if (currentUser.Email != email)
{
var culture = CultureInfo.GetCultureInfo(lng);
tenant.Language = culture.Name;
currentUser.Email = email;
currentUser.ActivationStatus = EmployeeActivationStatus.NotActivated;
}
catch (Exception err)
_userManager.SaveUserInfo(currentUser);
if (!string.IsNullOrWhiteSpace(promocode))
{
Log.Error(err);
}
}
private static string _amiId;
private bool IncorrectAmiId(string customAmiId)
{
customAmiId = (customAmiId ?? "").Trim();
if (string.IsNullOrEmpty(customAmiId)) return true;
if (string.IsNullOrEmpty(_amiId))
{
var getAmiIdUrl = SetupInfo.AmiMetaUrl + "instance-id";
var request = new HttpRequestMessage();
request.RequestUri = new Uri(getAmiIdUrl);
try
{
var httpClient = ClientFactory.CreateClient();
using (var response = httpClient.Send(request))
using (var responseStream = response.Content.ReadAsStream())
using (var reader = new StreamReader(responseStream))
{
_amiId = reader.ReadToEnd();
}
Log.Debug("Instance id: " + _amiId);
_paymentManager.ActivateKey(promocode);
}
catch (Exception e)
catch (Exception err)
{
Log.Error("Request AMI id", e);
_log.Error("Incorrect Promo: " + promocode, err);
throw new Exception(Resource.EmailAndPasswordIncorrectPromocode);
}
}
return string.IsNullOrEmpty(_amiId) || _amiId != customAmiId;
}
if (RequestLicense)
{
TariffSettings.SetLicenseAccept(_settingsManager);
_messageService.Send(MessageAction.LicenseKeyUploaded);
private void SubscribeFromSite(UserInfo user)
_licenseReader.RefreshLicense();
}
settings.Completed = true;
_settingsManager.Save(settings);
TrySetLanguage(tenant, lng);
tenant.TimeZone = _timeZoneConverter.GetTimeZone(timeZone).Id;
_tenantManager.SaveTenant(tenant);
_studioNotifyService.SendCongratulations(currentUser);
_studioNotifyService.SendRegData(currentUser);
if (subscribeFromSite && _tenantExtra.Opensource && !_coreBaseSettings.CustomMode)
{
SubscribeFromSite(currentUser);
}
return settings;
}
catch (BillingNotFoundException)
{
throw new Exception(UserControlsCommonResource.LicenseKeyNotFound);
}
catch (BillingNotConfiguredException)
{
throw new Exception(UserControlsCommonResource.LicenseKeyNotCorrect);
}
catch (BillingException)
{
throw new Exception(UserControlsCommonResource.LicenseException);
}
catch (Exception ex)
{
_log.Error(ex);
throw;
}
}
public bool RequestLicense
{
get
{
return _tenantExtra.EnableTariffSettings && _tenantExtra.Enterprise
&& !File.Exists(_licenseReader.LicensePath);
}
}
private void TrySetLanguage(Tenant tenant, string lng)
{
if (string.IsNullOrEmpty(lng)) return;
try
{
var culture = CultureInfo.GetCultureInfo(lng);
tenant.Language = culture.Name;
}
catch (Exception err)
{
_log.Error(err);
}
}
private static string _amiId;
private bool IncorrectAmiId(string customAmiId)
{
customAmiId = (customAmiId ?? "").Trim();
if (string.IsNullOrEmpty(customAmiId)) return true;
if (string.IsNullOrEmpty(_amiId))
{
var getAmiIdUrl = _setupInfo.AmiMetaUrl + "instance-id";
var request = new HttpRequestMessage();
request.RequestUri = new Uri(getAmiIdUrl);
try
{
var url = (SetupInfo.TeamlabSiteRedirect ?? "").Trim().TrimEnd('/');
if (string.IsNullOrEmpty(url)) return;
url += "/post.ashx";
var request = new HttpRequestMessage();
request.RequestUri = new Uri(url);
var values = new NameValueCollection
{
{ "type", "sendsubscription" },
{ "subscr_type", "Opensource" },
{ "email", user.Email }
};
var data = JsonSerializer.Serialize(values);
request.Content = new StringContent(data);
var httpClient = ClientFactory.CreateClient();
using var response = httpClient.Send(request);
Log.Debug("Subscribe response: " + response);//toto write
var httpClient = _clientFactory.CreateClient();
using (var response = httpClient.Send(request))
using (var responseStream = response.Content.ReadAsStream())
using (var reader = new StreamReader(responseStream))
{
_amiId = reader.ReadToEnd();
}
_log.Debug("Instance id: " + _amiId);
}
catch (Exception e)
{
Log.Error("Subscribe request", e);
_log.Error("Request AMI id", e);
}
}
return string.IsNullOrEmpty(_amiId) || _amiId != customAmiId;
}
private void SubscribeFromSite(UserInfo user)
{
try
{
var url = (_setupInfo.TeamlabSiteRedirect ?? "").Trim().TrimEnd('/');
if (string.IsNullOrEmpty(url)) return;
url += "/post.ashx";
var request = new HttpRequestMessage();
request.RequestUri = new Uri(url);
var values = new NameValueCollection
{
{ "type", "sendsubscription" },
{ "subscr_type", "Opensource" },
{ "email", user.Email }
};
var data = JsonSerializer.Serialize(values);
request.Content = new StringContent(data);
var httpClient = _clientFactory.CreateClient();
using var response = httpClient.Send(request);
_log.Debug("Subscribe response: " + response);//toto write
}
catch (Exception e)
{
_log.Error("Subscribe request", e);
}
}
}

View File

@ -23,24 +23,23 @@
*
*/
namespace ASC.Web.Studio.Core
namespace ASC.Web.Studio.Core;
public class OpensourceGiftSettings : ISettings
{
public class OpensourceGiftSettings : ISettings
public bool Readed { get; set; }
#region ISettings Members
public Guid ID
{
public bool Readed { get; set; }
#region ISettings Members
public Guid ID
{
get { return new Guid("{1F4FEA2C-2D9F-47A6-ADEF-CEC4D1E1E243}"); }
}
public ISettings GetDefault(IServiceProvider serviceProvider)
{
return new OpensourceGiftSettings { Readed = false };
}
#endregion
get { return new Guid("{1F4FEA2C-2D9F-47A6-ADEF-CEC4D1E1E243}"); }
}
}
public ISettings GetDefault(IServiceProvider serviceProvider)
{
return new OpensourceGiftSettings { Readed = false };
}
#endregion
}

View File

@ -0,0 +1,249 @@
/*
*
* (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 AuthenticationException = System.Security.Authentication.AuthenticationException;
using SecurityContext = ASC.Core.SecurityContext;
using SmtpClient = MailKit.Net.Smtp.SmtpClient;
namespace ASC.Api.Settings.Smtp;
public class SmtpOperation
{
public const string OWNER = "SMTPOwner";
public const string SOURCE = "SMTPSource";
public const string PROGRESS = "SMTPProgress";
public const string RESULT = "SMTPResult";
public const string ERROR = "SMTPError";
public const string FINISHED = "SMTPFinished";
protected DistributedTask TaskInfo { get; set; }
protected CancellationToken CancellationToken { get; private set; }
protected int Progress { get; private set; }
protected string Source { get; private set; }
protected string Status { get; set; }
protected string Error { get; set; }
protected int CurrentTenant { get; private set; }
protected Guid CurrentUser { get; private set; }
private readonly UserManager _userManager;
private readonly SecurityContext _securityContext;
private readonly TenantManager _tenantManager;
private readonly ILog _logger;
private readonly SmtpSettingsDto _smtpSettings;
private readonly string _messageSubject;
private readonly string _messageBody;
public SmtpOperation(
SmtpSettingsDto smtpSettings,
int tenant,
Guid user,
UserManager userManager,
SecurityContext securityContext,
TenantManager tenantManager,
IOptionsMonitor<ILog> options)
{
_smtpSettings = smtpSettings;
CurrentTenant = tenant;
CurrentUser = user;
_userManager = userManager;
_securityContext = securityContext;
_tenantManager = tenantManager;
//todo
_messageSubject = WebstudioNotifyPatternResource.subject_smtp_test;
_messageBody = WebstudioNotifyPatternResource.pattern_smtp_test;
Source = "";
Progress = 0;
Status = "";
Error = "";
Source = "";
TaskInfo = new DistributedTask();
_logger = options.CurrentValue;
}
public void RunJob(DistributedTask distributedTask, CancellationToken cancellationToken)
{
try
{
CancellationToken = cancellationToken;
SetProgress(5, "Setup tenant");
_tenantManager.SetCurrentTenant(CurrentTenant);
SetProgress(10, "Setup user");
_securityContext.AuthenticateMeWithoutCookie(CurrentUser); //Core.Configuration.Constants.CoreSystem);
SetProgress(15, "Find user data");
var currentUser = _userManager.GetUsers(_securityContext.CurrentAccount.ID);
SetProgress(20, "Create mime message");
var toAddress = new MailboxAddress(currentUser.UserName, currentUser.Email);
var fromAddress = new MailboxAddress(_smtpSettings.SenderDisplayName, _smtpSettings.SenderAddress);
var mimeMessage = new MimeMessage
{
Subject = _messageSubject
};
mimeMessage.From.Add(fromAddress);
mimeMessage.To.Add(toAddress);
var bodyBuilder = new BodyBuilder
{
TextBody = _messageBody
};
mimeMessage.Body = bodyBuilder.ToMessageBody();
mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");
using var client = GetSmtpClient();
SetProgress(40, "Connect to host");
client.Connect(_smtpSettings.Host, _smtpSettings.Port.GetValueOrDefault(25),
_smtpSettings.EnableSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None, cancellationToken);
if (_smtpSettings.EnableAuth)
{
SetProgress(60, "Authenticate");
client.Authenticate(_smtpSettings.CredentialsUserName,
_smtpSettings.CredentialsUserPassword, cancellationToken);
}
SetProgress(80, "Send test message");
client.Send(FormatOptions.Default, mimeMessage, cancellationToken);
}
catch (AuthorizingException authError)
{
Error = Resource.ErrorAccessDenied; // "No permissions to perform this action";
_logger.Error(Error, new SecurityException(Error, authError));
}
catch (AggregateException ae)
{
ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
}
catch (SocketException ex)
{
Error = ex.Message; //TODO: Add translates of ordinary cases
_logger.Error(ex.ToString());
}
catch (AuthenticationException ex)
{
Error = ex.Message; //TODO: Add translates of ordinary cases
_logger.Error(ex.ToString());
}
catch (Exception ex)
{
Error = ex.Message; //TODO: Add translates of ordinary cases
_logger.Error(ex.ToString());
}
finally
{
try
{
TaskInfo.SetProperty(FINISHED, true);
PublishTaskInfo();
_securityContext.Logout();
}
catch (Exception ex)
{
_logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
}
}
}
public SmtpClient GetSmtpClient()
{
var client = new SmtpClient
{
Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds
};
return client;
}
public virtual DistributedTask GetDistributedTask()
{
FillDistributedTask();
return TaskInfo;
}
protected virtual void FillDistributedTask()
{
TaskInfo.SetProperty(SOURCE, Source);
TaskInfo.SetProperty(OWNER, CurrentTenant);
TaskInfo.SetProperty(PROGRESS, Progress < 100 ? Progress : 100);
TaskInfo.SetProperty(RESULT, Status);
TaskInfo.SetProperty(ERROR, Error);
//TaskInfo.SetProperty(PROCESSED, successProcessed);
}
protected int GetProgress()
{
return Progress;
}
const string PROGRESS_STRING = "Progress: {0}% {1} {2}";
public void SetProgress(int? currentPercent = null, string currentStatus = null, string currentSource = null)
{
if (!currentPercent.HasValue && currentStatus == null && currentSource == null)
return;
if (currentPercent.HasValue)
Progress = currentPercent.Value;
if (currentStatus != null)
Status = currentStatus;
if (currentSource != null)
Source = currentSource;
_logger.InfoFormat(PROGRESS_STRING, Progress, Status, Source);
PublishTaskInfo();
}
protected void PublishTaskInfo()
{
FillDistributedTask();
TaskInfo.PublishChanges();
}
}

View File

@ -13,8 +13,8 @@ global using System.Web;
global using ASC.Api.Collections;
global using ASC.Api.Core;
global using ASC.Api.Security;
global using ASC.Api.Settings.Smtp;
global using ASC.Api.Core.Convention;
global using ASC.Api.Settings;
global using ASC.Api.Utils;
global using ASC.AuditTrail;
global using ASC.AuditTrail.Models;
@ -22,6 +22,7 @@ global using ASC.AuditTrail.Repositories;
global using ASC.Common;
global using ASC.Common.Caching;
global using ASC.Common.Logging;
global using ASC.Common.Mapping;
global using ASC.Common.Security.Authorizing;
global using ASC.Common.Threading;
global using ASC.Common.Utils;
@ -50,6 +51,9 @@ global using ASC.IPSecurity;
global using ASC.MessagingSystem.Core;
global using ASC.MessagingSystem.Models;
global using ASC.Security.Cryptography;
global using ASC.Web.Api;
global using ASC.Web.Api.ApiModel.RequestsDto;
global using ASC.Web.Api.ApiModel.ResponseDto;
global using ASC.Web.Api.Core;
global using ASC.Web.Api.Models;
global using ASC.Web.Api.Routing;
@ -63,9 +67,9 @@ global using ASC.Web.Core.Utility;
global using ASC.Web.Core.Utility.Settings;
global using ASC.Web.Core.WebZones;
global using ASC.Web.Core.WhiteLabel;
global using ASC.Web.Files.Services.DocumentService;
global using ASC.Web.Studio.Core;
global using ASC.Web.Studio.Core.Notify;
global using ASC.Web.Studio.Core.Quota;
global using ASC.Web.Studio.Core.SMS;
global using ASC.Web.Studio.Core.Statistic;
global using ASC.Web.Studio.Core.TFA;
@ -77,8 +81,11 @@ global using ASC.Web.Studio.Utility;
global using ASC.Webhooks.Core;
global using ASC.Webhooks.Core.Dao.Models;
global using Autofac;
global using Autofac.Extensions.DependencyInjection;
global using AutoMapper;
global using Google.Authenticator;
global using MailKit.Security;
@ -87,6 +94,7 @@ global using Microsoft.AspNetCore.Authorization;
global using Microsoft.AspNetCore.Mvc;
global using Microsoft.AspNetCore.Mvc.ModelBinding;
global using Microsoft.Extensions.Caching.Memory;
global using Microsoft.Extensions.Hosting.WindowsServices;
global using Microsoft.Extensions.Options;
global using MimeKit;

View File

@ -1,19 +0,0 @@
namespace ASC.Web.Api.Models
{
public class AuthModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string PasswordHash { get; set; }
public string Provider { get; set; }
public string AccessToken { get; set; }
public string SerializedProfile { get; set; }
public string Code { get; set; }
public bool Session { get; set; }
}
public class MobileModel
{
public string MobilePhone { get; set; }
}
}

View File

@ -1,34 +0,0 @@
namespace ASC.Web.Api.Models
{
public class AuthServiceModel
{
public string Name { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Instruction { get; set; }
public bool CanSet { get; set; }
public List<AuthKey> Props { get; set; }
public AuthServiceModel()
{
}
public AuthServiceModel(Consumer consumer)
{
var authService = new AuthService(consumer);
Name = authService.Name;
Title = authService.Title;
Description = authService.Description;
Instruction = authService.Instruction;
CanSet = authService.CanSet;
if (consumer.CanSet)
{
Props = authService.Props;
CanSet = authService.CanSet;
}
}
}
}

View File

@ -1,121 +0,0 @@
/*
*
* (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 ASC.Web.Files.Services.DocumentService;
namespace ASC.Api.Settings
{
[Scope]
public class BuildVersion
{
public string CommunityServer { get; set; }
public string DocumentServer { get; set; }
public string MailServer { get; set; }
public string XmppServer { get; set; }
[JsonIgnore]
private IConfiguration Configuration { get; }
[JsonIgnore]
private FilesLinkUtility FilesLinkUtility { get; }
[JsonIgnore]
private DocumentServiceConnector DocumentServiceConnector { get; }
public BuildVersion(IConfiguration configuration, FilesLinkUtility filesLinkUtility, DocumentServiceConnector documentServiceConnector)
{
Configuration = configuration;
FilesLinkUtility = filesLinkUtility;
DocumentServiceConnector = documentServiceConnector;
}
public async Task<BuildVersion> GetCurrentBuildVersionAsync()
{
CommunityServer = GetCommunityVersion();
DocumentServer = await GetDocumentVersionAsync();
MailServer = GetMailServerVersion();
XmppServer = GetXmppServerVersion();
return this;
}
private string GetCommunityVersion()
{
return Configuration["version:number"] ?? "8.5.0";
}
private Task<string> GetDocumentVersionAsync()
{
if (string.IsNullOrEmpty(FilesLinkUtility.DocServiceApiUrl))
return null;
return DocumentServiceConnector.GetVersionAsync();
}
private static string GetMailServerVersion()
{
//TODO
return "";
/*
try
{
var engineFactory = new EngineFactory(
CoreContext.TenantManager.GetCurrentTenant().TenantId,
SecurityContext.CurrentAccount.ID.ToString());
var version = engineFactory.ServerEngine.GetServerVersion();
return version;
}
catch (Exception e)
{
LogManager.GetLogger("ASC").Warn(e.Message, e);
}
return null;*/
}
private static string GetXmppServerVersion()
{
//try
//{
// if (ConfigurationManagerExtension.AppSettings["web.talk"] != "true")
// return null;
// return new JabberServiceClient().GetVersion();
//}
//catch (Exception e)
//{
// LogManager.GetLogger("ASC").Warn(e.Message, e);
//}
return null;
}
}
}

View File

@ -1,27 +0,0 @@
namespace ASC.Web.Api.Models
{
public class CapabilitiesData
{
public bool LdapEnabled { get; set; }
public List<string> Providers { get; set; }
public string SsoLabel { get; set; }
/// <summary>
/// if empty sso is disabled
/// </summary>
public string SsoUrl { get; set; }
public static CapabilitiesData GetSample()
{
return new CapabilitiesData
{
LdapEnabled = false,
// Providers = AccountLinkControl.AuthProviders,
SsoLabel = string.Empty,
SsoUrl = string.Empty,
};
}
}
}

View File

@ -1,13 +0,0 @@
namespace ASC.Web.Api.Models
{
public class EncryptionSettingsModel
{
public string Password { get; set; }
public EncryprtionStatus Status { get; set; }
public bool NotifyUsers { get; set; }
public string ServerRootPath { get; set; }
}
}

View File

@ -1,21 +0,0 @@

namespace ASC.Web.Api.Models
{
public class FirebaseWrapper
{
public string ApiKey { get; set; }
public string AuthDomain { get; set; }
public string ProjectId { get; set; }
public string StorageBucket { get; set; }
public string MessagingSenderId { get; set; }
public string AppId { get; set; }
public string MeasurementId { get; set; }
}
}

View File

@ -1,7 +0,0 @@
namespace ASC.Web.Api.Models
{
public class GreetingSettingsModel
{
public string Title { get; set; }
}
}

View File

@ -1,16 +0,0 @@
namespace ASC.Web.Api.Models
{
public class MailDomainSettingsModel
{
public TenantTrustedDomainsType Type { get; set; }
public List<string> Domains { get; set; }
public bool InviteUsersAsVisitors { get; set; }
}
public class AdminMessageSettingsModel
{
public string Email { get; set; }
public string Message { get; set; }
public bool TurnOn { get; set; }
}
}

View File

@ -1,7 +0,0 @@
namespace ASC.Web.Api.Models
{
public class MailWhiteLabelSettingsModel
{
public bool FooterEnabled { get; set; }
}
}

View File

@ -1,7 +0,0 @@
namespace ASC.Web.Api.Models
{
public class MobileAppModel
{
public MobileAppType Type { get; set; }
}
}

View File

@ -1,148 +0,0 @@
/*
*
* (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 Constants = ASC.Core.Users.Constants;
namespace ASC.Web.Studio.Core.Quota
{
public class QuotaWrapper
{
public ulong StorageSize { get; set; }
public ulong MaxFileSize { get; set; }
public ulong UsedSize { get; set; }
public int MaxUsersCount { get; set; }
public int UsersCount { get; set; }
public ulong AvailableSize
{
get { return Math.Max(0, StorageSize > UsedSize ? StorageSize - UsedSize : 0); }
set { throw new NotImplementedException(); }
}
public int AvailableUsersCount
{
get { return Math.Max(0, MaxUsersCount - UsersCount); }
set { throw new NotImplementedException(); }
}
public IList<QuotaUsage> StorageUsage { get; set; }
public long UserStorageSize { get; set; }
public long UserUsedSize { get; set; }
public long UserAvailableSize
{
get { return Math.Max(0, UserStorageSize - UserUsedSize); }
set { throw new NotImplementedException(); }
}
public long MaxVisitors { get; set; }
public long VisitorsCount { get; set; }
[JsonIgnore]
private TenantExtra TenantExtra { get; }
[JsonIgnore]
private TenantStatisticsProvider TenantStatisticsProvider { get; }
[JsonIgnore]
private WebItemManager WebItemManager { get; }
public QuotaWrapper()
{
}
public QuotaWrapper(
Tenant tenant,
CoreBaseSettings coreBaseSettings,
CoreConfiguration configuration,
TenantExtra tenantExtra,
TenantStatisticsProvider tenantStatisticsProvider,
AuthContext authContext,
SettingsManager settingsManager,
WebItemManager webItemManager,
Constants constants)
{
TenantExtra = tenantExtra;
TenantStatisticsProvider = tenantStatisticsProvider;
WebItemManager = webItemManager;
var quota = TenantExtra.GetTenantQuota();
var quotaRows = TenantStatisticsProvider.GetQuotaRows(tenant.Id).ToList();
StorageSize = (ulong)Math.Max(0, quota.MaxTotalSize);
UsedSize = (ulong)Math.Max(0, quotaRows.Sum(r => r.Counter));
MaxUsersCount = quota.ActiveUsers;
UsersCount = coreBaseSettings.Personal ? 1 : TenantStatisticsProvider.GetUsersCount();
MaxVisitors = coreBaseSettings.Standalone ? -1 : constants.CoefficientOfVisitors * quota.ActiveUsers;
VisitorsCount = coreBaseSettings.Personal ? 0 : TenantStatisticsProvider.GetVisitorsCount();
StorageUsage = quotaRows
.Select(x => new QuotaUsage { Path = x.Path.TrimStart('/').TrimEnd('/'), Size = x.Counter, })
.ToList();
if (coreBaseSettings.Personal && SetupInfo.IsVisibleSettings("PersonalMaxSpace"))
{
UserStorageSize = configuration.PersonalMaxSpace(settingsManager);
var webItem = WebItemManager[WebItemManager.DocumentsProductID];
if (webItem.Context.SpaceUsageStatManager is IUserSpaceUsage spaceUsageManager)
{
UserUsedSize = spaceUsageManager.GetUserSpaceUsageAsync(authContext.CurrentAccount.ID).Result;
}
}
MaxFileSize = Math.Min(AvailableSize, (ulong)quota.MaxFileSize);
}
public static QuotaWrapper GetSample()
{
return new QuotaWrapper
{
MaxFileSize = 25 * 1024 * 1024,
StorageSize = 1024 * 1024 * 1024,
UsedSize = 250 * 1024 * 1024,
StorageUsage = new List<QuotaUsage>
{
new QuotaUsage { Size = 100*1024*1024, Path = "crm" },
new QuotaUsage { Size = 150*1024*1024, Path = "files" }
}
};
}
public class QuotaUsage
{
public string Path { get; set; }
public long Size { get; set; }
}
}
}

View File

@ -1,17 +0,0 @@
namespace ASC.Web.Api.Models
{
public class SchemaModel
{
public string Id { get; set; }
public string Name { get; set; }
public string UserCaption { get; set; }
public string UsersCaption { get; set; }
public string GroupCaption { get; set; }
public string GroupsCaption { get; set; }
public string UserPostCaption { get; set; }
public string RegDateCaption { get; set; }
public string GroupHeadCaption { get; set; }
public string GuestCaption { get; set; }
public string GuestsCaption { get; set; }
}
}

View File

@ -1,11 +0,0 @@
namespace ASC.Web.Api.Models
{
public class SecurityModel
{
public Guid ProductId { get; set; }
public Guid UserId { get; set; }
public bool Administrator { get; set; }
}
}

View File

@ -1,19 +0,0 @@
namespace ASC.Web.Api.Models
{
public class SettingsModel
{
public Guid DefaultProductID { get; set; }
public string Lng { get; set; }
public string TimeZoneID { get; set; }
public string Theme { get; set; }
public bool Show { get; set; } //tips
public int VersionId { get; set; }
public Guid OwnerId { get; set; }
}
}

View File

@ -1,84 +0,0 @@
/*
*
* (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.
*
*/
namespace ASC.Api.Settings
{
public class SettingsWrapper
{
public string Timezone { get; set; }
public List<string> TrustedDomains { get; set; }
public TenantTrustedDomainsType TrustedDomainsType { get; set; }
public string Culture { get; set; }
public TimeSpan UtcOffset { get; set; }
public double UtcHoursOffset { get; set; }
public string GreetingSettings { get; set; }
public Guid OwnerId { get; set; }
public string NameSchemaId { get; set; }
public bool? EnabledJoin { get; set; }
public bool? EnableAdmMess { get; set; }
public bool? ThirdpartyEnable { get; set; }
public bool Personal { get; set; }
public string WizardToken { get; set; }
public PasswordHasher PasswordHash { get; set; }
public FirebaseWrapper Firebase { get; set; }
public string Version { get; set; }
public string RecaptchaPublicKey { get; set; }
public bool DebugInfo { get; set; }
public string SocketUrl { get; set; }
public static SettingsWrapper GetSample()
{
return new SettingsWrapper
{
Culture = "en-US",
Timezone = TimeZoneInfo.Utc.ToString(),
TrustedDomains = new List<string> { "mydomain.com" },
UtcHoursOffset = -8.5,
UtcOffset = TimeSpan.FromHours(-8.5),
GreetingSettings = "Web Office Applications",
OwnerId = new Guid()
};
}
}
}

View File

@ -1,7 +0,0 @@
namespace ASC.Web.Api.Models
{
public class ShortenLinkModel
{
public string Link { get; set; }
}
}

View File

@ -1,262 +0,0 @@
/*
*
* (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 AuthenticationException = System.Security.Authentication.AuthenticationException;
using SecurityContext = ASC.Core.SecurityContext;
using SmtpClient = MailKit.Net.Smtp.SmtpClient;
namespace ASC.Api.Settings.Smtp
{
public class SmtpOperation
{
public const string OWNER = "SMTPOwner";
public const string SOURCE = "SMTPSource";
public const string PROGRESS = "SMTPProgress";
public const string RESULT = "SMTPResult";
public const string ERROR = "SMTPError";
public const string FINISHED = "SMTPFinished";
protected DistributedTask TaskInfo { get; set; }
protected CancellationToken CancellationToken { get; private set; }
protected int Progress { get; private set; }
protected string Source { get; private set; }
protected string Status { get; set; }
protected string Error { get; set; }
protected int CurrentTenant { get; private set; }
protected Guid CurrentUser { get; private set; }
private UserManager UserManager { get; }
private SecurityContext SecurityContext { get; }
private TenantManager TenantManager { get; }
private IConfiguration Configuration { get; }
protected ILog Logger { get; private set; }
public SmtpSettingsWrapper SmtpSettings { get; private set; }
private readonly string messageSubject;
private readonly string messageBody;
public SmtpOperation(
SmtpSettingsWrapper smtpSettings,
int tenant,
Guid user,
UserManager userManager,
SecurityContext securityContext,
TenantManager tenantManager,
IConfiguration configuration,
IOptionsMonitor<ILog> options)
{
SmtpSettings = smtpSettings;
CurrentTenant = tenant;
CurrentUser = user;
UserManager = userManager;
SecurityContext = securityContext;
TenantManager = tenantManager;
Configuration = configuration;
//todo
messageSubject = WebstudioNotifyPatternResource.subject_smtp_test;
messageBody = WebstudioNotifyPatternResource.pattern_smtp_test;
Source = "";
Progress = 0;
Status = "";
Error = "";
Source = "";
TaskInfo = new DistributedTask();
Logger = options.CurrentValue;
}
public void RunJob(DistributedTask distributedTask, CancellationToken cancellationToken)
{
try
{
CancellationToken = cancellationToken;
SetProgress(5, "Setup tenant");
TenantManager.SetCurrentTenant(CurrentTenant);
SetProgress(10, "Setup user");
SecurityContext.AuthenticateMeWithoutCookie(CurrentUser); //Core.Configuration.Constants.CoreSystem);
SetProgress(15, "Find user data");
var currentUser = UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
SetProgress(20, "Create mime message");
var toAddress = new MailboxAddress(currentUser.UserName, currentUser.Email);
var fromAddress = new MailboxAddress(SmtpSettings.SenderDisplayName, SmtpSettings.SenderAddress);
var mimeMessage = new MimeMessage
{
Subject = messageSubject
};
mimeMessage.From.Add(fromAddress);
mimeMessage.To.Add(toAddress);
var bodyBuilder = new BodyBuilder
{
TextBody = messageBody
};
mimeMessage.Body = bodyBuilder.ToMessageBody();
mimeMessage.Headers.Add("Auto-Submitted", "auto-generated");
using var client = GetSmtpClient();
SetProgress(40, "Connect to host");
client.Connect(SmtpSettings.Host, SmtpSettings.Port.GetValueOrDefault(25),
SmtpSettings.EnableSSL ? SecureSocketOptions.Auto : SecureSocketOptions.None, cancellationToken);
if (SmtpSettings.EnableAuth)
{
SetProgress(60, "Authenticate");
client.Authenticate(SmtpSettings.CredentialsUserName,
SmtpSettings.CredentialsUserPassword, cancellationToken);
}
SetProgress(80, "Send test message");
client.Send(FormatOptions.Default, mimeMessage, cancellationToken);
}
catch (AuthorizingException authError)
{
Error = Resource.ErrorAccessDenied; // "No permissions to perform this action";
Logger.Error(Error, new SecurityException(Error, authError));
}
catch (AggregateException ae)
{
ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
}
catch (SocketException ex)
{
Error = ex.Message; //TODO: Add translates of ordinary cases
Logger.Error(ex.ToString());
}
catch (AuthenticationException ex)
{
Error = ex.Message; //TODO: Add translates of ordinary cases
Logger.Error(ex.ToString());
}
catch (Exception ex)
{
Error = ex.Message; //TODO: Add translates of ordinary cases
Logger.Error(ex.ToString());
}
finally
{
try
{
TaskInfo.SetProperty(FINISHED, true);
PublishTaskInfo();
SecurityContext.Logout();
}
catch (Exception ex)
{
Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
}
}
}
public SmtpClient GetSmtpClient()
{
var client = new SmtpClient
{
Timeout = (int)TimeSpan.FromSeconds(30).TotalMilliseconds
};
return client;
}
public virtual DistributedTask GetDistributedTask()
{
FillDistributedTask();
return TaskInfo;
}
protected virtual void FillDistributedTask()
{
TaskInfo.SetProperty(SOURCE, Source);
TaskInfo.SetProperty(OWNER, CurrentTenant);
TaskInfo.SetProperty(PROGRESS, Progress < 100 ? Progress : 100);
TaskInfo.SetProperty(RESULT, Status);
TaskInfo.SetProperty(ERROR, Error);
//TaskInfo.SetProperty(PROCESSED, successProcessed);
}
protected int GetProgress()
{
return Progress;
}
const string PROGRESS_STRING = "Progress: {0}% {1} {2}";
public void SetProgress(int? currentPercent = null, string currentStatus = null, string currentSource = null)
{
if (!currentPercent.HasValue && currentStatus == null && currentSource == null)
return;
if (currentPercent.HasValue)
Progress = currentPercent.Value;
if (currentStatus != null)
Status = currentStatus;
if (currentSource != null)
Source = currentSource;
Logger.InfoFormat(PROGRESS_STRING, Progress, Status, Source);
PublishTaskInfo();
}
protected void PublishTaskInfo()
{
FillDistributedTask();
TaskInfo.PublishChanges();
}
}
}

View File

@ -1,7 +0,0 @@
namespace ASC.Web.Api.Models
{
public class StorageEncryptionModel
{
public bool NotifyUsers { get; set; }
}
}

View File

@ -1,8 +0,0 @@
namespace ASC.Web.Api.Models
{
public class StorageModel
{
public string Module { get; set; }
public IEnumerable<ItemKeyValuePair<string, string>> Props { get; set; }
}
}

View File

@ -1,70 +0,0 @@
/*
*
* (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.
*
*/
namespace ASC.Api.Settings
{
public class StorageWrapper
{
public string Id { get; set; }
public string Title { get; set; }
public List<AuthKey> Properties { get; set; }
public bool Current { get; set; }
public bool IsSet { get; set; }
public StorageWrapper(DataStoreConsumer consumer, StorageSettings current)
{
StorageWrapperInit(consumer, current);
}
public StorageWrapper(DataStoreConsumer consumer, CdnStorageSettings current)
{
StorageWrapperInit(consumer, current);
}
private void StorageWrapperInit<T>(DataStoreConsumer consumer, BaseStorageSettings<T> current) where T : class, ISettings, new()
{
Id = consumer.Name;
Title = ConsumerExtension.GetResourceString(consumer.Name) ?? consumer.Name;
Current = consumer.Name == current.Module;
IsSet = consumer.IsSet;
var props = Current
? current.Props
: current.Switch(consumer).AdditionalKeys.ToDictionary(r => r, a => consumer[a]);
Properties = props.Select(
r => new AuthKey
{
Name = r.Key,
Value = r.Value,
Title = ConsumerExtension.GetResourceString(consumer.Name + r.Key) ?? r.Key
}).ToList();
}
}
}

View File

@ -1,13 +0,0 @@
namespace ASC.Web.Api.Models
{
public class TfaModel
{
public string Type { get; set; }
public Guid? Id { get; set; }
}
public class TfaValidateModel
{
public string Code { get; set; }
}
}

View File

@ -1,10 +0,0 @@
namespace ASC.Web.Api.Models
{
public class TfaSettings
{
public string Id { get; set; }
public string Title { get; set; }
public bool Enabled { get; set; }
public bool Avaliable { get; set; }
}
}

View File

@ -1,8 +0,0 @@
namespace ASC.Web.Api.Models
{
public class ThirdpartyModel
{
public string Code { get; set; }
public string Redirect { get; set; }
}
}

View File

@ -1,8 +0,0 @@
namespace ASC.Web.Api.Models
{
public class TimezonesModel
{
public string Id { get; set; }
public string DisplayName { get; set; }
}
}

View File

@ -1,7 +0,0 @@
namespace ASC.Web.Api.Models
{
public class UploadLicenseModel
{
public IEnumerable<IFormFile> Files { get; set; }
}
}

View File

@ -1,10 +0,0 @@
namespace ASC.Web.Api.Models
{
public class WebItemSecurityModel
{
public string Id { get; set; }
public bool Enabled { get; set; }
public IEnumerable<Guid> Subjects { get; set; }
public IEnumerable<ItemKeyValuePair<string, bool>> Items { get; set; }
}
}

Some files were not shown because too many files have changed in this diff Show More