public ActionResult CapNhat(FormCollection form)
        {
            var    user     = (NguoiDung)Session["Account"];
            string name     = form["name"].ToString();
            string phone    = form["phone"].ToString();
            string email    = form["email"].ToString();
            string address  = form["address"].ToString();
            string password = form["password"].ToString();

            var nguoidung = db.NguoiDungs.SingleOrDefault(n => n.UserName == user.UserName);

            if (nguoidung != null)
            {
                nguoidung.TenNguoiDung = name;
                nguoidung.SoDienThoai  = phone;
                nguoidung.Email        = email;
                nguoidung.DiaChi       = address;
                if (!String.IsNullOrEmpty(password))
                {
                    nguoidung.PassWord = MD5Encode.CreateMD5(password);
                }
                db.SaveChanges();
                SetAlert("Cập nhật thông tin thành công!", "success");
                Session["Account"] = nguoidung;
            }
            else
            {
                SetAlert("Không thể cập nhật thông tin", "error");
            }
            return(RedirectToAction("UserProfile"));
        }
        public ActionResult Create([Bind(Include = "MaNguoiDung,TenNguoiDung,DiaChi,SoDienThoai,Email,CMND,UserName,PassWord,MaChucVu,Avatar")] NguoiDung nguoiDung, HttpPostedFileBase avatar)
        {                                                                                                           //,IsDeleted
            if (ModelState.IsValid)
            {
                if (avatar != null && avatar.ContentLength > 0)
                {
                    try
                    {
                        Random random     = new Random();
                        string avatarfile = nguoiDung.UserName + "_" + random.Next(10000).ToString() + "_" + Path.GetFileName(avatar.FileName);
                        string path       = Path.Combine(Server.MapPath("~/images/avatar/"), avatarfile);
                        avatar.SaveAs(path);
                        nguoiDung.Avatar = avatarfile;
                    }
                    catch (Exception)
                    {
                        //
                    }
                }
                else
                {
                    nguoiDung.Avatar = "default.png";
                }
                nguoiDung.PassWord = MD5Encode.CreateMD5(nguoiDung.PassWord);
                db.NguoiDungs.Add(nguoiDung);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.MaChucVu = new SelectList(db.ChucVus, "MaChucVu", "TenChucVu", nguoiDung.MaChucVu);
            return(View(nguoiDung));
        }
Пример #3
0
        public static OperateResult  ModifyPasswd(long id, string pwdOld, string pwd)
        {
            try
            {
                using (SystemDB db = new SystemDB())
                {
                    var element = (from m in db.userList
                                   where id == m.id
                                   select m
                                   ).FirstOrDefault();

                    if (element == null)
                    {
                        return(new OperateResult
                        {
                            content = "访问错误",
                        });
                    }

                    if (element.passwd != MD5Encode.Encode16(pwdOld))
                    {
                        return(new OperateResult
                        {
                            content = "原密码错误",
                        });
                    }


                    element.passwd = MD5Encode.Encode16(pwd);

                    db.Entry(element).State = System.Data.Entity.EntityState.Modified;

                    db.SaveChanges();

                    LogManager.Add(new LogRecord
                    {
                        userId  = SessionHelper.GetUserId(),
                        time    = DateTime.Now,
                        type    = "Info",
                        content = "重置密码:" + element.name
                    });


                    return(new OperateResult
                    {
                        status = OperateStatus.Success,
                        content = "更新成功"
                    });
                }
            }
            catch (Exception ex)
            {
                return(new OperateResult
                {
                    content = Model.Utility.Utility.GetExceptionMsg(ex),
                });
            }
        }
Пример #4
0
        //public bool DoLoginForPort(string logintype, string username)
        //{
        //    string wHERE_CLAUSE = " 1 = 1 ";
        //    System.Collections.Generic.IList<StrObjectDict> list;
        //    if (logintype == "YHID")
        //    {
        //        list = DB.ListSod("LIST2_XT_YHXX", StrObjectDict.FromVariable(new
        //        {
        //            YHID = username,
        //            WHERE_CLAUSE = wHERE_CLAUSE,
        //            ZFPB = 0
        //        }));
        //    }
        //    else
        //    {
        //        list = DB.ListSod("LIST2_XT_YHXX", StrObjectDict.FromVariable(new
        //        {
        //            YHGH = username,
        //            WHERE_CLAUSE = wHERE_CLAUSE,
        //            ZFPB = 0
        //        }));
        //    }
        //    bool result;
        //    if (list.Count > 0)
        //    {
        //        HttpContext.Current.Session["LOGINED"] = true;
        //        LoginSession.Current.Refresh(list.FirstOrDefault<StrObjectDict>());
        //        HttpCookie httpCookie = new HttpCookie("YONGHUGH", username);
        //        httpCookie.Expires = System.DateTime.Now.AddYears(1);
        //        HttpContext.Current.Response.Cookies.Add(httpCookie);
        //        result = true;
        //    }
        //    else
        //    {
        //        HttpContext.Current.Session["LOGINED"] = null;
        //        result = false;
        //    }
        //    return result;
        //}

        #endregion


        /// <summary>
        /// 验证用户名和密码
        /// </summary>
        /// <param name="userName">工号</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        public StrObjectDict GetByUserNameAndPwd(string userName, string pwd)
        {
            string passwordMd5 = MD5Encode.Encode(pwd);

            return(this.LoadObjectSod <PubUser>(new
            {
                UserName = userName,
                Password = passwordMd5
            }.toStrObjDict()));
        }
 public ActionResult DangKy([Bind(Include = "MaNguoiDung,TenNguoiDung,SoDienThoai, Email,UserName,PassWord")] NguoiDung nguoiDung)
 {                                                                                                           //,IsDeleted
     if (ModelState.IsValid)
     {
         var nd = db.NguoiDungs.SingleOrDefault(n => n.UserName == nguoiDung.UserName ||
                                                n.SoDienThoai == nguoiDung.SoDienThoai || n.Email == nguoiDung.Email);
         if (nd == null)
         {
             try
             {
                 db.NguoiDungs.Add(new NguoiDung
                 {
                     TenNguoiDung = nguoiDung.TenNguoiDung,
                     DiaChi       = "",
                     SoDienThoai  = nguoiDung.SoDienThoai,
                     Email        = nguoiDung.Email,
                     CMND         = "",
                     UserName     = nguoiDung.UserName,
                     PassWord     = MD5Encode.CreateMD5(nguoiDung.PassWord),
                     IsDeleted    = false,
                     MaChucVu     = 6, // Customer
                     Avatar       = "default.png"
                 });
                 db.SaveChanges();
                 SetAlert("Tạo tài khoản thành công!", "success");
             }
             catch (Exception ex)
             {
                 SetAlert(ex.ToString(), "error");
                 RedirectToAction("Index");
             }
         }
         else
         {
             if (nd.UserName == nguoiDung.UserName)
             {
                 SetAlert("Tài khoản này đã có người sử dụng!", "error");
                 return(RedirectToAction("Index"));
             }
             if (nd.SoDienThoai == nguoiDung.SoDienThoai)
             {
                 SetAlert("Số điện thoại này đã có người sử dụng!", "error");
                 return(RedirectToAction("Index"));
             }
             SetAlert("Tạo tài khoản không thành công!", "error");
         }
     }
     else
     {
         SetAlert("Tạo tài khoản không thành công!", "error");
     }
     return(RedirectToAction("Index"));
 }
Пример #6
0
        private void ucBtnChangePwd_BtnClick(object sender, EventArgs e)
        {
            FrmInputs frm = new FrmInputs("修改密码",
                                          new string[] { "旧密码", "新密码", "确定密码" },
                                          new Dictionary <string, HZH_Controls.TextInputType>()
            {
            },
                                          new Dictionary <string, string>()
            {
            },
                                          new Dictionary <string, KeyBoardType>()
            {
                { "旧密码", KeyBoardType.UCKeyBorderAll_EN }, { "新密码", KeyBoardType.UCKeyBorderAll_EN }
            },
                                          new List <string>()
            {
                "旧密码", "新密码", "确定密码"
            });

            frm.ShowDialog(this);
            if (frm.DialogResult == DialogResult.OK)
            {
                string oldPwd = frm.Values[0];
                string newPwd = frm.Values[1];
                string comPwd = frm.Values[2];
                if (newPwd != comPwd)
                {
                    MessageBox.Show("两次密码不一致");
                    return;
                }

                //if (!Check.isPwd(newPwd))
                // {
                //     MessageBox.Show("密码最少6位,包括至少1个大写字母,1个小写字母,1个数字,1个特殊字符");
                //     return;
                // }

                if (MD5Encode.GetMd5(oldPwd) == teacher.PassWord)
                {
                    TeacherBLL bll = new TeacherBLL();
                    string     msg = bll.EditPwd(MD5Encode.GetMd5(newPwd), teacher.TID)?"修改成功":"修改失败";
                    MessageBox.Show(msg);
                }
                else
                {
                    MessageBox.Show("原密码错误");
                }
            }
        }
Пример #7
0
        /// <summary>
        /// 保存人员信息
        /// </summary>
        /// <returns></returns>
        public override ActionResult InsertOrUpdate()
        {
            StrObjectDict reqParam = GetParams();
            var           pwd      = reqParam.GetString("Password");

            reqParam.Remove("Password");
            reqParam["Password"] = MD5Encode.Encode(pwd);

            int result = UserManager.Instance.InsertOrUpdate <PubUser>(reqParam);

            if (result > 0)
            {
                return(this.MyJson(1, result));
            }
            return(this.MyJson(0, "保存失败"));
        }
Пример #8
0
    public static bool loginFromCookieOnly()
    {
        string username = cookieOperation.getOneCookie("userName").ToString();
        string logincode = cookieOperation.getOneCookie("loginCode").ToString();
        string realname = "", password = "", role = "";

        if (username != "" && logincode != "")
        {
            OleDbConnection con    = DB.createcon();
            string          sqlstr = "select * from [student] where [studentUsername]='" + username + "'";
            con.Open();
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandText = sqlstr;
            cmd.Connection  = con;
            OleDbDataReader sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                password = sdr["studentPassword"].ToString();
                role     = sdr["roleType"].ToString();
                realname = sdr["studentName"].ToString();
            }
            sdr.Close();
            con.Close();
            //HttpContext.Current.Response.Write(MD5Encode.docubleMD5_encode(username, password)+"<br>");
            //HttpContext.Current.Response.Write(logincode);
            if (MD5Encode.docubleMD5_encode(username, password) == logincode)
            {
                HttpContext.Current.Session["userType"] = role;
                HttpContext.Current.Session["realName"] = realname;
                HttpContext.Current.Session["userName"] = username;
                cookieOperation.setOneCookie("userType", role);
                cookieOperation.setOneCookie("realName", realname);
                cookieOperation.setOneCookie("userName", username);
                cookieOperation.setOneCookie("loginCode", logincode);
                return(true);
            }
            else
            {
                return(false);
            }
        }
        else
        {
            return(false);
        }
    }
        //添加学生
        private void ucBtnSave_BtnClick(object sender, EventArgs e)
        {
            bool b;

            if (!Check.isStudentID(txtSID.Text))
            {
                FrmTips.ShowTipsWarning(this, "学号格式不正确");
                return;
            }

            try
            {
                Student stu = new Student();
                stu.SID           = txtSID.Text;
                stu.SName         = txtSname.Text;
                stu.PassWord      = MD5Encode.GetMd5("123456"); //学生默认密码123456
                stu.SGender       = cmbGender.SelectedIndex % 2 == 0 ? "男" : "女";
                stu.Class         = cmbClass.SelectedValue.ToString();
                stu.Departments   = cmbCollege.SelectedValue.ToString();
                stu.Birthday      = Convert.ToDateTime(dtpBir.Value.ToString("yyy/MM/dd"));
                stu.AdmissionTime = Convert.ToDateTime(dtpAdm.Value.ToString("yyy/MM/dd"));
                stu.Image         = null;
                StudentBLL bll = new StudentBLL();
                b = bll.AddStudentInfo(stu);
            }
            catch (Exception)
            {
                b = false;
            }

            if (b)
            {
                FrmTips.ShowTipsSuccess(this, "添加成功");
                txtSID.Clear();
                txtSname.Clear();
                txtSID.Focus();
            }
            else
            {
                FrmTips.ShowTipsError(this, "添加失败");
            }

            //MessageBox.Show(cmbGender.SelectedValue.ToString());
            //MessageBox.Show(cmbClass.SelectedValue.ToString());
        }
Пример #10
0
        public OperateResult Add(User model)
        {
            using (SystemDB db = new SystemDB())
            {
                try
                {
                    var match = from m in db.userList
                                where m.name.Equals(model.name)
                                select m;
                    if (match.Count() > 0)
                    {
                        return(new OperateResult
                        {
                            content = "用户已经存在",
                        });
                    }

                    model.passwd = MD5Encode.Encode16(model.passwd);

                    db.userList.Add(model);
                    db.SaveChanges();

                    LogManager.Add(new LogRecord
                    {
                        userId  = SessionHelper.GetUserId(),
                        time    = DateTime.Now,
                        type    = "Info",
                        content = "添加用户:" + model.name
                    });

                    return(new OperateResult
                    {
                        status = OperateStatus.Success,
                    });
                }
                catch (Exception ex)
                {
                    return(new OperateResult
                    {
                        content = ex.Message,
                    });
                }
            }
        }
        private void ucBtnChangePwd_BtnClick(object sender, EventArgs e)
        {
            FrmInputs frm = new FrmInputs("修改密码",
                                          new string[] { "旧密码", "新密码", "确定密码" },
                                          new Dictionary <string, HZH_Controls.TextInputType>()
            {
            },
                                          new Dictionary <string, string>()
            {
            },
                                          new Dictionary <string, KeyBoardType>()
            {
                { "旧密码", KeyBoardType.UCKeyBorderAll_EN }, { "新密码", KeyBoardType.UCKeyBorderAll_EN }
            },
                                          new List <string>()
            {
                "旧密码", "新密码", "确定密码"
            });

            frm.ShowDialog(this);
            if (frm.DialogResult == DialogResult.OK)
            {
                string oldPwd = frm.Values[0];
                string newPwd = frm.Values[1];
                string comPwd = frm.Values[2];
                if (newPwd != comPwd)
                {
                    MessageBox.Show("两次密码不一致");
                    return;
                }
                if (MD5Encode.GetMd5(oldPwd) == student.PassWord)
                {
                    StudentBLL bll = new StudentBLL();
                    string     msg = bll.EditPwd(MD5Encode.GetMd5(newPwd), student.SID) ? "修改成功" : "修改失败";
                    MessageBox.Show(msg);
                }
                else
                {
                    MessageBox.Show("原密码错误");
                }
            }
        }
        public ActionResult DangNhap(FormCollection form)
        {
            string username = form["username"].ToString();
            string password = MD5Encode.CreateMD5(form["password"].ToString());

            var nguoiDung = db.NguoiDungs.SingleOrDefault(n => n.UserName == username && n.PassWord == password);

            if (nguoiDung != null)
            {
                if (nguoiDung.IsDeleted == false)
                {
                    IEnumerable <ChucVu> listQuyen = db.ChucVus.Where(n => n.MaChucVu == nguoiDung.MaChucVu);
                    string quyen = "";
                    foreach (var item in listQuyen)
                    {
                        quyen += item.TenChucVu + ",";
                    }
                    quyen = quyen.Substring(0, quyen.Length - 1);
                    PhanQuyen(nguoiDung.UserName.ToString(), quyen);
                    Session["Account"] = nguoiDung;
                    HoTen = nguoiDung.TenNguoiDung;
                    if (nguoiDung.ChucVu.TenChucVu != "KhachHang")
                    {
                        return(RedirectToAction("Index", "Manager/Home"));
                    }
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    SetAlert("Tài khoản của bạn đã bị khóa!", "error");
                    return(RedirectToAction("Index", "Home"));
                }
            }
            else
            {
                SetAlert("Sai tài khoản hoặc mật khẩu!", "error");
            }
            return(RedirectToAction("Index", "Home")); // Need add notification login not success
        }
Пример #13
0
        public ApiResult <IEnumerable <SysUserViewModel> > Import(IFormFile excelfile)
        {
            var res = new ApiResult <IEnumerable <SysUserViewModel> >()
            {
                statusCode = (int)ApiEnum.Status
            };

            if (excelfile != null)
            {
                List <UserInfo> userInfos  = new List <UserInfo>(); // 更新的列表
                List <UserInfo> userInfos2 = new List <UserInfo>(); // 添加的列表
                UserInfo        sysUserView;
                string          sWebRootFolder = _webHostEnvironment.WebRootPath + "\\UploadFiles\\excel\\import";
                string          sFileName      = $"{Guid.NewGuid()}.xlsx";
                FileInfo        file           = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
                try
                {
                    using (FileStream fs = new FileStream(file.ToString(), FileMode.Create))
                    {
                        excelfile.CopyTo(fs);
                        fs.Flush();
                    }
                    using (ExcelPackage package = new ExcelPackage(file))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                        int            rowCount  = worksheet.Dimension.Rows;
                        int            ColCount  = worksheet.Dimension.Columns;
                        DateTime       now       = DateTime.Now;
                        string         password  = MD5Encode.GetEncrypt("888888");
                        for (int row = 2; row <= rowCount; row++)
                        {
                            // 查询账号是否已经存在 - 如果单次数据超过100条建议把所有用户取出来对比
                            sysUserView = db.GetFirst(o => o.UserName == C.String(worksheet.Cells[row, 2].Value));
                            if (sysUserView != null)
                            {
                                userInfos.Add(new UserInfo
                                {
                                    UserName    = C.String(worksheet.Cells[row, 1].Value),
                                    NickName    = C.String(worksheet.Cells[row, 2].Value),
                                    FullName    = C.String(worksheet.Cells[row, 3].Value),
                                    MobilePhone = C.String(worksheet.Cells[row, 4].Value),
                                });
                            }
                            else
                            {
                                userInfos2.Add(new UserInfo
                                {
                                    UserName    = C.String(worksheet.Cells[row, 1].Value),
                                    NickName    = C.String(worksheet.Cells[row, 2].Value),
                                    FullName    = C.String(worksheet.Cells[row, 3].Value),
                                    MobilePhone = C.String(worksheet.Cells[row, 4].Value),
                                    RoleID      = 4, // 用户
                                    State       = 2, // 已审
                                    AddDate     = now,
                                    Password    = password,
                                });
                            }
                        }
                    }
                    // 新增或更新
                    int addCount = 0, updateCount = 0;
                    if (userInfos.Count > 0)
                    {
                        addCount = db.Update(userInfos);
                        res.msg += $"导入{addCount}条,";
                    }
                    if (userInfos2.Count > 0)
                    {
                        updateCount = db.Add(userInfos2);
                        res.msg    += $"更新{addCount}条,";
                    }
                    // 结果
                    res.success = addCount > 0 || updateCount > 0;
                    if (res.msg != null)
                    {
                        res.msg = res.msg.TrimEnd(',');
                    }
                }
                catch (Exception ex)
                {
                    res.success = false;
                    res.msg     = ApiEnum.Error.GetEnumText() + ex.Message;
                }
            }
            return(res);
        }
Пример #14
0
        public StrObjectDict DoLogin(string username, string password, out string retmsg)
        {
            string text  = MD5Encode.Encode(password);
            string text2 = " 1 = 1 ";
            string csz   = ParmManager.Instance.getCsz("XT_MD5ENCODE");

            if (string.IsNullOrEmpty(password))
            {
                text2 += " and (mm is null or mm ='')";
            }
            else
            {
                if (csz == "1")
                {
                    text2 = text2 + " and (mm = '" + text + "' )";
                }
                else
                {
                    string text3 = text2;
                    text2 = string.Concat(new string[]
                    {
                        text3,
                        " and  (mm = '",
                        text,
                        "' or mm='",
                        password,
                        "' )"
                    });
                }
            }
            //string sql = DB.GetSql("LIST2_XT_YHXX", StrObjectDict.FromVariable(new
            //{
            //    YHGH = username,
            //    WHERE_CLAUSE = text2,
            //    ZFPB = 0
            //}));
            IList <StrObjectDict> list = DB.ListSod("LIST2_XT_YHXX", StrObjectDict.FromVariable(new
            {
                YHGH         = username,
                WHERE_CLAUSE = text2,
                ZFPB         = 0
            }));

            if (list.Count > 0)
            {
                retmsg = "";
                return(list.FirstOrDefault <StrObjectDict>());
            }
            else
            {
                list = DB.ListSod("LIST2_XT_YHXX", StrObjectDict.FromVariable(new
                {
                    YHGH = username,
                    ZFPB = 0
                }));
                if (list.Count > 0)
                {
                    retmsg = "密码错误!";
                }
                else
                {
                    retmsg = "工号错误!";
                }
            }
            return(null);
        }
Пример #15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int i = 0;

        if (Session["tryCount"] == null)//用户名或密码错误次数不得超过一定界限
        {
            Session["tryCount"] = 1;
        }
        if (Convert.ToInt32(Session["tryCount"]) > 50)
        {
            i = 2;
        }
        else
        {
            if (Request.Form["uid"] != null && Request.Form["pwd"] != null)
            {
                try
                {
                    string          username = SqlString.keepoutSqlKey(Request.Form["uid"]);
                    string          password = SqlString.keepoutSqlKey(Request.Form["pwd"]);
                    OleDbConnection con      = DB.createcon();
                    string          sqlstr   = "select * from [student] where [studentUsername]='" + username + "'  and ([studentPassword]='" + password + "' or [studentPassword]='" + MD5_encode(password) + "')";
                    con.Open();
                    OleDbCommand cmd = new OleDbCommand();
                    cmd.CommandText = sqlstr;
                    cmd.Connection  = con;
                    OleDbDataReader sdr = cmd.ExecuteReader();
                    while (sdr.Read())
                    {
                        string role     = sdr["roleType"].ToString();
                        string realname = sdr["studentName"].ToString();
                        password            = sdr["studentPassword"].ToString();
                        Session["userType"] = role;
                        Session["realName"] = realname;
                        Session["userName"] = username;
                        cookieOperation.setOneCookie("userType", role);
                        cookieOperation.setOneCookie("realName", realname);
                        cookieOperation.setOneCookie("userName", username);
                        string logincode = MD5Encode.docubleMD5_encode(username, password);
                        cookieOperation.setOneCookie("loginCode", logincode);
                        i = 1;
                    }
                    sdr.Close();
                    con.Close();
                    if (i == 1)
                    {
                        string mydatetime = DateTime.Now.ToString();
                        string ip         = Request.ServerVariables["REMOTE_HOST"].ToString();
                        string sqlstr2    = "update [student] set loginCount=loginCount+1,lastLoinTime='" + mydatetime + "',lastLoinIP='" + ip + "' where studentUsername='******'";
                        cmd.CommandText = sqlstr2;
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                        switch (Session["userType"].ToString())
                        {
                        case "2":
                            countOperation.countAddOne("adminLoginCount");
                            countOperation.countAddOne("onlineStudent");
                            systemRecord.insertOneRecord("管理员“" + username + "“登陆成功!");
                            break;

                        case "3":
                            countOperation.countAddOne("superAdminLoginCount");
                            countOperation.countAddOne("onlineStudent");
                            systemRecord.insertOneRecord("超级管理员“" + username + "“登陆成功!");
                            break;

                        default:
                            countOperation.countAddOne("onlineStudent");
                            systemRecord.insertOneRecord("学生“" + username + "“登陆成功!");
                            break;
                        }
                    }
                }
                catch (Exception exp)
                {
                    saveErrorMessage.writeFile("用户登陆时发生错误!", exp.ToString());
                    i = 0;
                }
            }
        }
        if (i == 0)
        {
            Session["tryCount"] = Convert.ToInt32(Session["tryCount"]) + 1;
        }
        Response.Write(i.ToString());
    }
Пример #16
0
        public OperateResult Login(User model)
        {
            using (SystemDB db = new SystemDB())
            {
                try
                {
                    var passwd = MD5Encode.Encode16(model.passwd);

                    var element = (from e in db.userList.Include("role")
                                   where e.passwd == passwd && e.name == model.name
                                   select e
                                   ).FirstOrDefault();
                    if (element != null)
                    {
                        if (element.status == "锁定")
                        {
                            return(new OperateResult
                            {
                                content = "用户被锁定",
                            });
                        }

                        //更新最后一次登录
                        element.lastLogin = DateTime.Now;

                        if (element.status == "未激活")
                        {
                            element.status = "激活";
                        }

                        db.Entry(element).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();

                        LogManager.Add(new LogRecord
                        {
                            userId  = element.id,
                            time    = DateTime.Now,
                            type    = "Info",
                            content = "登录系统"
                        });

                        return(new OperateResult
                        {
                            status = OperateStatus.Success,
                            content = "登录成功",
                            data = element
                        });
                    }


                    return(new OperateResult
                    {
                        content = "用户名或密码不正确"
                    });
                }
                catch (Exception ex)
                {
                    return(new OperateResult
                    {
                        content = ex.Message,
                    });
                }
            }
        }
Пример #17
0
        public async Task <ApiResult <string> > SysItem2(int ID, APIUserViewModel vm)
        {
            // 以接口的形式返回数据
            var res    = new ApiResult <string>();
            int UserID = GetUserID();

            if (UserID > 0)
            {
                if (!string.IsNullOrWhiteSpace(vm.UserName))
                {
                    UserInfo m = db.GetId(ID);
                    if (m != null)
                    {
                        m.ID           = ID;
                        m.UserName     = vm.UserName;
                        m.HeadPortrait = vm.HeadPortrait;
                        m.NickName     = vm.NickName;
                        m.FullName     = vm.FullName;
                        m.Position     = vm.Position;
                        m.IdCard       = Utility.IdCardEncrypt(vm.IdCard);
                        m.Gender       = vm.Gender;
                        m.MobilePhone  = vm.MobilePhone;
                        m.QQ           = vm.QQ;
                        m.Mail         = vm.Mail;
                        m.State        = vm.State;
                        m.RoleID       = vm.RoleID;

                        // 设置默认密码
                        if (string.IsNullOrWhiteSpace(vm.Password))
                        {
                            vm.Password = "******";
                        }
                        // 如果设置了密码、就进行加密
                        if (!string.IsNullOrWhiteSpace(vm.Password))
                        {
                            m.Password = MD5Encode.GetEncrypt(vm.Password);
                        }
                    }
                    else
                    {
                        res.msg = "参数丢失";
                    }
                    try
                    {
                        res.success = db.Update(m) > 0;
                        if (res.success)
                        {
                            res.msg = "修改成功";
                        }
                        else
                        {
                            res.msg        = "修改失败";
                            res.statusCode = (int)ApiEnum.Status;
                        }
                    }
                    catch (Exception ex)
                    {
                        res.statusCode = (int)ApiEnum.Error;
                        res.msg        = ApiEnum.Error.GetEnumText() + ex.Message;
                    }
                }
                else
                {
                    res.msg = "参数丢失";
                }
            }
            else
            {
                res.msg        = "无法获取用户信息!";
                res.statusCode = (int)ApiEnum.Status;
            }
            return(await Task.Run(() => res));
        }
Пример #18
0
        public async Task <ApiResult <object> > UpdatePwd(string Oldpassword, string Newpassword1, string Newpassword2)
        {
            // 以接口的形式返回数据
            var res    = new ApiResult <object>();
            int UserID = GetUserID();

            if (UserID > 0)
            {
                TokenModelJwt tokenModelJwt = TokenDecode();
                int           UID           = C.Int(tokenModelJwt.Uid);
                try
                {
                    if (Newpassword1 == Newpassword2)
                    {
                        UserInfo m = db.GetId(UID);
                        if (m != null)
                        {
                            var user = db.GetFirst(a => a.UserName == m.UserName && a.Password == MD5Encode.GetEncrypt(Oldpassword));
                            if (user == null)
                            {
                                res.statusCode = (int)ApiEnum.ParameterError;
                                res.msg        = "原密码错误!";
                            }
                            else
                            {
                                if (!string.IsNullOrWhiteSpace(Newpassword1))
                                {
                                    m.Password  = MD5Encode.GetEncrypt(Newpassword1);
                                    res.success = db.Update(m) > 0;
                                }
                                else
                                {
                                    res.statusCode = (int)ApiEnum.ParameterError;
                                    res.msg        = "密码不能为空!";
                                }
                                if (res.success)
                                {
                                    res.statusCode = (int)ApiEnum.Status;
                                }
                            }
                        }
                        else
                        {
                            res.statusCode = (int)ApiEnum.Status;
                            res.msg        = "无该账号";
                        }
                    }
                    else
                    {
                        res.statusCode = (int)ApiEnum.ParameterError;
                        res.msg        = "两次密码不一样!";
                    }
                }
                catch (Exception ex)
                {
                    res.statusCode = (int)ApiEnum.Error;
                    res.msg        = ApiEnum.Error.GetEnumText() + ex.Message;
                }
            }
            else
            {
                res.statusCode = (int)ApiEnum.Status;
                res.msg        = "无法获取用户信息!";
            }
            return(await Task.Run(() => res));
        }