[Create(@"{code}", false, false)] //NOTE: this method doesn't requires auth!!!  //NOTE: this method doesn't check payment!!!
        public AuthenticationTokenData AuthenticateMe(string userName, string password, string provider, string accessToken, string code)
        {
            bool viaEmail;
            var  user = GetUser(userName, password, provider, accessToken, out viaEmail);

            try
            {
                SmsManager.ValidateSmsCode(user, code);

                var token = SecurityContext.AuthenticateMe(user.ID);

                MessageService.Send(Request, MessageAction.LoginSuccessViaApiSms);

                var tenant  = CoreContext.TenantManager.GetCurrentTenant().TenantId;
                var expires = TenantCookieSettings.GetExpiresTime(tenant);

                return(new AuthenticationTokenData
                {
                    Token = token,
                    Expires = new ApiDateTime(expires),
                    Sms = true,
                    PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone)
                });
            }
            catch
            {
                MessageService.Send(Request, user.DisplayUserName(false), MessageAction.LoginFailViaApiSms, MessageTarget.Create(user.ID));
                throw new AuthenticationException("User authentication failed");
            }
            finally
            {
                SecurityContext.Logout();
            }
        }
Пример #2
0
        private void RequestCode(HttpContext context)
        {
            var token = GetToken(context.Request["code"]);

            if (token == null)
            {
                Global.Logger.Error("BoxApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var boxUserId = context.Request["userId"];

            if (SecurityContext.IsAuthenticated)
            {
                if (!CurrentUser(boxUserId))
                {
                    Global.Logger.Debug("BoxApp: logout for " + boxUserId);
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    SecurityContext.Logout();
                }
            }

            if (!SecurityContext.IsAuthenticated)
            {
                bool isNew;
                var  userInfo = GetUserInfo(token, out isNew);

                if (userInfo == null)
                {
                    Global.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);

                if (isNew)
                {
                    UserHelpTourHelper.IsNewUser    = true;
                    PersonalSettings.IsNewUser      = true;
                    PersonalSettings.IsNotActivated = true;
                }

                if (!string.IsNullOrEmpty(boxUserId) && !CurrentUser(boxUserId))
                {
                    AddLinker(boxUserId);
                }
            }

            Token.SaveToken(token);

            var fileId = context.Request["id"];

            context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
        }
        [Create(@"", false, false)] //NOTE: this method doesn't requires auth!!!  //NOTE: this method doesn't check payment!!!
        public AuthenticationTokenData AuthenticateMe(string userName, string password, string provider, string accessToken)
        {
            bool viaEmail;
            var  user = GetUser(userName, password, provider, accessToken, out viaEmail);

            if (!StudioSmsNotificationSettings.IsVisibleSettings || !StudioSmsNotificationSettings.Enable)
            {
                try
                {
                    var token = SecurityContext.AuthenticateMe(user.ID);

                    MessageService.Send(Request, viaEmail ? MessageAction.LoginSuccessViaApi : MessageAction.LoginSuccessViaApiSocialAccount);

                    var tenant  = CoreContext.TenantManager.GetCurrentTenant().TenantId;
                    var expires = TenantCookieSettings.GetExpiresTime(tenant);

                    return(new AuthenticationTokenData
                    {
                        Token = token,
                        Expires = new ApiDateTime(expires)
                    });
                }
                catch
                {
                    MessageService.Send(Request, user.DisplayUserName(false), viaEmail ? MessageAction.LoginFailViaApi : MessageAction.LoginFailViaApiSocialAccount);
                    throw new AuthenticationException("User authentication failed");
                }
                finally
                {
                    SecurityContext.Logout();
                }
            }

            if (string.IsNullOrEmpty(user.MobilePhone) || user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
            {
                return new AuthenticationTokenData
                       {
                           Sms = true
                       }
            }
            ;

            SmsManager.PutAuthCode(user, false);

            return(new AuthenticationTokenData
            {
                Sms = true,
                PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
                Expires = new ApiDateTime(DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval))
            });
        }
Пример #4
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            LoginProfile loginProfile = null;

            try
            {
                loginProfile = new GoogleLoginProvider().GetLoginProfile(token.ToString());
            }
            catch (Exception ex)
            {
                Global.Logger.Error("GoogleDriveApp: userinfo request", ex);
            }

            if (loginProfile == null)
            {
                Global.Logger.Error("Error in userinfo request");
                return(null);
            }

            var userInfo = CoreContext.UserManager.GetUserByEmail(loginProfile.EMail);

            if (Equals(userInfo, Constants.LostUser))
            {
                userInfo = LoginWithThirdParty.ProfileToUserInfo(loginProfile);

                var cultureName = loginProfile.Locale;
                if (string.IsNullOrEmpty(cultureName))
                {
                    cultureName = Thread.CurrentThread.CurrentUICulture.Name;
                }

                var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.Name, cultureName, StringComparison.InvariantCultureIgnoreCase));
                if (cultureInfo != null)
                {
                    userInfo.CultureName = cultureInfo.Name;
                }
                else
                {
                    Global.Logger.DebugFormat("From google app new personal user '{0}' without culture {1}", userInfo.Email, cultureName);
                }

                try
                {
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                    userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword());
                }
                finally
                {
                    SecurityContext.Logout();
                }

                isNew = true;

                Global.Logger.Debug("GoogleDriveApp: new user " + userInfo.ID);
            }

            return(userInfo);
        }
Пример #5
0
        private static void RequestCode(HttpContext context)
        {
            var state = context.Request["state"];

            Global.Logger.Debug("GoogleDriveApp: state - " + state);
            if (string.IsNullOrEmpty(state))
            {
                Global.Logger.Error("GoogleDriveApp: empty state");
                throw new Exception("Empty state");
            }

            var token = GetToken(context.Request["code"]);

            if (token == null)
            {
                Global.Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var stateJson = JObject.Parse(state);

            var googleUserId = stateJson.Value <string>("userId");

            if (SecurityContext.IsAuthenticated)
            {
                if (!CurrentUser(googleUserId))
                {
                    Global.Logger.Debug("GoogleDriveApp: logout for " + googleUserId);
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    SecurityContext.Logout();
                }
            }

            if (!SecurityContext.IsAuthenticated)
            {
                bool isNew;
                var  userInfo = GetUserInfo(token, out isNew);

                if (userInfo == null)
                {
                    Global.Logger.Error("GoogleDriveApp: 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.LoginSuccessViaSocialAccount);

                if (isNew)
                {
                    UserHelpTourHelper.IsNewUser    = true;
                    PersonalSettings.IsNewUser      = true;
                    PersonalSettings.IsNotActivated = true;
                }

                if (!string.IsNullOrEmpty(googleUserId) && !CurrentUser(googleUserId))
                {
                    AddLinker(googleUserId);
                }
            }

            Token.SaveToken(token);

            var action = stateJson.Value <string>("action");

            switch (action)
            {
            case "create":
                var folderId = stateJson.Value <string>("folderId");

                context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FolderId + "=" + HttpUtility.UrlEncode(folderId), true);
                return;

            case "open":
                var idsArray = stateJson.Value <JArray>("ids") ?? stateJson.Value <JArray>("exportIds");
                if (idsArray == null)
                {
                    Global.Logger.Error("GoogleDriveApp: ids is empty");
                    throw new Exception("File id is null");
                }
                var fileId = idsArray.ToObject <List <string> >().FirstOrDefault();

                var driveFile = GetDriveFile(fileId, token);
                if (driveFile == null)
                {
                    Global.Logger.Error("GoogleDriveApp: file is null");
                    throw new Exception("File not found");
                }

                var jsonFile = JObject.Parse(driveFile);
                var ext      = GetCorrectExt(jsonFile);
                if (FileUtility.ExtsMustConvert.Contains(ext) ||
                    GoogleLoginProvider.GoogleDriveExt.Contains(ext))
                {
                    Global.Logger.Debug("GoogleDriveApp: file must be converted");
                    if (FilesSettings.ConvertNotify)
                    {
                        context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId), true);
                        return;
                    }

                    fileId = CreateConvertedFile(driveFile, token);
                }

                context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(ThirdPartySelector.BuildAppFileId(AppAttr, fileId)), true);
                return;
            }
            Global.Logger.Error("GoogleDriveApp: Action not identified");
            throw new Exception("Action not identified");
        }
Пример #6
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                SetProgress(5, "Setup tenant");

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                SetProgress(10, "Setup user");

                SecurityContext.AuthenticateMe(CurrentUser); //Core.Configuration.Constants.CoreSystem);

                SetProgress(15, "Find user data");

                var currentUser = CoreContext.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 = Resources.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);
                }
            }
        }
Пример #7
0
        public void RunJob(DistributedTask _, CancellationToken cancellationToken)
        {
            try
            {
                CancellationToken = cancellationToken;

                CoreContext.TenantManager.SetCurrentTenant(CurrentTenant);

                SecurityContext.AuthenticateMe(Core.Configuration.Constants.CoreSystem);

                Thread.CurrentThread.CurrentCulture   = CultureInfo.GetCultureInfo(_culture);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(_culture);

                Logger = LogManager.GetLogger("ASC");

                if (LDAPSettings == null)
                {
                    Error = Resource.LdapSettingsErrorCantGetLdapSettings;
                    Logger.Error("Can't save default LDAP settings.");
                    return;
                }

                switch (OperationType)
                {
                case LdapOperationType.Save:
                case LdapOperationType.SaveTest:

                    Logger.InfoFormat("Start '{0}' operation",
                                      Enum.GetName(typeof(LdapOperationType), OperationType));

                    SetProgress(1, Resource.LdapSettingsStatusCheckingLdapSettings);

                    Logger.Debug("PrepareSettings()");

                    PrepareSettings(LDAPSettings);

                    if (!string.IsNullOrEmpty(Error))
                    {
                        Logger.DebugFormat("PrepareSettings() Error: {0}", Error);
                        return;
                    }

                    Importer = new NovellLdapUserImporter(LDAPSettings, Resource);

                    if (LDAPSettings.EnableLdapAuthentication)
                    {
                        var ldapSettingsChecker = new NovellLdapSettingsChecker(Importer);

                        SetProgress(5, Resource.LdapSettingsStatusLoadingBaseInfo);

                        var result = ldapSettingsChecker.CheckSettings();

                        if (result != LdapSettingsStatus.Ok)
                        {
                            if (result == LdapSettingsStatus.CertificateRequest)
                            {
                                TaskInfo.SetProperty(CERT_REQUEST,
                                                     ldapSettingsChecker.CertificateConfirmRequest);
                            }

                            Error = GetError(result);

                            Logger.DebugFormat("ldapSettingsChecker.CheckSettings() Error: {0}", Error);

                            return;
                        }
                    }

                    break;

                case LdapOperationType.Sync:
                case LdapOperationType.SyncTest:
                    Logger.InfoFormat("Start '{0}' operation",
                                      Enum.GetName(typeof(LdapOperationType), OperationType));

                    Importer = new NovellLdapUserImporter(LDAPSettings, Resource);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                Do();
            }
            catch (AuthorizingException authError)
            {
                Error = Resource.ErrorAccessDenied;
                Logger.Error(Error, new SecurityException(Error, authError));
            }
            catch (AggregateException ae)
            {
                ae.Flatten().Handle(e => e is TaskCanceledException || e is OperationCanceledException);
            }
            catch (TenantQuotaException e)
            {
                Error = Resource.LdapSettingsTenantQuotaSettled;
                Logger.ErrorFormat("TenantQuotaException. {0}", e);
            }
            catch (FormatException e)
            {
                Error = Resource.LdapSettingsErrorCantCreateUsers;
                Logger.ErrorFormat("FormatException error. {0}", e);
            }
            catch (Exception e)
            {
                Error = Resource.LdapSettingsInternalServerError;
                Logger.ErrorFormat("Internal server error. {0}", e);
            }
            finally
            {
                try
                {
                    TaskInfo.SetProperty(FINISHED, true);
                    PublishTaskInfo();
                    Dispose();
                    SecurityContext.Logout();
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("LdapOperation finalization problem. {0}", ex);
                }
            }
        }
Пример #8
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("BoxApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = string.Empty;

            try
            {
                resultResponse = RequestHelper.PerformRequest(BoxUrlUserInfo,
                                                              headers: new Dictionary <string, string> {
                    { "Authorization", "Bearer " + token }
                });
                Global.Logger.Debug("BoxApp: userinfo response - " + resultResponse);
            }
            catch (Exception ex)
            {
                Global.Logger.Error("BoxApp: userinfo request", ex);
            }

            var boxUserInfo = JObject.Parse(resultResponse);

            if (boxUserInfo == null)
            {
                Global.Logger.Error("Error in userinfo request");
                return(null);
            }

            var email    = boxUserInfo.Value <string>("login");
            var userInfo = CoreContext.UserManager.GetUserByEmail(email);

            if (Equals(userInfo, Constants.LostUser))
            {
                userInfo = new UserInfo
                {
                    FirstName   = boxUserInfo.Value <string>("name"),
                    Email       = email,
                    MobilePhone = boxUserInfo.Value <string>("phone"),
                };

                var cultureName = boxUserInfo.Value <string>("language");
                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)
                {
                    userInfo.CultureName = cultureInfo.Name;
                }
                else
                {
                    Global.Logger.DebugFormat("From box app new personal user '{0}' without culture {1}", userInfo.Email, cultureName);
                }

                if (string.IsNullOrEmpty(userInfo.FirstName))
                {
                    userInfo.FirstName = FilesCommonResource.UnknownFirstName;
                }
                if (string.IsNullOrEmpty(userInfo.LastName))
                {
                    userInfo.LastName = FilesCommonResource.UnknownLastName;
                }

                try
                {
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                    userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword());
                }
                finally
                {
                    SecurityContext.Logout();
                }

                isNew = true;

                Global.Logger.Debug("BoxApp: new user " + userInfo.ID);
            }

            return(userInfo);
        }
Пример #9
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = RequestHelper.PerformRequest(GoogleUrlUserInfo.Replace("{access_token}", token.AccessToken));

            Global.Logger.Debug("GoogleDriveApp: userinfo response - " + resultResponse);

            var googleUserInfo = JObject.Parse(resultResponse);

            if (googleUserInfo == null)
            {
                Global.Logger.Error("Error in userinfo request");
                return(null);
            }

            var email    = googleUserInfo.Value <string>("email");
            var userInfo = CoreContext.UserManager.GetUserByEmail(email);

            if (Equals(userInfo, Constants.LostUser))
            {
                userInfo = new UserInfo
                {
                    Status       = EmployeeStatus.Active,
                    FirstName    = googleUserInfo.Value <string>("given_name"),
                    LastName     = googleUserInfo.Value <string>("family_name"),
                    Email        = email,
                    WorkFromDate = TenantUtil.DateTimeNow(),
                };

                var gender = googleUserInfo.Value <string>("gender");
                if (!string.IsNullOrEmpty(gender))
                {
                    userInfo.Sex = gender == "male";
                }

                var cultureName = googleUserInfo.Value <string>("locale") ?? CultureInfo.CurrentUICulture.Name;
                var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.TwoLetterISOLanguageName, cultureName, StringComparison.InvariantCultureIgnoreCase));
                if (cultureInfo != null)
                {
                    userInfo.CultureName = cultureInfo.Name;
                }

                if (string.IsNullOrEmpty(userInfo.FirstName))
                {
                    userInfo.FirstName = FilesCommonResource.UnknownFirstName;
                }
                if (string.IsNullOrEmpty(userInfo.LastName))
                {
                    userInfo.LastName = FilesCommonResource.UnknownLastName;
                }

                var pwd = UserManagerWrapper.GeneratePassword();

                try
                {
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                    userInfo = UserManagerWrapper.AddUser(userInfo, pwd);
                }
                finally
                {
                    SecurityContext.Logout();
                }

                isNew = true;

                Global.Logger.Debug("GoogleDriveApp: new user " + userInfo.ID);
            }

            return(userInfo);
        }
Пример #10
0
        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (MobileDetector.IsRequestMatchesMobile(Context))
            {
                Response.Redirect(CommonLinkUtility.GetFileWebViewerUrl(Request[UrlConstant.FileId]) +
                                  (string.IsNullOrEmpty(Request[UrlConstant.DocUrlKey]) ? "" : "&" + UrlConstant.DocUrlKey + "=" + Request[UrlConstant.DocUrlKey]));
            }

            if (!FileUtility.EnableHtml5)
            {
                Server.Transfer("editor.aspx", true);
            }

            //check if cookie from this portal
            if (SecurityContext.CurrentAccount is IUserAccount &&
                ((IUserAccount)SecurityContext.CurrentAccount).Tenant != CoreContext.TenantManager.GetCurrentTenant().TenantId)
            {
                SecurityContext.Logout();
                Response.Redirect("~/");
            }

            var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

            if (currentUser == Constants.LostUser || currentUser.Status != EmployeeStatus.Active)
            {
                SecurityContext.Logout();
                Response.Redirect("~/");
            }

            ProcessSecureFilter();

            if (!SecurityContext.IsAuthenticated &&
                DocumentUtils.ParseShareLink(Request[UrlConstant.DocUrlKey]) == null)
            {
                //for demo
                if (SetupInfo.WorkMode == WorkMode.Promo)
                {
                    if (AutoAuthByPromo())
                    {
                        UserOnlineManager.Instance.RegistryOnlineUser(SecurityContext.CurrentAccount.ID);

                        Response.Redirect("~/");
                        return;
                    }
                }

                var refererURL = Request.GetUrlRewriter().AbsoluteUri;
                if (!ValidateRefererUrl(refererURL))
                {
                    refererURL = (string)Session["refererURL"];
                }

                if (!AutoAuthByCookies() && !CoreContext.TenantManager.GetCurrentTenant().Public)
                {
                    Session["refererURL"] = refererURL;
                    Response.Redirect("~/auth.aspx");
                    return;
                }
            }

            if (SecurityContext.IsAuthenticated)
            {
                UserOnlineManager.Instance.RegistryOnlineUser(SecurityContext.CurrentAccount.ID);
            }

            CurrentSkin = WebSkin.GetUserSkin();
            Theme       = CurrentSkin.ASPTheme;
        }
Пример #11
0
        internal static void RequestCode(HttpContext context)
        {
            var state = context.Request["state"];

            Global.Logger.Debug("GoogleDriveApp: state - " + state);
            if (string.IsNullOrEmpty(state))
            {
                Global.Logger.Info("GoogleDriveApp: empty state");
                throw new Exception("Empty state");
            }

            var token = GetToken(context.Request["code"]);

            if (token == null)
            {
                Global.Logger.Info("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var stateJson = JObject.Parse(state);

            if (SecurityContext.IsAuthenticated)
            {
                Global.Logger.Debug("GoogleDriveApp: is authenticated");

                if (!CurrentUser(stateJson.Value <string>("userId")))
                {
                    Global.Logger.Debug("GoogleDriveApp: logout");
                    CookiesManager.ClearCookies(CookiesType.AuthKey);
                    SecurityContext.Logout();
                }
            }

            if (!SecurityContext.IsAuthenticated)
            {
                var userInfo = GetUserInfo(token);

                if (userInfo == null)
                {
                    Global.Logger.Error("GoogleDriveApp: UserInfo is null");
                    throw new Exception("Profile is null");
                }

                var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
            }

            Token.SaveToken(token);

            var action = stateJson.Value <string>("action");

            switch (action)
            {
            case "create":
                var folderId = stateJson.Value <string>("folderId");

                context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FolderId + "=" + folderId, true);
                return;

            case "open":
                var idsArray = stateJson.Value <JArray>("ids") ?? stateJson.Value <JArray>("exportIds");
                if (idsArray == null)
                {
                    Global.Logger.Error("GoogleDriveApp: ids is empty");
                    throw new Exception("File id is null");
                }
                var fileId = idsArray.ToObject <List <string> >().FirstOrDefault();

                var driveFile = GetDriveFile(fileId, token);
                if (driveFile == null)
                {
                    Global.Logger.Error("GoogleDriveApp: file is null");
                    throw new Exception("File not found");
                }

                var jsonFile = JObject.Parse(driveFile);
                var ext      = GetCorrectExt(jsonFile);
                var mimeType = (jsonFile.Value <string>("mimeType") ?? "").ToLower();
                if (FileUtility.ExtsMustConvert.Contains(ext) ||
                    GoogleMimeTypes.Keys.Contains(mimeType))
                {
                    Global.Logger.Debug("GoogleDriveApp: file must be converted");
                    if (FilesSettings.ConvertNotify)
                    {
                        context.Response.Redirect(App.Location + "?" + FilesLinkUtility.FileId + "=" + fileId, true);
                        return;
                    }

                    fileId = CreateConvertedFile(driveFile, token);
                }

                context.Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(fileId) + "&" + FilesLinkUtility.Action + "=app", true);
                return;
            }
            Global.Logger.Error("GoogleDriveApp: Action not identified");
            throw new Exception("Action not identified");
        }
Пример #12
0
        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (!FileUtility.EnableHtml5)
            {
                Server.Transfer("viewer.aspx", true);
            }

            //check if cookie from this portal
            if (SecurityContext.CurrentAccount is IUserAccount &&
                ((IUserAccount)SecurityContext.CurrentAccount).Tenant != CoreContext.TenantManager.GetCurrentTenant().TenantId)
            {
                SecurityContext.Logout();
                Response.Redirect("~/");
            }

            var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

            if (currentUser == Constants.LostUser || currentUser.Status != EmployeeStatus.Active)
            {
                SecurityContext.Logout();
                Response.Redirect("~/");
            }

            ProcessSecureFilter();

            if (!SecurityContext.IsAuthenticated &&
                DocumentUtils.ParseShareLink(Request[UrlConstant.DocUrlKey]) == null)
            {
                //for demo
                if (SetupInfo.WorkMode == WorkMode.Promo)
                {
                    if (AutoAuthByPromo())
                    {
                        UserOnlineManager.Instance.RegistryOnlineUser(SecurityContext.CurrentAccount.ID);

                        Response.Redirect("~/");
                        return;
                    }
                }

                var refererURL = Request.GetUrlRewriter().AbsoluteUri;
                if (!ValidateRefererUrl(refererURL))
                {
                    refererURL = (string)Session["refererURL"];
                }

                if (!AutoAuthByCookies() && !CoreContext.TenantManager.GetCurrentTenant().Public)
                {
                    Session["refererURL"] = refererURL;
                    Response.Redirect("~/auth.aspx");
                    return;
                }
            }

            if (SecurityContext.IsAuthenticated)
            {
                UserOnlineManager.Instance.RegistryOnlineUser(SecurityContext.CurrentAccount.ID);

                //try
                //{
                //    StatisticManager.SaveUserVisit(TenantProvider.CurrentTenantID, SecurityContext.CurrentAccount.ID,
                //                                                     (currentProduct == null ? Guid.Empty : currentProduct.ProductID));
                //}
                //catch (Exception exc)
                //{
                //    Log.Error("failed save user visit", exc);
                //}
            }

            CurrentSkin = WebSkin.GetUserSkin();
            Theme       = CurrentSkin.ASPTheme;
        }
Пример #13
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = string.Empty;

            try
            {
                resultResponse = RequestHelper.PerformRequest(GoogleUrlUserInfo.Replace("{access_token}", HttpUtility.UrlEncode(token.ToString())));
                Global.Logger.Debug("GoogleDriveApp: userinfo response - " + resultResponse);
            }
            catch (Exception ex)
            {
                Global.Logger.Error("GoogleDriveApp: userinfo request", ex);
            }

            var googleUserInfo = JObject.Parse(resultResponse);

            if (googleUserInfo == null)
            {
                Global.Logger.Error("Error in userinfo request");
                return(null);
            }

            var email    = googleUserInfo.Value <string>("email");
            var userInfo = CoreContext.UserManager.GetUserByEmail(email);

            if (Equals(userInfo, Constants.LostUser))
            {
                userInfo = new UserInfo
                {
                    FirstName = googleUserInfo.Value <string>("given_name"),
                    LastName  = googleUserInfo.Value <string>("family_name"),
                    Email     = email,
                };

                var gender = googleUserInfo.Value <string>("gender");
                if (!string.IsNullOrEmpty(gender))
                {
                    userInfo.Sex = gender == "male";
                }

                var cultureName = googleUserInfo.Value <string>("locale");
                if (string.IsNullOrEmpty(cultureName))
                {
                    cultureName = Thread.CurrentThread.CurrentUICulture.Name;
                }

                var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.Name, cultureName, StringComparison.InvariantCultureIgnoreCase));
                if (cultureInfo != null)
                {
                    userInfo.CultureName = cultureInfo.Name;
                }
                else
                {
                    Global.Logger.DebugFormat("From google app new personal user '{0}' without culture {1}", userInfo.Email, cultureName);
                }

                if (string.IsNullOrEmpty(userInfo.FirstName))
                {
                    userInfo.FirstName = FilesCommonResource.UnknownFirstName;
                }
                if (string.IsNullOrEmpty(userInfo.LastName))
                {
                    userInfo.LastName = FilesCommonResource.UnknownLastName;
                }

                var pwd = UserManagerWrapper.GeneratePassword();

                try
                {
                    SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                    userInfo = UserManagerWrapper.AddUser(userInfo, pwd);
                }
                finally
                {
                    SecurityContext.Logout();
                }

                isNew = true;

                Global.Logger.Debug("GoogleDriveApp: new user " + userInfo.ID);
            }

            return(userInfo);
        }
        [Create(@"register", false)] //NOTE: this method doesn't requires auth!!!
        public string RegisterUserOnPersonal(string email, string lang, bool spam, bool analytics)
        {
            if (!CoreContext.Configuration.Personal)
            {
                throw new MethodAccessException("Method is only available on personal.onlyoffice.com");
            }

            try
            {
                if (CoreContext.Configuration.CustomMode)
                {
                    lang = "ru-RU";
                }

                var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.TwoLetterISOLanguageName, lang, StringComparison.InvariantCultureIgnoreCase));
                if (cultureInfo != null)
                {
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;
                }

                email.ThrowIfNull(new ArgumentException(Resource.ErrorEmailEmpty, "email"));

                if (!email.TestEmailRegex())
                {
                    throw new ArgumentException(Resource.ErrorNotCorrectEmail, "email");
                }

                var newUserInfo = CoreContext.UserManager.GetUserByEmail(email);

                if (CoreContext.UserManager.UserExists(newUserInfo.ID))
                {
                    if (!SetupInfo.IsSecretEmail(email) || SecurityContext.IsAuthenticated)
                    {
                        throw new Exception(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
                    }

                    try
                    {
                        SecurityContext.AuthenticateMe(Constants.CoreSystem);
                        CoreContext.UserManager.DeleteUser(newUserInfo.ID);
                    }
                    finally
                    {
                        SecurityContext.Logout();
                    }
                }
                if (!spam)
                {
                    try
                    {
                        const string _databaseID = "com";
                        using (var db = DbManager.FromHttpContext(_databaseID))
                        {
                            db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
                                               .InColumnValue("email", email.ToLowerInvariant())
                                               .InColumnValue("reason", "personal")
                                               );
                            LogManager.GetLogger("ASC.Web").Debug(String.Format("Write to template_unsubscribe {0}", email.ToLowerInvariant()));
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.GetLogger("ASC.Web").Debug(String.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, email.ToLowerInvariant()));
                    }
                }
                StudioNotifyService.Instance.SendInvitePersonal(email, String.Empty, analytics);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            return(string.Empty);
        }
Пример #15
0
        [Create(@"register", false)] //NOTE: This method doesn't require auth!!!
        public string RegisterUserOnPersonal(string email, string lang, bool spam, string recaptchaResponse)
        {
            if (!CoreContext.Configuration.Personal)
            {
                throw new MethodAccessException("Method is only available on personal.onlyoffice.com");
            }

            try
            {
                if (CoreContext.Configuration.CustomMode)
                {
                    lang = "ru-RU";
                }

                var cultureInfo = SetupInfo.GetPersonalCulture(lang).Value;

                if (cultureInfo != null)
                {
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;
                }

                email.ThrowIfNull(new ArgumentException(Resource.ErrorEmailEmpty, "email"));

                if (!email.TestEmailRegex())
                {
                    throw new ArgumentException(Resource.ErrorNotCorrectEmail, "email");
                }

                if (!SetupInfo.IsSecretEmail(email) &&
                    !string.IsNullOrEmpty(SetupInfo.RecaptchaPublicKey) && !string.IsNullOrEmpty(SetupInfo.RecaptchaPrivateKey))
                {
                    var ip = Request.Headers["X-Forwarded-For"] ?? Request.UserHostAddress;

                    if (String.IsNullOrEmpty(recaptchaResponse) ||
                        !Authorize.ValidateRecaptcha(recaptchaResponse, ip))
                    {
                        throw new Authorize.RecaptchaException(Resource.RecaptchaInvalid);
                    }
                }

                var newUserInfo = CoreContext.UserManager.GetUserByEmail(email);

                if (CoreContext.UserManager.UserExists(newUserInfo.ID))
                {
                    if (!SetupInfo.IsSecretEmail(email) || SecurityContext.IsAuthenticated)
                    {
                        throw new Exception(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
                    }

                    try
                    {
                        SecurityContext.CurrentAccount = Constants.CoreSystem;
                        CoreContext.UserManager.DeleteUser(newUserInfo.ID);
                    }
                    finally
                    {
                        SecurityContext.Logout();
                    }
                }
                if (!spam)
                {
                    try
                    {
                        const string _databaseID = "com";
                        using (var db = DbManager.FromHttpContext(_databaseID))
                        {
                            db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
                                               .InColumnValue("email", email.ToLowerInvariant())
                                               .InColumnValue("reason", "personal")
                                               );
                            Log.Debug(String.Format("Write to template_unsubscribe {0}", email.ToLowerInvariant()));
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Debug(String.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, email.ToLowerInvariant()));
                    }
                }
                StudioNotifyService.Instance.SendInvitePersonal(email);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            return(string.Empty);
        }
Пример #16
0
        [Create(@"{code}", false, false)] //NOTE: This method doesn't require auth!!!  //NOTE: This method doesn't check payment!!!
        public AuthenticationTokenData AuthenticateMe(string userName, string password, string provider, string accessToken, string code, string codeOAuth)
        {
            bool viaEmail;
            var  user = GetUser(userName, password, provider, accessToken, out viaEmail, codeOAuth);

            var sms = false;

            try
            {
                if (StudioSmsNotificationSettings.IsVisibleAndAvailableSettings && StudioSmsNotificationSettings.Enable)
                {
                    sms = true;

                    SmsManager.ValidateSmsCode(user, code, true);
                }
                else if (TfaAppAuthSettings.IsVisibleSettings && TfaAppAuthSettings.Enable)
                {
                    if (user.ValidateAuthCode(code, true, true))
                    {
                        MessageService.Send(Request, MessageAction.UserConnectedTfaApp, MessageTarget.Create(user.ID));
                    }
                }
                else
                {
                    throw new SecurityException("Auth code is not available");
                }

                var token   = CookiesManager.AuthenticateMeAndSetCookies(user.Tenant, user.ID, MessageAction.LoginSuccess);
                var tenant  = CoreContext.TenantManager.GetCurrentTenant().TenantId;
                var expires = TenantCookieSettings.GetExpiresTime(tenant);

                var result = new AuthenticationTokenData
                {
                    Token   = token,
                    Expires = new ApiDateTime(expires)
                };

                if (sms)
                {
                    result.Sms        = true;
                    result.PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone);
                }
                else
                {
                    result.Tfa = true;
                }

                return(result);
            }
            catch
            {
                MessageService.Send(Request, user.DisplayUserName(false), sms
                                                                              ? MessageAction.LoginFailViaApiSms
                                                                              : MessageAction.LoginFailViaApiTfa,
                                    MessageTarget.Create(user.ID));
                throw new AuthenticationException("User authentication failed");
            }
            finally
            {
                SecurityContext.Logout();
            }
        }