예제 #1
0
        //TODO: Rename method accc to what it does
        public LDAPUser AuthenticateUserWithLdap(UserCredential userCredential)
        {
            var ldapAuthentication = new LDAPAuthentication()
            {
                DomainName = ConfigurationManager.AppSettings["Domain"],
                UserName   = userCredential.Username,
                Password   = userCredential.Password
            };

            _logMessages.AppendFormat("Performing LDAP logon for user {0} with domain {1}", ldapAuthentication.UserName, ldapAuthentication.DomainName);
            LDAPUser response = null;

            try
            {
                response = _ldapAuthenticationService.IsAuthenticated(ldapAuthentication);
                _logMessages.Append("Successfully invoked ldap service. Response received");
            }
            catch (Exception ex)
            {
                _logMessages.AppendFormat("An Error occurred invoking ldap authentication. Exception details {0}", ex.Message);
                Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(ex));
            }
            _logger.Info(_logMessages.ToString());
            return(response);
        }
 public LDAPAuthenticationRepository(IActiveAnalyticsLogger logger)
 {
     _logger      = logger;
     _logMessages = new StringBuilder();
     _userDetails = new LDAPUser()
     {
         AccountName      = string.Empty,
         LDAPAccessStatus = LDAPAccessStatus.UserLogonUnsuccessful
     };
 }
예제 #3
0
        public ActionResult Login(UserViewModel uvm)
        {
            if (ModelState.IsValid)
            {
                LDAPUser ldapUserDetails = LDAPService.Instance.AuthenticationAndIdentification(uvm.User.Username, uvm.User.Password);
                if (ldapUserDetails == null)
                {
                    ModelState.AddModelError(string.Empty, "Wrong username or password.");

                    return(View("Index", uvm));
                }

                var user = userRepository.GetByFilter(u => u.Username == uvm.User.Username).FirstOrDefault();

                if (user == null)
                {
                    var newUser = new User
                    {
                        Firstname = ldapUserDetails.Firstname,
                        Lastname  = ldapUserDetails.Lastname,
                        Username  = ldapUserDetails.Username,
                        Email     = ldapUserDetails.Email,
                        Zone      = zoneRepository.GetByFilter(z => z.Label == ldapUserDetails.Zone).FirstOrDefault(),
                        Role      = roleRepository.GetByFilter(r => r.RoleName == Roles.COLLABORATOR).FirstOrDefault()
                    };

                    userRepository.Insert(newUser);
                    userRepository.SaveChanges();

                    Session["username"] = newUser.Username;
                    Session["role"]     = newUser.Role.RoleName.ToString("g");
                    Session["id"]       = newUser.Id;
                    Session["Zone"]     = newUser.Zone.Label;
                }
                else
                {
                    user.Role = roleRepository.GetById(user.RoleId);

                    Session["username"] = user.Username;
                    Session["role"]     = user.Role.RoleName.ToString("g");
                    Session["id"]       = user.Id;
                    Session["Zone"]     = user.Zone.Label;

                    if (this.IsAdmin())
                    {
                        return(RedirectToAction("Index", "Admin"));
                    }
                }

                return(RedirectToAction("Index", "Portfolio"));
            }

            return(View());
        }
        /// <summary>
        /// Compares LDAPUser class with what is already stored in eDirectory.
        /// Returns the results of the comparison if there are changes.
        /// Local differences always override eDirectory
        /// </summary>
        /// <returns>
        /// A <see cref="ArrayList"/>
        /// </returns>
        internal static ArrayList BuildLDAPUserModifications(LDAPUser newUser, LDAPUser currUser)
        {
            modList = new ArrayList ();
            /* If values do not match, replace */
            if (AttrEqual(newUser.Title, currUser.Title) == false)
                MakeLdapMod(ATTRNAME.TITLE, newUser.Title);

            if (AttrEqual(newUser.DISPLAYNAME, currUser.DISPLAYNAME) == false)
                MakeLdapMod(ATTRNAME.DISPLAYNAME, newUser.DISPLAYNAME);

            if (AttrEqual(newUser.DEPARTMENTNUMBER, currUser.DEPARTMENTNUMBER) == false)
                MakeLdapMod(ATTRNAME.DEPARTMENTNUMBER, newUser.DEPARTMENTNUMBER);

            return modList;
        }
예제 #5
0
 public static LDAPUser GetUserFromActiveDirectory(string username, string domainPath, out string message)
 {
     try
     {
         LDAPUser          adUser     = new LDAPUser();
         DirectoryEntry    searchRoot = new DirectoryEntry(domainPath);
         DirectorySearcher search     = new DirectorySearcher(searchRoot);
         search.Filter = "(&(objectClass=user)(objectCategory=person))";
         search.PropertiesToLoad.Add("samaccountname");
         search.PropertiesToLoad.Add("mail");
         search.PropertiesToLoad.Add("displayname");
         SearchResult           result;
         SearchResultCollection resultCol = search.FindAll();
         if (resultCol != null)
         {
             for (int counter = 0; counter < resultCol.Count; counter++)
             {
                 result = resultCol[counter];
                 if (result.Properties.Contains("samaccountname") &&
                     result.Properties.Contains("mail") &&
                     result.Properties.Contains("displayname"))
                 {
                     string smaName = (String)result.Properties["samaccountname"][0];
                     if (!string.IsNullOrWhiteSpace(smaName) &&
                         smaName.Trim().ToLower() == username.Trim().ToLower())
                     {
                         adUser             = new LDAPUser();
                         adUser.UserName    = (String)result.Properties["samaccountname"][0];
                         adUser.DisplayName = (String)result.Properties["displayname"][0];
                         adUser.Email       = !string.IsNullOrWhiteSpace((String)result.Properties["mail"][0]) ? (String)result.Properties["mail"][0]
                             : string.Empty;
                         break;
                     }
                 }
             }
         }
         message = "OK";
         return(adUser);
     }
     catch (Exception ex)
     {
         message = ex.Message;
         return(null);
     }
 }
예제 #6
0
        public HttpResponseMessage Post(JObject o)
        {
            string username = o["username"].ToString();
            string password = o["password"].ToString();

            LDAPUser ldapUserDetails = LDAPService.Instance.AuthenticationAndIdentification(username, password);

            if (ldapUserDetails == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Uknowing username or password"));
            }

            var user = userRepository.GetByFilter(u => u.Username == username).FirstOrDefault();

            if (user == null)
            {
                var newUser = new User
                {
                    Firstname = ldapUserDetails.Firstname,
                    Lastname  = ldapUserDetails.Lastname,
                    Username  = ldapUserDetails.Username,
                    Email     = ldapUserDetails.Email,
                    //Zone = ldapUserDetails.Zone,
                    Role = roleRepository.GetByFilter(r => r.RoleName == Roles.COLLABORATOR).FirstOrDefault()
                };
                user = newUser;
                userRepository.Insert(newUser);
                userRepository.SaveChanges();
            }

            HttpContext.Current.Session["Username"] = username;
            JObject us = new JObject
            {
                { "username", ldapUserDetails.Username },
                { "firstanme", ldapUserDetails.Firstname },
                { "lastname", ldapUserDetails.Lastname },
                { "email", ldapUserDetails.Email },
                { "adress", ldapUserDetails.Address },
                { "zone", ldapUserDetails.Zone },
                { "role", user.Role.RoleName.ToString() }
            };

            return(Request.CreateResponse(HttpStatusCode.OK, us));
        }
예제 #7
0
        public void Login_Internal_Using_Correct_Credentials()
        {
            LDAPUser authResponse = new LDAPUser();

            authResponse.AccountName             = "TEST_USER";
            authResponse.DisplayName             = "TEST_USER";
            authResponse.FirstName               = "TEST";
            authResponse.LastName                = "USER";
            authResponse.LDAPAccessStatus        = LDAPAccessStatus.UserLogonSuccessful;
            authResponse.LDAPAccessStatusMessage = string.Empty;
            mockRestClient.Setup(restClient => restClient.IsLDAPAuthenticated(It.IsAny <string>(), It.IsAny <string>())).Returns(authResponse);
            _accountController     = new AccountController(mockLogger.Object, mockRestClient.Object, _mockOwinAuthManager.Object, _mockTableauConnector.Object);
            _accountController.Url = MockUrlHelper.Object;
            Web.Models.User loginRequest = new User()
            {
                IsInternalUser = true,
                UserName       = "******",
                Password       = "******"
            };
            var loginResponse = _accountController.Login(loginRequest);

            Assert.IsNotNull(loginResponse);
            Assert.IsInstanceOfType(loginResponse, typeof(ViewResult));
        }
예제 #8
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            xml = new XmlDocument();
            DataSet ds = new DataSet();
            string  Pass_Desencriptado = "";
            string  userDesencriptado  = "";

            IPUsr = ObtenerIPCliente();
            Azteca.Utility.Security.Rijndael _ChyperRijndael = new Azteca.Utility.Security.Rijndael();

            try
            {
                string ruta       = _ChyperRijndael.Transmute(ConfigurationManager.AppSettings["LlavePrivada"], Azteca.Utility.Security.enmTransformType.intDecrypt);
                string Passphrase = "";
                try
                {
                    Passphrase = (string)Registry.LocalMachine.OpenSubKey(_ChyperRijndael.Transmute(ConfigurationSettings.AppSettings["Registro"], Azteca.Utility.Security.enmTransformType.intDecrypt)).GetValue("passphrase");
                }
                catch
                {
                    //Esto es para Win 7 64 bits

                    RegistryKey localKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64);
                    localKey   = localKey.OpenSubKey(_ChyperRijndael.Transmute(ConfigurationSettings.AppSettings["Registro"], Azteca.Utility.Security.enmTransformType.intDecrypt));
                    Passphrase = localKey.GetValue("passphrase").ToString();
                    localKey.Dispose();
                }
                StreamReader stream = new StreamReader(PGPUtil.DesencriptarTexto(txtContraseña.Text,
                                                                                 File.OpenRead(ruta),
                                                                                 null, Passphrase.ToCharArray()).datos);
                StreamReader streamUser = new StreamReader(PGPUtil.DesencriptarTexto(txtUsuario.Text,
                                                                                     File.OpenRead(ruta),
                                                                                     null, Passphrase.ToCharArray()).datos);

                Pass_Desencriptado = stream.ReadToEnd();
                userDesencriptado  = streamUser.ReadToEnd();

                string TipoUsuario = userDesencriptado.ToUpper().Replace("TVA", "").Replace("PTV", "");

                if (isNumeric(TipoUsuario))
                {
                    isUserName = false;
                    UsuarioTVA = userDesencriptado.ToUpper();
                    usuario    = userDesencriptado.ToUpper();
                }
                else
                {
                    isUserName = true;
                    usuario    = userDesencriptado.ToUpper();
                    XmlDocument DatosUsua = MgnTDI_Menus.GetUserDataByNumEmpl("", usuario, "1,2,5");
                    string      NumUsua   = (DatosUsua.GetElementsByTagName("NUMUSUA").Count > 0) ? DatosUsua.GetElementsByTagName("NUMUSUA")[0].InnerText : "";
                    if (userDesencriptado.ToUpper().Contains("TVA"))
                    {
                        UsuarioTVA = "TVA" + NumUsua;
                    }
                    else if (userDesencriptado.ToUpper().Contains("PTV"))
                    {
                        UsuarioTVA = "PTV" + NumUsua;
                    }
                    else
                    {
                        UsuarioTVA = "TVA" + NumUsua;
                    }
                }

                //Primeras Validacion Tipo de Usuario (Red o TVA)

                #region Validaciones de Usuario Bloqueado, Firmado, etc.
                IntentosXIP = MngNegocioBloqueoIP.ConsultaUltimoAccesos();

                if (ValidaIP(IPUsr, IntentosXIP) >= 10)
                {
                    string strMessage = string.Empty;
                    strMessage       += strMessage == string.Empty ? "" : "<br>";
                    strMessage       += " * Su IP ha sido bloqueada";
                    strMessage       += "<br>";
                    tdError.InnerHtml = strMessage;
                    tdError.Visible   = true;
                    txtUsuario.Text   = usuario;
                    GuardaLogAcceso(8);
                    return;
                }


                //Aqui se debe de mandar a validar si el usuario esta bloqueado por Intentos fallidos
                UserBlock = MngNegocioBloqueoUsuario.ConsultaUsuarioBloqueadoXIdUsuario(usuario.ToUpper().ToString(), "1");
                if (UserBlock.Count > 0)
                {
                    //El Usuario ya ha sido bloqueado
                    string strMessage = string.Empty;
                    strMessage       += strMessage == string.Empty ? "" : "<br>";
                    strMessage       += " * El Usuario ha sido bloqueado por : " + UserBlock[0].TipoBloqueo.DescTipoBloqueo;
                    strMessage       += "<br>";
                    strMessage       += "Favor de Solicitar su desbloqueo por DATASEC";
                    tdError.InnerHtml = strMessage;
                    Random random    = new Random();
                    int    NumMsgBox = random.Next(-999999999, 999999999);
                    ClientScript.RegisterStartupScript(Page.GetType(), "AlertBloqueo" + NumMsgBox, "<script>alert('El Usuario ha sido bloqueado por " + UserBlock[0].TipoBloqueo.DescTipoBloqueo + ". Para desbloquearlo deberá realizar la solicitud en DATASEC');</script>");
                    tdError.Visible = true;
                    txtUsuario.Text = usuario;
                    GuardaLogAcceso(9);
                    return;
                }
                #endregion

                string respuesta = string.Empty;

                #region Login
                LDAPUser ldapUser = new LDAPUser();

                if (!validaLlaveMaestra(TipoUsuario, userDesencriptado, Pass_Desencriptado))
                {
                    try
                    {
                        if (isUserName)
                        {
                            ldapUser = ActiveDirectory.GetCurrentUser2(userDesencriptado.ToUpper(), Pass_Desencriptado);
                        }
                        else
                        {
                            ldapUser = ActiveDirectory.GetCurrentUser(userDesencriptado.ToUpper(), Pass_Desencriptado);
                        }
                    }
                    catch { ldapUser = null; }


                    if (ldapUser != null)
                    {
                        if (AutenticaUsuario.Validar("", userDesencriptado, Pass_Desencriptado))
                        {
                            XmlDocument UserData = new XmlDocument();
                            if (isUserName)
                            {
                                UserData = MgnTDI_Menus.GetUserDataByNumEmpl("", ldapUser.LoginName, "1,2,5");
                            }
                            else
                            {
                                UserData   = MgnTDI_Menus.GetUserDataByNumEmpl(ldapUser.EmployeeID, "", "1,2,5");
                                isUserName = true;
                            }
                            ObtieneDatosUsuario(UserData);
                        }
                        else
                        {
                            ValidaBloqueosErrorPass();
                        }
                    }
                    else
                    {
                        ValidaBloqueosErrorPass();
                    }
                }
            }
            catch (Exception ex)
            {
                THE_LogErrores oLogErrores = new THE_LogErrores();
                TDI_EMPL       oEmpl       = new TDI_EMPL();
                oEmpl.EmpleadoLlavePrimaria = !UsuarioTVA.Replace("TVA", "").Trim().Equals(String.Empty) ? int.Parse(UsuarioTVA.Replace("TVA", "")) : 0;
                oLogErrores.CveEmpleado     = oEmpl;
                oLogErrores.DirIP           = IPUsr;
                oLogErrores.Error           = ex.Message + "\n" + ex.StackTrace.ToString();
                oLogErrores.Pantalla        = "Default.aspx";
                oLogErrores.MachineName     = "";
                oLogErrores.FechaCreacion   = DateTime.Now;
                oLogErrores.Dominio         = Request.Url.Host.ToLower();
                MngNegocioLogErrores.GuardarLogErrores(oLogErrores);
                this.div_txtUsuario.InnerHtml = "El usuario no tiene permisos para acceder al sistema";
                GuardaLogAcceso(2);
            }

            #endregion
        }
예제 #9
0
        public ActionResult Login(User usrLogin)
        {
            _logMessages.Append("Initiating Login in AccountController.Login .");
            bool           success       = false;
            string         tableauTicket = string.Empty;
            string         serviceId     = string.Empty;
            string         defaultDomain = "";
            ClaimsIdentity userClaims    = null;
            bool           enableTableau = false;

            if (ModelState.IsValid)
            {
                try
                {
                    enableTableau = ConfigurationManager.AppSettings["enableTableau"].Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase);
                    defaultDomain = ConfigurationManager.AppSettings["DefaultDomain"].ToString();
                    if (usrLogin.IsInternalUser)
                    {
                        _logMessages.Append("Performing logon as internal user LDAP Authentication. Username " + usrLogin.UserName + ".");
                        LDAPUser ldapUser = _restClient.IsLDAPAuthenticated(usrLogin.UserName, usrLogin.Password);

                        if (ldapUser == null)
                        {
                            success = false;
                            ModelState.AddModelError(string.Empty, "An error occurred please try again.");
                        }
                        else
                        {
                            switch (ldapUser.LDAPAccessStatus)
                            {
                            case LDAPAccessStatus.UserLogonSuccessful:
                                _logMessages.Append("Ldap Authentication successfull.");
                                userClaims = new ClaimsIdentity(
                                    new[]
                                {
                                    new Claim(ClaimTypes.Name, usrLogin.UserName),
                                    new Claim(ClaimTypes.GivenName, ldapUser.FirstName),
                                    new Claim(ClaimTypes.Surname, ldapUser.LastName),
                                    new Claim(AHP.Core.ClaimTypes.DisplayName, ldapUser.DisplayName),
                                    new Claim(AHP.Core.ClaimTypes.IsInternalUser, usrLogin.IsInternalUser.ToString())
                                },
                                    Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);

                                success = true;

                                _logMessages.AppendFormat("Retrieving tableau account name for internal user {0}.", usrLogin.UserName);

                                //Authenticate with Tableau for trusted ticket
                                GenericAjaxResponse <string> getAccnameResponse = _restClient.GetTableauAccountname(usrLogin.UserName);

                                _logMessages.AppendFormat("Tableau account name mapped to user {0} is '{1}'.", usrLogin.UserName, getAccnameResponse.Data);

                                if (getAccnameResponse.Success && !string.IsNullOrEmpty(getAccnameResponse.Data))
                                {
                                    GenericAjaxResponse <string> tabSigninResponse = _tableauClient.SignIn(getAccnameResponse.Data);
                                    if (tabSigninResponse.Success)
                                    {
                                        tableauTicket = tabSigninResponse.Data;
                                    }
                                }

                                //add tableau ticket to claims
                                userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.TableauAuthTicket, tableauTicket));

                                //Authenticate with BO again to get the Token for Reports
                                _logMessages.Append("Requesting BO Server for user information and token.");

                                //get session information along wit user information
                                GenericAjaxResponse <AHP.Core.Model.BOUserSessionInfo> sessionInfo = _restClient.LogonToWebIntelligence(usrLogin.UserName);
                                if (sessionInfo.Success)
                                {
                                    userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.MustChangeSecurityQuestion, bool.FalseString));
                                    //AD Users are always a User. They can't be admin
                                    userClaims.AddClaim(new Claim(ClaimTypes.Role, "User"));
                                    userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.LogonToken, sessionInfo.Data.DefaultToken));
                                    userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.BOSessionId, sessionInfo.Data.SessionId));
                                    userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.BOSerializedSession, sessionInfo.Data.SerializedSession));
                                    //Internal users can't change pwd
                                    userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.MustChangePassword, bool.FalseString));
                                    //for internal users last login date is now
                                    userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.LastLogonDate, DateTime.Now.ToShortDateString()));
                                    //internal users don't have pwd expiry
                                    userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.PasswordExpired, bool.FalseString));
                                    success = true;
                                }
                                else
                                {
                                    ModelState.AddModelError(string.Empty, sessionInfo.Errors[0]);
                                    success = false;
                                }
                                break;

                            case LDAPAccessStatus.UserLogonUnsuccessful:
                                success = false;
                                ModelState.AddModelError(string.Empty, "The username and password combination you entered is incorrect. Please use the same username and password as your AHM computer and try again.");
                                _logMessages.Append("Internal user authentication failed for user " + usrLogin.UserName + ".");
                                break;

                            case LDAPAccessStatus.UserAccountLocked:
                                success = false;
                                ModelState.AddModelError(string.Empty, "Your user account is locked. Please contact AHM IT for further assistance");
                                _logMessages.Append("Internal user account has been locked for user " + usrLogin.UserName + ".");
                                break;

                            default:
                                success = false;
                                ModelState.AddModelError(string.Empty, "Unknown error has occurred. Please try again.");
                                _logMessages.AppendFormat("User :{0}, got response from AD which is either not success and nor Account locked.", usrLogin.UserName);
                                break;
                            }
                        }
                    }
                    else
                    {
                        _logMessages.Append("Performing Logon as External user. Authenticating with BO System. Username " + usrLogin.UserName + ".");

                        GenericAjaxResponse <AHP.Core.DTO.ExternalUserInfo> apiResponse = _restClient.Login(usrLogin.UserName, usrLogin.Password);

                        if (apiResponse == null)
                        {
                            ModelState.AddModelError(string.Empty, "An error occurred. Please try again");
                            success = false;
                        }
                        else
                        {
                            if (!apiResponse.Success)
                            {
                                success = false;
                                if (apiResponse.Errors.Count >= 1)
                                {
                                    string errMessage = apiResponse.Errors[0];
                                    if (!string.IsNullOrEmpty(errMessage))
                                    {
                                        errMessage = errMessage.Replace("<<click here>>", "<a href='" + Url.Action("ResetPassword", "AccountRecovery") + "' title='reset password'>click here</a>");
                                    }
                                    ModelState.AddModelError(string.Empty, errMessage);
                                }
                                else
                                {
                                    ModelState.AddModelError(string.Empty, "An error occurred. Please try again");
                                }
                            }
                            else
                            {
                                if (apiResponse.Data == null)
                                {
                                    success = false;
                                    ModelState.AddModelError(string.Empty, "An error occurred. Please try again");
                                }
                                else
                                {
                                    _logMessages.AppendFormat("Retrieving tableau account name for external user {0}.", usrLogin.UserName);

                                    //get session information along wit user information
                                    GenericAjaxResponse <AHP.Core.Model.BOUserSessionInfo> sessionInfo = _restClient.LogonToWebIntelligence(apiResponse.Data.Username);

                                    //get security question for the user, if nothing exists then ask user to setup his security questions
                                    GenericAjaxResponse <List <AHP.Core.DTO.UserSecurityOption> > usrQuestions = _restClient.GetSecurityQuestionsForUser(apiResponse.Data.Username);

                                    if (sessionInfo.Success)
                                    {
                                        userClaims = new ClaimsIdentity(new[]
                                        {
                                            new Claim(ClaimTypes.Name, usrLogin.UserName),
                                            new Claim(AHP.Core.ClaimTypes.IsInternalUser, usrLogin.IsInternalUser.ToString())
                                        }, Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);

                                        userClaims.AddClaim(new Claim(ClaimTypes.GivenName, apiResponse.Data.Firstname));
                                        userClaims.AddClaim(new Claim(ClaimTypes.Surname, apiResponse.Data.Lastname));
                                        userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.DisplayName, string.Format("{0},{1}", apiResponse.Data.Lastname, apiResponse.Data.Firstname)));
                                        userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.Company, apiResponse.Data.Company ?? string.Empty));
                                        userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.MustChangeSecurityQuestion, usrQuestions.Success ? (usrQuestions.Data.Count != 3).ToString() : bool.FalseString));
                                        userClaims.AddClaim(new Claim(ClaimTypes.Email, apiResponse.Data.Email));
                                        userClaims.AddClaim(new Claim(ClaimTypes.Role, apiResponse.Data.Role));
                                        userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.LogonToken, sessionInfo.Data.DefaultToken));
                                        userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.BOSessionId, sessionInfo.Data.SessionId));
                                        userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.BOSerializedSession, sessionInfo.Data.SerializedSession));
                                        userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.MustChangePassword, apiResponse.Data.ChangePasswordOnLogon.ToString()));
                                        userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.LastLogonDate, apiResponse.Data.LastLogonDate));
                                        userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.PasswordExpired, (apiResponse.Data.PasswordExpiresOn.Date - DateTime.Today).TotalDays <= 0 ? bool.TrueString:bool.FalseString));


                                        _logMessages.AppendFormat("Using Service SID for tableau account name for external user {0}.", usrLogin.UserName);

                                        serviceId = System.Configuration.ConfigurationManager.AppSettings["SID"];
                                        GenericAjaxResponse <string> tabSigninResponse = _tableauClient.SignIn(serviceId);
                                        if (tabSigninResponse.Success)
                                        {
                                            tableauTicket = tabSigninResponse.Data;
                                        }

                                        _logMessages.AppendFormat("Obtained ticket '{0} for external user {1} using SID'", tableauTicket, usrLogin.UserName);

                                        //add tableau ticket to claims
                                        userClaims.AddClaim(new Claim(AHP.Core.ClaimTypes.TableauAuthTicket, tableauTicket));

                                        success = true;
                                    }
                                    else
                                    {
                                        ModelState.AddModelError(string.Empty, sessionInfo.Errors[0]);
                                        success = false;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logMessages.Append("An Error occurred Exception Message is " + ex.Message + ".");
                    Elmah.ErrorLog.GetDefault(null).Log(new Elmah.Error(ex));
                    ModelState.AddModelError(string.Empty, "Error occurred processing your request. Please try again");
                    success = false;
                }
            }
            else
            {
                _logMessages.Append("Model Validation Failed.");
                success = false;
            }
            _logger.Info(_logMessages.ToString());

            if (success)
            {
                _authManager.SignIn(Request, userClaims);
                //redirect to customer logon page
                return(RedirectToAction("Home", "Customer"));
            }
            else
            {
                usrLogin.UserName       = string.Empty;
                usrLogin.Password       = string.Empty;
                usrLogin.IsInternalUser = false;
                return(View("~/Views/Default/login.cshtml", usrLogin));
            }
        }
예제 #10
0
        /// <summary>
        /// Parses a LdapAttributeSet and the specified user DN
        /// Returns a user object.
        /// </summary>
        /// <param name="attrSet">
        /// A <see cref="LdapAttributeSet"/>
        /// </param>
        /// <param name="dn">
        /// A <see cref="System.String"/>
        /// </param>
        /// <returns>
        /// A <see cref="LDAPUser"/>
        /// </returns>
        public static LDAPUser iterUsrAttrs(LdapAttributeSet attrSet, string dn)
        {
            LDAPUser user;
            System.Collections.IEnumerator ienum =  attrSet.GetEnumerator();

            if (attrSet.Count == 0) {
                Logger.Debug("No attributes in the AttributeSet for {0}", dn);
                return null;
            }

            user = new LDAPUser(dn);

            while(ienum.MoveNext())
            {

                LdapAttribute attribute=(LdapAttribute)ienum.Current;
                Logger.Debug("Parsing {0}", attribute);

                if (AttrEquals(attribute, ATTRNAME.NDSHOMEDIRECTORY))
                    user.parseNdsHomeDirPath(AttributeUtil.getAttr(attrSet, ATTRNAME.NDSHOMEDIRECTORY));

                if (AttrEquals(attribute, ATTRNAME.SN))
                    user.setSN(AttributeUtil.getAttr(attrSet, ATTRNAME.SN));

                if (AttrEquals(attribute, ATTRNAME.GIVENNAME))
                    user.setGivenName(AttributeUtil.getAttr(attrSet, ATTRNAME.GIVENNAME));

                if (AttrEquals(attribute, ATTRNAME.TITLE))
                    user.Title = AttributeUtil.getAttr(attrSet, ATTRNAME.TITLE);

                if (AttrEquals(attribute, ATTRNAME.HOMEPHONE))
                    user.HOMEPHONE = AttributeUtil.getAttr(attrSet, ATTRNAME.HOMEPHONE);

                if (AttrEquals(attribute, ATTRNAME.DISPLAYNAME))
                    user.DISPLAYNAME = AttributeUtil.getAttr(attrSet, ATTRNAME.DISPLAYNAME);

                if (AttrEquals(attribute, ATTRNAME.NGWFID))
                    user.GW_FID = AttributeUtil.getAttr(attrSet, ATTRNAME.NGWFID);
            }
            return user;
        }
예제 #11
0
파일: LDAPTests.cs 프로젝트: chrisdns/TPGP
        public void AuthenticationAndIdentification_AuthFakeUser_ReturnNull()
        {
            LDAPUser u = LDAPService.Instance.AuthenticationAndIdentification("fakeUsername", "fakePassword");

            Assert.IsNull(u);
        }
예제 #12
0
파일: LDAPTests.cs 프로젝트: chrisdns/TPGP
        public void AuthenticationAndIdentification_AuthNotFakeUser_ReturnUser()
        {
            LDAPUser u = LDAPService.Instance.AuthenticationAndIdentification("Sarra", "Sarra");

            Assert.IsNotNull(u);
        }
        public LDAPUser CreateUser(string accountName)
        {
            LDAPUser adUser = LDAPHelper.SearchAccurateUserInfo(accountName, true).Where(x => string.IsNullOrEmpty(x.Mail) != true && x.AccountDisabled != true && !x.SamaccountName.Contains("_")).OrderBy(x => x.DisplayName).FirstOrDefault();

            return(adUser);
        }
예제 #14
0
        public static bool ValidausuarioIpad(string Usuario_TVA, string Pass_Desencript)
        {
            XmlDocument xml = new XmlDocument();
            DataSet     ds  = new DataSet();
            string      Pass_Desencriptado = "";
            string      userDesencriptado  = "";
            string      usuario            = "";

            string UsuarioTVA = string.Empty;
            bool   isUserName = false;

            try
            {
                Pass_Desencriptado = Pass_Desencript;
                userDesencriptado  = Usuario_TVA;

                string TipoUsuario = userDesencriptado.ToUpper().Replace("TVA", "").Replace("PTV", "");

                if (isNumeric(TipoUsuario))
                {
                    isUserName = false;
                    UsuarioTVA = userDesencriptado.ToUpper();
                    usuario    = userDesencriptado.ToUpper();
                }
                else
                {
                    isUserName = true;
                    usuario    = userDesencriptado.ToUpper();
                    XmlDocument DatosUsua = MngNegocioEmpleadoRol.GetUserDataByNumEmpleado("", usuario);
                    string      NumUsua   = (DatosUsua.GetElementsByTagName("NUMUSUA").Count > 0) ? DatosUsua.GetElementsByTagName("NUMUSUA")[0].InnerText : "";
                    if (userDesencriptado.ToUpper().Contains("TVA"))
                    {
                        UsuarioTVA = "TVA" + NumUsua;
                    }
                    else if (userDesencriptado.ToUpper().Contains("PTV"))
                    {
                        UsuarioTVA = "PTV" + NumUsua;
                    }
                    else
                    {
                        UsuarioTVA = "TVA" + NumUsua;
                    }
                }



                string respuesta = string.Empty;


                LDAPUser ldapUser = new LDAPUser();

                try
                {
                    if (isUserName)
                    {
                        ldapUser = ActiveDirectory.GetCurrentUser2(userDesencriptado.ToUpper(), Pass_Desencriptado);
                    }
                    else
                    {
                        ldapUser = ActiveDirectory.GetCurrentUser(userDesencriptado.ToUpper(), Pass_Desencriptado);
                    }
                }
                catch { ldapUser = null; }


                if (ldapUser != null)
                {
                    if (AutenticaUsuario.Validar("", userDesencriptado, Pass_Desencriptado))
                    {
                        XmlDocument UserData = new XmlDocument();
                        if (isUserName)
                        {
                            UserData = MngNegocioEmpleadoRol.GetUserDataByNumEmpleado("", ldapUser.LoginName);
                        }
                        else
                        {
                            UserData   = MngNegocioEmpleadoRol.GetUserDataByNumEmpleado(ldapUser.EmployeeID, "");
                            isUserName = true;
                        }
                    }
                    else
                    {
                    }
                }
                else
                {
                    try
                    {
                        if (isNumeric(TipoUsuario))
                        {
                            respuesta = Llave.validaEmpleado(userDesencriptado, Pass_Desencriptado);
                        }
                        else
                        {
                            respuesta = Llave.validaEmpleado(UsuarioTVA, Pass_Desencriptado);
                        }
                        xml.LoadXml(respuesta);
                    }
                    catch (Exception ex)
                    {
                        THE_LogError oLogErrores = new THE_LogError();
                        oLogErrores.EmplUsua      = UsuarioTVA.Replace("TVA", "").Replace("PTV", "");
                        oLogErrores.DirIP         = "";
                        oLogErrores.Error         = ex.Message + "\n" + ex.StackTrace.ToString();
                        oLogErrores.Pantalla      = "Autenticausuario";
                        oLogErrores.MachineName   = "";
                        oLogErrores.FechaCreacion = DateTime.Now;
                        oLogErrores.Dominio       = "";
                        MngNegocioLogErrores.GuardarLogErrores(oLogErrores);
                    }

                    if ((respuesta.IndexOf("Respuesta=\"[OK]\"") != -1) || respuesta.IndexOf("0 - [") != -1)
                    {
                        string numeroUsuario = xml.FirstChild.ChildNodes[0].Attributes["NumEmp"].Value;

                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }