Exemplo n.º 1
0
        public HttpResponseMessage ChangeSecurityPin(string id, UserModels.ChangeSecurityPinRequest request)
        {
            DomainServices.UserService userService = new DomainServices.UserService(_ctx);

            var user = userService.GetUserById(id);

            if (!securityService.Decrypt(user.SecurityPin).Equals(request.currentSecurityPin))
            {
                var message = new HttpResponseMessage(HttpStatusCode.BadRequest);
                message.ReasonPhrase = "Security Pin doesn't match";
                return message;
            }
            if (request.newSecurityPin.Length < 4)
            {
                var error = @"Invalid Security Pin";

                _logger.Log(LogLevel.Error, String.Format("Unable to Setup Security Pin for {0}. {1}", id, error));

                var message = new HttpResponseMessage(HttpStatusCode.BadRequest);
                message.ReasonPhrase = error;

                return message;
            }

            user.SecurityPin = securityService.Encrypt(request.newSecurityPin);
            userService.UpdateUser(user);

            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        public ActionResult Registration(UserModels.RegisterUserModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    MembershipCreateStatus createStatus;
                    Membership.CreateUser(model.Login, model.Password, null, null, null, true, null, out createStatus);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        ViewBag.Mess = "Welcome to the system ! Your registration was successful :)";

                        return View(model);
                    }

                    ModelState.AddModelError("name", createStatus.ToString());
                }
                catch (MembershipCreateUserException e)
                {
                    MvcApplication.log.ErrorException(" Exeption during save data in the database: " + e.StatusCode, e);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public ActionResult Login(UserModels.LoginUserModel model, string returnUrl)
        {
            if (ModelState.IsValid && Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

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

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");

            return View(model);
        }
Exemplo n.º 4
0
        public List <UserModels> GetListUser2ndRole()
        {
            var lstUser = new List <UserModels>();

            var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());

            if (con.State == System.Data.ConnectionState.Closed)
            {
                con.Open();
            }
            string query = @"SELECT
	                        U.*,
	                        WM.IsConfirmed,
	                        ro.RoleName FROM Users U
                        Left JOIN webpages_Membership WM on U.Id = WM.UserId
                        Left JOIN webpages_UsersInRoles WU on U.Id = WU.UserId
                        Left JOIN webpages_Roles ro on WU.RoleId = ro.RoleId";
            var    cmd   = new SqlCommand(query, con);

            try
            {
                var reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    var model = new UserModels();
                    model.UserId    = reader.GetInt32(0);
                    model.UserName  = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
                    model.FullName  = reader.IsDBNull(2) ? string.Empty : reader.GetString(2);
                    model.Email     = reader.IsDBNull(3) ? string.Empty : reader.GetString(3);
                    model.Address   = reader.IsDBNull(4) ? string.Empty : reader.GetString(4);
                    model.isActived = reader.GetBoolean(5);
                    model.RoleName  = reader.IsDBNull(6) ? string.Empty : reader.GetString(6);
                    lstUser.Add(model);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                con.Close();
                cmd.Dispose();
            }

            return(lstUser);
        }
Exemplo n.º 5
0
        public ActionResult List_user_permission(string user_name, string type, string act, string ctrl, string type_act)
        {
            UserModels    userModels      = new UserModels();
            var           permission_view = new Web.Areas.Admin.ViewModels.List_user_permission_view();
            StringBuilder sb = new StringBuilder();

            if (string.IsNullOrEmpty(type))
            {
                type = Request.QueryString["type"] != null ? Request.QueryString["type"].ToString() : CommonGlobal.RoleAdmin;
            }

            if (string.IsNullOrEmpty(act))
            {
                act = Request.QueryString["act"] != null ? Request.QueryString["act"].ToString() : "list_user_permission";
            }

            if (string.IsNullOrEmpty(ctrl))
            {
                ctrl = Request.QueryString["ctrl"] != null ? Request.QueryString["ctrl"].ToString() : "adminUser";
            }

            if (user_name == null)
            {
                user_name = Request.QueryString["user_name"] != null ? Request.QueryString["user_name"].ToString() : string.Empty;
            }

            List <PagePermission> lstPagePermission = userModels.GetListPermissionByUser(user_name);

            permission_view.List_permission = lstPagePermission;
            permission_view.TotalPage       = lstPagePermission.Where(p => p.Parent_ID > 0).ToList().Count;
            permission_view.User_name       = user_name;
            permission_view.Type            = type;
            permission_view.Type_act        = type_act;

            sb.Append("<li><a href=\"" + Url.Action("index", "dashboard", new { act = "list_user", ctrl = "adminUser", type = type, page = "1" }) + "\"><span><span>Danh sách Admin</span></span></a></li>");
            sb.Append("<li><a href=\"" + Url.Action("index", "dashboard", new { act = "change_user", ctrl = "adminUser", type = type, type_act = CommonGlobal.Edit, user_name = user_name }) + "\"><span><span>Cập nhật Admin</span></span></a></li>");
            sb.Append("<li class=\"active\"><a href=\"#\"><span>Page Permission</span></a></li>");
            permission_view.Html_link_tab = sb.ToString();

            ////action and parent action
            permission_view.Act               = act;
            permission_view.Ctrl              = ctrl;
            permission_view.Parent_action     = HttpContext.Request.RequestContext.RouteData.Values["action"].ToString();
            permission_view.Parent_controller = HttpContext.Request.RequestContext.RouteData.Values["controller"].ToString();

            return(this.PartialView("../control/list_user_permission", permission_view));
        }
Exemplo n.º 6
0
        public IActionResult ListUserPage(string type, string search, int?parentId, int?pageIndex, int?pageSize)
        {
            IActionResult response   = null;
            BaseClass     baseClass  = new BaseClass();
            UserModels    userModels = new UserModels();
            RoleModels    roleModels = new RoleModels();
            User          cuser      = new User();

            var mess         = string.Empty;
            var listPageView = new AdminListPageView();
            var isOk         = true;

            string lang = LanguageModels.ActiveLanguage().LangCultureName;

            type = type ?? string.Empty;

            if (parentId == null)
            {
                parentId = -1; // get all
            }

            var action = userModels.GetActionByActionName(CommonGlobal.View);

            string typeAct = action != null?action.Id.ToString() : string.Empty;

            if (type == string.Empty)
            {
                isOk     = false;
                response = Json(new { code = Constant.NotExist, message = Constant.MessageNotExist });
            }

            if (!isOk)
            {
                return(response);
            }

            listPageView.ListUserPage = userModels.AdminGetAllPageFullTree(type, lang, search, (int)parentId, (int)pageIndex, (int)pageSize, out int totalRecord);
            listPageView.CateType     = roleModels.GetRoleByRole(type);
            listPageView.PageIndex    = (int)pageIndex;
            listPageView.PageSize     = (int)pageSize;
            listPageView.TotalPage    = totalRecord > 0 ? (int)System.Math.Ceiling((double)totalRecord / (double)pageSize) : 0;
            listPageView.TotalRecord  = totalRecord;

            response = Json(listPageView);

            return(response);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Updates the status user.
        /// </summary>
        /// <param name="user_name">Name of the user.</param>
        /// <param name="status">The status.</param>
        /// <param name="type">The type.</param>
        /// <returns>update status user</returns>
        public ActionResult Update_status_user(string user_name, string status, string type)
        {
            UserModels userModels = new UserModels();
            C_User     cuser      = new C_User();
            bool       isOk       = false;

            if (UserModels.CheckPermission(this.Session["mem"] != null ? this.Session["mem"].ToString() : string.Empty, "change_user", "adminUser", CommonGlobal.Edit, type))
            {
                isOk = true;
            }
            else
            {
                isOk = false;
            }

            if (!string.IsNullOrEmpty(user_name))
            {
                cuser = userModels.GetUserbyUserName(user_name);
                if (cuser != null)
                {
                    try
                    {
                        if (bool.Parse(status) == true)
                        {
                            cuser.Online = true;
                        }
                        else
                        {
                            cuser.Online = false;
                        }

                        if (isOk)
                        {
                            userModels.Update_User(cuser);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            var jsonSerialiser = new JavaScriptSerializer();
            var results        = Convert.ToDateTime(DateTime.Now).ToString("dd/MM/yyyy") + "|" + cuser.Online;

            return(this.Json(results));
        }
Exemplo n.º 8
0
        public ActionResult Edit(string id)
        {
            UserModels viewModel = null;
            UserEdit   userEdit  = new UserEdit();
            var        intId     = 0;

            int.TryParse(id, out intId);
            try{
                User user = userRepository.GetUserById(intId);
                if (user == null || user.Name == null || user.Name == "")
                {
                    return(RedirectToAction("Error404", "Error"));
                }
                else
                {
                    var path     = "";
                    var fileName = user.Id + ".jpg";
                    var savePath = Server.MapPath("~/Uploads/User/") + user.Id;
                    // Check for Directory, If not exist, then create it
                    if (Directory.Exists(savePath))
                    {
                        path       = "/Uploads/User/" + user.Id + "/" + fileName;
                        user.Image = path;
                    }
                    else
                    {
                        savePath = Server.MapPath("~/Uploads/");
                        fileName = "default.jpg";
                    }
                    userEdit.ImageStream = ImageHelper.BaseDateImage(savePath + "/" + fileName);
                    user.Image           = Common.ConcatHost(path);
                }

                viewModel = new UserModels
                {
                    user      = user,
                    userEdit  = userEdit,
                    checkPost = false
                };
            }
            catch (Exception ex)
            {
                log.Error(ex);
                ModelState.AddModelError("error", Translator.UnexpectedError);
            }
            return(View(viewModel));
        }
Exemplo n.º 9
0
        public HttpResponseMessage Login(UserModels user, string crm = null)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
            string joinCrm          = string.Empty;
            string loginCrm         = string.Empty;

            if (!string.IsNullOrEmpty(crm))
            {
                joinCrm  = "JOIN TB_USUARIO_CLINICA CLI ON USU.ID = CLI.ID_USUARIO";
                loginCrm = "AND CLI.CRM = @CRM";
            }

            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                MySqlCommand comando = new MySqlCommand("SELECT USU.SENHA, USU.BLOQUEIO FROM TB_USUARIO USU " + joinCrm + " WHERE USU.EMAIL=@EMAIL " + loginCrm, conn);
                comando.Parameters.AddWithValue("@EMAIL", user.email);
                comando.Parameters.AddWithValue("@CRM", crm ?? string.Empty);
                try
                {
                    conn.Open();
                    MySqlDataReader rdr = comando.ExecuteReader();

                    while (rdr.Read())
                    {
                        if (rdr[1].ToString() == "1")
                        {
                            return(Request.CreateResponse(HttpStatusCode.OK, "Usuário Bloqueado."));
                        }

                        if (!UserRules.VerifyHash(user.senha, "MD5", rdr[0].ToString()))
                        {
                            return(Request.CreateResponse(HttpStatusCode.OK, "Usuário/Senha Inválido."));
                        }
                        else
                        {
                            return(Request.CreateResponse(HttpStatusCode.OK, user));
                        }
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK, "Usuário/Senha Inválido."));
                }
                finally
                {
                    conn.Close();
                }
            }
        }
Exemplo n.º 10
0
        public IActionResult Delete(string userName)
        {
            IActionResult response   = null;
            string        mess       = string.Empty;
            UserModels    userModels = new UserModels();

            User     cuser    = userModels.GetUserbyUserName(userName);
            UserInfo userInfo = userModels.GetUserInforByEmail(userName);

            if (cuser != null)
            {
                //// delete user
                bool rt = userModels.DeleteUser(userName);

                if (rt)
                {
                    //// delete avatar file
                    if (!string.IsNullOrEmpty(userInfo.Avatar) && userInfo.Avatar.Contains("/"))
                    {
                        string webRootPath = _hostingEnvironment.WebRootPath;
                        string fileDelete  = Path.Combine(webRootPath, userInfo.Avatar.Replace("/", "\\"));
                        if (System.IO.File.Exists(fileDelete))
                        {
                            System.IO.File.Delete(fileDelete);
                        }

                        string fileDelete2 = Path.Combine(webRootPath, userInfo.Avatar.Replace("/", "\\").Replace("sc_small_", "sc_full_"));
                        if (System.IO.File.Exists(fileDelete2))
                        {
                            System.IO.File.Delete(fileDelete2);
                        }
                    }

                    response = Json(new { code = Constant.Success, message = Constant.MessageDeleteCompleted });
                }
                else
                {
                    response = Json(new { code = Constant.Fail, message = Constant.MessageDeleteUncompleted });
                }
            }
            else
            {
                response = Json(new { code = Constant.NotExist, message = Constant.MessageNotExist });
            }

            return(response);
        }
Exemplo n.º 11
0
        public ActionResult Edit(user user)
        {
            user.updatetime = DateTime.Now;

            // Update chinh tai khoan cua minh
            if (user.idnd == Session[Constants.SESSION_ID].ToString().Trim())
            {
                if (new UserModels().update(user, 1) == 1)
                {
                    return(RedirectToAction("Details", "User", new { @id = user.idnd.Trim() }));
                }
            }

            // Update tai khoan k la admin
            if (user.kieuuser != Constants.G_ADMIN)
            {
                // admin update
                if (Session[Constants.SESSION_GROUPID].ToString() == Constants.G_ADMIN)
                {
                    if (new UserModels().update(user, 2) == 1)
                    {
                        return(RedirectToAction("Details", "User", new { @id = user.idnd.Trim() }));
                    }
                }

                // manager update
                if ((Session[Constants.SESSION_GROUPID] as string) == Constants.G_MANAGER &&
                    Session[Constants.SESSION_HOSPITAL_ID].ToString().Trim() == user.idbv.Trim())
                {
                    if (new UserModels().update(user, 3) == 1)
                    {
                        return(RedirectToAction("Details", "User", new { @id = user.idnd.Trim() }));
                    }
                }
            }
            // Can check lai = -3, -2, -1, 0
            ViewBag.getListHospitals = new HospitalModels().getListHospitals();
            ViewBag.getListTinhs     = new TinhModels().getListTinhs();
            ViewBag.getListXas       = new XaModels().getListXas();
            ViewBag.getListHuyens    = new HuyenModels().getListHuyens();
            ViewBag.getListRoles     = new CommonModels().getListGroup();
            ViewBag.Err = "Kiểm tra lại các trường còn thiếu";
            var model = new UserModels().detail(user.idnd);

            return(View(model));
        }
Exemplo n.º 12
0
        // GET: UserModels/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            UserModels userModels = db.UserModels.Find(id);

            if (userModels == null)
            {
                return(HttpNotFound());
            }
            var view = ToView(userModels);

            return(View(view));
            // return View(userModels);
        }
Exemplo n.º 13
0
        public static int CreateUser(string firstName, string lastName, string emailAddress, string password, DateTime birthday, string gender)
        {
            UserModels data = new UserModels
            {
                FirstName    = firstName,
                LastName     = lastName,
                EmailAddress = emailAddress,
                Password     = password,
                BirthDay     = birthday,
                Gender       = gender
            };

            string sql = @"INSERT INTO dbo.[User] (FirstName, LastName, EmailAddress, Password, BirthDay, Gender)
                            VALUES (@FirstName, @LastName, @EmailAddress, @Password, @BirthDay, @Gender)";

            return(SqlDataAccess.SaveData(sql, data));
        }
        public IActionResult Get(int id)
        {
            UserModels     sv             = new UserModels();
            IActionResult  response       = null;
            UserPageAction userPageAction = sv.GetUserPageActionbyId(id);

            if (userPageAction != null)
            {
                response = Json(userPageAction);
            }
            else
            {
                response = Json(new { code = Constant.NotExist, message = Constant.MessageNotExist });
            }

            return(response);
        }
Exemplo n.º 15
0
        private void ApplicarPermissoes(UserModels userModels)
        {
            if (checkEdit11.IsOn)
            {
                //Guardar Configurações
                conLogin.Estado = (bool)checkEdit11.EditValue;
                conLogin.Nome   = txtUserName.Text;
                conLogin.Senha  = txtPassword.Text;
                conLogin.Save();
            }

            var admin = new MenuDesign(userModels.GruposModels.PermissoesModels, new IPAGEBiblioteca.Repository.LogsRepository(new BiblioteContext()));

            this.Visible = false;
            admin.Show();
            admin.FormClosing += delegate { this.Visible = true; };
        }
Exemplo n.º 16
0
        public void ModifyFunctionary(UserModels _functionary)
        {
            string sqlQuery = $"exec sp_modificar_funcionario " + _functionary.Cedula + ",'" + _functionary.Name + "','" + _functionary.FirstLastName
                              + "','" + _functionary.SecondLastName + "','" + _functionary.PersonalPhone + "','" + _functionary.RoomPhone + "','" + _functionary.Birthday
                              + "','" + _functionary.Gender + "','" + _functionary.Scholarship + "','" + _functionary.Province + "','" + _functionary.Canton
                              + "','" + _functionary.District + "','" + _functionary.CivilStatus + "','" + _functionary.Address + "','" + _functionary.OficePhone
                              + "','" + _functionary.Mail + "','" + _functionary.IdPlaca + "','" + _functionary.PortationExpirationDay + "'," +
                              _functionary.PlaceID + "," + _functionary.AreaID + "," + _functionary.OfficeID + ",'" + _functionary.AdmissionDate + "'," + _functionary.Assistance;

            using (SqlCommand command = new SqlCommand(sqlQuery, connection))
            {
                command.CommandType = CommandType.Text;
                connection.Open();
                command.ExecuteReader();
                connection.Close();
            }
        }
Exemplo n.º 17
0
 public void Verification(UserModels model)
 {
     try
     {
         db = new BMotionDBEntities();
         User usr = (from u in db.Users
                     where u.NIP.Equals(model.NIP)
                     select u).First();
         usr.IsVerify = "Y";
         usr.Password = model.Password;
         db.SaveChanges();
     }
     catch (Exception e)
     {
         throw e;
     }
 }
        // GET: /Contrats/GenerateContrat/idClient/idAnnonce
        public ActionResult GenerateContrat(string idClient, int idAnnonce)
        {
            Contrat      contrat      = contratService.GetContrat(idClient, idAnnonce);
            User         client       = userService.GetById(User.Identity.GetUserId());
            Annonce      annonce      = annonceService.getAnnonceById(idAnnonce);
            User         owner        = userService.GetById(annonce.UserID);
            ContratModel contratModel = new ContratModel
            {
                ClientIDM       = contrat.ClientID,
                AnnonceIdM      = contrat.AnnonceId,
                DateContratM    = contrat.DateContrat,
                DateFinContratM = contrat.DateFinContrat,
                DescriptionM    = contrat.Description,
                PrixContratM    = contrat.PrixContrat,
                motifM          = (ContratModel.Motif)contrat.motif,
            };
            UserModels clientModel = new UserModels
            {
                Num             = client.Id,
                Nom             = client.LastName,
                Prenom          = client.FirstName,
                DateDeNaissance = client.DateOfBirth.Date,
                NumTel          = client.Cin
            };
            UserModels ownerModel = new UserModels
            {
                Num             = User.Identity.GetUserId(),
                Nom             = owner.LastName,
                Prenom          = owner.FirstName,
                DateDeNaissance = owner.DateOfBirth.Date,
                NumTel          = owner.Cin
            };

            ViewBag.Client = clientModel;
            ViewBag.Owner  = ownerModel;

            ViewBag.Contrat = contratModel;

            return(new ViewAsPdf(contratModel)
            {
                FileName = Server.MapPath("~/Content/MyContrat.pdf")
            });

/*            return View();
 */
        }
Exemplo n.º 19
0
        public ActionResult Forgot_password(FormCollection collection)
        {
            OrderModels   orderModels = new OrderModels();
            WebInfoModels web_infor   = new WebInfoModels();
            UserModels    sv          = new UserModels();
            C_User        it          = new C_User();
            var           login_view  = new Login_view();

            this.TryUpdateModel(login_view);

            login_view.Parent_action     = HttpContext.Request.RequestContext.RouteData.Values["action"].ToString();
            login_view.Parent_controller = HttpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
            login_view.Return_url        = Url.Action("login", "dashboard", new { area = "admin" });

            ////check user_name or email
            it = sv.GetUserbyUserName(login_view.User_name);
            if (it != null)
            {
                login_view.Message = App_GlobalResources.Lang.strMessageSendNewPassword;
                string code = GetCodeUniqueKey(8); ////orderModels.getOrderCodeUnique();
                string link = Url.Action("change_password", "dashboard", new { cfcode = MD5Extend.EncodePassword(code + " " + login_view.User_name), area = "admin" });
                //// send email to client
                var strBody_email_client = GeneralModels.GetContent(CommonGlobal.EmailConfirmForgotPassword, Lang).ToString(); ////get from email template
                strBody_email_client = strBody_email_client.Replace("{domain}", Util.GetConfigValue("Domain", Request.UserHostName).ToString());
                strBody_email_client = strBody_email_client.Replace("{store_name}", GeneralModels.GetContent(CommonGlobal.PageName, Lang).ToString());
                strBody_email_client = strBody_email_client.Replace("{email}", web_infor.GetContent(CommonGlobal.Email).ToString());
                strBody_email_client = strBody_email_client.Replace("{email_client}", login_view.User_name);
                strBody_email_client = strBody_email_client.Replace("{code}", code);
                strBody_email_client = strBody_email_client.Replace("{link}", Util.GetConfigValue("Domain", Request.UserHostName).ToString() + link);
                ////send email to email system
                if (login_view.User_name == "Admin")
                {
                    CommonGlobal.SendMail(web_infor.GetContent(CommonGlobal.Email), App_GlobalResources.Lang.strSubjectConfirmForgotPassword + "- " + Util.GetConfigValue("Domain", Request.UserHostName).ToString(), strBody_email_client);
                }
                else
                {
                    CommonGlobal.SendMail(login_view.User_name, App_GlobalResources.Lang.strSubjectConfirmForgotPassword + "- " + Util.GetConfigValue("Domain", Request.UserHostName).ToString(), strBody_email_client);
                }
            }
            else
            {
                login_view.Message = App_GlobalResources.Lang.strMessageForgotPassword;
            }

            return(this.PartialView("../page/forgot_password", login_view));
        }
Exemplo n.º 20
0
        public ActionResult EditUserProfile()
        {
            UserEdit   userEdit  = new UserEdit();
            UserModels viewModel = null;
            User       user      = null;

            try
            {
                var objSession = Session["user"] as MyClinic.Infrastructure.SessUser;
                if (objSession == null)
                {
                    return(HttpNotFound());
                }
                else
                {
                    user = userRepository.GetUserById(objSession.UserId);
                    if (user == null)
                    {
                        return(HttpNotFound());
                    }
                    var path     = "/Uploads/default.jpg";
                    var fileName = user.Id + ".jpg";
                    var savePath = Server.MapPath("~/Uploads/User/") + user.Id;
                    // Check for Directory, If not exist, then create it
                    if (Directory.Exists(savePath))
                    {
                        path = "/Uploads/User/" + user.Id + "/" + fileName;
                    }
                    userEdit.ImageStream = ImageHelper.BaseDateImage(savePath + "/" + fileName);
                    user.Image           = Common.ConcatHost(path);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                ModelState.AddModelError(string.Empty, Translator.UnexpectedError);
            }

            viewModel = new UserModels
            {
                user      = user,
                userEdit  = userEdit,
                checkPost = false
            };
            return(View(viewModel));
        }
Exemplo n.º 21
0
        /*
         * Return a professional acording to the identification
         */
        public List <UserModels> GetProfessionalByIdentification(UserModels _professional)
        {
            List <UserModels> professional = new List <UserModels>();



            string sqlQuery = $"exec sp_buscar_profesional_por_cedula('" + _professional.Cedula + "')";

            using (SqlCommand command = new SqlCommand(sqlQuery, connection))
            {
                command.CommandType = CommandType.Text;
                connection.Open();
                SqlDataReader catalogueReader = command.ExecuteReader();
                while (catalogueReader.Read())
                {
                    UserModels professionalTemp = new UserModels();
                    professionalTemp.Cedula                 = Int32.Parse(catalogueReader["pk_cedula_usuario"].ToString());
                    professionalTemp.Name                   = catalogueReader["tc_nombre"].ToString();
                    professionalTemp.FirstLastName          = catalogueReader["tc_primer_apellido"].ToString();
                    professionalTemp.SecondLastName         = catalogueReader["tc_segundo_apellido"].ToString();
                    professionalTemp.PersonalPhone          = catalogueReader["tc_telefono_personal"].ToString();
                    professionalTemp.RoomPhone              = catalogueReader["tc_telefono_habitacion"].ToString();
                    professionalTemp.Birthday               = catalogueReader["tf_fecha_nacimiento"].ToString();
                    professionalTemp.Gender                 = Char.Parse(catalogueReader["tc_sexo"].ToString());
                    professionalTemp.CivilStatus            = catalogueReader["tc_estado_civil"].ToString();
                    professionalTemp.PlaceNumber            = Int32.Parse(catalogueReader["tn_numero_plaza"].ToString());
                    professionalTemp.Status                 = Int32.Parse(catalogueReader["tc_estado"].ToString());
                    professionalTemp.EmergencyContact       = catalogueReader["tc_contacto_emergencia"].ToString();
                    professionalTemp.EmergencyContactNumber = Int32.Parse(catalogueReader["tn_contacto_emergencia"].ToString());
                    professionalTemp.Scholarship            = catalogueReader["tc_escolaridad"].ToString();
                    professionalTemp.Specialty              = catalogueReader["tc_especialidad"].ToString();
                    professionalTemp.SchoolCode             = catalogueReader["tn_codigo_colegio"].ToString();
                    professionalTemp.Province               = catalogueReader["tc_provincia"].ToString();
                    professionalTemp.Canton                 = catalogueReader["tc_canton"].ToString();
                    professionalTemp.District               = catalogueReader["tc_distrito"].ToString();
                    professionalTemp.Address                = catalogueReader["tc_direccion"].ToString();

                    professional.Add(professionalTemp);
                }
                connection.Close();
            }



            return(professional);
        }
Exemplo n.º 22
0
        public UserModels GetUserById(string id)
        {
            UserModels usr  = new UserModels();
            var        list = db.Users.Where(us => us.NIP.Equals(id)).ToList();

            foreach (var item in list)
            {
                usr.NIP      = item.NIP == null?"":item.NIP;
                usr.Email    = item.Email == null?"":item.Email;
                usr.IsVerify = item.IsVerify == null?"":item.IsVerify;
                usr.Name     = item.Name == null?"":item.Name;
                usr.Password = item.Password == null?"":item.Password;
                usr.Profesi  = item.Profession == null?"":item.Profession;
                usr.Telp     = item.Phone == null?"":item.Phone;
            }
            return(usr);
        }
Exemplo n.º 23
0
        public UserModels GetSelectedUser(string userID)
        {
            DbOperations_LATEST.DBUtil obj = new DbOperations_LATEST.DBUtil();
            SqlDataReader SqlDtr           = null;
            UserModels    user             = new UserModels();

            obj.SelectQuery("select loginname, password, username,role_name from user_master um, roles r where um.role_id=r.role_id and UserId='" + userID + "'", ref SqlDtr);
            while (SqlDtr.Read())
            {
                user.LoginName = SqlDtr.GetValue(0).ToString();
                user.Password  = SqlDtr.GetValue(1).ToString();
                user.UserName  = SqlDtr.GetValue(2).ToString();
                user.RoleName  = SqlDtr.GetValue(3).ToString();
            }
            SqlDtr.Close();
            return(user);
        }
Exemplo n.º 24
0
        public ActionResult Create()
        {
            UserModels userModels = new UserModels();

            if (Session["userid"] != null)
            {
                userModels         = db.User.Find(Session["userid"]);
                ViewBag.userModels = userModels;
                List <ProvincesModels> provincesModelsList = db.Provinces.ToList();
                ViewBag.provincesModelsList = provincesModelsList;
            }
            else
            {
                return(RedirectToAction("Login", "User"));
            }
            return(View());
        }
Exemplo n.º 25
0
        public UserModels GetSelectedUser(string UserID)
        {
            InventoryClass obj = new InventoryClass();
            SqlDataReader  SqlDtr;
            string         sql;
            UserModels     user = new UserModels();

            sql    = "select UserID,UserName from User_Master where LoginName='" + UserID + "'";
            SqlDtr = obj.GetRecordSet(sql);
            while (SqlDtr.Read())
            {
                user.UserID   = SqlDtr.GetValue(0).ToString();
                user.UserName = SqlDtr.GetValue(1).ToString();
            }
            SqlDtr.Close();
            return(user);
        }
Exemplo n.º 26
0
        /*
         * Modify a professional acording to the identification
         */
        public void ModifyProfessional(UserModels _professional)
        {
            int processQuantity = _professional.Process.Length;
            var connection      = new SqlConnection(ConfigurationManager.ConnectionStrings["connDB"].ConnectionString);

            string sqlQuery = $"exec sp_modificar_profesional " + _professional.Cedula + ",'" + _professional.Name + "','" + _professional.FirstLastName + "','" +
                              _professional.SecondLastName + "','" + _professional.PersonalPhone + "','" + _professional.RoomPhone + "','" + _professional.Birthday + "','" +
                              _professional.Gender + "','" + _professional.CivilStatus + "'," + _professional.PlaceNumber + "," + _professional.Status + ",'" +
                              _professional.EmergencyContact + "'," + _professional.EmergencyContactNumber + ",'" + _professional.Scholarship + "','" +
                              _professional.Specialty + "'," + _professional.SchoolCode + ",'" + _professional.Province + "','" + _professional.Canton + "','" + _professional.District + "','" +
                              _professional.Address + "'";

            using (SqlCommand command = new SqlCommand(sqlQuery, connection))
            {
                command.CommandType = CommandType.Text;
                connection.Open();
                command.ExecuteReader();
                connection.Close();
            }


            string sqlQueryDeleteProcess = $"exec sp_eliminar_procesos_profesional  @cedula='{_professional.Cedula}'";


            using (SqlCommand command = new SqlCommand(sqlQueryDeleteProcess, connection))
            {
                command.CommandType = CommandType.Text;
                connection.Open();
                command.ExecuteReader();
                connection.Close();
            }

            for (int i = 0; i < processQuantity; i++)
            {
                string sqlQueryProcess = $"exec sp_registrar_procesos_profesional  @cedula='{_professional.Cedula}',@proceso='{_professional.Process[i]}'";

                using (SqlCommand command = new SqlCommand(sqlQueryProcess, connection))
                {
                    command.CommandType = CommandType.Text;
                    connection.Open();
                    command.ExecuteReader();
                    connection.Close();
                }
            }
        }
Exemplo n.º 27
0
        public ActionResult EditUser(UserModels model)
        {
            using (UserRepository repository = new UserRepository())
            {
                Users a = repository.GetUserById(model.id);
                a.UserName  = model.userName;
                a.Password  = model.password;
                a.FirstName = model.firstName;
                a.LastName  = model.lastName;
                a.Mail      = model.mail;

                if (ModelState.IsValid)
                {
                    repository.Save();
                }
                return(RedirectToAction("ReadUsers"));
            }
        }
Exemplo n.º 28
0
        public IActionResult Login(UserModels user)
        {
            UserModels u = new UserRepository().GetUser(user.Username);

            if (u == null)
            {
                return(this.StatusCode(Convert.ToInt32(HttpStatusCode.NotFound), "The user was not found."));  //Request.CreateResponse(HttpStatusCode.NotFound, // "The user was not found.");
            }
            bool credentials = u.Password.Equals(user.Password);

            if (!credentials)
            {
                return(this.StatusCode(Convert.ToInt32(HttpStatusCode.Forbidden), "The username / password combination was wrong."));
            }
            ObjectResult result = this.StatusCode(Convert.ToInt32(HttpStatusCode.OK), TokenManager.GenerateToken(user.Username));

            return(result);
        }
Exemplo n.º 29
0
        public IActionResult getUserInforDetail(string userName)
        {
            UserModels    sv       = new UserModels();
            IActionResult response = null;

            var userInfor = sv.GetUserInforByEmail(userName);

            if (userInfor != null)
            {
                response = Json(userInfor);
            }
            else
            {
                response = Json(new { code = Constant.NotExist, message = Constant.MessageNotExist });
            }

            return(response);
        }
Exemplo n.º 30
0
        public IActionResult Get(int id)
        {
            UserModels    sv       = new UserModels();
            IActionResult response = null;
            UserPage      userPage = sv.GetUserPagebyId(id);

            ////check permission update
            if (userPage != null)
            {
                response = Json(userPage);
            }
            else
            {
                response = Json(new { code = Constant.NotExist, message = Constant.MessageNotExist });
            }

            return(response);
        }
Exemplo n.º 31
0
        public MyMembershipUser(string UserName)
        {
            UserModels usermodel = new UserModels();
            string     cmd       = string.Format(@"select u.srl,u.userid,u.username,u.lname,u.fname,u.inuse,u.svadept_srl,u.svaacst_srl  from QCUSERT u 
                                Where USERName='******' and InUse=1", UserName);

            object[] lstUserModel = DBHelper.GetDBObjectByObj(usermodel, null, cmd);    // get data
            //result.Cast<ProductStatistics>()
            Users = lstUserModel.Cast <UserModels>();
            List <UserModels> lstUserModel2 = new List <UserModels>();

            lstUserModel2 = lstUserModel.Cast <UserModels>().ToList();
            USERID        = lstUserModel2[0].USERID.ToString();
            UserName      = lstUserModel2[0].USERNAME;
            FName         = lstUserModel2[0].FNAME;
            LName         = lstUserModel2[0].LNAME;
            SRL           = lstUserModel2[0].SRL;
        }
Exemplo n.º 32
0
        public String ConsultDateAdministrator(String initialDate, String finalDate, int process, int assistance,
                                               int office, int identification, char gender, String dateStatus, int consecutive, int age, int professional)
        {
            UserModels user = new UserModels();

            user.Cedula     = identification;
            user.Gender     = gender;
            user.OfficeID   = office;
            user.Assistance = assistance;
            AppointmentModels appointment = new AppointmentModels();

            appointment.Functionary = user;
            appointment.Id          = consecutive;
            AppointmentBusiness appointmentBusiness = new AppointmentBusiness();

            //appointmentBusiness.SearchAppointmentByFiltersAdministrator(appointment, initialDate, finalDate, process, dateStatus, age, age);
            return(JsonConvert.SerializeObject(appointmentBusiness.SearchAppointmentByFiltersAdministrator(appointment, initialDate, finalDate, process, dateStatus, age, professional)));
        }
Exemplo n.º 33
0
 public ActionResult Authorize(User userModel)
 {
     using (UserModels user = new UserModels())
     {
         var userDetails = user.Users.Where(x => x.Username == userModel.Username && x.Password == userModel.Password).FirstOrDefault();
         if (userDetails == null)
         {
             ViewBag.LoginErrorMessage = "Wrong username or password!";
             return(View("Login", userModel));
         }
         else
         {
             Session["userID"]   = userDetails.UserID;
             Session["userName"] = userDetails.Username;
             return(RedirectToAction("Index", "RSSFeed"));
         }
     }
 }
Exemplo n.º 34
0
        //POST /api/users/signin_withfacebook
        public HttpResponseMessage<UserModels.FacebookSignInResponse> SignInWithFacebook(UserModels.FacebookSignInRequest request)
        {
            _logger.Log(LogLevel.Info, String.Format("Sign in with Facebook {0}", request.deviceToken));

            DomainServices.UserService _userService = new DomainServices.UserService(_ctx);

            Domain.User user = null;

            try
            {
                user = _userService.SignInWithFacebook(Guid.Parse(request.apiKey), request.accountId, request.emailAddress, request.firstName, request.lastName,
                    request.deviceToken);
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Fatal, String.Format("Exception Signing in With Facebook. Account {0}", request.accountId));

                var message = new HttpResponseMessage<UserModels.FacebookSignInResponse>(HttpStatusCode.InternalServerError);
                message.ReasonPhrase = ex.Message;

                return message;
            }

            bool hasACHAccount = false;

            if (user.PaymentAccounts.Where(a => a.IsActive = true).Count() > 0)
                hasACHAccount = true;

            var response = new UserModels.FacebookSignInResponse() {
                hasACHAccount = hasACHAccount,
                hasSecurityPin = user.SetupSecurityPin,
                userId = user.UserId.ToString(),
                mobileNumber = (!String.IsNullOrEmpty(user.MobileNumber) ? user.MobileNumber : ""),
                paymentAccountId = (user.PaymentAccounts != null && user.PaymentAccounts.Count() > 0 ? user.PaymentAccounts[0].Id.ToString() : ""),
                upperLimit = Convert.ToInt32(user.Limit)
            };

            return new HttpResponseMessage<UserModels.FacebookSignInResponse>(response, HttpStatusCode.OK);
        }
Exemplo n.º 35
0
 // POST /api/users
 public HttpResponseMessage Post(UserModels.SubmitUserRequest request)
 {
     return new HttpResponseMessage(HttpStatusCode.OK);
 }
        // PUT /api/{userId}/mecodes/{id}
        public HttpResponseMessage Put(string userId, string id, UserModels.UpdateMECodeRequest request)
        {
            Guid userIdGuid;
            Guid idGuid;
            HttpResponseMessage message;

            Guid.TryParse(userId, out userIdGuid);

            if (userIdGuid == null)
            {
                message = new HttpResponseMessage(HttpStatusCode.BadRequest);
                message.ReasonPhrase = String.Format("Invalid userId {0}", userId);

                return message;
            }

            Guid.TryParse(id, out idGuid);

            if(idGuid == null)
            {
                message = new HttpResponseMessage(HttpStatusCode.BadRequest);
                message.ReasonPhrase = String.Format("Invalid MECode Id {0}", id);

                return message;
            }

            Domain.MECode meCode;

            meCode = _ctx.MECodes
                .FirstOrDefault(m => m.UserId.Equals(userIdGuid) && m.Id.Equals(idGuid));

            if(meCode == null)
            {
                 message = new HttpResponseMessage(HttpStatusCode.NotFound);
                 message.ReasonPhrase = String.Format("Resource {0} Not Found", id);

                return message;
            }
            try
            {
                meCode.IsActive = request.IsActive;
                meCode.LastUpdatedDate = System.DateTime.Now;
                meCode.IsApproved = request.IsApproved;
                meCode.ApprovedDate = request.ApprovedDate;

                _ctx.SaveChanges();
            }
            catch(Exception ex)
            {
                string errorMessage = String.Format("Exception updating MECode {0} for user {1}. {2}", id, userId, ex.Message);

                message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                message.ReasonPhrase = errorMessage;

                return message;
            }

            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        // POST /api/{userId}/mecodes
        public HttpResponseMessage Post(string userId, UserModels.SubmitMECodeRequest request)
        {
            Guid id;
            HttpResponseMessage message;

            Guid.TryParse(userId, out id);

            if (id == null)
            {
                message = new HttpResponseMessage(HttpStatusCode.BadRequest);
                message.ReasonPhrase = String.Format("Invalid userId {0}", userId);

                return message;
            }

               Domain.MECode meCode;

               try
               {
               meCode = _ctx.MECodes.Add(new Domain.MECode()
               {
                   CreateDate = System.DateTime.Now,
                   Id = Guid.NewGuid(),
                   IsActive = true,
                   IsApproved = false,
                   UserId = id,
                   MeCode = request.MeCode
               });

               _ctx.SaveChanges();
               }
               catch (Exception ex)
               {
               string errorMessage = String.Format("Exception adding MECode {0} for userId {1}. {2}", request.MeCode, userId, ex.Message);
               _logger.Log(LogLevel.Error, errorMessage);

               message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
               message.ReasonPhrase = errorMessage;

               return message;
               }

               message = new HttpResponseMessage(HttpStatusCode.Created);

               return message;
        }
Exemplo n.º 38
0
        private void AddFormsCookie(UserModels.BaseUserData userData)
        {
            var userDataStr = new JavaScriptSerializer().Serialize(userData);

            var ticket = new FormsAuthenticationTicket(1, userData.Username,
                DateTime.Now, DateTime.Now + FormsAuthentication.Timeout, false, userDataStr);

            var ticketStr = FormsAuthentication.Encrypt(ticket);
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketStr);
            FormsAuthentication.SetAuthCookie(userData.Username, true);
            HttpContext.Response.Cookies.Add(cookie);
        }
Exemplo n.º 39
0
        // POST /api/user
        public HttpResponseMessage<UserModels.SubmitUserResponse> Post(UserModels.SubmitUserRequest request)
        {
            _logger.Log(LogLevel.Error, string.Format("Registering User  {0}", request.userName));

            DomainServices.UserService _userService = new DomainServices.UserService(_ctx);

            var memberRole = _ctx.Roles.FirstOrDefault(r => r.RoleName == "Member");

            //_logger.Log(LogLevel.Error, string.Format("Formatting Mobile Number"));

            //try
            //{
            //    if (!String.IsNullOrEmpty(request.mobileNumber))
            //    {

            //        formattingService.RemoveFormattingFromMobileNumber(request.mobileNumber);

            //        _logger.Log(LogLevel.Error, string.Format("Registering User Mobile Number {0}", mobileNumber));

            //    }
            //}
            //catch (Exception ex)
            //{
            //    _logger.Log(LogLevel.Error, string.Format("Exception formatting mobile number. {0}", ex.Message));

            //}
            User user;

            //validate that email address is not already user
            user = _userService.FindUserByEmailAddress(request.userName);

            if (user != null)
            {
                var errorMessage = new HttpResponseMessage<UserModels.SubmitUserResponse>(HttpStatusCode.BadRequest);
                errorMessage.ReasonPhrase = String.Format("The email address {0} is already registered.", request.emailAddress);

                return errorMessage;
            }

            //if(!String.IsNullOrEmpty(mobileNumber))
            //{
            //    user = _userService.FindUserByMobileNumber(mobileNumber);

            //    if (user != null)
            //    {
            //        var errorMessage = new HttpResponseMessage<UserModels.SubmitUserResponse>(HttpStatusCode.BadRequest);
            //        errorMessage.ReasonPhrase = String.Format("The mobile number {0} is already registered.", request.mobileNumber);

            //        return errorMessage;
            //    }
            //}

            try
            {
                _logger.Log(LogLevel.Info, String.Format("Adding user {0}", request.userName));

                user = _userService.AddUser(Guid.Parse(request.apiKey), request.userName, request.password, request.emailAddress,
                    request.deviceToken);

                _ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, string.Format("Exception registering user {0}. Exception {1}.", request.emailAddress, ex.Message));

                var message = new HttpResponseMessage<UserModels.SubmitUserResponse>(HttpStatusCode.InternalServerError);
                message.ReasonPhrase = String.Format("Unable to register user. {0}", ex.Message);

                return message;
            }

            _amazonNotificationService.PushSNSNotification(ConfigurationManager.AppSettings["UserPostedTopicARN"], "New User Account Created", user.UserId.ToString());

            var responseMessage = new UserModels.SubmitUserResponse()
            {
                userId = user.UserId.ToString()
            };

            return new HttpResponseMessage<UserModels.SubmitUserResponse>(responseMessage, HttpStatusCode.Created);
        }
Exemplo n.º 40
0
 // PUT /api/users/5
 public HttpResponseMessage Put(int id, UserModels.UpdateUserRequest request)
 {
     return new HttpResponseMessage(HttpStatusCode.OK);
 }
Exemplo n.º 41
0
        //POST /api/users/{userId}/setup_securitypin
        public HttpResponseMessage SetupSecurityPin(string id, UserModels.UpdateSecurityPin request)
        {
            _logger.Log(LogLevel.Info, String.Format("Setting up Security Pin for {0}", id));

            DomainServices.UserService userService = new DomainServices.UserService(_ctx);

            if(request.securityPin.Length < 4)
            {
                var error = @"Invalid Security Pin";

                _logger.Log(LogLevel.Error, String.Format("Unable to Setup Security Pin for {0}. {1}", id, error));

                var message =  new HttpResponseMessage(HttpStatusCode.BadRequest);
                message.ReasonPhrase = error;

                return message;
            }

            try
            {
                userService.SetupSecurityPin(id, request.securityPin);
            }
            catch (Exception ex)
            {
                var error = ex.Message;

                _logger.Log(LogLevel.Error, String.Format("Unable to Setup Security Pin for {0}. {1}", id, error));

                var message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                message.ReasonPhrase = error;

                return message;
            }

            return new HttpResponseMessage(HttpStatusCode.OK);
        }
Exemplo n.º 42
0
        //POST /api/users/validate_user
        public HttpResponseMessage<UserModels.ValidateUserResponse> ValidateUser(UserModels.ValidateUserRequest request)
        {
            var userService = new DomainServices.UserService(_ctx);

            User user;
            var isValid = userService.ValidateUser(request.userName, request.password, out user);

            bool hasACHAccount = false;
            if (user.PaymentAccounts.Where(a => a.IsActive = true).Count() > 0)
                hasACHAccount = true;

            if (isValid){
                var message = new UserModels.ValidateUserResponse()
                {
                    userId = user.UserId.ToString(),
                    mobileNumber = user.MobileNumber,
                    paymentAccountId = (user.PaymentAccounts != null && user.PaymentAccounts.Count() > 0 ? user.PaymentAccounts[0].Id.ToString() : ""),
                    setupSecurityPin = user.SetupSecurityPin,
                    upperLimit = Convert.ToInt32(user.Limit),
                    hasACHAccount = hasACHAccount,
                    hasSecurityPin = user.SetupSecurityPin
                };

                return new HttpResponseMessage<UserModels.ValidateUserResponse>(message, HttpStatusCode.OK);
            }
            else
                return new HttpResponseMessage<UserModels.ValidateUserResponse>(HttpStatusCode.Forbidden);
        }