Exemplo n.º 1
0
        public ActionResult Edit()
        {
            PSD.Model.User auxUser  = controller.GetUser(CurrentUser.Id);
            string         userRole = auxUser.RolesXUser.FirstOrDefault().Cat_UserRole.IdB;

            switch (userRole)
            {
            case "sysadmin":
            case "appadmin":
                return(View(controller.GetBayerEmployee(CurrentUser.Id)));

            case "employee-manager_operation":
            case "employee-rtv_operation":
                return(RedirectToAction("EditBayerEmployee"));

            case "customer-distributor_operation":
            case "customer-distributor_view":
                return(RedirectToAction("EditDistributorEmployee"));

            case "customer-subdistributor_operation":
            case "customer-subdistributor_view":
                return(RedirectToAction("EditSubdistributorEmployee"));

            default:
                break;
            }
            return(RedirectToError(errorDefault, "Unexpected user Role '" + userRole + "'"));
        }
Exemplo n.º 2
0
        public ActionResult Index()
        {
            PSD.Model.User auxUser = controller.GetUser(CurrentUser.Id);
            if (auxUser == null)
            {
                return(RedirectToError(errorDefault, "El usuario actualmente logueado '[" + CurrentUser.Id + "] " + CurrentUser.Nick + "' no se encontró en la base de datos, puede que haya sido eliminado mientras estaba logueado"));
            }
            string userRole = auxUser.RolesXUser.FirstOrDefault().Cat_UserRole.IdB;

            switch (userRole)
            {
            case "sysadmin":
            case "appadmin":
                return(View(controller.GetBayerEmployee(CurrentUser.Id)));

            case "employee-manager_operation":
            case "employee-rtv_operation":
                return(RedirectToAction("IndexBayerEmployee"));

            case "customer-distributor_operation":
            case "customer-distributor_view":
                return(RedirectToAction("IndexDistributorEmployee"));

            case "customer-subdistributor_operation":
            case "customer-subdistributor_view":
                return(RedirectToAction("IndexSubdistributorEmployee"));

            default:
                break;
            }
            return(RedirectToError(errorDefault, "Unexpected user role: '" + userRole + "'"));
        }
Exemplo n.º 3
0
        public ActionResult NewUserConfirmation(string token)
        {
            //Deprecated, using token instead, this is cleaner and can help to reuse this function
            //this 'NewUserConfirmation' method can be only accessed by comming from 'LoginByToken' method, which will always set up this user object into TempData
            //User model = (Model.User)TempData["currentUser"];
            if (string.IsNullOrWhiteSpace(token))
            {
                NotifyUser(messageError: errorDefault, messageDebug: controllerTraceId + "NewUserConfirmation.511 User object was not received");
                return(RedirectToError());
            }

            PSD.Model.User model = controller.GetUserByToken(token);
            //TODO:handle model null or error

            return(View(model));
        }
Exemplo n.º 4
0
        public bool Login(string nickName, string password)
        {
            //business validations
            //-has nickname
            if (string.IsNullOrWhiteSpace(nickName))
            {
                ResultManager.Add("Credenciales inválidas, no se indicó el correo del usuario", Trace + "Login.111 No nickname was provided. ");
                return(false);
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                ResultManager.Add("Credenciales inválidas, no se indicó la contraseña", Trace + "Login.121 No password was provided (empty passwords are not allowed on any case)");
                return(false);
            }

            nickName = nickName.Trim();
            password = password.Trim();


            PSD.Model.User userLogin = null;
            IEnumerable <PSD.Model.RolesXUser> userRoles;

            try
            {
                userLogin = Repository.Users.GetByNickName(nickName);
            }
            catch (Exception ex)
            {
                ResultManager.Add(ErrorDefault, Trace + "Login.311 Error while trying to retrieve user '" + nickName + "' from database. ", ex);
                return(false);
            }

            if (userLogin == null)
            {
                ResultManager.Add("Credenciales inválidas", Trace + "Login.411 User with nickname '" + nickName + "'not found in DB");
                return(false);
            }

            //validate user able to perform login
            switch (userLogin.Cat_UserStatus.IdB)
            {
            case "active":
            case "toconfirm":
            case "tocomplete":
                break;

            case "disabled":
                ResultManager.Add("Credenciales inválidas, el usuario '" + nickName + "' esta deshabilitado. Contacte a su administrador para rehabilitarlo", Trace + "Login.511 user '" + nickName + "' was disabled");
                return(false);

            case "deleted":
                ResultManager.Add("Credenciales inválidas, usuario no encontrado.", Trace + "Login.511 user '" + nickName + "' was deleted");
                return(false);

            default:     //unknown status
                ResultManager.Add(ErrorDefault, Trace + "Login.531 User nickname '" + nickName + "' is on an unknown status '" + userLogin.Cat_UserStatus.IdB + "'");
                return(false);
            }
            if (userLogin.FailedLoginAttempts >= 5)
            {
                try
                {
                    userLogin.Cat_UserStatusId = Repository.UserStatuses.Get(3).Id;//disabled ///TODO: change to dynamic status id set by IdB
                }
                catch (Exception ex)
                {
                    ResultManager.Add("El usuario esta inhabilitado", Trace + "Login.551 Exception while trying to inactivate user (due max failed login attempts reached)", ex);
                    return(false);
                }
                ResultManager.Add("Credenciales inválidas. Por seguridad, el usuario ha sido deshabilitado. Contacte a su administrador para rehabilitarlo", Trace + "Login.631 User has been disabled");
                return(false);
            }

            //validate user password
            bool resultPasswordValid = false;

            if (string.IsNullOrWhiteSpace(userLogin.Salt) || string.IsNullOrWhiteSpace(userLogin.Hash))
            {
                ResultManager.Add("El usuario no tiene un login asociado", Trace + "Login.561 User nickname '" + nickName + "' has not yet defined a login password (hash/salt)");
                return(false);
            }
            else
            {
                try
                {
                    if (Identity.ValidatePassword(password, userLogin.Salt, userLogin.Hash))
                    {
                        resultPasswordValid = true;
                    }
                }
                catch (Exception ex)
                {
                    ResultManager.Add(ErrorDefault, Trace + "Login.571 Exception while trying to validate password for user nickname '" + nickName + "'", ex);
                    return(false);
                }
            }
            if (!resultPasswordValid)
            {
                ResultManager.Add("Credenciales inválidas", Trace + "581. Invalid password for user with nickname '" + nickName + "'");

                //increase fail login attempts counter
                try
                {
                    userLogin.FailedLoginAttempts++;
                }
                catch (Exception ex)
                {
                    ResultManager.Add(ErrorDefault, Trace + "Login.611 Exception while trying to inactivate user due max failed login attempts reached", ex);
                    return(false);
                }

                //verify if max login attempts reached so it needs to be disabled
                if (userLogin.FailedLoginAttempts >= 5)
                {
                    try
                    {
                        userLogin.Cat_UserStatusId = Repository.UserStatuses.Get(3).Id;//disabled ///TODO: change to dynamic status id set by IdB
                        ResultManager.Add("El usuario ha sido deshabilitado debido a que ha alcanzado el número máximo de intentos de logueo fallidos permitido, contacte a su administrador para reactivar su usuario", Trace + "Login.631 User is disabled so can't login");
                    }
                    catch (Exception ex)
                    {
                        ResultManager.Add(ErrorDefault, Trace + "Login.651 Exception while trying to inactivate user due max failed login attempts reached", ex);
                        return(false);
                    }
                }
                Repository.Complete();
                return(false);
            }

            //at this point credentials are valid, perform login

            // validate password expiracy, false or true either way we need to login
            HasPasswordExpired = userLogin.LastPasswordChangeDate.HasValue
                                ? (DateTime.Today - userLogin.LastPasswordChangeDate.Value).Days > Configurations.PasswordExpireDays
                                : true;

            //-update db info about login
            try
            {
                userLogin.FailedLoginAttempts = 0;
                userLogin.LastLoginDate       = Common.Dates.Today;
                //Repository.Complete();
            }
            catch (Exception ex)
            {
                ResultManager.Add(ErrorDefault, Trace + "Login.711 Error while trying to update user info about login on DB", ex);
                return(false);
            }

            //-create user session object (recover db user details)
            try
            {
                userRoles = userLogin.RolesXUser;//repository.RolesXUser.GetUserRoles(userLogin.Id);
                if (userRoles == null)
                {
                    throw new Exception("Error while trying to get user roles, userId '" + userLogin.Id + "'");
                }

                string[] userRolesArray    = new string[userRoles.Count()];
                string[] userRoleIdBsArray = new string[userRoles.Count()];
                int      i = 0;
                foreach (PSD.Model.RolesXUser item in userRoles)
                {
                    userRolesArray[i]      = item.Cat_UserRole.IdB;
                    userRoleIdBsArray[i++] = item.Cat_UserRole.Name;
                }

                string employeeId = "";
                string userType   = "";
                string parentId   = "";
                switch (userRolesArray[0])
                {
                case "sysadmin":
                case "appadmin":
                case "employee-manager_operation":
                case "employee-manager_view":
                case "employee-rtv_operation":
                case "employee-rtv_view":
                    employeeId = Repository.BayerEmployees.Get(userLogin.Person.Id).IdB; break;

                case "customer-distributor_operation":
                case "customer-distributor_view":
                    Distributor auxDistributor = Repository.DistributorEmployees.Get(userLogin.Person.Id).Distributor;
                    employeeId = auxDistributor.IdB;
                    parentId   = auxDistributor.Id.ToString();
                    break;

                case "customer-subdistributor_operation":
                case "customer-subdistributor_view":
                    Subdistributor auxSubdistributor = Repository.SubdistributorEmployees.Get(userLogin.Person.Id).Subdistributor;
                    employeeId = auxSubdistributor.IdB;
                    userType   = auxSubdistributor.Type;
                    parentId   = auxSubdistributor.Id.ToString();
                    break;

                default: employeeId = ""; break;
                }

                Security.Entity.User auxUser = new Security.Entity.User(
                    userLogin.Id.ToString()
                    , employeeId
                    , userLogin.NickName
                    , userLogin.Person.Name + " " + userLogin.Person.LastNameF ///TODO:implement displayname on partial model class
                    , userLogin.Person.EMail
                    , userRolesArray
                    , userRoleIdBsArray
                    , userLogin.Cat_UserStatus.IdB
                    , userLogin.Cat_UserStatus.Name
                    , userType
                    , parentId
                    );

                if (!Identity.InitSession(auxUser))
                {
                    throw new Exception("Error while performing 'InitSession' for user.");
                }

                Repository.Complete();
                ResultManager.IsCorrect = true;
            }
            catch (Exception ex)
            {
                ResultManager.Add(ErrorDefault, Trace + "Login.811 Error while creating user session object", ex);
                return(false);
            }

            if (!ResultManager.IsCorrect)
            {
                return(false);
            }

            return(ResultManager.IsCorrect);
        }