Files: BoxApp

This commit is contained in:
pavelbannov 2020-02-03 13:41:24 +03:00
parent 0a8aa83813
commit 51d8b9758c
5 changed files with 328 additions and 100 deletions

View File

@ -32,6 +32,7 @@ using System.Security.Authentication;
using System.Security.Claims;
using System.Threading;
using System.Web;
using ASC.Common.Logging;
using ASC.Common.Security;
using ASC.Common.Security.Authentication;
@ -43,6 +44,7 @@ using ASC.Core.Security.Authorizing;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Security.Cryptography;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
@ -263,7 +265,7 @@ namespace ASC.Core
public void Logout()
{
AuthContext.Principal = null;
AuthContext.Logout();
}
public void SetUserPassword(Guid userID, string password)
@ -333,6 +335,11 @@ namespace ASC.Core
get { return CurrentAccount.IsAuthenticated; }
}
public void Logout()
{
Principal = null;
}
internal ClaimsPrincipal Principal
{
get => Thread.CurrentPrincipal as ClaimsPrincipal ?? HttpContextAccessor?.HttpContext?.User;

View File

@ -33,7 +33,14 @@ using System.Security;
using System.Text;
using System.Threading;
using System.Web;
using ASC.Common.Caching;
using ASC.Common.Logging;
using ASC.Common.Web;
using ASC.Core;
using ASC.Core.Common;
using ASC.Core.Common.Configuration;
using ASC.Core.Common.Settings;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.FederatedLogin;
@ -51,7 +58,13 @@ using ASC.Web.Files.Resources;
using ASC.Web.Files.Services.DocumentService;
using ASC.Web.Studio.Core;
using ASC.Web.Studio.Utility;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using File = ASC.Files.Core.File;
using SecurityContext = ASC.Core.SecurityContext;
@ -77,22 +90,78 @@ namespace ASC.Web.Files.ThirdPartyApp
get { return !string.IsNullOrEmpty(ClientID) && !string.IsNullOrEmpty(ClientSecret); }
}
public TenantUtil TenantUtil { get; }
public AuthContext AuthContext { get; }
public SecurityContext SecurityContext { get; }
public UserManager UserManager { get; }
public UserManagerWrapper UserManagerWrapper { get; }
public CookiesManager CookiesManager { get; }
public MessageService MessageService { get; }
public Global Global { get; }
public EmailValidationKeyProvider EmailValidationKeyProvider { get; }
public FilesLinkUtility FilesLinkUtility { get; }
public SettingsManager SettingsManager { get; }
public PersonalSettingsHelper PersonalSettingsHelper { get; }
public BaseCommonLinkUtility BaseCommonLinkUtility { get; }
public IOptionsSnapshot<AccountLinker> Snapshot { get; }
public SetupInfo SetupInfo { get; }
public ILog Logger { get; }
public BoxApp() { }
public BoxApp(string name, int order, Dictionary<string, string> additional)
: base(name, order, additional)
public BoxApp(
TenantUtil tenantUtil,
IOptionsMonitor<ILog> option,
AuthContext authContext,
SecurityContext securityContext,
UserManager userManager,
UserManagerWrapper userManagerWrapper,
CookiesManager cookiesManager,
MessageService messageService,
Global global,
EmailValidationKeyProvider emailValidationKeyProvider,
FilesLinkUtility filesLinkUtility,
SettingsManager settingsManager,
PersonalSettingsHelper personalSettingsHelper,
BaseCommonLinkUtility baseCommonLinkUtility,
IOptionsSnapshot<AccountLinker> snapshot,
TenantManager tenantManager,
CoreBaseSettings coreBaseSettings,
CoreSettings coreSettings,
ConsumerFactory consumerFactory,
SetupInfo setupInfo,
IConfiguration configuration,
ICacheNotify<ConsumerCacheItem> cache,
string name, int order, Dictionary<string, string> additional)
: base(tenantManager, coreBaseSettings, coreSettings, consumerFactory, configuration, cache, name, order, additional)
{
TenantUtil = tenantUtil;
AuthContext = authContext;
SecurityContext = securityContext;
UserManager = userManager;
UserManagerWrapper = userManagerWrapper;
CookiesManager = cookiesManager;
MessageService = messageService;
Global = global;
EmailValidationKeyProvider = emailValidationKeyProvider;
FilesLinkUtility = filesLinkUtility;
SettingsManager = settingsManager;
PersonalSettingsHelper = personalSettingsHelper;
BaseCommonLinkUtility = baseCommonLinkUtility;
Snapshot = snapshot;
SetupInfo = setupInfo;
Logger = option.CurrentValue;
}
public bool Request(HttpContext context)
{
if ((context.Request[FilesLinkUtility.Action] ?? "").Equals("stream", StringComparison.InvariantCultureIgnoreCase))
if ((context.Request.Query[FilesLinkUtility.Action].FirstOrDefault() ?? "").Equals("stream", StringComparison.InvariantCultureIgnoreCase))
{
StreamFile(context);
return true;
}
if (!string.IsNullOrEmpty(context.Request["code"]))
if (!string.IsNullOrEmpty(context.Request.Query["code"]))
{
RequestCode(context);
return true;
@ -108,7 +177,7 @@ namespace ASC.Web.Files.ThirdPartyApp
public File GetFile(string fileId, out bool editable)
{
Global.Logger.Debug("BoxApp: get file " + fileId);
Logger.Debug("BoxApp: get file " + fileId);
fileId = ThirdPartySelector.GetFileId(fileId);
var token = Token.GetToken(AppAttr);
@ -121,14 +190,14 @@ namespace ASC.Web.Files.ThirdPartyApp
var jsonFile = JObject.Parse(boxFile);
var file = new File
{
ID = ThirdPartySelector.BuildAppFileId(AppAttr, jsonFile.Value<string>("id")),
Title = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value<string>("name")),
CreateOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("created_at")),
ModifiedOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("modified_at")),
ContentLength = Convert.ToInt64(jsonFile.Value<string>("size")),
ProviderKey = "Box"
};
{
ID = ThirdPartySelector.BuildAppFileId(AppAttr, jsonFile.Value<string>("id")),
Title = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value<string>("name")),
CreateOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("created_at")),
ModifiedOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("modified_at")),
ContentLength = Convert.ToInt64(jsonFile.Value<string>("size")),
ProviderKey = "Box"
};
var modifiedBy = jsonFile.Value<JObject>("modified_by");
if (modifiedBy != null)
@ -150,7 +219,7 @@ namespace ASC.Web.Files.ThirdPartyApp
if (lockedBy != null)
{
var lockedUserId = lockedBy.Value<string>("id");
Global.Logger.Debug("BoxApp: locked by " + lockedUserId);
Logger.Debug("BoxApp: locked by " + lockedUserId);
editable = CurrentUser(lockedUserId);
}
@ -165,9 +234,9 @@ namespace ASC.Web.Files.ThirdPartyApp
var fileId = ThirdPartySelector.GetFileId(file.ID.ToString());
Global.Logger.Debug("BoxApp: get file stream url " + fileId);
Logger.Debug("BoxApp: get file stream url " + fileId);
var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(ThirdPartyAppHandler.HandlerPath));
var uriBuilder = new UriBuilder(BaseCommonLinkUtility.GetFullAbsolutePath(ThirdPartyAppHandler.HandlerPath));
if (uriBuilder.Uri.IsLoopback)
{
uriBuilder.Host = Dns.GetHostName();
@ -175,8 +244,8 @@ namespace ASC.Web.Files.ThirdPartyApp
var query = uriBuilder.Query;
query += FilesLinkUtility.Action + "=stream&";
query += FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId) + "&";
query += CommonLinkUtility.ParamName_UserUserID + "=" + HttpUtility.UrlEncode(SecurityContext.CurrentAccount.ID.ToString()) + "&";
query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(fileId + SecurityContext.CurrentAccount.ID) + "&";
query += CommonLinkUtility.ParamName_UserUserID + "=" + HttpUtility.UrlEncode(AuthContext.CurrentAccount.ID.ToString()) + "&";
query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(fileId + AuthContext.CurrentAccount.ID) + "&";
query += ThirdPartySelector.AppAttr + "=" + AppAttr;
return uriBuilder.Uri + "?" + query;
@ -184,7 +253,7 @@ namespace ASC.Web.Files.ThirdPartyApp
public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream)
{
Global.Logger.Debug("BoxApp: save file stream " + fileId +
Logger.Debug("BoxApp: save file stream " + fileId +
(stream == null
? " from - " + downloadUrl
: " from stream"));
@ -195,7 +264,7 @@ namespace ASC.Web.Files.ThirdPartyApp
var boxFile = GetBoxFile(fileId, token);
if (boxFile == null)
{
Global.Logger.Error("BoxApp: file is null");
Logger.Error("BoxApp: file is null");
throw new Exception("File not found");
}
@ -212,7 +281,7 @@ namespace ASC.Web.Files.ThirdPartyApp
downloadUrl = DocumentServiceConnector.ReplaceCommunityAdress(downloadUrl);
}
Global.Logger.Debug("BoxApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl);
Logger.Debug("BoxApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl);
var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, null, false, out downloadUrl);
@ -220,7 +289,7 @@ namespace ASC.Web.Files.ThirdPartyApp
}
catch (Exception e)
{
Global.Logger.Error("BoxApp: Error convert", e);
Logger.Error("BoxApp: Error convert", e);
}
}
@ -241,7 +310,7 @@ namespace ASC.Web.Files.ThirdPartyApp
}
else
{
var downloadRequest = (HttpWebRequest) WebRequest.Create(downloadUrl);
var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl);
using (var downloadStream = new ResponseStream(downloadRequest.GetResponse()))
{
downloadStream.CopyTo(tmpStream);
@ -256,7 +325,7 @@ namespace ASC.Web.Files.ThirdPartyApp
request.Headers.Add("Authorization", "Bearer " + token);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.ContentLength = tmpStream.Length;
Global.Logger.Debug("BoxApp: save file totalSize - " + tmpStream.Length);
Logger.Debug("BoxApp: save file totalSize - " + tmpStream.Length);
const int bufferSize = 2048;
var buffer = new byte[bufferSize];
@ -270,24 +339,20 @@ namespace ASC.Web.Files.ThirdPartyApp
try
{
using (var response = request.GetResponse())
using (var responseStream = response.GetResponseStream())
using var response = request.GetResponse();
using var responseStream = response.GetResponseStream();
string result = null;
if (responseStream != null)
{
string result = null;
if (responseStream != null)
{
using (var readStream = new StreamReader(responseStream))
{
result = readStream.ReadToEnd();
}
}
Global.Logger.Debug("BoxApp: save file response - " + result);
using var readStream = new StreamReader(responseStream);
result = readStream.ReadToEnd();
}
Logger.Debug("BoxApp: save file response - " + result);
}
catch (WebException e)
{
Global.Logger.Error("BoxApp: Error save file", e);
Logger.Error("BoxApp: Error save file", e);
request.Abort();
var httpResponse = (HttpWebResponse)e.Response;
if (httpResponse.StatusCode == HttpStatusCode.Forbidden || httpResponse.StatusCode == HttpStatusCode.Unauthorized)
@ -301,45 +366,47 @@ namespace ASC.Web.Files.ThirdPartyApp
private void RequestCode(HttpContext context)
{
var token = GetToken(context.Request["code"]);
var token = GetToken(context.Request.Query["code"]);
if (token == null)
{
Global.Logger.Error("BoxApp: token is null");
Logger.Error("BoxApp: token is null");
throw new SecurityException("Access token is null");
}
var boxUserId = context.Request["userId"];
var boxUserId = context.Request.Query["userId"];
if (SecurityContext.IsAuthenticated)
if (AuthContext.IsAuthenticated)
{
if (!CurrentUser(boxUserId))
{
Global.Logger.Debug("BoxApp: logout for " + boxUserId);
Logger.Debug("BoxApp: logout for " + boxUserId);
CookiesManager.ClearCookies(CookiesType.AuthKey);
SecurityContext.Logout();
AuthContext.Logout();
}
}
if (!SecurityContext.IsAuthenticated)
if (!AuthContext.IsAuthenticated)
{
bool isNew;
var userInfo = GetUserInfo(token, out isNew);
var userInfo = GetUserInfo(token, out var isNew);
if (userInfo == null)
{
Global.Logger.Error("BoxApp: UserInfo is null");
Logger.Error("BoxApp: UserInfo is null");
throw new Exception("Profile is null");
}
var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
MessageService.Send(HttpContext.Current.Request, MessageAction.LoginSuccessViaSocialApp);
MessageService.Send(MessageAction.LoginSuccessViaSocialApp);
if (isNew)
{
UserHelpTourHelper.IsNewUser = true;
PersonalSettings.IsNewUser = true;
PersonalSettings.IsNotActivated = true;
var userHelpTourSettings = SettingsManager.LoadForCurrentUser<UserHelpTourSettings>();
userHelpTourSettings.IsNewUser = true;
SettingsManager.SaveForCurrentUser(userHelpTourSettings);
PersonalSettingsHelper.IsNewUser = true;
PersonalSettingsHelper.IsNotActivated = true;
}
if (!string.IsNullOrEmpty(boxUserId) && !CurrentUser(boxUserId))
@ -350,27 +417,27 @@ namespace ASC.Web.Files.ThirdPartyApp
Token.SaveToken(token);
var fileId = context.Request["id"];
var fileId = context.Request.Query["id"];
context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
}
private static void StreamFile(HttpContext context)
private void StreamFile(HttpContext context)
{
try
{
var fileId = context.Request[FilesLinkUtility.FileId];
var auth = context.Request[FilesLinkUtility.AuthKey];
var userId = context.Request[CommonLinkUtility.ParamName_UserUserID];
var fileId = context.Request.Query[FilesLinkUtility.FileId];
var auth = context.Request.Query[FilesLinkUtility.AuthKey];
var userId = context.Request.Query[CommonLinkUtility.ParamName_UserUserID];
Global.Logger.Debug("BoxApp: get file stream " + fileId);
Logger.Debug("BoxApp: get file stream " + fileId);
var validateResult = EmailValidationKeyProvider.ValidateEmailKey(fileId + userId, auth, Global.StreamUrlExpire);
if (validateResult != EmailValidationKeyProvider.ValidationResult.Ok)
{
var exc = new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException);
Global.Logger.Error(string.Format("BoxApp: validate error {0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url), exc);
Logger.Error(string.Format("BoxApp: validate error {0} {1}: {2}", FilesLinkUtility.AuthKey, validateResult, context.Request.Url()), exc);
throw exc;
}
@ -378,7 +445,7 @@ namespace ASC.Web.Files.ThirdPartyApp
var token = Token.GetToken(AppAttr, userId);
if (token == null)
{
Global.Logger.Error("BoxApp: token is null");
Logger.Error("BoxApp: token is null");
throw new SecurityException("Access token is null");
}
@ -388,50 +455,49 @@ namespace ASC.Web.Files.ThirdPartyApp
using (var stream = new ResponseStream(request.GetResponse()))
{
stream.StreamCopyTo(context.Response.OutputStream);
stream.StreamCopyTo(context.Response.Body);
}
}
catch (Exception ex)
{
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Response.Write(ex.Message);
Global.Logger.Error("BoxApp: Error request " + context.Request.Url, ex);
context.Response.WriteAsync(ex.Message).Wait();
Logger.Error("BoxApp: Error request " + context.Request.Url(), ex);
}
try
{
context.Response.Flush();
context.Response.SuppressContent = true;
context.ApplicationInstance.CompleteRequest();
context.Response.Body.Flush();
//TODO
//context.Response.Body.SuppressContent = true;
//context.ApplicationInstance.CompleteRequest();
}
catch (HttpException ex)
{
Global.Logger.Error("BoxApp StreamFile", ex);
Logger.Error("BoxApp StreamFile", ex);
}
}
private static bool CurrentUser(string boxUserId)
private bool CurrentUser(string boxUserId)
{
var linkedProfiles = new AccountLinker("webstudio")
var linkedProfiles = Snapshot.Get("webstudio")
.GetLinkedObjectsByHashId(HashHelper.MD5(string.Format("{0}/{1}", ProviderConstants.Box, boxUserId)));
Guid tmp;
return
linkedProfiles.Any(profileId => Guid.TryParse(profileId, out tmp) && tmp == SecurityContext.CurrentAccount.ID);
return linkedProfiles.Any(profileId => Guid.TryParse(profileId, out var tmp) && tmp == AuthContext.CurrentAccount.ID);
}
private static void AddLinker(string boxUserId)
private void AddLinker(string boxUserId)
{
Global.Logger.Debug("BoxApp: AddLinker " + boxUserId);
var linker = new AccountLinker("webstudio");
linker.AddLink(SecurityContext.CurrentAccount.ID.ToString(), boxUserId, ProviderConstants.Box);
Logger.Debug("BoxApp: AddLinker " + boxUserId);
var linker = Snapshot.Get("webstudio");
linker.AddLink(AuthContext.CurrentAccount.ID.ToString(), boxUserId, ProviderConstants.Box);
}
private static UserInfo GetUserInfo(Token token, out bool isNew)
private UserInfo GetUserInfo(Token token, out bool isNew)
{
isNew = false;
if (token == null)
{
Global.Logger.Error("BoxApp: token is null");
Logger.Error("BoxApp: token is null");
throw new SecurityException("Access token is null");
}
@ -439,34 +505,34 @@ namespace ASC.Web.Files.ThirdPartyApp
try
{
resultResponse = RequestHelper.PerformRequest(BoxUrlUserInfo,
headers: new Dictionary<string, string> {{"Authorization", "Bearer " + token}});
Global.Logger.Debug("BoxApp: userinfo response - " + resultResponse);
headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token } });
Logger.Debug("BoxApp: userinfo response - " + resultResponse);
}
catch (Exception ex)
{
Global.Logger.Error("BoxApp: userinfo request", ex);
Logger.Error("BoxApp: userinfo request", ex);
}
var boxUserInfo = JObject.Parse(resultResponse);
if (boxUserInfo == null)
{
Global.Logger.Error("Error in userinfo request");
Logger.Error("Error in userinfo request");
return null;
}
var email = boxUserInfo.Value<string>("login");
var userInfo = CoreContext.UserManager.GetUserByEmail(email);
var userInfo = UserManager.GetUserByEmail(email);
if (Equals(userInfo, Constants.LostUser))
{
userInfo = new UserInfo
{
FirstName = boxUserInfo.Value<string>("name"),
Email = email,
MobilePhone = boxUserInfo.Value<string>("phone"),
};
{
FirstName = boxUserInfo.Value<string>("name"),
Email = email,
MobilePhone = boxUserInfo.Value<string>("phone"),
};
var cultureName = boxUserInfo.Value<string>("language");
if(string.IsNullOrEmpty(cultureName))
if (string.IsNullOrEmpty(cultureName))
cultureName = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
var cultureInfo = SetupInfo.EnabledCultures.Find(c => string.Equals(c.TwoLetterISOLanguageName, cultureName, StringComparison.InvariantCultureIgnoreCase));
if (cultureInfo != null)
@ -475,7 +541,7 @@ namespace ASC.Web.Files.ThirdPartyApp
}
else
{
Global.Logger.DebugFormat("From box app new personal user '{0}' without culture {1}", userInfo.Email, cultureName);
Logger.DebugFormat("From box app new personal user '{0}' without culture {1}", userInfo.Email, cultureName);
}
if (string.IsNullOrEmpty(userInfo.FirstName))
@ -494,35 +560,35 @@ namespace ASC.Web.Files.ThirdPartyApp
}
finally
{
SecurityContext.Logout();
AuthContext.Logout();
}
isNew = true;
Global.Logger.Debug("BoxApp: new user " + userInfo.ID);
Logger.Debug("BoxApp: new user " + userInfo.ID);
}
return userInfo;
}
private static string GetBoxFile(string boxFileId, Token token)
private string GetBoxFile(string boxFileId, Token token)
{
if (token == null)
{
Global.Logger.Error("BoxApp: token is null");
Logger.Error("BoxApp: token is null");
throw new SecurityException("Access token is null");
}
try
{
var resultResponse = RequestHelper.PerformRequest(BoxUrlFile.Replace("{fileId}", boxFileId),
headers: new Dictionary<string, string> {{"Authorization", "Bearer " + token}});
Global.Logger.Debug("BoxApp: file response - " + resultResponse);
headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token } });
Logger.Debug("BoxApp: file response - " + resultResponse);
return resultResponse;
}
catch (Exception ex)
{
Global.Logger.Error("BoxApp: file request", ex);
Logger.Error("BoxApp: file request", ex);
}
return null;
}
@ -531,13 +597,13 @@ namespace ASC.Web.Files.ThirdPartyApp
{
try
{
Global.Logger.Debug("BoxApp: GetAccessToken by code " + code);
var token = OAuth20TokenHelper.GetAccessToken<BoxApp>(code);
Logger.Debug("BoxApp: GetAccessToken by code " + code);
var token = OAuth20TokenHelper.GetAccessToken<BoxApp>(ConsumerFactory, code);
return new Token(token, AppAttr);
}
catch (Exception ex)
{
Global.Logger.Error(ex);
Logger.Error(ex);
}
return null;
}

View File

@ -26,6 +26,9 @@
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;
using File = ASC.Files.Core.File;
namespace ASC.Web.Files.ThirdPartyApp

View File

@ -0,0 +1,101 @@
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
using System;
using System.Runtime.Serialization;
using ASC.Core.Common.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ASC.Web.Studio.Core
{
[Serializable]
[DataContract]
public class PersonalSettings : ISettings
{
[DataMember(Name = "IsNewUser")]
public bool IsNewUserSetting { get; set; }
[DataMember(Name = "IsNotActivated")]
public bool IsNotActivatedSetting { get; set; }
public Guid ID
{
get { return new Guid("{B3427865-8E32-4E66-B6F3-91C61922239F}"); }
}
public ISettings GetDefault(IServiceProvider serviceProvider)
{
return new PersonalSettings
{
IsNewUserSetting = false,
IsNotActivatedSetting = false,
};
}
}
public class PersonalSettingsHelper
{
public PersonalSettingsHelper(SettingsManager settingsManager)
{
SettingsManager = settingsManager;
}
public bool IsNewUser
{
get { return SettingsManager.LoadForCurrentUser<PersonalSettings>().IsNewUserSetting; }
set
{
var settings = SettingsManager.LoadForCurrentUser<PersonalSettings>();
settings.IsNewUserSetting = value;
SettingsManager.SaveForCurrentUser(settings);
}
}
public bool IsNotActivated
{
get { return SettingsManager.LoadForCurrentUser<PersonalSettings>().IsNotActivatedSetting; }
set
{
var settings = SettingsManager.LoadForCurrentUser<PersonalSettings>();
settings.IsNotActivatedSetting = value;
SettingsManager.SaveForCurrentUser(settings);
}
}
public SettingsManager SettingsManager { get; }
}
public static class PersonalSettingsExtention
{
public static IServiceCollection AddTenantCookieSettingsService(this IServiceCollection services)
{
services.TryAddScoped<PersonalSettingsHelper>();
return services.AddSettingsManagerService();
}
}
}

View File

@ -0,0 +1,51 @@
/*
*
* (c) Copyright Ascensio System Limited 2010-2018
*
* This program is freeware. You can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) version 3 as published by the Free Software Foundation (https://www.gnu.org/copyleft/gpl.html).
* In accordance with Section 7(a) of the GNU GPL its Section 15 shall be amended to the effect that
* Ascensio System SIA expressly excludes the warranty of non-infringement of any third-party rights.
*
* THIS PROGRAM IS DISTRIBUTED WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. For more details, see GNU GPL at https://www.gnu.org/copyleft/gpl.html
*
* You can contact Ascensio System SIA by email at sales@onlyoffice.com
*
* The interactive user interfaces in modified source and object code versions of ONLYOFFICE must display
* Appropriate Legal Notices, as required under Section 5 of the GNU GPL version 3.
*
* Pursuant to Section 7 § 3(b) of the GNU GPL you must retain the original ONLYOFFICE logo which contains
* relevant author attributions when distributing the software. If the display of the logo in its graphic
* form is not reasonably feasible for technical reasons, you must include the words "Powered by ONLYOFFICE"
* in every copy of the program you distribute.
* Pursuant to Section 7 § 3(e) we decline to grant you any rights under trademark law for use of our trademarks.
*
*/
using System;
using System.Runtime.Serialization;
using ASC.Core.Common.Settings;
namespace ASC.Web.Studio.Core
{
[Serializable]
[DataContract]
public class PromotionsSettings : ISettings
{
[DataMember(Name = "Show")]
public bool Show { get; set; }
public Guid ID
{
get { return new Guid("{D291A4C1-179D-4ced-895A-E094E809C859}"); }
}
public ISettings GetDefault(IServiceProvider serviceProvider)
{
return new PromotionsSettings { Show = true };
}
}
}