Ejemplo n.º 1
0
 /// <summary>
 /// 更新密码
 /// </summary>
 /// <param name="username"></param>
 /// <param name="password"></param>
 /// <param name="newpwd"></param>
 /// <returns></returns>
 public bool UpdatePwd(string username, string password, string newpwd)
 {
     using (UpdateAction action = new UpdateAction(Entity))
     {
         action.SqlKeyValue(SmsAccountInfo.Columns.Password, newpwd);
         action.SqlWhere(SmsAccountInfo.Columns.Account, username);
         action.SqlWhere(SmsAccountInfo.Columns.Password, md5.Encrypt(password));
         action.Excute();
         return(action.ReturnCode > 0);
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// 注册用户信息
        /// </summary>
        /// <param name="strUserName"></param>
        /// <param name="strRealName"></param>
        /// <param name="strphoneNumber"></param>
        /// <param name="strPassword"></param>
        /// <param name="strRegisterTime"></param>
        /// <param name="iStatus"></param>
        /// <param name="strAddress"></param>
        /// <param name="iRole"></param>
        /// <param name="strProvince"></param>
        /// <param name="strCity"></param>
        /// <param name="strTelephone"></param>
        /// <param name="strOtherContact"></param>
        /// <param name="strFax"></param>
        /// <param name="iIsActive"></param>
        /// <param name="strLastLoginIp"></param>
        /// <param name="strEmail"></param>
        /// <returns></returns>
        public static bool Register(string strUserName, string strRealName,
                                    string strphoneNumber,
                                    string strAddress, string strProvince, string strCity,
                                    string strTelephone, string strOtherContact, string strFax,
                                    string strEmail, string Brno, string iRole)
        {
            bool bResult = false;

            try
            {
                string strRegisterTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //进行MD5 加密
                string strPassword = MD5Encrypt.Encrypt("123456");
                string strSql      = string.Format("insert into huabao.userinfo set " +
                                                   "userName='******',realName='{1}',phoneNumber='{2}',password='******'," +
                                                   "registertime='{4}',lastLoginTime='{5}',status='{6}',address='{7}'," +
                                                   "role='{8}',province='{9}',city='{10}',telephone='{11}',otherContact='{12}'," +
                                                   "fax='{13}',isActive='{14}',lastLoginIp='{15}',email='{16}',Brno='{17}' ",
                                                   strUserName, strRealName,
                                                   strphoneNumber, strPassword, strRegisterTime, "",
                                                   "1", strAddress, iRole, strProvince, strCity,
                                                   strTelephone, strOtherContact, strFax, "1",
                                                   "", strEmail, Brno);
                bResult = MySqlHelper.ExecuteSql(strSql) == 1 ? true : false;
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            return(bResult);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 检查账号密码是否正确
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public Sys_User CheckUser(string userName, string passWord)
        {
            Sys_User result = null;

            try
            {
                if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(passWord))
                {
                    return(result);
                }

                using (var db = SugarDao.GetInstance())
                {
                    string uName = userName.ToLower();
                    string pwd   = MD5Encrypt.Encrypt(passWord);

                    result = db.Queryable <Sys_User>().FirstOrDefault(t => t.Account == uName && t.Password == pwd && t.IsEnabled);
                }

                return(result);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 4
0
        public int Insert(UserVM form)
        {
            //string sql = "insert into Sys_User (UserName) values (@0)";
            //SqlParameter[] parameter = new SqlParameter[] {
            //    new SqlParameter("@0", SqlDbType.VarChar, 50)
            //};
            //parameter[0].Value = user.UserName;

            //return this.userRepository.ExecuteSqlCommand(ContextDB.managerDBContext, sql, parameter);
            //return this.userRepository.Insert(ContextDB.managerDBContext, user);

            //SqlParameter[] parameters = {
            //          new SqlParameter("@UserName", user.UserName),
            //          new SqlParameter("@Ret", SqlDbType.Int)
            //};
            //parameters[1].Direction = ParameterDirection.Output;

            //var result = ContextDB.managerDBContext.Database.ExecuteSqlCommand("exec proc_userInsert @UserName, @Ret out", parameters);
            //int ret = (int)parameters[1].Value;

            //            SqlParameter[] p =
            //{
            //                SqlHelper.MakeInParam("@UserId",SqlDbType.VarChar,20,UserId),
            //                SqlHelper.MakeInParam("@Pwd",SqlDbType.VarChar,50,Pwd)
            //            };

            Sys_User model = new Sys_User();

            Ext.CopyFrom(model, form);
            model.UpdateDate = DateTime.Now;
            model.Password   = MD5Encrypt.Encrypt(model.Password);

            return(this._userRepository.Insert(ContextDB.managerDBContext, model));
        }
Ejemplo n.º 5
0
        public string ChekLogin(string strUserName, string strPassword)
        {
            string retstr = string.Empty;
            Dictionary <string, string> loginrst = new Dictionary <string, string>();
            int iResult = 0;

            try
            {
                strPassword = MD5Encrypt.Encrypt(strPassword);
                string strSql = string.Format("select username,password ,status,Brno,companyname,role from huabao.userinfo where username='******' ",
                                              strUserName);
                //int iResult= MySqlHelper.ExecuteSql(strSql);
                DataTable dt = MySqlHelper.ExecuteQuery(strSql);
                if (dt.Rows.Count == 0)
                {
                    loginrst.Add("Success", "false");
                    loginrst.Add("msg", "用户不存在!");
                }
                else
                {
                    string dbpsd  = dt.Rows[0][1].ToString();
                    string status = dt.Rows[0][2].ToString();
                    if (!"1".Equals(status))
                    {
                        loginrst.Add("Success", "false");
                        loginrst.Add("msg", "用户已停用!");
                    }
                    else if (!dbpsd.Equals(strPassword))
                    {
                        loginrst.Add("Success", "false");
                        loginrst.Add("msg", "输入密码有误!");
                    }
                    else
                    {
                        string updatesql = "update huabao.userinfo set lastLoginTime='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where   username='******'";
                        iResult = MySqlHelper.ExecuteSql(updatesql);
                        if (iResult == 1)
                        {
                            loginrst.Add("Success", "true");
                            loginrst.Add("msg", "登录成功!");
                            loginrst.Add("LoginTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            loginrst.Add("departid", dt.Rows[0][3].ToString());
                            loginrst.Add("departname", dt.Rows[0][4].ToString());
                            loginrst.Add("role", dt.Rows[0][5].ToString());
                            loginrst.Add("username", dt.Rows[0][0].ToString());
                        }
                        else
                        {
                            loginrst.Add("Success", "false");
                            loginrst.Add("msg", "登记末次登录时间失败!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
            return(JsonConvert.SerializeObject(loginrst));
        }
Ejemplo n.º 6
0
        public JsonResult PubArticle([FromBody] ArticleParam msg)
        {
            ReplyModel reply = new ReplyModel();

            try
            {
                Users users = _userRepository.Get(msg.UserId);
                if (users != null)
                {
                    msg.Password = MD5Encrypt.Encrypt(msg.Password);
                    Article.Add(_articleRepository, msg);
                    UserArticleEventExtend.TriggerAlterUserAritlceCountEvent(users, ServiceProvider);
                    bool result = ServiceProvider.GetService <IUnitOfWork>().Commit();
                    if (result)
                    {
                        reply.Status = "002";
                        reply.Msg    = "保存文章成功";
                    }
                    else
                    {
                        reply.Msg = "保存文章失败";
                    }
                }
                else
                {
                    reply.Msg = "未找到用户信息";
                }
            }
            catch (Exception ex)
            {
                reply.Msg = "文章发布或保存草稿失败,请重试";
                // _Logger.LogError($"文章发布或保存草稿失败,请重试{JsonConvert.SerializeObject(ex)}");
            }
            return(Json(reply));
        }
Ejemplo n.º 7
0
        public static string UserRegister(string name, string pwd)
        {
            IUserAccountService service = DIFactory.GetContainer().Resolve <IUserAccountService>();
            UserAccount         user    = service.UserLogin(name);

            if (user != null)
            {
                return("该账号已经被注册");
            }
            else
            {
                var model = new UserAccount()
                {
                    Name       = name,
                    Password   = MD5Encrypt.Encrypt(pwd),
                    Account    = name,
                    CreatorId  = 1,
                    CreateTime = DateTime.Now,
                    UserType   = 1,
                    State      = 1,
                };
                var result = service.InsertUser(model);
                if (result != null)
                {
                    return("成功");
                }
                return("失败");
            }
        }
Ejemplo n.º 8
0
        public static LoginResult UserLogin(this HttpContextBase context, string name = "", string pwd = "",
                                            string verify = "")
        {
            if (string.IsNullOrEmpty(verify) || context.Session["CheckCode"] == null || !context.Session["CheckCode"].ToString().Equals(verify))
            {
                return(LoginResult.WrongVerify);
            }
            var service = DIFactory.GetContainer().Resolve <IUserMenuService>();
            var user    = service.UserLogin(name);

            if (user == null)
            {
                return(LoginResult.NoUser);
            }
            else if (!user.Password.Equals(MD5Encrypt.Encrypt(pwd)))
            {
                return(LoginResult.WrongPwd);
            }
            else if (user.State == (int)UserState.Frozen)
            {
                return(LoginResult.Frozen);
            }
            else
            {
                return(LoginResult.Success);
            }
        }
Ejemplo n.º 9
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            MTADbContext db = new MTADbContext();

            Mapper.CreateMap <AU_NGUOIDUNG, AuNguoiDungVm.CurrentUser>();
            AuNguoiDungVm.CurrentUser result = null;
            var user = db.AU_NGUOIDUNGs.Where(x => x.Username == context.UserName).FirstOrDefault();

            if (user != null)
            {
                if (user.Password == MD5Encrypt.Encrypt(context.Password))
                {
                    result = Mapper.Map <AU_NGUOIDUNG, AuNguoiDungVm.CurrentUser>(user);
                }
            }
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            Action <ClaimsIdentity, string> addClaim = (ClaimsIdentity obj, string username) => { return; };
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            addClaim.Invoke(identity, user.Username);
            identity.AddClaim(new Claim(ClaimTypes.Role, "MEMBER"));
            identity.AddClaim(new Claim("unitCode", user.UnitCode));
            identity.AddClaim(new Claim("parentUnitCode", user.ParentUnitcode));
            AuthenticationProperties properties = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "userName", string.IsNullOrEmpty(user.Username)?string.Empty:user.Username
                },
                {
                    "fullName", string.IsNullOrEmpty(user.TenNhanVien)?string.Empty:user.TenNhanVien
                },
                {
                    "code", string.IsNullOrEmpty(user.MaNhanVien)?string.Empty:user.MaNhanVien
                },
                {
                    "phone", string.IsNullOrEmpty(user.SoDienThoai)?string.Empty:user.SoDienThoai
                },
                {
                    "chungMinhThu", string.IsNullOrEmpty(user.ChungMinhThu)?string.Empty:user.ChungMinhThu
                },
                {
                    "unitCode", string.IsNullOrEmpty(user.UnitCode)?string.Empty:user.UnitCode
                },
                {
                    "parentUnitCode", string.IsNullOrEmpty(user.ParentUnitcode)?string.Empty:user.ParentUnitcode
                }
            });

            AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(identity);
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> CreateEmployee([FromForm] EmployeeCreateDto createDto)
        {
            var id = Convert.ToInt32(User.Identity.Name);
            //生成密钥
            SymmetricSecurityKey key = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes("asdadhajhdkjahsdkjahdkj9au8d9adasidoad89asu813e"));
            //Auto映射
            var employee = mapper.Map <Employees>(createDto);

            employee.CreateID    = id;
            employee.Code        = Guid.NewGuid().ToString();
            employee.CreateTime  = DateTime.Now;
            employee.HeadImage   = "https://www.zhangqueque.top:5001/UserImg/1_1_1.png";
            employee.IsDel       = 0;
            employee.EmployeePID = 1;
            //employee.Password = "******";
            employee.Password = MD5Encrypt.Encrypt(employee.Password);



            if (createDto.UploadFile != null)
            {
                if (createDto.UploadFile.Length > 25165824)
                {
                    return(Ok(new { code = 1, msg = "文件不能大于3M!" }));
                }
                //文件名复杂,避免重复覆盖
                string fileName = employee.Name + employee.Email + employee.Phone + createDto.UploadFile.FileName;

                //设置文件存储的路劲
                string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "CustomerImg", fileName);

                //服务端保存文件
                using (var stream = System.IO.File.Create(filePath))
                {
                    await createDto.UploadFile.CopyToAsync(stream);
                }
                employee.HeadImage = Request.Scheme + "://" + Request.Host + "/CustomerImg/" + fileName;
            }


            await context.Employees.AddAsync(employee);

            await context.SaveChangesAsync();


            Employees_Roles employees_Roles = new Employees_Roles();

            employees_Roles.EmployeeID   = employee.ID;
            employees_Roles.EmployeeName = employee.Name;
            employees_Roles.RoleID       = 3;
            employees_Roles.RoleName     = "员工";

            await context.Employees_Roles.AddAsync(employees_Roles);

            await context.SaveChangesAsync();

            return(Ok(new { code = 0, msg = "员工添加成功!" }));
        }
Ejemplo n.º 11
0
        public Staff GetByUsername(string username, string password)
        {
            string encPassword = MD5Encrypt.Encrypt(password);

            using (UnileverEntities entity = new UnileverEntities())
            {
                return(entity.Staffs.Where(s => s.Username == username && s.Password == encPassword).FirstOrDefault());
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 保存文件,返回文件的MD5值
        /// </summary>
        /// <param name="formFile">文件</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task <string> SaveWidthMd5Async(IFormFile formFile, string savePath, CancellationToken cancellationToken = default)
        {
            //写入
            await using var stream = new FileStream(savePath, FileMode.Create);
            var md5 = MD5Encrypt.Encrypt(stream);
            await formFile.CopyToAsync(stream, cancellationToken);

            return(md5);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userPassword"></param>
        /// <returns></returns>
        public ActionResult Enter(string userName, string userPassword, string verifyCode)
        {
            using (Dbcontext context = new Dbcontext())
            {
                // 第一步检验验证码
                // 从缓存获取验证码作为校验基准
                // 先用当前类的全名称拼接上字符串 “verifyCode” 作为缓存的key
                Cache  cache         = new Cache();
                var    verifyCodeKey = $"{this.GetType().FullName}_verifyCode";
                object cacheobj      = cache.Get(verifyCodeKey);
                if (cacheobj == null)
                {
                    return(Json(new
                    {
                        success = false,
                        Message = "验证码已失效"
                    }, JsonRequestBehavior.AllowGet));
                }// 不区分大小写 比较
                else if (!(cacheobj.ToString().Equals(verifyCode, StringComparison.CurrentCultureIgnoreCase)))
                {
                    return(Json(new
                    {
                        success = false,
                        Message = "验证码错误"
                    }, JsonRequestBehavior.AllowGet));
                }
                cache.Remove(verifyCodeKey);
                User_infor userinfo = context.User_infor.FirstOrDefault(u => u.User_name == userName);

                if (userinfo == null)
                {
                    return(Json(new
                    {
                        success = false,
                        Message = "当前用户不存在",
                    }, JsonRequestBehavior.AllowGet));
                }
                if (MD5Encrypt.Encrypt(userPassword) != userinfo.User_pwd)
                {
                    return(Json(new
                    {
                        success = false,
                        Message = "密码错误",
                    }, JsonRequestBehavior.AllowGet));
                }

                //用session确认用户已经登录
                HttpContext.Session["CurentUser"] = userinfo;
                HttpContext.Session.Timeout       = 2;

                return(Json(new
                {
                    success = true,
                    Message = "登录成功",
                }, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 0成功 1用户不存在 2密码错误 3 验证码错误 4账号已冻结
        /// </summary>
        /// <param name="context"></param>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="verify"></param>
        /// <returns></returns>
        public static LoginResult UserLogin(this HttpContextBase context, string name = "", string pwd = "", string verify = "")
        {
            if (string.IsNullOrEmpty(verify) || context.Session["CheckCode"] == null || !context.Session["CheckCode"].ToString().Equals(verify, StringComparison.OrdinalIgnoreCase))
            {
                return(LoginResult.WrongVerify);
            }

            IUserMenuService service = DIFactory.GetContainer().Resolve <IUserMenuService>();
            User             user    = service.UserLogin(name);

            if (user == null)
            {
                return(LoginResult.NoUser);
            }
            else if (!user.Password.Equals(MD5Encrypt.Encrypt(pwd)))
            {
                return(LoginResult.WrongPwd);
            }
            else if (user.State == (int)UserState.Frozen)
            {
                return(LoginResult.Frozen);
            }
            else
            {
                #region Cookie
                CurrentUser currentUser = new CurrentUser()
                {
                    Id        = user.Id,
                    Name      = user.Name,
                    Account   = user.Account,
                    Email     = user.Email,
                    Password  = user.Password,
                    LoginTime = DateTime.Now
                };
                //HttpCookie cookie = context.Request.Cookies.Get("CurrentUser");
                //if (cookie == null)
                //{
                HttpCookie myCookie = new HttpCookie("CurrentUser");
                myCookie.Value   = JsonHelper.ObjectToString <CurrentUser>(currentUser);
                myCookie.Expires = DateTime.Now.AddMinutes(5);
                context.Response.Cookies.Add(myCookie);
                //}
                #endregion Cookie

                #region Session
                //context.Session.RemoveAll();
                var sessionUser = context.Session["CurrentUser"];

                context.Session["CurrentUser"] = currentUser;
                context.Session.Timeout        = 3;//minute  session过期等于Abandon
                #endregion Session
                logger.Debug(string.Format("用户id={0} Name={1}登录系统", currentUser.Id, currentUser.Name));
                service.LastLogin(user);
                return(LoginResult.Success);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 0成功 1用户不存在 2密码错误 3 验证码错误 4账号已冻结
        /// </summary>
        /// <param name="context"></param>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="verify"></param>
        /// <returns></returns>
        public static LoginResult UserLogin(this HttpContextBase context, string name = "", string pwd = "", string verify = "", IUserService UserService = null)
        {
            if (string.IsNullOrEmpty(verify) || context.Session["CheckCode"] == null || !context.Session["CheckCode"].ToString().Equals(verify, StringComparison.OrdinalIgnoreCase))
            {
                return(LoginResult.WrongVerify);
            }
            Base_User user = UserService.getUserInfoByUserName(name);

            if (user == null)
            {
                return(LoginResult.NoUser);
            }
            else if (!user.Password.Equals(MD5Encrypt.Encrypt(pwd)))
            {
                return(LoginResult.WrongPwd);
            }
            else if (user.State == (int)UserState.Frozen)
            {
                return(LoginResult.Frozen);
            }
            else
            {
                CurrentUser currentUser = new CurrentUser()
                {
                    Id          = user.Id,
                    Name        = user.UserName,
                    Account     = user.UserId,
                    PhoneNumber = user.PhoneNumber,
                    Password    = user.Password,
                    LoginTime   = DateTime.Now
                };
                #region 用户信息:Cookie、Session(可省略)

                #region Cookie
                HttpCookie myCookie = new HttpCookie("CurrentUser");
                myCookie.Value   = JsonHelper.ObjectToString <CurrentUser>(currentUser);
                myCookie.Expires = DateTime.Now.AddMinutes(5);
                context.Response.Cookies.Add(myCookie);
                #endregion Cookie

                #region Session
                //context.Session.RemoveAll();
                var sessionUser = context.Session["CurrentUser"];
                context.Session["CurrentUser"] = currentUser;
                context.Session.Timeout        = 3;//minute  session过期等于Abandon
                #endregion Session

                #endregion


                logger.Debug(string.Format("用户id={0} Name={1}登录系统", currentUser.Id, currentUser.Name));

                return(LoginResult.Success);
            }
        }
Ejemplo n.º 16
0
        public bool Add(Staff staff)
        {
            using (UnileverEntities entity = new UnileverEntities())
            {
                staff.Password = MD5Encrypt.Encrypt(staff.Password);
                entity.Staffs.Add(staff);
                entity.SaveChanges();

                return(true);
            }
        }
Ejemplo n.º 17
0
        public JsonResult Login(JObject data)
        {
            string   UserCode = data.Value <string>("username");
            string   Password = data.Value <string>("password");
            string   IP       = data.Value <string>("ip");
            string   City     = data.Value <string>("city");
            Sys_User user     = new Sys_User()
            {
                Code     = UserCode,
                Password = MD5Encrypt.Encrypt(Password, 64)
            };

            ISys_UserService bLL = DIFactory.GetService <ISys_UserService>();
            var loginResult      = bLL.Login(user);

            if (loginResult.Succeed && loginResult.ResultData != null)
            {
                //登录成功后,查询当前用户数据
                user = loginResult.ResultData as Sys_User;

                //调用框架中的登录机制
                var loginer = new BaseLoginer
                {
                    UserId   = 0,// user.UserId,
                    ID       = user.Id,
                    UserCode = user.Code,
                    Password = user.Password,
                    UserName = user.Name,
                    Data     = user,
                    IsAdmin  = user.Explain == "管理员用户" //根据用户Explain判断。用户类型:0=未定义 1=超级管理员 2=普通用户 3=其他
                };

                //读取配置登录默认失效时长:小时
                var effectiveHours = Convert.ToInt32(60 * ConfigUtil.GetConfigDecimal("LoginEffectiveHours"));


                //执行web登录
                FormsAuth.SignIn(loginer.ID.ToString(), loginer, effectiveHours);
                log.Info("登录成功!用户:" + loginer.UserName + ",账号:" + loginer.UserCode + ",密码:---");
                //设置服务基类中,当前登录用户信息
                // this.CurrentBaseLoginer = loginer;
                //登陆后处理
                //更新用户登陆次数及时间(存储过程登录,数据库已经处理)
                //添加登录日志
                string userinfo = string.Format("用户姓名:{0},用户编号:{1},登录账号:{2},登录密码:{3}",
                                                loginer.UserName, loginer.UserCode, loginer.UserCode, "---" /*loginer.Password*/);
                //更新其它业务
            }
            else
            {
                log.Info("登录失败!账号:" + UserCode + ",密码:" + Password + "。原因:" + loginResult.ResultMsg);
            }
            return(Json(loginResult, JsonRequestBehavior.DenyGet));
        }
Ejemplo n.º 18
0
        public AuNguoiDungVm.Dto CreateNewUser(AuNguoiDungVm.ModelRegister model)
        {
            var entity = Mapper.Map <AuNguoiDungVm.ModelRegister, AU_NGUOIDUNG>(model);

            entity.Password = MD5Encrypt.Encrypt(entity.Password);
            entity.Id       = Guid.NewGuid().ToString();
            Repository.Insert(entity);
            var result = Mapper.Map <AU_NGUOIDUNG, AuNguoiDungVm.Dto>(entity);

            return(result);
        }
Ejemplo n.º 19
0
        public int UserResetPwd(UserVM form)
        {
            Sys_User model = this._userRepository.Entity(ContextDB.managerDBContext, t => t.Id == form.Id);

            if (model != null)
            {
                model.Password = MD5Encrypt.Encrypt("123456");
            }

            return(this._userRepository.Update(ContextDB.managerDBContext, model));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 密码修改
        /// </summary>
        /// <returns></returns>
        private string AlterPwd()
        {
            string before = Request.Form.Get("pwd_before");
            string news   = Request.Form.Get("pwd_news");
            string newsto = Request.Form.Get("pwd_newsTo");

            //验证旧密码
            if (before == null || string.IsNullOrEmpty(before))
            {
                return(ReturnString.JsonToString(Prompt.error, "旧密码不能为空", "pwd_before"));
            }
            if (!Regex.IsMatch(before, @"^(\w){6,20}$"))
            {
                return(ReturnString.JsonToString(Prompt.error, "旧密码输入不正确", "pwd_before"));
            }
            //验证新密码
            if (news == null || string.IsNullOrEmpty(news))
            {
                return(ReturnString.JsonToString(Prompt.error, "新密码不能为空", "pwd_news"));
            }
            if (!Regex.IsMatch(news, @"^(\w){6,20}$"))
            {
                return(ReturnString.JsonToString(Prompt.error, "新密码输入不正确", "pwd_news"));
            }
            //验证新密码与旧密码相同
            if (!news.Equals(newsto))
            {
                return(ReturnString.JsonToString(Prompt.error, "新密码与确认密码不一致!", "pwd_newsTo"));
            }
            //判断新密码与旧密码是否相同
            if (before.Equals(news))
            {
                return(ReturnString.JsonToString(Prompt.error, "旧密码与新密码相同无须修改!", "pwd_news"));
            }

            EDRS.BLL.XT_ZZJG_RYBM bll = new EDRS.BLL.XT_ZZJG_RYBM(this.Request);
            string msg = string.Empty;
            List <EDRS.Model.XT_QX_JSBM> jsbmList;

            EDRS.Model.XT_ZZJG_RYBM rybm = bll.UserLogin(UserInfo.DWBM, UserInfo.DLBM, before, out jsbmList, out msg);
            if (rybm != null)
            {
                rybm.KL = MD5Encrypt.Encrypt(news).ToLower();
                if (bll.Update(rybm))
                {
                    return(ReturnString.JsonToString(Prompt.win, "密码修改成功,重新登录生效!", null));
                }
                return(ReturnString.JsonToString(Prompt.error, "密码修改失败!", null));
            }
            else
            {
                return(ReturnString.JsonToString(Prompt.error, msg, null));
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 注册用户信息
        /// </summary>
        /// <returns></returns>
        public static bool Register(IUserRepository userRepository, string userName, string email, string password, string nickName, string Tel)
        {
            Users user = new Users();

            user.AddTime  = DateTime.Now;
            user.Email    = email;
            user.NickName = nickName;
            user.Password = MD5Encrypt.Encrypt(password);
            user.Tel      = Tel;
            user.UserName = userName;
            return(userRepository.Set(user));
        }
Ejemplo n.º 22
0
        public string Login(string userName, string pwd, string validateCode, ref t_user userModel)
        {
            userModel = new t_user();
            try
            {
                //判断用户信息
                userModel = APIServer.DataAccess.DBPlatform.Data.UserData.Get(userName);
                string loginResult = "0";  //初始状态
                if (userModel == null)
                {
                    loginResult = "1";
                    return("用户不存在,请注册后再登陆!");
                }
                if (!userModel.status.ToString().Equals("1"))
                {
                    loginResult = "3";
                    return("用户状态异常,请联系管理员!");
                }

                if (userModel.wrongCounts >= 5 && userModel.lastLoginTime.Value.Equals(DateTime.Now.Date))
                {
                    //当天错误次数已经超过了5次
                    loginResult = "5";
                    return("当天密码错误次数已经超过5次,请明天再登陆!");
                }

                if (!MD5Encrypt.Encrypt(pwd).Equals(userModel.passWord))
                {
                    //登陆密码错误
                    loginResult            = "2";
                    userModel.wrongCounts += 1;
                    LoginingWrite(userModel);
                    return("密码输入错误,请重新输入!");
                }

                userModel.lastLoginTime = DateTime.Now;
                string result = LoginingWrite(userModel);

                if (result.Length < 1)
                {
                    loginResult = "10";
                }
                else
                {
                    result = "FAIL";
                }
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 23
0
        public async Task <Employees> LoginAsync(LoginDto loginDto)
        {
            var encryptPassword = MD5Encrypt.Encrypt(loginDto.Password);

            //md5 加密密码 与数据库密码进行比对

            var emp = await context.Set <Employees>().FirstOrDefaultAsync(
                x => x.Email == loginDto.Email && x.Password == encryptPassword &&
                x.IsDel == 0
                );

            return(emp);
        }
Ejemplo n.º 24
0
        public bool Login(String username, String password)
        {
            using (UnileverEntities entity = new UnileverEntities())
            {
                String encryptedPwd = MD5Encrypt.Encrypt(password);
                if (entity.Staffs.Where(c => c.Username.Equals(username) && c.Password.Equals(encryptedPwd)).Any())
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 25
0
        public ActionResult CheckLogin(string userName, string pwd, string code)
        {
            if (!string.IsNullOrEmpty(Session["VerifyCode"].ToString()) || code != Session["VerifyCode"].ToString())
            {
                throw new AlertException("验证码错误,请重新输入");
            }

            // 登录账号验证


            FormsAuthentication.SetAuthCookie("UserId", true);

            // 网页cookie验证
            var userCookies = Request.Cookies[FormsAuthentication.FormsCookieName];

            if (userCookies != null)
            {
                var lastAuthValue = FormsAuthentication.Decrypt(userCookies.Value);
                if (lastAuthValue != null)
                {
                    //重新创建票据信息将加密后的密码传入新cookies中
                    var authValue = new FormsAuthenticationTicket(
                        lastAuthValue.Version,
                        lastAuthValue.Name,
                        lastAuthValue.IssueDate,
                        lastAuthValue.Expiration,
                        lastAuthValue.IsPersistent,
                        MD5Encrypt.Encrypt(pwd + MD5Encrypt.appKey),
                        lastAuthValue.CookiePath);

                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                                                FormsAuthentication.Encrypt(authValue))
                    {
                        HttpOnly = true,
                        Path     = userCookies.Path,
                        Secure   = userCookies.Secure
                    };
                    if (userCookies.Domain != null)
                    {
                        cookie.Domain = userCookies.Domain;
                    }
                    if (authValue.IsPersistent)
                    {
                        cookie.Expires = authValue.Expiration;
                    }
                    HttpContext.Response.Cookies.Add(cookie);
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 26
0
        public int UpdatePwd(string oldPassword, string password, int userId)
        {
            Sys_User user = this._userRepository.Entity(ContextDB.managerDBContext, m => m.Id == userId);

            if (user.Password != MD5Encrypt.Encrypt(oldPassword))
            {
                throw new BaseException(SuperConstants.AJAX_RETURN_STATE_ERROR, "原始密码错误");
            }
            else
            {
                user.Password = MD5Encrypt.Encrypt(oldPassword);
                return(this._userRepository.Update(ContextDB.managerDBContext, user));
            }
        }
Ejemplo n.º 27
0
        public AuNguoiDungVm.CurrentUser Login(AuNguoiDungVm.ModelLogin model)
        {
            AuNguoiDungVm.CurrentUser result = null;
            var user = Repository.DbSet.FirstOrDefault(x => x.Username == model.Username);

            if (user != null)
            {
                if (user.Password == MD5Encrypt.Encrypt(model.Password))
                {
                    result = Mapper.Map <AU_NGUOIDUNG, AuNguoiDungVm.CurrentUser>(user);
                }
            }
            return(result);
        }
Ejemplo n.º 28
0
        public NguoiDungViewModel.Dto Login(NguoiDungViewModel.Dto model)
        {
            NguoiDungViewModel.Dto result = null;
            var user = Repository.DbSet.FirstOrDefault(x => x.USERNAME == model.USERNAME);

            if (user != null)
            {
                if (user.PASSWORD == MD5Encrypt.Encrypt(model.PASSWORD))
                {
                    result = Mapper.Map <NGUOIDUNG, NguoiDungViewModel.Dto>(user);
                }
            }
            return(result);
        }
Ejemplo n.º 29
0
        //[Authorize]
        public ActionResult <ReplyModel> PubArticle([FromBody] PubArticleModel msg)
        {
            ReplyModel reply = new ReplyModel();

            try
            {
                Users users = _userRepository.Get(msg.UserId);
                if (users != null)
                {
                    Article article = new Article();
                    article.UserId       = msg.UserId;
                    article.NickName     = users.NickName;
                    article.Title        = msg.Title;
                    article.IsDraft      = msg.IsDraft;
                    article.Content      = msg.Content;
                    article.Summary      = msg.Summary;
                    article.Img          = msg.Img;
                    article.Config       = msg.AdvancedOptions;
                    article.EntryName    = msg.EntryName;
                    article.CategoryId   = msg.TagId;
                    article.CategoryName = msg.TagName;
                    article.ReadCount    = 0;
                    article.Password     = MD5Encrypt.Encrypt(msg.Password);
                    article.PubTime      = DateTime.Now;
                    article.AddTime      = DateTime.Now;
                    _articleRepository.Set(article);
                    bool result = ServiceProvider.GetService <IUnitOfWork>().Commit();
                    if (result)
                    {
                        reply.Status = "002";
                        reply.Msg    = "保存文章成功";
                    }
                    else
                    {
                        reply.Msg = "保存文章失败";
                    }
                }
                else
                {
                    reply.Msg = "未找到用户信息";
                }
            }
            catch (Exception ex)
            {
                reply.Msg = "文章发布或保存草稿失败,请重试";
                // _Logger.LogError($"文章发布或保存草稿失败,请重试{JsonConvert.SerializeObject(ex)}");
            }
            return(reply);
        }
Ejemplo n.º 30
0
        public static LoginResult UserLogin(this HttpContextBase context, string name = "", string pwd = "", string verify = "")
        {
            if (string.IsNullOrEmpty(verify) || context.Session["VerfyCode"] == null || !context.Session["VerfyCode"].ToString().Equals(verify, StringComparison.OrdinalIgnoreCase))
            {
                return(LoginResult.WrongVerify);
            }

            IUserMenuService service = DIFactory.GetContainer().Resolve <IUserMenuService>();
            User             user    = service.UserLogin(name);

            if (user == null)
            {
                return(LoginResult.NoUser);
            }
            else if (!user.Password.Equals(MD5Encrypt.Encrypt(pwd)))
            {
                return(LoginResult.WrongPwd);
            }
            else if (user.State == (int)UserState.Frozen)
            {
                return(LoginResult.Frozen);
            }
            else
            {
                CurrentUser currentUser = new CurrentUser
                {
                    Id        = user.Id,
                    Name      = user.Name,
                    Account   = user.Account,
                    Email     = user.Email,
                    Password  = user.Password,
                    LoginTime = DateTime.Now
                };
                #region cookie
                HttpCookie userCookie = new HttpCookie("CurrentUser");
                userCookie.Value   = JsonHelper.ObjectToString <CurrentUser>(currentUser);
                userCookie.Expires = DateTime.Now.AddMinutes(5);
                context.Response.Cookies.Add(userCookie);
                #endregion
                #region session
                context.Session["CurrentUser"] = currentUser;
                context.Session.Timeout        = 3;//minute  session过期等于Abandon
                #endregion
                service.UserLastLogin(user);
                return(LoginResult.Success);
            }
        }