public UserInfo CreateUserInfo(SamlResponse samlResponse)
        {
            var      profile   = samlResponse.GetIssuer();
            var      extUserId = samlResponse.GetExtUserId();
            var      email     = samlResponse.GetNameID();
            UserInfo userInfo  = null;

            if (!string.IsNullOrWhiteSpace(extUserId))
            {
                var wrapper = new CommonDbWrapper();
                var userId  = wrapper.GetUserId(extUserId, profile);
                if (userId != null)
                {
                    _log.DebugFormat("Updating new user with extUserId: {0}", extUserId);
                    userInfo = CoreContext.UserManager.GetUsers(Guid.Parse(userId));

                    while (true)
                    {
                        int count       = 0;
                        var userByEmail = CoreContext.UserManager.GetUserByEmail(email);
                        if (userByEmail == Constants.LostUser || userByEmail.ID == userInfo.ID)
                        {
                            break;
                        }
                        email += count++;
                    }
                }
                if (userId == null || userInfo == Constants.LostUser)
                {
                    _log.DebugFormat("Creating new user with extUserId: {0}", extUserId);
                    userInfo = new UserInfo {
                        ID = Guid.NewGuid()
                    };
                    wrapper.SaveExtUserId(userInfo.ID.ToString(), extUserId, profile);
                    while (true)
                    {
                        int count = 0;
                        if (CoreContext.UserManager.GetUserByEmail(email) == Constants.LostUser)
                        {
                            break;
                        }
                        email += count++;
                    }
                }
            }
            else
            {
                userInfo = CoreContext.UserManager.GetUserByEmail(email);
                if (userInfo == Constants.LostUser)
                {
                    _log.DebugFormat("Creating new user with email: {0}", email);
                    userInfo = new UserInfo();
                }
                else
                {
                    _log.DebugFormat("Updating user with email: {0}", email);
                }
            }
            userInfo.Email            = email;
            userInfo.ActivationStatus = EmployeeActivationStatus.Activated;

            string firstName       = samlResponse.GetFirstName();
            string lastName        = samlResponse.GetLastName();
            string mobilePhone     = samlResponse.GetMobilePhone();
            string title           = samlResponse.GetTitle();
            string location        = samlResponse.GetStreetAddress();
            string birthDateString = samlResponse.GetBirthDate();
            string sexString       = samlResponse.GetSex();

            if (!string.IsNullOrEmpty(firstName))
            {
                if (firstName.Length > MAX_NUMBER_OF_SYMBOLS)
                {
                    firstName = firstName.Substring(0, MAX_NUMBER_OF_SYMBOLS);
                }
                userInfo.FirstName = firstName;
            }
            if (!string.IsNullOrEmpty(lastName))
            {
                if (lastName.Length > MAX_NUMBER_OF_SYMBOLS)
                {
                    lastName = lastName.Substring(0, MAX_NUMBER_OF_SYMBOLS);
                }
                userInfo.LastName = lastName;
            }
            if (!string.IsNullOrEmpty(mobilePhone))
            {
                userInfo.MobilePhone = mobilePhone;
            }
            if (!string.IsNullOrEmpty(title))
            {
                userInfo.Title = title;
            }
            if (!string.IsNullOrEmpty(location))
            {
                userInfo.Location = location;
            }
            if (!string.IsNullOrEmpty(birthDateString))
            {
                try
                {
                    userInfo.BirthDate = DateTime.Parse(birthDateString);
                }
                catch (Exception e)
                {
                    _log.ErrorFormat("Parse birthDateString error: {0}, {1}", e, birthDateString);
                }
            }

            if (!string.IsNullOrEmpty(sexString))
            {
                try
                {
                    userInfo.Sex = Convert.ToBoolean(sexString);
                }
                catch (Exception e)
                {
                    _log.ErrorFormat("Parse sexString error: {0}, {1}", e, sexString);
                }
            }

            if (!userInfo.WorkFromDate.HasValue)
            {
                userInfo.WorkFromDate = TenantUtil.DateTimeNow();
            }

            return(userInfo);
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                if (!SetupInfo.IsVisibleSettings(ManagementType.SingleSignOnSettings.ToString()))
                {
                    _log.DebugFormat("Single sign-on settings are disabled");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsDisabled), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }
                var settings = SettingsManager.Instance.LoadSettings<SsoSettings>(TenantProvider.CurrentTenantID);
                if (!settings.EnableSso)
                {
                    _log.DebugFormat("Single sign-on is disabled");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsDisabled), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                if (context.User.Identity.IsAuthenticated)
                {
                    _log.DebugFormat("User {0} already authenticated");
                    context.Response.Redirect(CommonLinkUtility.GetDefault(), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                UserInfo userInfo;
                if (settings.TokenType != TokenTypes.SAML)
                {
                    _log.Error("Settings TokenType  is not SAML");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsEnexpectedTokenType), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                if (context.Request["auth"] == "true")
                {
                    SamlRequest req = new SamlRequest(settings);
                    string assertionConsumerServiceUrl = context.Request.Url.AbsoluteUri.Substring(0,
                        context.Request.Url.AbsoluteUri.IndexOf("?"));
                    context.Response.Redirect(settings.SsoEndPoint + "?" +
                        req.GetRequest(SamlRequestFormat.Base64,
                            assertionConsumerServiceUrl,
                            Path.Combine(context.Request.PhysicalApplicationPath, "App_Data\\certificates\\sp.pfx"),
                            ConfigurationManager.AppSettings["saml.request.certificate.password"] ?? PASSWORD),
                            false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                var samlEncodedString = context.Request.Form[SAML_RESPONSE];
                if (string.IsNullOrWhiteSpace(samlEncodedString))
                {
                    _log.Error("SAML response is null or empty");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsEmptyToken), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }
                _log.Debug("Trying to authenticate using SAML");
                SamlResponse samlResponse = new SamlResponse(settings);
                samlResponse.LoadXmlFromBase64(samlEncodedString);
                if (!samlResponse.IsValid())
                {
                    _log.Error("SAML response is not valid");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsNotValidToken), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }
                SamlUserCreator userCreator = new SamlUserCreator();
                userInfo = userCreator.CreateUserInfo(samlResponse);
                if (userInfo == Constants.LostUser)
                {
                    _log.Error("Can't create userInfo using current SAML response");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsCantCreateUser), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }
                if (userInfo.Status == EmployeeStatus.Terminated)
                {
                    _log.Error("Current user is terminated");
                    context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(Resource.SsoSettingsUserTerminated), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }
                AddUser(samlResponse, userInfo);
                MessageService.Send(context.Request, MessageAction.LoginSuccessViaSSO);
                context.Response.Redirect(CommonLinkUtility.GetDefault(), false);
                context.ApplicationInstance.CompleteRequest();
            }
            catch (Exception e)
            {
                _log.ErrorFormat("Unexpected error. {0}", e);
                context.Response.Redirect(AUTH_PAGE + "?m=" + HttpUtility.UrlEncode(e.Message), false);
                context.ApplicationInstance.CompleteRequest();
            }
        }
        public UserInfo CreateUserInfo(SamlResponse samlResponse)
        {
            var profile = samlResponse.GetIssuer();
            var extUserId = samlResponse.GetExtUserId();
            var email = samlResponse.GetNameID();
            UserInfo userInfo = null;

            if (!string.IsNullOrWhiteSpace(extUserId))
            {
                var wrapper = new CommonDbWrapper();
                var userId = wrapper.GetUserId(extUserId, profile);
                if (userId != null)
                {
                    _log.DebugFormat("Updating new user with extUserId: {0}", extUserId);
                    userInfo = CoreContext.UserManager.GetUsers(Guid.Parse(userId));

                    while (true)
                    {
                        int count = 0;
                        var userByEmail = CoreContext.UserManager.GetUserByEmail(email);
                        if (userByEmail == Constants.LostUser || userByEmail.ID == userInfo.ID)
                        {
                            break;
                        }
                        email += count++;
                    }
                }
                if (userId == null || userInfo == Constants.LostUser)
                {
                    _log.DebugFormat("Creating new user with extUserId: {0}", extUserId);
                    userInfo = new UserInfo { ID = Guid.NewGuid() };
                    wrapper.SaveExtUserId(userInfo.ID.ToString(), extUserId, profile);
                    while (true)
                    {
                        int count = 0;
                        if (CoreContext.UserManager.GetUserByEmail(email) == Constants.LostUser)
                        {
                            break;
                        }
                        email += count++;
                    }
                }
            }
            else
            {
                userInfo = CoreContext.UserManager.GetUserByEmail(email);
                if (userInfo == Constants.LostUser)
                {
                    _log.DebugFormat("Creating new user with email: {0}", email);
                    userInfo = new UserInfo();
                }
                else
                {
                    _log.DebugFormat("Updating user with email: {0}", email);
                }
            }
            userInfo.Email = email;
            userInfo.ActivationStatus = EmployeeActivationStatus.Activated;

            string firstName = samlResponse.GetFirstName();
            string lastName = samlResponse.GetLastName();
            string mobilePhone = samlResponse.GetMobilePhone();
            string title = samlResponse.GetTitle();
            string location = samlResponse.GetStreetAddress();
            string birthDateString = samlResponse.GetBirthDate();
            string sexString = samlResponse.GetSex();

            if (!string.IsNullOrEmpty(firstName))
            {
                if (firstName.Length > MAX_NUMBER_OF_SYMBOLS)
                {
                    firstName = firstName.Substring(0, MAX_NUMBER_OF_SYMBOLS);
                }
                userInfo.FirstName = firstName;
            }
            if (!string.IsNullOrEmpty(lastName))
            {
                if (lastName.Length > MAX_NUMBER_OF_SYMBOLS)
                {
                    lastName = lastName.Substring(0, MAX_NUMBER_OF_SYMBOLS);
                }
                userInfo.LastName = lastName;
            }
            if (!string.IsNullOrEmpty(mobilePhone))
            {
                userInfo.MobilePhone = mobilePhone;
            }
            if (!string.IsNullOrEmpty(title))
            {
                userInfo.Title = title;
            }
            if (!string.IsNullOrEmpty(location))
            {
                userInfo.Location = location;
            }
            if (!string.IsNullOrEmpty(birthDateString))
            {
                try
                {
                    userInfo.BirthDate = DateTime.Parse(birthDateString);
                }
                catch (Exception e)
                {
                    _log.ErrorFormat("Parse birthDateString error: {0}, {1}", e, birthDateString);
                }
            }

            if (!string.IsNullOrEmpty(sexString))
            {
                try
                {
                    userInfo.Sex = Convert.ToBoolean(sexString);
                }
                catch (Exception e)
                {
                    _log.ErrorFormat("Parse sexString error: {0}, {1}", e, sexString);
                }
            }

            if (!userInfo.WorkFromDate.HasValue)
            {
                userInfo.WorkFromDate = TenantUtil.DateTimeNow();
            }

            return userInfo;
        }
 private void AddUser(SamlResponse samlResponse, UserInfo userInfo)
 {
     try
     {
         _log.DebugFormat("Adding or updating user in database, userId={0}", userInfo.ID);
         SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
         if (!string.IsNullOrEmpty(userInfo.MobilePhone))
         {
             userInfo.MobilePhone = SmsManager.GetPhoneValueDigits(userInfo.MobilePhone);
         }
         if (string.IsNullOrEmpty(userInfo.UserName))
         {
             if (string.IsNullOrWhiteSpace(userInfo.FirstName))
             {
                 userInfo.FirstName = Resource.FirstName;
             }
             if (string.IsNullOrWhiteSpace(userInfo.LastName))
             {
                 userInfo.LastName = Resource.LastName;
             }
             if (TenantStatisticsProvider.GetUsersCount() < TenantExtra.GetTenantQuota().ActiveUsers)
             {
                 userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), true, false);
             }
             else
             {
                 userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), true, false, true);
             }
         }
         else
         {
             CoreContext.UserManager.SaveUserInfo(userInfo);
         }
         var photoUrl = samlResponse.GetRemotePhotoUrl();
         if (!string.IsNullOrEmpty(photoUrl))
         {
             var photoLoader = new UserPhotoLoader();
             photoLoader.SaveOrUpdatePhoto(photoUrl, userInfo.ID);
         }
     }
     finally
     {
         SecurityContext.Logout();
     }
     var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);
     CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
 }