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);
        }
Example #2
0
 public IEnumerable <string> GetLinkedObjects(LoginProfile profile)
 {
     return(GetLinkedObjectsByHashId(profile.HashId));
 }
Example #3
0
 public void RemoveLink(string obj, LoginProfile profile)
 {
     RemoveProvider(obj, hashId: profile.HashId);
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            var accountLink = (AccountLinkControl)LoadControl(AccountLinkControl.Location);

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

            var loginProfile = Request.Url.GetProfile();

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

            string cookiesKey;

            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 = SecurityContext.AuthenticateMe(userInfo.ID);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                MessageService.Send(HttpContext.Current.Request, 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 = (string)Session["refererURL"];

            if (String.IsNullOrEmpty(refererURL))
            {
                refererURL = CommonLinkUtility.GetDefault();
            }
            if (Request.DesktopApp())
            {
                refererURL += (refererURL.Contains("?") ? "&" : "?") + "token=" + HttpUtility.HtmlEncode(cookiesKey);
            }

            Session["refererURL"] = null;
            Response.Redirect(refererURL);
        }
Example #5
0
 private void SendJsCallback(HttpContext context, LoginProfile profile)
 {
     //Render a page
     context.Response.ContentType = "text/html";
     context.Response.Write(JsCallbackHelper.GetCallbackPage().Replace("%PROFILE%", profile.ToJson()).Replace("%CALLBACK%", Callback));
 }
        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.AuthenticateMe(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.AuthenticateMe(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
            {
                var cookiesKey = SecurityContext.AuthenticateMe(user.Email, passwordHash);
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                MessageService.Send(HttpContext.Current.Request, 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());
        }
        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.IsVisibleSettings &&
                    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 cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
                    CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey, session);
                    MessageService.Send(HttpContext.Current.Request,
                                        authMethod == AuthMethod.ThirdParty
                                            ? MessageAction.LoginSuccessViaSocialAccount
                                            : MessageAction.LoginSuccess
                                        );
                }
            }
            catch (InvalidCredentialException ex)
            {
                Auth.ProcessLogout();

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

                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)
            {
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorDisabledProfile;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailDisabledProfile);
                return(false);
            }
            catch (IPSecurityException)
            {
                Auth.ProcessLogout();
                ErrorMessage = Resource.ErrorIpSecurity;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFailIpSecurity);
                return(false);
            }
            catch (Exception ex)
            {
                Auth.ProcessLogout();
                ErrorMessage = ex.Message;
                MessageService.Send(HttpContext.Current.Request, Login, MessageAction.LoginFail);
                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);
        }
 public IEnumerable <string> GetLinkedObjects(LoginProfile profile)
 {
     return(_accountLinkers.Values.SelectMany(x => x.GetLinkedObjects(profile)));
 }
 public void RemoveLink(string hostedRegion, string obj, LoginProfile profile)
 {
     _accountLinkers[GetDatabaseId(hostedRegion)].RemoveLink(obj, profile);
 }
        private UserInfo GetUser(AuthModel memberModel, out bool viaEmail)
        {
            viaEmail = true;
            var      action = MessageAction.LoginFailViaApi;
            UserInfo user;

            try
            {
                if ((string.IsNullOrEmpty(memberModel.Provider) && string.IsNullOrEmpty(memberModel.SerializedProfile)) || memberModel.Provider == "email")
                {
                    memberModel.UserName.ThrowIfNull(new ArgumentException(@"userName empty", "userName"));
                    if (!string.IsNullOrEmpty(memberModel.Password))
                    {
                        memberModel.Password.ThrowIfNull(new ArgumentException(@"password empty", "password"));
                    }
                    else
                    {
                        memberModel.PasswordHash.ThrowIfNull(new ArgumentException(@"PasswordHash empty", "PasswordHash"));
                    }
                    int counter;
                    int.TryParse(Cache.Get <string>("loginsec/" + memberModel.UserName), out counter);
                    if (++counter > SetupInfo.LoginThreshold && !SetupInfo.IsSecretEmail(memberModel.UserName))
                    {
                        throw new BruteForceCredentialException();
                    }
                    Cache.Insert("loginsec/" + memberModel.UserName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));


                    memberModel.PasswordHash = (memberModel.PasswordHash ?? "").Trim();

                    if (string.IsNullOrEmpty(memberModel.PasswordHash))
                    {
                        memberModel.Password = (memberModel.Password ?? "").Trim();

                        if (!string.IsNullOrEmpty(memberModel.Password))
                        {
                            memberModel.PasswordHash = PasswordHasher.GetClientPassword(memberModel.Password);
                        }
                    }

                    user = UserManager.GetUsersByPasswordHash(
                        TenantManager.GetCurrentTenant().TenantId,
                        memberModel.UserName,
                        memberModel.PasswordHash);

                    if (user == null || !UserManager.UserExists(user))
                    {
                        throw new Exception("user not found");
                    }

                    Cache.Insert("loginsec/" + memberModel.UserName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }
                else
                {
                    viaEmail = false;
                    action   = MessageAction.LoginFailViaApiSocialAccount;
                    LoginProfile thirdPartyProfile;
                    if (!string.IsNullOrEmpty(memberModel.SerializedProfile))
                    {
                        thirdPartyProfile = new LoginProfile(Signature, InstanceCrypto, memberModel.SerializedProfile);
                    }
                    else
                    {
                        thirdPartyProfile = ProviderManager.GetLoginProfile(memberModel.Provider, memberModel.AccessToken);
                    }

                    memberModel.UserName = thirdPartyProfile.EMail;

                    user = GetUserByThirdParty(thirdPartyProfile);
                }
            }
            catch (BruteForceCredentialException)
            {
                MessageService.Send(!string.IsNullOrEmpty(memberModel.UserName) ? memberModel.UserName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce);
                throw new AuthenticationException("Login Fail. Too many attempts");
            }
            catch
            {
                MessageService.Send(!string.IsNullOrEmpty(memberModel.UserName) ? memberModel.UserName : AuditResource.EmailNotSpecified, action);
                throw new AuthenticationException("User authentication failed");
            }

            return(user);
        }
        private UserInfo GetUserByThirdParty(LoginProfile loginProfile)
        {
            try
            {
                if (!string.IsNullOrEmpty(loginProfile.AuthorizationError))
                {
                    // ignore cancellation
                    if (loginProfile.AuthorizationError != "Canceled at provider")
                    {
                        throw new Exception(loginProfile.AuthorizationError);
                    }
                    return(Constants.LostUser);
                }

                var userInfo = Constants.LostUser;

                Guid userId;
                if (TryGetUserByHash(loginProfile.HashId, out userId))
                {
                    userInfo = UserManager.GetUsers(userId);
                }

                var isNew = false;
                if (CoreBaseSettings.Personal)
                {
                    if (UserManager.UserExists(userInfo.ID) && SetupInfo.IsSecretEmail(userInfo.Email))
                    {
                        try
                        {
                            SecurityContext.AuthenticateMeWithoutCookie(ASC.Core.Configuration.Constants.CoreSystem);
                            UserManager.DeleteUser(userInfo.ID);
                            userInfo = Constants.LostUser;
                        }
                        finally
                        {
                            SecurityContext.Logout();
                        }
                    }

                    if (!UserManager.UserExists(userInfo.ID))
                    {
                        userInfo = JoinByThirdPartyAccount(loginProfile);

                        isNew = true;
                    }
                }

                if (isNew)
                {
                    //TODO:
                    //var spam = HttpContext.Current.Request["spam"];
                    //if (spam != "on")
                    //{
                    //    try
                    //    {
                    //        const string _databaseID = "com";
                    //        using (var db = DbManager.FromHttpContext(_databaseID))
                    //        {
                    //            db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
                    //                                   .InColumnValue("email", userInfo.Email.ToLowerInvariant())
                    //                                   .InColumnValue("reason", "personal")
                    //                );
                    //            Log.Debug(string.Format("Write to template_unsubscribe {0}", userInfo.Email.ToLowerInvariant()));
                    //        }
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        Log.Debug(string.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, userInfo.Email.ToLowerInvariant()));
                    //    }
                    //}

                    StudioNotifyService.UserHasJoin();
                    UserHelpTourHelper.IsNewUser     = true;
                    PersonalSettingsHelper.IsNewUser = true;
                }

                return(userInfo);
            }
            catch (Exception)
            {
                CookiesManager.ClearCookies(CookiesType.AuthKey);
                CookiesManager.ClearCookies(CookiesType.SocketIO);
                SecurityContext.Logout();
                throw;
            }
        }
        public override LoginProfile GetLoginProfile(string accessToken)
        {
            var tokenPayloadString = JsonWebToken.Decode(accessToken, string.Empty, false, true);
            var tokenPayload       = JObject.Parse(tokenPayloadString);

            if (tokenPayload == null)
            {
                throw new Exception("Payload is incorrect");
            }
            var oid = tokenPayload.Value <string>("urn:esia:sbj_id");

            var userInfoString = RequestHelper.PerformRequest(GosUslugiProfileUrl + oid, "application/x-www-form-urlencoded", headers: new Dictionary <string, string> {
                { "Authorization", "Bearer " + accessToken }
            });
            var userInfo = JObject.Parse(userInfoString);

            if (userInfo == null)
            {
                throw new Exception("userinfo is incorrect");
            }

            var profile = new LoginProfile(Signature, InstanceCrypto)
            {
                Id        = oid,
                FirstName = userInfo.Value <string>("firstName"),
                LastName  = userInfo.Value <string>("lastName"),

                Provider = ProviderConstants.GosUslugi,
            };

            var userContactsString = RequestHelper.PerformRequest(GosUslugiProfileUrl + oid + "/ctts", "application/x-www-form-urlencoded", headers: new Dictionary <string, string> {
                { "Authorization", "Bearer " + accessToken }
            });
            var userContacts = JObject.Parse(userContactsString);

            if (userContacts == null)
            {
                throw new Exception("usercontacts is incorrect");
            }

            var contactElements = userContacts.Value <JArray>("elements");

            if (contactElements == null)
            {
                throw new Exception("usercontacts elements is incorrect");
            }

            foreach (var contactElement in contactElements.ToObject <List <string> >())
            {
                var userContactString = RequestHelper.PerformRequest(contactElement, "application/x-www-form-urlencoded", headers: new Dictionary <string, string> {
                    { "Authorization", "Bearer " + accessToken }
                });

                var userContact = JObject.Parse(userContactString);
                if (userContact == null)
                {
                    throw new Exception("usercontacts is incorrect");
                }

                var type = userContact.Value <string>("type");
                if (type != "EML")
                {
                    continue;
                }

                profile.EMail = userContact.Value <string>("value");
                break;
            }

            return(profile);
        }
Example #13
0
        private async Task <User> RegisterUserAsync(User user, string password, bool isMigrating = false)
        {
            ArgumentGuard.NotNull(user, nameof(user));
            ArgumentGuard.NotNullOrEmpty(user.Email, nameof(user.Email));
            ArgumentGuard.NotNullOrEmpty(user.FirstName, nameof(user.FirstName));
            ArgumentGuard.NotNullOrEmpty(user.LastName, nameof(user.LastName));

            var dbUser = await _userService.FindUserByEmailAsync(user.Email.Trim().ToLower());

            if (!dbUser.IsNull())
            {
                throw new AppException($"User With {user.Email} Already Exists");
            }

            var userRoles = new List <UserRole>();

            var roleUser = await _userRepository.GetRole(UserRoleEnum.User.ToString());

            if (roleUser.IsNull())
            {
                throw new Exception("Role not found");
            }
            userRoles.Add(new UserRole {
                Role = roleUser
            });

            // add admin role to admin users specified in appsettings
            var admins = _configuration.GetValue <string>("Admins");

            if (admins.Contains(user.Email.ToLower()))
            {
                var roleAdmin = await _userRepository.GetRole(UserRoleEnum.Admin.ToString());

                if (roleAdmin.IsNull())
                {
                    throw new Exception("Admin role not found in db");
                }
                userRoles.Add(new UserRole {
                    Role = roleAdmin
                });
            }

            // add admin role to admin users specified in appsettings
            var superAdmins = _configuration.GetValue <string>("SuperAdmins");

            if (superAdmins.Contains(user.Email.ToLower()))
            {
                var roleSuperAdmin = await _userRepository.GetRole(UserRoleEnum.SuperAdmin.ToString());

                if (roleSuperAdmin.IsNull())
                {
                    throw new Exception("Super Admin role not found in db");
                }
                userRoles.Add(new UserRole {
                    Role = roleSuperAdmin
                });
            }

            var newUser = new User
            {
                Email                 = user.Email.Trim().ToLower(),
                FirstName             = user.FirstName,
                LastName              = user.LastName,
                PhoneNumber           = user.PhoneNumber,
                InformationPreference = user.InformationPreference,
                PhotoUrl              = user.PhotoUrl,
                CreatedAt             = DateTime.UtcNow,
                UserRoles             = userRoles
            };

            if (!string.IsNullOrEmpty(password))
            {
                var loginProfile = new LoginProfile();
                var salt         = _cryptoService.GenerateSalt(32);
                loginProfile.Salt     = salt;
                loginProfile.Password = _cryptoService.Hash(password, salt, 1963);

                var loginProfileId = await _userRepository.AddLoginProfileAsync(loginProfile);

                newUser.LoginProfileId = loginProfileId;

                var resUser = await _userRepository.AddUserAsync(newUser);

                var emailConfirmationToken = _cryptoService.CreateUniqueKey();

                resUser.Token = emailConfirmationToken;

                await _userRepository.UpdateUserAsync(resUser);

                if (isMigrating)
                {
                    // send a migration notice email with link to change their password
                    await _emailSender.SendMigrationEmail(resUser, emailConfirmationToken);
                }
                else
                {
                    await _emailSender.SendRegistrationConfirmationEmail(resUser, emailConfirmationToken);
                }

                return(resUser);
            }
            else
            {
                return(await _userRepository.AddUserAsync(newUser));
            }
        }
Example #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "confirm_invite_activation_style", "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + WebSkin.GetUserSkin().GetAbsoluteWebPath("usercontrols/management/confirminviteactivation/css/<theme_folder>/confirm_invite_activation.css") + "\">", false);
            Page.ClientScript.RegisterClientScriptInclude(typeof(string), "confirm_invite_activation_script", WebPath.GetPath("usercontrols/management/confirminviteactivation/js/confirm_invite_activation.js"));

            _tenantInfoSettings = SettingsManager.Instance.LoadSettings <TenantInfoSettings>(TenantProvider.CurrentTenantID);

            Guid uid = Guid.Empty;

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

            var type = typeof(ConfirmType).TryParseEnum(Request["type"] ?? "", ConfirmType.EmpInvite);

            var email = GetEmailAddress();
            var key   = Request["key"] ?? "";
            var fap   = Request["fap"] ?? "";

            //if (!string.IsNullOrEmpty(_email))
            //{
            //var thrd = LoadControl(AccountLinkControl.Location) as AccountLinkControl;
            //thrd.InviteView = true;
            //thrd.ClientCallback = "loginJoinCallback";
            //thrdParty.Controls.Add(thrd);
            //}
            Page.Title = HeaderStringHelper.GetPageTitle(Resources.Resource.Authorization, null, null);

            UserInfo user;

            try
            {
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);

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

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

            if (type == ConfirmType.LinkInvite || type == ConfirmType.EmpInvite)
            {
                if (!user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID))
                {
                    ShowError(CustomNamingPeople.Substitute <Resources.Resource>("ErrorEmailAlreadyExists"));
                    return;
                }
            }

            else if (type == ConfirmType.Activation)
            {
                if (user.IsActive)
                {
                    ShowError(Resources.Resource.ErrorConfirmURLError);
                    return;
                }

                if (user.ID.Equals(ASC.Core.Users.Constants.LostUser.ID))
                {
                    ShowError(string.Format(Resources.Resource.ErrorUserNotFoundByEmail, email));
                    return;
                }
            }

            if (!IsPostBack)
            {
                return;
            }

            var          firstName = GetFirstName();
            var          lastName  = GetLastName();
            var          pwd       = (Request["pwdInput"] ?? "").Trim();
            var          repwd     = (Request["repwdInput"] ?? "").Trim();
            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(Resources.Resource.ErrorNotCorrectEmail));
                    return;
                }
            }

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

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

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

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

                var checkPassResult = CheckPassword(pwd, repwd);
                if (!String.IsNullOrEmpty(checkPassResult))
                {
                    _errorMessage = checkPassResult;
                    return;
                }
            }
            var userID = Guid.Empty;

            try
            {
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                if (type == ConfirmType.EmpInvite || type == ConfirmType.LinkInvite)
                {
                    UserInfo newUser;
                    if (Request["__EVENTTARGET"] == "confirmInvite")
                    {
                        newUser = CreateNewUser(firstName, lastName, email, pwd);
                        userID  = newUser.ID;
                    }

                    if (Request["__EVENTTARGET"] == "thirdPartyLogin")
                    {
                        if (!String.IsNullOrEmpty(CheckPassword(pwd, repwd)))
                        {
                            pwd = UserManagerWrapper.GeneratePassword();
                        }
                        var valueRequest = Request["__EVENTARGUMENT"];
                        thirdPartyProfile = new LoginProfile(valueRequest);
                        newUser           = CreateNewUser(GetFirstName(thirdPartyProfile), GetLastName(thirdPartyProfile), GetEmailAddress(thirdPartyProfile), pwd);
                        userID            = newUser.ID;

                        var linker = new AccountLinker(WebConfigurationManager.ConnectionStrings["webstudio"]);
                        linker.AddLink(userID.ToString(), thirdPartyProfile);
                    }

                    #region Department

                    try
                    {
                        var deptID = new Guid((Request["deptID"] ?? "").Trim());
                        CoreContext.UserManager.AddUserIntoGroup(userID, deptID);
                    }
                    catch
                    {
                    }

                    #endregion
                }
                else if (type == ConfirmType.Activation)
                {
                    user.ActivationStatus = EmployeeActivationStatus.Activated;
                    user.FirstName        = firstName;
                    user.LastName         = lastName;
                    CoreContext.UserManager.SaveUserInfo(user);
                    SecurityContext.SetUserPassword(user.ID, pwd);

                    userID = user.ID;

                    //notify
                    StudioNotifyService.Instance.UserInfoAddedAfterInvite(user, pwd);
                }

                if (String.Equals(fap, "1"))
                {
                    CoreContext.UserManager.AddUserIntoGroup(userID, ASC.Core.Users.Constants.GroupAdmin.ID);
                }
            }
            catch (Exception exception)
            {
                (Page as confirm).ErrorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }
            finally
            {
                SecurityContext.Logout();
            }

            try
            {
                var cookiesKey = SecurityContext.AuthenticateMe(userID.ToString(), pwd);
                CookiesManager.SetCookies(CookiesType.UserID, userID.ToString());
                CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
                StudioNotifyService.Instance.UserHasJoin();
            }
            catch (Exception exception)
            {
                (Page as confirm).ErrorMessage = HttpUtility.HtmlEncode(exception.Message);
                return;
            }

            UserOnlineManager.Instance.RegistryOnlineUser(SecurityContext.CurrentAccount.ID);
            WebItemManager.Instance.ItemGlobalHandlers.Login(SecurityContext.CurrentAccount.ID);
            var smsAuthSettings = SettingsManager.Instance.LoadSettings <StudioSmsNotificationSettings>(TenantProvider.CurrentTenantID);
            if (smsAuthSettings.Enable)
            {
                var uData = new UserTransferData();
                var usr   = CoreContext.UserManager.GetUsers(userID);
                uData.Login  = usr.Email;
                uData.UserId = userID;
                Session["UserTransferData"] = uData;
            }

            Response.Redirect("~/");
        }
Example #15
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            var response = Openid.GetResponse();

            if (response == null)
            {
                if (Identifier.TryParse(@params["oid"], out var id))
                {
                    try
                    {
                        IAuthenticationRequest request;

                        var realmUrlString = string.Empty;

                        if (@params.ContainsKey("realmUrl"))
                        {
                            realmUrlString = @params["realmUrl"];
                        }

                        if (!string.IsNullOrEmpty(realmUrlString))
                        {
                            request = Openid.CreateRequest(id, new Realm(realmUrlString));
                        }
                        else
                        {
                            request = Openid.CreateRequest(id);
                        }

                        request.AddExtension(new ClaimsRequest
                        {
                            Email      = DemandLevel.Require,
                            Nickname   = DemandLevel.Require,
                            Country    = DemandLevel.Request,
                            Gender     = DemandLevel.Request,
                            PostalCode = DemandLevel.Request,
                            TimeZone   = DemandLevel.Request,
                            FullName   = DemandLevel.Request,
                        });
                        var fetch = new FetchRequest();
                        fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                        //Duplicating attributes
                        fetch.Attributes.AddRequired("http://schema.openid.net/contact/email");//Add two more
                        fetch.Attributes.AddRequired("http://openid.net/schema/contact/email");
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Alias);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Media.Images.Default);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Middle);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Person.Gender);
                        fetch.Attributes.AddRequired(WellKnownAttributes.BirthDate.WholeBirthDate);
                        request.AddExtension(fetch);
                        request.RedirectToProvider();
                        //context.Response.End();//TODO This will throw thread abort
                    }
                    catch (ProtocolException ex)
                    {
                        return(LoginProfile.FromError(ex));
                    }
                }
                else
                {
                    return(LoginProfile.FromError(new Exception("invalid OpenID identifier")));
                }
            }
            else
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    var spprofile    = response.GetExtension <ClaimsResponse>();
                    var fetchprofile = response.GetExtension <FetchResponse>();

                    var realmUrlString = string.Empty;
                    if (@params.ContainsKey("realmUrl"))
                    {
                        realmUrlString = @params["realmUrl"];
                    }

                    var profile = ProfileFromOpenId(spprofile, fetchprofile, response.ClaimedIdentifier.ToString(), realmUrlString);
                    return(profile);

                case AuthenticationStatus.Canceled:
                    return(LoginProfile.FromError(new Exception("Canceled at provider")));

                case AuthenticationStatus.Failed:
                    return(LoginProfile.FromError(response.Exception));
                }
            }
            return(null);
        }
Example #16
0
        public static UserInfo GetUserByThirdParty(LoginProfile loginProfile)
        {
            try
            {
                if (!string.IsNullOrEmpty(loginProfile.AuthorizationError))
                {
                    // ignore cancellation
                    if (loginProfile.AuthorizationError != "Canceled at provider")
                    {
                        throw new Exception(loginProfile.AuthorizationError);
                    }
                    return(ASC.Core.Users.Constants.LostUser);
                }

                if (string.IsNullOrEmpty(loginProfile.EMail))
                {
                    throw new Exception(Resource.ErrorNotCorrectEmail);
                }

                var userInfo = new UserInfo();

                Guid userId;
                if (TryGetUserByHash(loginProfile.HashId, out userId))
                {
                    userInfo = CoreContext.UserManager.GetUsers(userId);
                }
                if (!CoreContext.UserManager.UserExists(userInfo.ID))
                {
                    userInfo = CoreContext.UserManager.GetUserByEmail(loginProfile.EMail);
                }

                var isNew = false;
                if (CoreContext.Configuration.Personal)
                {
                    if (CoreContext.UserManager.UserExists(userInfo.ID) && SetupInfo.IsSecretEmail(userInfo.Email))
                    {
                        try
                        {
                            SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                            CoreContext.UserManager.DeleteUser(userInfo.ID);
                            userInfo = ASC.Core.Users.Constants.LostUser;
                        }
                        finally
                        {
                            SecurityContext.Logout();
                        }
                    }

                    if (!CoreContext.UserManager.UserExists(userInfo.ID))
                    {
                        userInfo = JoinByThirdPartyAccount(loginProfile);

                        isNew = true;
                    }
                }

                if (isNew)
                {
                    StudioNotifyService.Instance.UserHasJoin();
                    UserHelpTourHelper.IsNewUser = true;
                    PersonalSettings.IsNewUser   = true;
                }

                return(userInfo);
            }
            catch (Exception)
            {
                Auth.ProcessLogout();
                throw;
            }
        }
        private string GetLastName(LoginProfile account)
        {
            var value = GetLastName();

            return(String.IsNullOrEmpty(value) ? account.LastName : value);
        }
        public static UserInfo GetUserByThirdParty(LoginProfile loginProfile)
        {
            try
            {
                if (!string.IsNullOrEmpty(loginProfile.AuthorizationError))
                {
                    // ignore cancellation
                    if (loginProfile.AuthorizationError != "Canceled at provider")
                    {
                        throw new Exception(loginProfile.AuthorizationError);
                    }
                    return(Constants.LostUser);
                }

                var userInfo = Constants.LostUser;

                Guid userId;
                if (TryGetUserByHash(loginProfile.HashId, out userId))
                {
                    userInfo = CoreContext.UserManager.GetUsers(userId);
                }

                var isNew = false;
                if (CoreContext.Configuration.Personal)
                {
                    if (CoreContext.UserManager.UserExists(userInfo.ID) && SetupInfo.IsSecretEmail(userInfo.Email))
                    {
                        try
                        {
                            SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                            CoreContext.UserManager.DeleteUser(userInfo.ID);
                            userInfo = Constants.LostUser;
                        }
                        finally
                        {
                            SecurityContext.Logout();
                        }
                    }

                    if (!CoreContext.UserManager.UserExists(userInfo.ID))
                    {
                        userInfo = JoinByThirdPartyAccount(loginProfile);

                        isNew = true;
                    }
                }

                if (isNew)
                {
                    var spam = HttpContext.Current.Request["spam"];
                    if (spam != "on")
                    {
                        try
                        {
                            const string _databaseID = "com";
                            using (var db = DbManager.FromHttpContext(_databaseID))
                            {
                                db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
                                                   .InColumnValue("email", userInfo.Email.ToLowerInvariant())
                                                   .InColumnValue("reason", "personal")
                                                   );
                                LogManager.GetLogger("ASC.Web").Debug(String.Format("Write to template_unsubscribe {0}", userInfo.Email.ToLowerInvariant()));
                            }
                        }
                        catch (Exception ex)
                        {
                            LogManager.GetLogger("ASC.Web").Debug(String.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, userInfo.Email.ToLowerInvariant()));
                        }
                    }

                    var analytics = HttpContext.Current.Request["analytics"] == "on";
                    var settings  = TenantAnalyticsSettings.LoadForCurrentUser();
                    settings.Analytics = analytics;
                    settings.SaveForCurrentUser();

                    StudioNotifyService.Instance.UserHasJoin();
                    UserHelpTourHelper.IsNewUser = true;
                    PersonalSettings.IsNewUser   = true;
                }

                return(userInfo);
            }
            catch (Exception)
            {
                Auth.ProcessLogout();
                throw;
            }
        }
        private string GetEmailAddress(LoginProfile account)
        {
            var value = GetEmailAddress();

            return(String.IsNullOrEmpty(value) ? account.EMail : value);
        }
Example #20
0
 public IEnumerable <string> GetLinkedObjects(LoginProfile profile)
 {
     //Retrieve by uinque id
     return(GetLinkedObjectsByHashId(profile.HashId));
 }