Exemple #1
0
        private void UserAuth(UserInfo user)
        {
            if (SecurityContext.IsAuthenticated)
            {
                return;
            }

            if (StudioSmsNotificationSettings.IsVisibleAndAvailableSettings && StudioSmsNotificationSettings.Enable)
            {
                Response.Redirect(Request.AppendRefererURL(Confirm.SmsConfirmUrl(user)), true);
                return;
            }
            if (TfaAppAuthSettings.IsVisibleSettings && TfaAppAuthSettings.Enable)
            {
                Response.Redirect(Request.AppendRefererURL(Confirm.TfaConfirmUrl(user)), true);
                return;
            }
            try
            {
                CookiesManager.AuthenticateMeAndSetCookies(user.Tenant, user.ID, MessageAction.LoginSuccess);
            }
            catch (Exception ex)
            {
                ShowError(ex.Message);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var accountLink = (AccountLinkControl)LoadControl(AccountLinkControl.Location);

            accountLink.ClientCallback = "loginJoinCallback";
            accountLink.SettingsView   = false;
            accountLink.RenderDisabled = RenderDisabled;
            ThirdPartyList.Controls.Add(accountLink);

            var loginProfile = Request.Url.GetProfile();

            if (loginProfile == null && !IsPostBack || SecurityContext.IsAuthenticated)
            {
                return;
            }

            string cookiesKey = string.Empty;

            try
            {
                if (loginProfile == null)
                {
                    if (string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) || Request["__EVENTTARGET"] != "thirdPartyLogin")
                    {
                        return;
                    }

                    loginProfile = new LoginProfile(Request["__EVENTARGUMENT"]);
                }

                var userInfo = GetUserByThirdParty(loginProfile);
                if (!CoreContext.UserManager.UserExists(userInfo.ID))
                {
                    return;
                }

                cookiesKey = CookiesManager.AuthenticateMeAndSetCookies(userInfo.Tenant, userInfo.ID, MessageAction.LoginSuccessViaSocialAccount);
            }
            catch (System.Security.SecurityException)
            {
                LoginMessage = Resource.InvalidUsernameOrPassword;
                MessageService.Send(HttpContext.Current.Request, loginProfile != null ? loginProfile.EMail : AuditResource.EmailNotSpecified, MessageAction.LoginFailDisabledProfile);
                return;
            }
            catch (Exception exception)
            {
                LoginMessage = exception.Message;
                MessageService.Send(HttpContext.Current.Request, AuditResource.EmailNotSpecified, MessageAction.LoginFail);
                return;
            }

            var refererURL = Context.GetRefererURL();

            Response.Redirect(
                Request.DesktopApp()
                              ? refererURL + ((refererURL.Contains("?") ? "&" : "?") + "token=" + HttpUtility.HtmlEncode(cookiesKey))
                              : refererURL);
        }
Exemple #3
0
        public static bool ValidateAuthCode(this UserInfo user, string code, bool checkBackup = true, bool isEntryPoint = false)
        {
            if (!TfaAppAuthSettings.IsVisibleSettings ||
                !TfaAppAuthSettings.Enable)
            {
                return(false);
            }

            if (user == null || Equals(user, Constants.LostUser))
            {
                throw new Exception(Resource.ErrorUserNotFound);
            }

            code = (code ?? "").Trim();

            if (string.IsNullOrEmpty(code))
            {
                throw new Exception(Resource.ActivateTfaAppEmptyCode);
            }

            int counter;

            int.TryParse(Cache.Get <string>("tfa/" + user.ID), out counter);
            if (++counter > SetupInfo.LoginThreshold)
            {
                throw new Authorize.BruteForceCredentialException(Resource.TfaTooMuchError);
            }
            Cache.Insert("tfa/" + user.ID, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

            if (!Tfa.ValidateTwoFactorPIN(GenerateAccessToken(user), code))
            {
                if (checkBackup && TfaAppUserSettings.BackupCodesForUser(user.ID).Any(x => x.Code == code && !x.IsUsed))
                {
                    TfaAppUserSettings.DisableCodeForUser(user.ID, code);
                }
                else
                {
                    throw new ArgumentException(Resource.TfaAppAuthMessageError);
                }
            }

            Cache.Insert("tfa/" + user.ID, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

            if (!SecurityContext.IsAuthenticated)
            {
                var action = isEntryPoint ? MessageAction.LoginSuccessViaApiTfa : MessageAction.LoginSuccesViaTfaApp;
                CookiesManager.AuthenticateMeAndSetCookies(user.Tenant, user.ID, action);
            }

            if (!TfaAppUserSettings.EnableForUser(user.ID))
            {
                user.GenerateBackupCodes();
                return(true);
            }

            return(false);
        }
Exemple #4
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");
                }

                CookiesManager.AuthenticateMeAndSetCookies(userInfo.Tenant, userInfo.ID, 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);
        }
Exemple #5
0
        public static void ValidateSmsCode(UserInfo user, string code, bool isEntryPoint = false)
        {
            if (!StudioSmsNotificationSettings.IsVisibleAndAvailableSettings ||
                !StudioSmsNotificationSettings.Enable)
            {
                return;
            }

            if (user == null || Equals(user, Constants.LostUser))
            {
                throw new Exception(Resource.ErrorUserNotFound);
            }

            var valid = SmsKeyStorage.ValidateKey(user.MobilePhone, code);

            switch (valid)
            {
            case SmsKeyStorage.Result.Empty:
                throw new Exception(Resource.ActivateMobilePhoneEmptyCode);

            case SmsKeyStorage.Result.TooMuch:
                throw new Authorize.BruteForceCredentialException(Resource.SmsTooMuchError);

            case SmsKeyStorage.Result.Timeout:
                throw new TimeoutException(Resource.SmsAuthenticationTimeout);

            case SmsKeyStorage.Result.Invalide:
                throw new ArgumentException(Resource.SmsAuthenticationMessageError);
            }
            if (valid != SmsKeyStorage.Result.Ok)
            {
                throw new Exception("Error: " + valid);
            }

            if (!SecurityContext.IsAuthenticated)
            {
                var action = isEntryPoint ? MessageAction.LoginSuccessViaApiSms : MessageAction.LoginSuccessViaSms;
                CookiesManager.AuthenticateMeAndSetCookies(user.Tenant, user.ID, action);
            }

            if (user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
            {
                user.MobilePhoneActivationStatus = MobilePhoneActivationStatus.Activated;
                CoreContext.UserManager.SaveUserInfo(user);
            }
        }
Exemple #6
0
        private bool AuthProcess(LoginProfile thirdPartyProfile, bool withAccountLink)
        {
            var authMethod   = AuthMethod.Login;
            var tfaLoginUrl  = string.Empty;
            var loginCounter = 0;

            ShowRecaptcha = false;
            try
            {
                if (thirdPartyProfile != null)
                {
                    if (string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError))
                    {
                        HashId = thirdPartyProfile.HashId;
                        Login  = thirdPartyProfile.EMail;
                    }
                    else
                    {
                        // ignore cancellation
                        if (thirdPartyProfile.AuthorizationError != "Canceled at provider")
                        {
                            ErrorMessage = thirdPartyProfile.AuthorizationError;
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Request["__EVENTARGUMENT"]) && Request["__EVENTTARGET"] == "signInLogin" && withAccountLink)
                    {
                        HashId = ASC.Common.Utils.Signature.Read <string>(Request["__EVENTARGUMENT"]);
                    }
                }

                if (!string.IsNullOrEmpty(Request["login"]))
                {
                    Login = Request["login"].Trim();
                }
                else if (string.IsNullOrEmpty(HashId))
                {
                    IsLoginInvalid = true;
                    throw new InvalidCredentialException("login");
                }

                if (!string.IsNullOrEmpty(Request["passwordHash"]))
                {
                    PasswordHash = Request["passwordHash"];
                }
                else if (string.IsNullOrEmpty(HashId))
                {
                    IsPasswordInvalid = true;
                    throw new InvalidCredentialException("password");
                }

                if (string.IsNullOrEmpty(HashId) && !SetupInfo.IsSecretEmail(Login))
                {
                    int.TryParse(cache.Get <String>("loginsec/" + Login), out loginCounter);

                    loginCounter++;

                    if (!RecaptchaEnable)
                    {
                        if (loginCounter > SetupInfo.LoginThreshold)
                        {
                            throw new BruteForceCredentialException();
                        }
                    }
                    else
                    {
                        if (loginCounter > SetupInfo.LoginThreshold - 1)
                        {
                            ShowRecaptcha = true;
                        }
                        if (loginCounter > SetupInfo.LoginThreshold)
                        {
                            var ip = Request.Headers["X-Forwarded-For"] ?? Request.UserHostAddress;

                            var recaptchaResponse = Request["g-recaptcha-response"];
                            if (String.IsNullOrEmpty(recaptchaResponse) ||
                                !ValidateRecaptcha(recaptchaResponse, ip))
                            {
                                throw new RecaptchaException();
                            }
                        }
                    }

                    cache.Insert("loginsec/" + Login, loginCounter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }

                var userInfo = GetUser(out authMethod);
                if (!CoreContext.UserManager.UserExists(userInfo.ID) || userInfo.Status != EmployeeStatus.Active)
                {
                    IsLoginInvalid    = true;
                    IsPasswordInvalid = true;
                    throw new InvalidCredentialException();
                }

                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = IPRestrictionsSettings.Load();
                if (settings.Enable && userInfo.ID != tenant.OwnerId && !IPSecurity.IPSecurity.Verify(tenant))
                {
                    throw new IPSecurityException();
                }

                if (StudioSmsNotificationSettings.IsVisibleAndAvailableSettings &&
                    StudioSmsNotificationSettings.Enable)
                {
                    tfaLoginUrl = Studio.Confirm.SmsConfirmUrl(userInfo);
                }
                else if (TfaAppAuthSettings.IsVisibleSettings &&
                         TfaAppAuthSettings.Enable)
                {
                    tfaLoginUrl = Studio.Confirm.TfaConfirmUrl(userInfo);
                }
                else
                {
                    var session = EnableSession && string.IsNullOrEmpty(Request["remember"]);

                    var action = authMethod == AuthMethod.ThirdParty ? MessageAction.LoginSuccessViaSocialAccount : MessageAction.LoginSuccess;
                    CookiesManager.AuthenticateMeAndSetCookies(userInfo.Tenant, userInfo.ID, action, session);
                }
            }
            catch (InvalidCredentialException ex)
            {
                Auth.MessageKey messageKey;
                MessageAction   messageAction;

                if (ex is BruteForceCredentialException)
                {
                    messageKey    = Auth.MessageKey.LoginWithBruteForce;
                    messageAction = MessageAction.LoginFailBruteForce;
                }
                else if (ex is RecaptchaException)
                {
                    messageKey    = Auth.MessageKey.RecaptchaInvalid;
                    messageAction = MessageAction.LoginFailRecaptcha;
                }
                else if (authMethod == AuthMethod.ThirdParty)
                {
                    messageKey    = Auth.MessageKey.LoginWithAccountNotFound;
                    messageAction = MessageAction.LoginFailSocialAccountNotFound;
                }
                else
                {
                    messageKey    = Auth.MessageKey.InvalidUsernameOrPassword;
                    messageAction = MessageAction.LoginFailInvalidCombination;
                }

                var loginName = !string.IsNullOrWhiteSpace(Login)
                                    ? Login
                                    : authMethod == AuthMethod.ThirdParty && !string.IsNullOrWhiteSpace(HashId)
                                          ? HashId
                                          : AuditResource.EmailNotSpecified;

                MessageService.Send(HttpContext.Current.Request, loginName, messageAction);

                Auth.ProcessLogout();

                if (authMethod == AuthMethod.ThirdParty && thirdPartyProfile != null)
                {
                    Response.Redirect("~/Auth.aspx?am=" + (int)messageKey + (Request.DesktopApp() ? "&desktop=true" : ""), true);
                }
                else
                {
                    ErrorMessage = Auth.GetAuthMessage(messageKey);
                }

                return(false);
            }
            catch (SecurityException)
            {
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailDisabledProfile);
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorDisabledProfile;
                return(false);
            }
            catch (IPSecurityException)
            {
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailIpSecurity);
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorIpSecurity;
                return(false);
            }
            catch (Exception ex)
            {
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFail);
                Auth.ProcessLogout();
                ErrorMessage = ex.Message;
                return(false);
            }

            if (loginCounter > 0)
            {
                cache.Insert("loginsec/" + Login, (--loginCounter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
            }

            if (!string.IsNullOrEmpty(tfaLoginUrl))
            {
                if (Request.DesktopApp())
                {
                    tfaLoginUrl += "&desktop=true";
                }

                Response.Redirect(tfaLoginUrl, true);
            }

            return(true);
        }
Exemple #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.RegisterBodyScripts("~/js/third-party/xregexp.js", "~/UserControls/Management/ConfirmInviteActivation/js/confirm_invite_activation.js")
            .RegisterStyle("~/UserControls/Management/ConfirmInviteActivation/css/confirm_invite_activation.less");

            var uid = Guid.Empty;

            try
            {
                uid = new Guid(Request["uid"]);
            }
            catch
            {
            }

            var email = GetEmailAddress();

            if (_type != ConfirmType.Activation && AccountLinkControl.IsNotEmpty && !CoreContext.Configuration.Personal)
            {
                var thrd = (AccountLinkControl)LoadControl(AccountLinkControl.Location);
                thrd.InviteView     = true;
                thrd.ClientCallback = "loginJoinCallback";
                thrdParty.Visible   = true;
                thrdParty.Controls.Add(thrd);
            }

            Page.Title = HeaderStringHelper.GetPageTitle(Resource.Authorization);

            UserInfo user;

            try
            {
                SecurityContext.CurrentAccount = ASC.Core.Configuration.Constants.CoreSystem;

                user = CoreContext.UserManager.GetUserByEmail(email);
                var usr = CoreContext.UserManager.GetUsers(uid);
                if (usr.ID.Equals(Constants.LostUser.ID) || usr.ID.Equals(ASC.Core.Configuration.Constants.Guest.ID))
                {
                    usr = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId);
                }

                var photoData = UserPhotoManager.GetUserPhotoData(usr.ID, UserPhotoManager.MediumFotoSize);

                _userAvatar = photoData == null?usr.GetMediumPhotoURL() : "data:image/png;base64," + Convert.ToBase64String(photoData);

                _userName = usr.DisplayUserName(true);
                _userPost = (usr.Title ?? "").HtmlEncode();
            }
            finally
            {
                SecurityContext.Logout();
            }

            if (_type == ConfirmType.LinkInvite || _type == ConfirmType.EmpInvite)
            {
                if (!CoreContext.Configuration.Personal)
                {
                    if (_employeeType == EmployeeType.User && TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers)
                    {
                        ShowError(UserControlsCommonResource.TariffUserLimitReason);
                        return;
                    }

                    if (_employeeType == EmployeeType.Visitor && !(CoreContext.Configuration.Standalone || TenantStatisticsProvider.GetVisitorsCount() < TenantExtra.GetTenantQuota().ActiveUsers *Constants.CoefficientOfVisitors))
                    {
                        ShowError(UserControlsCommonResource.TariffVisitorLimitReason);
                        return;
                    }
                }

                if (!user.ID.Equals(Constants.LostUser.ID))
                {
                    ShowError(CustomNamingPeople.Substitute <Resource>("ErrorEmailAlreadyExists"));
                    return;
                }
            }

            else if (_type == ConfirmType.Activation)
            {
                if (user.IsActive)
                {
                    Response.Redirect(CommonLinkUtility.GetDefault());
                    return;
                }

                if (user.ID.Equals(Constants.LostUser.ID) || user.Status == EmployeeStatus.Terminated)
                {
                    ShowError(string.Format(Resource.ErrorUserNotFoundByEmail, email));
                    return;
                }
            }

            var tenant = CoreContext.TenantManager.GetCurrentTenant();

            if (tenant != null)
            {
                var settings = IPRestrictionsSettings.Load();
                if (settings.Enable && !IPSecurity.IPSecurity.Verify(tenant))
                {
                    ShowError(Resource.ErrorAccessRestricted);
                    return;
                }
            }

            if (!IsPostBack)
            {
                return;
            }

            var firstName = GetFirstName();
            var lastName  = GetLastName();

            var          passwordHash       = (Request["passwordHash"] ?? "").Trim();
            var          mustChangePassword = false;
            LoginProfile thirdPartyProfile;

            //thirdPartyLogin confirmInvite
            if (Request["__EVENTTARGET"] == "thirdPartyLogin")
            {
                var valueRequest = Request["__EVENTARGUMENT"];
                thirdPartyProfile = new LoginProfile(valueRequest);

                if (!string.IsNullOrEmpty(thirdPartyProfile.AuthorizationError))
                {
                    // ignore cancellation
                    if (thirdPartyProfile.AuthorizationError != "Canceled at provider")
                    {
                        ShowError(HttpUtility.HtmlEncode(thirdPartyProfile.AuthorizationError));
                    }
                    return;
                }

                if (string.IsNullOrEmpty(thirdPartyProfile.EMail))
                {
                    ShowError(HttpUtility.HtmlEncode(Resource.ErrorNotCorrectEmail));
                    return;
                }
            }

            if (Request["__EVENTTARGET"] == "confirmInvite")
            {
                if (String.IsNullOrEmpty(email))
                {
                    _errorMessage = Resource.ErrorEmptyUserEmail;
                    return;
                }

                if (!email.TestEmailRegex())
                {
                    _errorMessage = Resource.ErrorNotCorrectEmail;
                    return;
                }

                if (String.IsNullOrEmpty(firstName))
                {
                    _errorMessage = Resource.ErrorEmptyUserFirstName;
                    return;
                }

                if (String.IsNullOrEmpty(lastName))
                {
                    _errorMessage = Resource.ErrorEmptyUserLastName;
                    return;
                }

                if (String.IsNullOrEmpty(passwordHash))
                {
                    _errorMessage = Resource.ErrorPasswordEmpty;
                    return;
                }
            }
            var userID = Guid.Empty;

            try
            {
                SecurityContext.CurrentAccount = ASC.Core.Configuration.Constants.CoreSystem;
                if (_type == ConfirmType.EmpInvite || _type == ConfirmType.LinkInvite)
                {
                    if (!CoreContext.Configuration.Personal && TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers&& _employeeType == EmployeeType.User)
                    {
                        ShowError(UserControlsCommonResource.TariffUserLimitReason);
                        return;
                    }

                    UserInfo newUser;
                    if (Request["__EVENTTARGET"] == "confirmInvite")
                    {
                        var fromInviteLink = _type == ConfirmType.LinkInvite;
                        newUser = CreateNewUser(firstName, lastName, email, passwordHash, _employeeType, fromInviteLink);

                        var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite;
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, MessageTarget.Create(newUser.ID), newUser.DisplayUserName(false));

                        userID = newUser.ID;
                    }

                    if (Request["__EVENTTARGET"] == "thirdPartyLogin")
                    {
                        if (String.IsNullOrEmpty(passwordHash))
                        {
                            passwordHash       = UserManagerWrapper.GeneratePassword();
                            mustChangePassword = true;
                        }

                        var valueRequest = Request["__EVENTARGUMENT"];
                        thirdPartyProfile = new LoginProfile(valueRequest);
                        newUser           = CreateNewUser(GetFirstName(thirdPartyProfile), GetLastName(thirdPartyProfile), GetEmailAddress(thirdPartyProfile), passwordHash, _employeeType, false);

                        var messageAction = _employeeType == EmployeeType.User ? MessageAction.UserCreatedViaInvite : MessageAction.GuestCreatedViaInvite;
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, messageAction, MessageTarget.Create(newUser.ID), newUser.DisplayUserName(false));

                        userID = newUser.ID;
                        if (!String.IsNullOrEmpty(thirdPartyProfile.Avatar))
                        {
                            SaveContactImage(userID, thirdPartyProfile.Avatar);
                        }

                        var linker = new AccountLinker("webstudio");
                        linker.AddLink(userID.ToString(), thirdPartyProfile);
                    }
                }
                else if (_type == ConfirmType.Activation)
                {
                    if (!UserFormatter.IsValidUserName(firstName, lastName))
                    {
                        throw new Exception(Resource.ErrorIncorrectUserName);
                    }

                    SecurityContext.SetUserPasswordHash(user.ID, passwordHash);

                    user.ActivationStatus = EmployeeActivationStatus.Activated;
                    user.FirstName        = firstName;
                    user.LastName         = lastName;
                    CoreContext.UserManager.SaveUserInfo(user);

                    userID = user.ID;

                    //notify
                    if (user.IsVisitor())
                    {
                        StudioNotifyService.Instance.GuestInfoAddedAfterInvite(user);
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.GuestActivated, MessageTarget.Create(user.ID), user.DisplayUserName(false));
                    }
                    else
                    {
                        StudioNotifyService.Instance.UserInfoAddedAfterInvite(user);
                        MessageService.Send(HttpContext.Current.Request, MessageInitiator.System, MessageAction.UserActivated, MessageTarget.Create(user.ID), user.DisplayUserName(false));
                    }
                }
            }
            catch (SecurityContext.PasswordException)
            {
                _errorMessage = HttpUtility.HtmlEncode(Resource.ErrorPasswordRechange);
                return;
            }
            catch (Exception exception)
            {
                _errorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }
            finally
            {
                SecurityContext.Logout();
            }

            user = CoreContext.UserManager.GetUsers(userID);
            try
            {
                CookiesManager.AuthenticateMeAndSetCookies(user.Email, passwordHash, MessageAction.LoginSuccess);

                StudioNotifyService.Instance.UserHasJoin();

                if (mustChangePassword)
                {
                    StudioNotifyService.Instance.UserPasswordChange(user);
                }
            }
            catch (Exception exception)
            {
                (Page as Confirm).ErrorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }

            UserHelpTourHelper.IsNewUser = true;
            if (CoreContext.Configuration.Personal)
            {
                PersonalSettings.IsNewUser = true;
            }
            Response.Redirect(CommonLinkUtility.GetDefault());
        }
Exemple #8
0
        public object SaveData(string email, string passwordHash, string lng, string promocode, string amiid, bool subscribeFromSite)
        {
            try
            {
                var tenant   = CoreContext.TenantManager.GetCurrentTenant();
                var settings = WizardSettings.Load();
                if (settings.Completed)
                {
                    throw new Exception("Wizard passed.");
                }

                if (IsAmi && IncorrectAmiId(amiid))
                {
                    throw new Exception(Resource.EmailAndPasswordIncorrectAmiId);
                }

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

                var currentUser = CoreContext.UserManager.GetUsers(CoreContext.TenantManager.GetCurrentTenant().OwnerId);
                CookiesManager.AuthenticateMeAndSetCookies(currentUser.Tenant, currentUser.ID, MessageAction.LoginSuccess);

                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;
                }
                CoreContext.UserManager.SaveUserInfo(currentUser);

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

                if (RequestLicense)
                {
                    TariffSettings.LicenseAccept = true;
                    MessageService.Send(HttpContext.Current.Request, MessageAction.LicenseKeyUploaded);

                    LicenseReader.RefreshLicense();
                }

                settings.Completed = true;
                settings.Save();

                TrySetLanguage(tenant, lng);

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

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

                return(new { Status = 1, Message = Resource.EmailAndPasswordSaved });
            }
            catch (BillingNotFoundException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseKeyNotFound });
            }
            catch (BillingNotConfiguredException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseKeyNotCorrect });
            }
            catch (BillingException)
            {
                return(new { Status = 0, Message = UserControlsCommonResource.LicenseException });
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(new { Status = 0, Message = ex.Message });
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginMessage = Auth.GetAuthMessage(Request["am"]);

            Page.RegisterStyle("~/UserControls/Common/AuthorizeDocs/css/authorizedocs.less", "~/UserControls/Common/AuthorizeDocs/css/slick.less")
            .RegisterBodyScripts("~/js/third-party/lodash.min.js", "~/js/third-party/masonry.pkgd.min.js", "~/UserControls/Common/AuthorizeDocs/js/reviews.js", "~/UserControls/Common/AuthorizeDocs/js/review_builder_script.js", "~/UserControls/Common/AuthorizeDocs/js/authorizedocs.js", "~/UserControls/Common/Authorize/js/authorize.js", "~/js/third-party/slick.min.js");

            if (CoreContext.Configuration.CustomMode)
            {
                Page.RegisterStyle("~/UserControls/Common/AuthorizeDocs/css/custom-mode.less");
            }

            ThirdpartyEnable = SetupInfo.ThirdPartyAuthEnabled && AccountLinkControl.IsNotEmpty;
            if (Request.DesktopApp() &&
                PrivacyRoomSettings.Available &&
                PrivacyRoomSettings.Enabled)
            {
                ThirdpartyEnable = false;
                Page
                .RegisterBodyScripts("~/UserControls/Common/Authorize/js/desktop.js");
            }

            Page.Title           = CoreContext.Configuration.CustomMode ? CustomModeResource.TitlePageNewCustomMode : PersonalResource.AuthDocsTitlePage;
            Page.MetaDescription = CoreContext.Configuration.CustomMode ? CustomModeResource.AuthDocsMetaDescriptionCustomMode.HtmlEncode() : PersonalResource.AuthDocsMetaDescription.HtmlEncode();
            Page.MetaKeywords    = CoreContext.Configuration.CustomMode ? CustomModeResource.AuthDocsMetaKeywordsCustomMode : PersonalResource.AuthDocsMetaKeywords;

            HelpLink = GetHelpLink();

            PersonalFooterHolder.Controls.Add(LoadControl(CoreContext.Configuration.CustomMode
                                                              ? PersonalFooter.PersonalFooter.LocationCustomMode
                                                              : PersonalFooter.PersonalFooter.Location));

            if (ThirdpartyEnable)
            {
                var loginWithThirdParty = (LoginWithThirdParty)LoadControl(LoginWithThirdParty.Location);
                loginWithThirdParty.RenderDisabled = true;
                HolderLoginWithThirdParty.Controls.Add(loginWithThirdParty);
                var loginWithThirdPartySocial = (LoginWithThirdParty)LoadControl(LoginWithThirdParty.Location);
                loginWithThirdPartySocial.RenderDisabled = true;
                LoginSocialNetworks.Controls.Add(loginWithThirdPartySocial);
            }
            pwdReminderHolder.Controls.Add(LoadControl(PwdTool.Location));

            if (IsPostBack)
            {
                var loginCounter = 0;
                ShowRecaptcha = false;
                try
                {
                    Login = Request["login"].Trim();
                    var passwordHash = Request["passwordHash"];

                    if (string.IsNullOrEmpty(Login) || string.IsNullOrEmpty(passwordHash))
                    {
                        if (AccountLinkControl.IsNotEmpty &&
                            (Request.Url.GetProfile() != null ||
                             Request["__EVENTTARGET"] == "thirdPartyLogin"))
                        {
                            return;
                        }
                        throw new InvalidCredentialException(Resource.InvalidUsernameOrPassword);
                    }

                    if (!SetupInfo.IsSecretEmail(Login))
                    {
                        int.TryParse(cache.Get <string>("loginsec/" + Login), out loginCounter);

                        loginCounter++;

                        if (!RecaptchaEnable)
                        {
                            if (loginCounter > SetupInfo.LoginThreshold)
                            {
                                throw new Authorize.BruteForceCredentialException();
                            }
                        }
                        else
                        {
                            if (loginCounter > SetupInfo.LoginThreshold - 1)
                            {
                                ShowRecaptcha = true;
                            }
                            if (loginCounter > SetupInfo.LoginThreshold)
                            {
                                var ip = Request.Headers["X-Forwarded-For"] ?? Request.UserHostAddress;

                                var recaptchaResponse = Request["g-recaptcha-response"];
                                if (String.IsNullOrEmpty(recaptchaResponse) ||
                                    !Authorize.ValidateRecaptcha(recaptchaResponse, ip))
                                {
                                    throw new Authorize.RecaptchaException();
                                }
                            }
                        }

                        cache.Insert("loginsec/" + Login, loginCounter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                    }

                    var session = string.IsNullOrEmpty(Request["remember"]);
                    CookiesManager.AuthenticateMeAndSetCookies(Login, passwordHash, MessageAction.LoginSuccess, session);

                    cache.Insert("loginsec/" + Login, (--loginCounter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }
                catch (InvalidCredentialException ex)
                {
                    MessageAction messageAction;

                    if (ex is Authorize.BruteForceCredentialException)
                    {
                        LoginMessage  = Resource.LoginWithBruteForce;
                        messageAction = MessageAction.LoginFailBruteForce;
                    }
                    else if (ex is Authorize.RecaptchaException)
                    {
                        LoginMessage  = Resource.RecaptchaInvalid;
                        messageAction = MessageAction.LoginFailRecaptcha;
                    }
                    else
                    {
                        LoginMessage     = Resource.InvalidUsernameOrPassword;
                        messageAction    = MessageAction.LoginFailInvalidCombination;
                        DontShowMainPage = true;
                    }

                    var loginName = string.IsNullOrWhiteSpace(Login) ? AuditResource.EmailNotSpecified : Login;

                    MessageService.Send(HttpContext.Current.Request, loginName, messageAction);

                    Auth.ProcessLogout();

                    return;
                }
                catch (System.Security.SecurityException)
                {
                    LoginMessage = Resource.ErrorDisabledProfile;
                    MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailDisabledProfile);
                    Auth.ProcessLogout();
                    return;
                }
                catch (Exception ex)
                {
                    LoginMessage = ex.Message;
                    MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFail);
                    Auth.ProcessLogout();
                    return;
                }

                if (loginCounter > 0)
                {
                    cache.Insert("loginsec/" + Login, (--loginCounter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }

                Response.Redirect(Context.GetRefererURL());
            }
            else
            {
                var confirmedEmail = (Request.QueryString["confirmed-email"] ?? "").Trim();

                if (String.IsNullOrEmpty(confirmedEmail) || !confirmedEmail.TestEmailRegex())
                {
                    return;
                }

                Login            = confirmedEmail;
                LoginMessage     = Resource.MessageEmailConfirmed + " " + Resource.MessageAuthorize;
                LoginMessageType = 1;
            }
        }
Exemple #10
0
        private bool CheckValidationKey()
        {
            var key      = Request["key"] ?? "";
            var emplType = Request["emplType"] ?? "";
            var social   = Request["social"] ?? "";

            var validInterval = SetupInfo.ValidEmailKeyInterval;
            var authInterval  = SetupInfo.ValidAuthKeyInterval;

            EmailValidationKeyProvider.ValidationResult checkKeyResult;
            switch (_type)
            {
            case ConfirmType.PortalContinue:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key);
                break;

            case ConfirmType.PhoneActivation:
            case ConfirmType.PhoneAuth:
            case ConfirmType.TfaActivation:
            case ConfirmType.TfaAuth:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key, authInterval);
                break;

            case ConfirmType.Auth:
            {
                var first      = Request["first"] ?? "";
                var module     = Request["module"] ?? "";
                var smsConfirm = Request["sms"] ?? "";

                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + first + module + smsConfirm, key, authInterval);

                if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Ok)
                {
                    var user = _email.Contains("@")
                                       ? CoreContext.UserManager.GetUserByEmail(_email)
                                       : CoreContext.UserManager.GetUsers(new Guid(_email));

                    if (SecurityContext.IsAuthenticated && SecurityContext.CurrentAccount.ID != user.ID)
                    {
                        Auth.ProcessLogout();
                    }

                    if (!SecurityContext.IsAuthenticated)
                    {
                        if (!CoreContext.UserManager.UserExists(user.ID) || user.Status != EmployeeStatus.Active)
                        {
                            ShowError(Auth.MessageKey.ErrorUserNotFound);
                            return(false);
                        }

                        if (StudioSmsNotificationSettings.IsVisibleAndAvailableSettings && StudioSmsNotificationSettings.Enable && smsConfirm.ToLower() != "true")
                        {
                            //todo: think about 'first' & 'module'
                            Response.Redirect(SmsConfirmUrl(user), true);
                        }

                        if (TfaAppAuthSettings.IsVisibleSettings && TfaAppAuthSettings.Enable)
                        {
                            //todo: think about 'first' & 'module'
                            Response.Redirect(TfaConfirmUrl(user), true);
                        }

                        var messageAction = social == "true" ? MessageAction.LoginSuccessViaSocialAccount : MessageAction.LoginSuccess;
                        CookiesManager.AuthenticateMeAndSetCookies(user.Tenant, user.ID, messageAction);
                    }

                    SetDefaultModule(module);

                    AuthRedirect(first.ToLower() == "true");
                }
            }
            break;

            case ConfirmType.DnsChange:
            {
                var dnsChangeKey = string.Join(string.Empty, new[] { _email, _type.ToString(), Request["dns"], Request["alias"] });
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(dnsChangeKey, key, validInterval);
            }
            break;

            case ConfirmType.PortalOwnerChange:
            {
                Guid uid;
                try
                {
                    uid = new Guid(Request["uid"]);
                }
                catch
                {
                    uid = Guid.Empty;
                }
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + uid, key, validInterval);
            }
            break;

            case ConfirmType.EmpInvite:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + emplType, key, validInterval);
                break;

            case ConfirmType.LinkInvite:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_type + emplType, key, validInterval);
                break;

            case ConfirmType.EmailChange:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + SecurityContext.CurrentAccount.ID, key, validInterval);
                break;

            case ConfirmType.PasswordChange:
                var userInfo      = CoreContext.UserManager.GetUserByEmail(_email);
                var auditEvent    = AuditEventsRepository.GetByFilter(action: MessageAction.UserSentPasswordChangeInstructions, entry: EntryType.User, target: MessageTarget.Create(userInfo.ID).ToString(), limit: 1).FirstOrDefault();
                var passwordStamp = CoreContext.Authentication.GetUserPasswordStamp(userInfo.ID);

                string hash;

                if (auditEvent != null)
                {
                    var auditEventDate = TenantUtil.DateTimeToUtc(auditEvent.Date);

                    hash = (auditEventDate.CompareTo(passwordStamp) > 0 ? auditEventDate : passwordStamp).ToString("s");
                }
                else
                {
                    hash = passwordStamp.ToString("s");
                }

                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type + hash, key, validInterval);

                break;

            default:
                checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(_email + _type, key, validInterval);
                break;
            }

            if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Expired)
            {
                ShowError(Auth.MessageKey.ErrorExpiredActivationLink);
                return(false);
            }

            if (checkKeyResult == EmailValidationKeyProvider.ValidationResult.Invalid)
            {
                ShowError(_type == ConfirmType.LinkInvite
                              ? Auth.MessageKey.ErrorInvalidActivationLink
                              : Auth.MessageKey.ErrorConfirmURLError);
                return(false);
            }

            if (!string.IsNullOrEmpty(_email) && !_email.TestEmailRegex())
            {
                ShowError(Auth.MessageKey.ErrorNotCorrectEmail);
                return(false);
            }

            return(true);
        }
Exemple #11
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                if (!SetupInfo.IsVisibleSettings(ManagementType.SingleSignOnSettings.ToString()) && !CoreContext.Configuration.Standalone)
                {
                    _log.DebugFormat("Single sign-on settings are disabled");
                    context.Response.Redirect(AUTH_PAGE + "?am=" + (int)Auth.MessageKey.SsoSettingsDisabled,
                                              false);
                    return;
                }
                if (!(CoreContext.Configuration.Standalone || CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Sso))
                {
                    _log.DebugFormat("Single sign-on settings are not paid");
                    context.Response.Redirect(
                        AUTH_PAGE + "?am=" + (int)Auth.MessageKey.ErrorNotAllowedOption, false);
                    return;
                }
                var settings = SsoSettingsV2.Load();

                if (context.Request["config"] == "saml")
                {
                    context.Response.StatusCode = 200;
                    var signedSettings = Signature.Create(settings);
                    var ssoConfig      = JavaScriptSerializer.Serialize(signedSettings);
                    context.Response.Write(ssoConfig.Replace("\"", ""));
                    return;
                }

                if (!settings.EnableSso)
                {
                    _log.DebugFormat("Single sign-on is disabled");
                    context.Response.Redirect(AUTH_PAGE + "?am=" + (int)Auth.MessageKey.SsoSettingsDisabled,
                                              false);
                    return;
                }

                var data = context.Request["data"];

                if (string.IsNullOrEmpty(data))
                {
                    _log.Error("SAML response is null or empty");
                    context.Response.Redirect(
                        AUTH_PAGE + "?am=" + (int)Auth.MessageKey.SsoSettingsEmptyToken, false);
                    return;
                }

                if (context.Request["auth"] == "true")
                {
                    var userData = Signature.Read <SsoUserData>(data);

                    if (userData == null)
                    {
                        _log.Error("SAML response is not valid");
                        MessageService.Send(context.Request, MessageAction.LoginFailViaSSO);
                        context.Response.Redirect(
                            AUTH_PAGE + "?am=" + (int)Auth.MessageKey.SsoSettingsNotValidToken, false);
                        return;
                    }

                    var userInfo = userData.ToUserInfo(true);

                    if (Equals(userInfo, Constants.LostUser))
                    {
                        _log.Error("Can't create userInfo using current SAML response (fields Email, FirstName, LastName are required)");
                        context.Response.Redirect(
                            AUTH_PAGE + "?am=" + (int)Auth.MessageKey.SsoSettingsCantCreateUser, false);
                        return;
                    }

                    if (userInfo.Status == EmployeeStatus.Terminated)
                    {
                        _log.Error("Current user is terminated");
                        context.Response.Redirect(
                            AUTH_PAGE + "?am=" + (int)Auth.MessageKey.SsoSettingsUserTerminated, false);
                        return;
                    }

                    if (context.User != null && context.User.Identity != null && context.User.Identity.IsAuthenticated)
                    {
                        var authenticatedUserInfo = CoreContext.UserManager.GetUsers(((IUserAccount)context.User.Identity).ID);

                        if (!Equals(userInfo, authenticatedUserInfo))
                        {
                            var loginName = authenticatedUserInfo.DisplayUserName(false);
                            MessageService.Send(HttpContext.Current.Request, loginName, MessageAction.Logout);
                            CookiesManager.ResetUserCookie();
                            SecurityContext.Logout();
                        }
                        else
                        {
                            _log.DebugFormat("User {0} already authenticated", context.User.Identity);
                        }
                    }

                    userInfo = AddUser(userInfo);

                    var authKey = CookiesManager.AuthenticateMeAndSetCookies(userInfo.Tenant, userInfo.ID, MessageAction.LoginSuccessViaSSO);

                    context.Response.Redirect(CommonLinkUtility.GetDefault() + "?token=" + HttpUtility.UrlEncode(authKey), false);
                }
                else if (context.Request["logout"] == "true")
                {
                    var logoutSsoUserData = Signature.Read <LogoutSsoUserData>(data);

                    if (logoutSsoUserData == null)
                    {
                        _log.Error("SAML Logout response is not valid");
                        MessageService.Send(context.Request, MessageAction.LoginFailViaSSO);
                        context.Response.Redirect(
                            AUTH_PAGE + "?am=" + (int)Auth.MessageKey.SsoSettingsNotValidToken, false);
                        return;
                    }

                    var userInfo = CoreContext.UserManager.GetSsoUserByNameId(logoutSsoUserData.NameId);

                    if (Equals(userInfo, Constants.LostUser))
                    {
                        _log.Error("Can't logout userInfo using current SAML response");
                        context.Response.Redirect(
                            AUTH_PAGE + "?am=" + (int)Auth.MessageKey.SsoSettingsCantCreateUser, false);
                        return;
                    }

                    if (userInfo.Status == EmployeeStatus.Terminated)
                    {
                        _log.Error("Current user is terminated");
                        context.Response.Redirect(
                            AUTH_PAGE + "?am=" + (int)Auth.MessageKey.SsoSettingsUserTerminated, false);
                        return;
                    }

                    SecurityContext.CurrentUser = userInfo.ID;

                    var loginName = userInfo.DisplayUserName(false);
                    MessageService.Send(HttpContext.Current.Request, loginName, MessageAction.Logout);

                    CookiesManager.ResetUserCookie();
                    SecurityContext.Logout();

                    context.Response.Redirect(AUTH_PAGE, false);
                }
            }
            catch (Exception e)
            {
                _log.ErrorFormat("Unexpected error. {0}", e);
                context.Response.Redirect(AUTH_PAGE + "?am=" + (int)Auth.MessageKey.Error, false);
            }
            finally
            {
                context.ApplicationInstance.CompleteRequest();
            }
        }
Exemple #12
0
        [Create(@"", 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 codeOAuth)
        {
            bool viaEmail;
            var  user = GetUser(userName, password, provider, accessToken, out viaEmail, codeOAuth);

            if (StudioSmsNotificationSettings.IsVisibleAndAvailableSettings && StudioSmsNotificationSettings.Enable)
            {
                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))
                });
            }

            if (TfaAppAuthSettings.IsVisibleSettings && TfaAppAuthSettings.Enable)
            {
                if (!TfaAppUserSettings.EnableForUser(user.ID))
                {
                    return new AuthenticationTokenData
                           {
                               Tfa    = true,
                               TfaKey = user.GenerateSetupCode().ManualEntryKey
                           }
                }
                ;

                return(new AuthenticationTokenData
                {
                    Tfa = true
                });
            }

            try
            {
                var action = viaEmail ? MessageAction.LoginSuccessViaApi : MessageAction.LoginSuccessViaApiSocialAccount;
                var token  = CookiesManager.AuthenticateMeAndSetCookies(user.Tenant, user.ID, action);

                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();
            }
        }
Exemple #13
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();
            }
        }
        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");
                }

                CookiesManager.AuthenticateMeAndSetCookies(userInfo.Tenant, userInfo.ID, MessageAction.LoginSuccessViaSocialApp);

                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");
        }