Пример #1
0
        public ActionResult Login(LoginViewModel model, string returnUrl = "")
        {
            Session["BlockUser"] = null;
            if (ModelState.ContainsKey("LanguageList"))
            {
                ModelState["LanguageList"].Errors.Clear();
            }

            if (ModelState.IsValid)
            {
                string passwordEncripted = EncryptHelper.CalculateMD5Hash(model.Password);
                if (!_tokenManager.GenerateToken(model.UserName, passwordEncripted))
                {
                    ModelState.AddModelError("", Resources.LoginResources.InvalidUserPassword);
                    if (SessionHelper.Relogin)
                    {
                        return(Json(Resources.LoginResources.InvalidUserPassword));
                    }
                }

                _ISpartan_SettingsApiConsumer.SetAuthHeader(_tokenManager.Token);
                var FailedAttemptDB = _ISpartan_SettingsApiConsumer.GetByKey("FailedAttempts", false).Resource;
                int FailedAttempts  = Convert.ToInt32(FailedAttemptDB.Valor);
                model.MaxFailedAttempts = FailedAttempts;

                if (Session["UserName"] != null && Session["UserName"].ToString() != model.UserName)
                {
                    model.FailedAttempts = 1;
                }
                Session["UserName"] = model.UserName;
                _IUseroApiConsumer.SetAuthHeader(_tokenManager.Token);

                Spartan_Security_Log oSecurityLog = new Spartan_Security_Log();
                var UsersByName = _IUseroApiConsumer.ListaSelAll(0, 10, "Spartan_User.Username = '******'", "").Resource;
                if (UsersByName.RowCount == 0)
                {
                    ModelState.AddModelError("", Resources.LoginResources.InvalidUserPassword);
                    model.LanguageList    = GetLanguage();
                    SessionHelper.Relogin = false;
                    return(View(model));
                }
                // Call Validate User API for user Exists in application
                Spartan_User_Core UserDetails = _IUseroApiConsumer.ValidateUser(1, 10, "Username = '******'  COLLATE SQL_Latin1_General_CP1_CS_AS And Password = '******'  COLLATE SQL_Latin1_General_CP1_CS_AS").Resource;
                if (UserDetails.Spartan_Users != null && UserDetails.Spartan_Users.Count() > 0)
                {
                    if (UserDetails.Spartan_Users[0].Status == 1)
                    {
                        var spartan_user = new Core.Domain.Spartan_User.Spartan_User
                        {
                            Id_User  = UserDetails.Spartan_Users[0].Id_User,
                            Name     = UserDetails.Spartan_Users[0].Name,
                            Password = UserDetails.Spartan_Users[0].Password
                        };

                        TTUsuario user = new TTUsuario
                        {
                            IdUsuario       = Convert.ToInt16(UserDetails.Spartan_Users[0].Id_User),
                            Nombre          = Convert.ToString(UserDetails.Spartan_Users[0].Name),
                            Clave_de_Acceso = UserDetails.Spartan_Users[0].Username,
                            //Activo = UserDetails.Spartan_Users[0].Status
                        };

                        SetSecurityLogging(ref oSecurityLog, (short)Event_Type.Login, UserDetails.Spartan_Users[0].Id_User, UserDetails.Spartan_Users[0].Role, (short)Result_Type.Granted);
                        int SecurityLogId = _ISpartanSecurityApiConsumer.Insert(oSecurityLog).Resource;

                        SetAuthentication(UserDetails);
                        //_authenticationService.SignIn(user, model.RememberMe);

                        //Adding user Core entity Data
                        SessionHelper.UserEntity = UserDetails.Spartan_Users[0];

                        //Getting User Image
                        _ISpartane_FileApiConsumer.SetAuthHeader(_tokenManager.Token);
                        var userImage =
                            _ISpartane_FileApiConsumer.GetByKey(Convert.ToInt32(UserDetails.Spartan_Users[0].Image))
                            .Resource;
                        if (userImage != null && userImage.File != null)
                        {
                            SessionHelper.UserImage = userImage.File;
                        }
                        Response.Cookies["UserSettings"]["SecurityLogId"] = SecurityLogId.ToString();

                        Spartan_Session_Log oSessionLog = new Spartan_Session_Log();
                        SetSessionLogging(ref oSessionLog, (short)Event_Type.Login, (short)Event_Type.Login, SecurityLogId, UserDetails.Spartan_Users[0].Id_User, UserDetails.Spartan_Users[0].Role, (short)Result_Type.Granted);
                        _ISpartanSessionApiConsumer.Insert(oSessionLog);


                        //Saving Credentials
                        SessionHelper.UserCredential = new Spartane_Credential
                        {
                            Password = EncryptHelper.CalculateMD5Hash(model.Password),
                            UserName = model.UserName,
                        };
                        // save role id in session
                        SessionHelper.Role = UserDetails.Spartan_Users[0].Role;
                        // save role object in session
                        SessionHelper.Sprtan_Role = new RoleSpartanUserRole
                        {
                            Id          = UserDetails.Spartan_Users[0].Role_Spartan_User_Role.Id,
                            Description = UserDetails.Spartan_Users[0].Role_Spartan_User_Role.Description,
                            Status      = UserDetails.Spartan_Users[0].Role_Spartan_User_Role.Status,
                            Status_Spartan_User_Role_Status = UserDetails.Spartan_Users[0].Role_Spartan_User_Role.Status_Spartan_User_Role_Status,
                            User_Role_Id = UserDetails.Spartan_Users[0].Role_Spartan_User_Role.User_Role_Id,
                        };
                        Session["USERID"]     = user.IdUsuario;
                        Session["USERROLEID"] = UserDetails.Spartan_Users[0].Role_Spartan_User_Role.User_Role_Id;
                        Session.Timeout       = Convert.ToInt32(ConfigurationManager.AppSettings["SessionTimeOut"]);
                        Session["LANGUAGEID"] = (model.SelectedLanguage.HasValue) ? model.SelectedLanguage.Value : 1;
                        SessionHelper.Relogin = false;
                        return(RedirectToLocal("~/Frontal/Home/Index"));
                    }
                    else
                    {
                        SetSecurityLogging(ref oSecurityLog, (short)Event_Type.Login, null, null, (short)Result_Type.Denied);
                        _ISpartanSecurityApiConsumer.Insert(oSecurityLog);

                        ModelState.AddModelError("", Resources.LoginResources.DeactivateAccount);
                        if (SessionHelper.Relogin)
                        {
                            return(Json(Resources.LoginResources.DeactivateAccount));
                        }
                    }
                }
                else
                {
                    SetSecurityLogging(ref oSecurityLog, (short)Event_Type.Login, null, null, (short)Result_Type.Denied);
                    _ISpartanSecurityApiConsumer.Insert(oSecurityLog);

                    ModelState.AddModelError("", Resources.LoginResources.InvalidUserPassword);

                    if (model.FailedAttempts < model.MaxFailedAttempts)
                    {
                        model.FailedAttempts = model.FailedAttempts + 1;
                    }
                    else
                    {
                        if (UsersByName.RowCount == 1)
                        {
                            var UserByName = UsersByName.Spartan_Users.First();
                            UserByName.Status = 2;
                            int status = _IUseroApiConsumer.Update(UserByName, null, null).Resource;
                            model.FailedAttempts = 1;
                        }
                        Session["BlockUser"] = true;
                    }
                    if (SessionHelper.Relogin)
                    {
                        return(Json(Resources.LoginResources.InvalidUserPassword));
                    }
                }
            }
            model.LanguageList = GetLanguage();
            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public ActionResult Create(string Id = "", int consult = 0, int ModuleId = 0)
        {
            if (ModuleId == 0)
            {
                ModuleId = (Session["CurrentModuleId"] != null) ? Convert.ToInt32(Session["CurrentModuleId"]) : 0;
            }
            else
            {
                Session["CurrentModuleId"] = ModuleId;
            }
            var permission = PermissionHelper.GetRoleObjectPermission(SessionHelper.Role, 136, ModuleId);

            if ((!permission.New && Id.ToString() == "0") || (!permission.Edit && Id.ToString() != "0" && (!permission.Consult && consult == 1)))
            {
                Response.Redirect("~/");
            }
            ViewBag.Permission = permission;
            var varSpartan_Settings = new Spartan_SettingsModel();

            ViewBag.ObjectId  = "136";
            ViewBag.Operation = "New";

            ViewBag.IsNew = true;



            if ((Id.GetType() == typeof(string) && Id.ToString() != "") || ((Id.GetType() == typeof(int) || Id.GetType() == typeof(Int16) || Id.GetType() == typeof(Int32) || Id.GetType() == typeof(Int64) || Id.GetType() == typeof(short)) && Id.ToString() != "0"))
            {
                ViewBag.IsNew     = false;
                ViewBag.Operation = "Update";
                if (!_tokenManager.GenerateToken())
                {
                    return(Json(null, JsonRequestBehavior.AllowGet));
                }
                _ISpartan_SettingsApiConsumer.SetAuthHeader(_tokenManager.Token);
                var Spartan_SettingsData = _ISpartan_SettingsApiConsumer.GetByKeyComplete(Id).Resource.Spartan_Settingss[0];
                if (Spartan_SettingsData == null)
                {
                    return(HttpNotFound());
                }

                varSpartan_Settings = new Spartan_SettingsModel
                {
                    Clave   = (string)Spartan_SettingsData.Clave
                    , Valor = Spartan_SettingsData.Valor
                };
            }
            if (!_tokenManager.GenerateToken())
            {
                return(Json(null, JsonRequestBehavior.AllowGet));
            }



            ViewBag.Consult = consult == 1;
            if (consult == 1)
            {
                ViewBag.Operation = "Consult";
            }
            return(View(varSpartan_Settings));
        }
Пример #3
0
        public ActionResult ChangePassword(Spartan_User spartan_user)
        {
            if (!_tokenManager.GenerateToken())
            {
                return(Json(null, JsonRequestBehavior.AllowGet));
            }
            int userId = Convert.ToInt32(Session["USERID"]);

            _ISpartan_UserApiConsumer.SetAuthHeader(_tokenManager.Token);
            _ISpartan_ChangePasswordAutorizationApiConsumer.SetAuthHeader(_tokenManager.Token);
            var user = _ISpartan_UserApiConsumer.GetByKey(userId, false).Resource;

            if (Session["EstatusChangePassword"].ToString() == "0" || Session["EstatusChangePassword"].ToString() == "4")
            {
                Spartan_ChangePasswordAutorization newChange = new Spartan_ChangePasswordAutorization();
                newChange.Estatus           = 1;
                newChange.Fecha_de_Registro = DateTime.Now;
                newChange.Hora_de_Registro  = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();
                newChange.Usuario           = userId;
                newChange.Email             = user.Email;

                var result = _ISpartan_ChangePasswordAutorizationApiConsumer.Insert(newChange, null, null).Resource;

                //SEND EMAIL TO ADMIN
                var           usersAdmin = _ISpartan_UserApiConsumer.ListaSelAll(0, 10, "Spartan_User.Role = 1", "").Resource;
                List <string> to         = new List <string>();
                if (usersAdmin.RowCount > 0)
                {
                    foreach (var userAdmin in usersAdmin.Spartan_Users)
                    {
                        to.Add(userAdmin.Email);
                    }
                    Helper.SendEmail(to, "Pedido de cambio de Password", "El usuario " + user.Name + " con ID=" + user.Id_User + " ha solicitado cambio de password.");
                }
            }
            else
            {
                _ISpartan_UserApiConsumer.SetAuthHeader(_tokenManager.Token);
                _ISpartan_User_Historical_PasswordApiConsumer.SetAuthHeader(_tokenManager.Token);

                var model = _ISpartan_UserApiConsumer.GetByKey(spartan_user.Id_User, false).Resource;
                model.Password = EncryptHelper.CalculateMD5Hash(spartan_user.Password);
                _ISpartan_UserApiConsumer.Update(model, null, null);
                _ISpartan_SettingsApiConsumer.SetAuthHeader(_tokenManager.Token);
                var      ExpirationDaysDB  = _ISpartan_SettingsApiConsumer.GetByKey("ExpirationDays", false).Resource;
                int      ExpirationDays    = Convert.ToInt32(ExpirationDaysDB.Valor);
                DateTime newDateExpiracion = DateTime.Now.AddDays(ExpirationDays);
                var      fechaJSON         = _ISpartaneQueryApiConsumer.ExecuteRawQuery("UPDATE Spartan_User SET Fecha_de_Expiracion = '" + newDateExpiracion.ToString("yyyy-MM-dd") + "' where Id_User="******"Spartan_ChangePasswordAutorization.Estatus=2", "").Resource;
                if (changes.RowCount > 0)
                {
                    var lastChange = changes.Spartan_ChangePasswordAutorizations.First();
                    lastChange.Estatus = 4;
                    var result = _ISpartan_ChangePasswordAutorizationApiConsumer.Update(lastChange, null, null).Resource;
                }

                //ADD TO HISTORICAL
                Spartan_User_Historical_Password newData = new Spartan_User_Historical_Password();
                newData.Fecha_de_Registro = DateTime.Now;
                newData.Password          = EncryptHelper.CalculateMD5Hash(spartan_user.Password);
                newData.Usuario           = spartan_user.Id_User;
                var resultInsert = _ISpartan_User_Historical_PasswordApiConsumer.Insert(newData, null, null).Resource;
            }
            return(Redirect("~/"));
        }