/// <summary>
 /// 登录
 /// </summary>
 /// <param name="isReamber">是否记住</param>
 /// <param name="uname">用户名</param>
 /// <param name="pwd">密码</param>
 protected void login(string isReamber, string uname, string pwd)
 {
     bool isexist = new yonghuDAL().ExistsUserName(uname);
     if (isexist == true)
     {
         yonghuModel yhm = new yonghuDAL().GetModelByUsername(uname);
         string pwd2 = new MD5Encrypt().GetMD5(pwd + uname);
         if (pwd2 == yhm.nvc_pwd)
         {
             string[,] array = new string[5, 2];
             array[0, 0] = "username";
             array[0, 1] = yhm.nvc_username;
             array[1, 0] = "userpwd";
             array[1, 1] = pwd;
             array[2, 0] = "isAutoLogin";
             array[2, 1] = isReamber;
             array[3, 0] = "uright";
             array[3, 1] = yhm.int_right.ToString();
             array[4, 0] = "uid";
             array[4, 1] = new MD5Encrypt().GetMD5(uname + yhm.nc_uid);
             new SetCookie().CreateCookie("ISAccountCookie", 0, 8, 0, 0, array);
             new SetCookie().CreateCookie("ISReamberAccountCookie", 5, 0, 0, 0, array);
             Response.Redirect(domain + "/default.aspx");
         }
         else
         {
             loginErrorMsg = "密码错误。";
             loginUname = uname;
             loginUpwdStyle = "loginError";
             loginFocus = "userpwd";
         }
     }
     else
     {
         loginErrorMsg = "用户名不存在。";
         loginUnameStyle = "loginError";
         loginFocus = "username";
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Aim.Portal.Web.WebPortalService.CheckLogon();
            }
            catch
            {
                Response.Write("<script> window.location.href = '/Login.aspx';</script>");
                Response.End();
            }
            string action = Request["action"];

            UserId = Request["UserId"];
            MD5Encrypt encrypt = new MD5Encrypt();

            switch (action)
            {
            case "loadgroupdata":
                string Id = Request["id"];
                sql = "select GroupID,replace(Name,'江西瑞林建设监理有限公司','') as Name from SysGroup where ParentId='" + Id + "' order by Code asc";
                IList <EasyDictionary> dics = DataHelper.QueryDictList(sql);
                string result = "[";
                int    i      = 0;
                foreach (EasyDictionary dic_temp in dics)
                {
                    if (i != dics.Count - 1)
                    {
                        result += "{id:'" + dic_temp.Get <string>("GroupID") + "',text:'" + dic_temp.Get <string>("Name") + "',leaf:true},";
                    }
                    else
                    {
                        result += "{id:'" + dic_temp.Get <string>("GroupID") + "',text:'" + dic_temp.Get <string>("Name") + "',leaf:true}";
                    }
                    i++;
                }
                result += "]";
                Response.Write(result);
                Response.End();
                break;

            case "Create":
                obj = Request["json"];
                ent = JsonHelper.GetObject <SysUser>(obj);

                ent.Server_Seed = (ent.Server_Seed.IndexOf("江西瑞林建设监理有限公司") < 0 ? "江西瑞林建设监理有限公司" : "") + ent.Server_Seed;
                ent.LoginName   = ent.IDNumber;
                ent.Password    = encrypt.GetMD5FromString(ent.LoginName);
                ent.DoCreate();
                Response.Write("{success:true}");
                Response.End();
                break;

            case "Update":
                obj = Request["json"];
                ent = JsonHelper.GetObject <SysUser>(obj);
                SysUser        ori_Ent = SysUser.Find(ent.UserID);
                EasyDictionary dic     = JsonHelper.GetObject <EasyDictionary>(obj);
                ent             = DataHelper.MergeData <SysUser>(ori_Ent, ent, dic.Keys);
                ent.Password    = encrypt.GetMD5FromString(ent.LoginName);
                ent.Server_Seed = (ent.Server_Seed.IndexOf("江西瑞林建设监理有限公司") < 0 ? "江西瑞林建设监理有限公司" : "") + ent.Server_Seed;
                ent.DoUpdate();
                Response.Write("{success:true}");
                Response.End();
                break;

            case "SelectEdit":
                SelectEdit();
                break;

            case "check":
                Check();
                break;
            }
        }
Ejemplo n.º 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Aim.Portal.Web.WebPortalService.CheckLogon();
            }
            catch
            {
                Response.Write("<script> window.parent.location.href = '/Login.aspx';</script>");
                Response.End();
            }
            string          action = Request["action"];
            SysGroup        sgEnt  = null;
            SysUser         suEnt  = null;
            IList <SysUser> suEnts = null;
            string          sql    = "";
            DataTable       dt     = null;

            string where = "";
            MD5Encrypt encrypt = new MD5Encrypt();

            switch (action)
            {
            case "sync":
                string           connstr = ConfigurationManager.ConnectionStrings["NimsConn"].ToString();
                OracleConnection conn    = new OracleConnection(connstr);
                sql = "select * from apps.cux_hr_org_structrue_v where ORG_ID_CHILD='228' or org_id_parent='228'";
                OracleCommand     com = new OracleCommand(sql, conn);
                OracleDataAdapter da  = new OracleDataAdapter(com);
                DataSet           ds  = new DataSet();
                da.Fill(ds);
                //首先同步部门信息
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    sgEnt = SysGroup.TryFind(dr["ORG_ID_CHILD"] + "");
                    if (sgEnt == null)    //如果不存在该部门
                    {
                        //此处将PATH字段用来存储父部门的名称
                        sql = "insert into SysGroup (GroupID,Name,Code,ParentID,Path,Status) values('{0}','{1}','{2}','{3}','{4}',1)";
                        sql = string.Format(sql, dr["ORG_ID_CHILD"], dr["ORG_NAME_CHILD"], dr["ORG_CODE_CHILD"], dr["ORG_ID_PARENT"], dr["ORG_NAME_PARENT"]);
                        DataHelper.ExecSql(sql);
                    }
                    else
                    {
                        sql = "update SysGroup set Name='{0}',Code='{1}',ParentID='{2}',Path='{3}' where GroupID='{4}'";
                        sql = string.Format(sql, dr["ORG_NAME_CHILD"], dr["ORG_CODE_CHILD"], dr["ORG_ID_PARENT"], dr["ORG_NAME_PARENT"], dr["ORG_ID_CHILD"]);
                        DataHelper.ExecSql(sql);
                    }
                }
                //同步人员信息
                sql = @"select * from apps.cux_hr_employee_v where ORG_ID in 
                    (select ORG_ID_CHILD from apps.cux_hr_org_structrue_v where ORG_ID_CHILD='228' or org_id_parent='228') and primary_flag='Y'";
                com = new OracleCommand(sql, conn);
                da  = new OracleDataAdapter(com);
                ds  = new DataSet();
                da.Fill(ds);
                SqlConnection conn_sql = new SqlConnection();
                conn_sql.ConnectionString = ConfigurationManager.AppSettings["Con_Portal"];
                conn_sql.Open();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    suEnts = SysUser.FindAllByProperty(SysUser.Prop_IDNumber, dr["NATIONAL_IDENTIFIER"]);    //通过身份证就行匹配
                    if (suEnts.Count == 0)
                    {
                        sql = @"insert into SysUser (UserID,LoginName,Name,Password,Email,Phone,HomePhone,Sex,IDNumber,Server_IAGUID,Server_Seed,Status,CreateDate)
                            values(@UserID,@LoginName,@Name,@Password,@Email,@Phone,@HomePhone,@Sex,@IDNumber,@Server_IAGUID,@Server_Seed,@Status,@CreateDate)";
                        SqlParameter[] sparray = new SqlParameter[13];
                        sparray[0]        = new SqlParameter("@UserID", dr["PERSON_ID"]);
                        sparray[1]        = new SqlParameter("@LoginName", dr["EMP_NUM"]);//NIMS数据库工号是不能为空的 即进入的NIMS系统的员工工号是肯定有的
                        sparray[2]        = new SqlParameter("@Name", dr["LAST_NAME"]);
                        sparray[3]        = new SqlParameter("@Password", encrypt.GetMD5FromString(dr["SYS_ACCOUNT"].ToString()));
                        sparray[4]        = new SqlParameter("@Email", dr["EMAIL_ADDRESS"]);
                        sparray[5]        = new SqlParameter("@Phone", dr["MOBILE_PHONE_NUMBER"]);
                        sparray[6]        = new SqlParameter("@HomePhone", dr["OFFICE_PHONE_NUMBER"]);
                        sparray[7]        = new SqlParameter("@Sex", dr["SEX"]);
                        sparray[8]        = new SqlParameter("@IDNumber", dr["NATIONAL_IDENTIFIER"]);
                        sparray[9]        = new SqlParameter("@Server_IAGUID", dr["ORG_ID"]);
                        sparray[10]       = new SqlParameter("@Server_Seed", dr["ORG_NAME"]);
                        sparray[11]       = new SqlParameter("@Status", SqlDbType.TinyInt);
                        sparray[11].Value = 1;
                        sparray[12]       = new SqlParameter("@CreateDate", dr["HIRE_DATE"]);
                        SqlCommand com_sql = new SqlCommand(sql, conn_sql);
                        com_sql.Parameters.AddRange(sparray);
                        com_sql.ExecuteNonQuery();
                    }
                    else
                    {
                        sql = @"update SysUser set LoginName=@LoginName,Name=@Name,Email=@Email,Phone=@Phone,HomePhone=@HomePhone,
                            Sex=@Sex,Server_IAGUID=@Server_IAGUID,Server_Seed=@Server_Seed,CreateDate=@CreateDate where IDNumber=@IDNumber";
                        SqlParameter[] sparray = new SqlParameter[10];
                        sparray[0] = new SqlParameter("@LoginName", dr["EMP_NUM"]);
                        sparray[1] = new SqlParameter("@Name", dr["LAST_NAME"]);
                        sparray[2] = new SqlParameter("@Email", dr["EMAIL_ADDRESS"]);
                        sparray[3] = new SqlParameter("@Phone", dr["MOBILE_PHONE_NUMBER"]);
                        sparray[4] = new SqlParameter("@HomePhone", dr["OFFICE_PHONE_NUMBER"]);
                        sparray[5] = new SqlParameter("@Sex", dr["SEX"]);
                        sparray[6] = new SqlParameter("@Server_IAGUID", dr["ORG_ID"]);
                        sparray[7] = new SqlParameter("@Server_Seed", dr["ORG_NAME"]);
                        sparray[8] = new SqlParameter("@CreateDate", dr["HIRE_DATE"]);
                        sparray[9] = new SqlParameter("@IDNumber", dr["NATIONAL_IDENTIFIER"]);
                        SqlCommand com_sql = new SqlCommand(sql, conn_sql);
                        com_sql.Parameters.AddRange(sparray);
                        com_sql.ExecuteNonQuery();
                    }
                }
                conn_sql.Close();
                Response.Write("{success:true}");
                Response.End();
                break;

            case "inipsd":
                suEnt          = SysUser.Find(Request["UserId"]);
                suEnt.Password = encrypt.GetMD5FromString(suEnt.LoginName);
                suEnt.DoUpdate();
                Response.Write("{success:true}");
                Response.End();
                break;

            case "loadtreedata":
                string id = Request["id"];
                sql = "select GroupID as id,replace(Name,'江西瑞林建设监理有限公司','') as name,1 as leaf from SysGroup where ParentId='" + id + "' order by Code asc";
                dt  = DataHelper.QueryDataTable(sql);
                Response.Write(JsonHelper.GetJsonStringFromDataTable(dt));
                Response.End();
                break;

            case "loaduser":
                string groupid = Request["groupid"];
                if (!string.IsNullOrEmpty(Request["name_workno"]))
                {
                    where += " and (LoginName like '%" + Request["name_workno"] + "%' or Name like '%" + Request["name_workno"] + "%')";
                }
                if (!string.IsNullOrEmpty(Request["UserType"]))
                {
                    where += "  and UserType='" + Request["UserType"] + "'";
                }
                if (!string.IsNullOrEmpty(Request["Status"]))
                {
                    where += "  and Status='" + Request["Status"] + "'";
                }
                if (string.IsNullOrEmpty(groupid) || groupid == "228")
                {
                    sql = @"select UserID as UserId,Name,LoginName,Sex,Phone,Replace(Server_Seed,'江西瑞林建设监理有限公司','') as  Server_Seed,
                        HomePhone,IDNumber,CreateDate from SysUser where 
                        (Server_Seed like '%江西瑞林建设监理有限公司%' ) " + where;
                }
                else
                {
                    sql = @"select UserID as UserId,Name,LoginName,Sex,Phone,Replace(Server_Seed,'江西瑞林建设监理有限公司','') as  Server_Seed,
                        HomePhone,IDNumber,CreateDate from SysUser
                        where Server_Seed like '%江西瑞林建设监理有限公司%' and Server_IAGUID='" + groupid + "'" + where;
                }
                dt = DataHelper.QueryDataTable(sql);
                Response.Write("{'rows':" + JsonHelper.GetJsonStringFromDataTable(dt) + ",total:'" + totalProperty + "'}");
                Response.End();
                break;
            }
        }
        /// <summary>
        ///         /// 查看激活码信息
        /// </summary>
        /// <param name="serverIP"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public static ArrayList ActiveCode_Query(string account, int actionType, ref string strDesc)
        {
            string      getUser   = null;
            string      sign      = null;
            string      parameter = "";
            XmlDocument xmlfile   = new XmlDocument();

            getUser   = account;
            parameter = account;
            MD5Encrypt md5 = new MD5Encrypt();

            sign = md5.getMD5ofStr(parameter + "|T4pb5A.QueryGdCode").ToLower();
            try
            {
                System.Data.DataSet ds = SqlHelper.ExecuteDataset("select ServerIP from gmtools_serverInfo where gameid=10");
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    string         serverIP = ds.Tables[0].Rows[0].ItemArray[0].ToString();
                    string         url      = "http://" + serverIP + "/PayCenter/QueryGdCode.php";
                    HttpWebRequest request  = (HttpWebRequest)
                                              WebRequest.Create(url);
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.KeepAlive   = false;
                    request.Method      = "POST";
                    //参数POST到商城的接口
                    Stream        writer    = request.GetRequestStream();
                    string        postData  = "getcode=" + account + "&sign=" + sign + "&encoding=UTF-8";
                    ASCIIEncoding encoder   = new ASCIIEncoding();
                    byte[]        ByteArray = encoder.GetBytes(postData);
                    writer.Write(ByteArray, 0, postData.Length);
                    writer.Close();
                    //得到商城接口的回应
                    WebResponse
                                 resp = request.GetResponse();
                    StreamReader sr   = new System.IO.StreamReader(resp.GetResponseStream());
                    //Console.WriteLine(sr.ReadToEnd().Trim());
                    xmlfile.Load(sr);
                    XmlNode descNodes = xmlfile.SelectSingleNode("you9/status");
                    strDesc = descNodes.InnerText;
                    if (strDesc != null && strDesc.Equals("RESULT_0"))
                    {
                        strDesc = "查询成功";
                    }
                    else if (strDesc != null && strDesc.Equals("RESULT_3"))
                    {
                        strDesc = "无此激活码";
                    }
                    else if (strDesc != null && strDesc.Equals("RESULT_2"))
                    {
                        strDesc = "查询密钥错误";
                    }
                    else
                    {
                        strDesc = "异常";
                    }
                    XmlNode nodes = xmlfile.SelectSingleNode("you9/user");
                    System.Collections.ArrayList colList = new System.Collections.ArrayList();
                    foreach (XmlNode xmlnodes in nodes.ChildNodes)
                    {
                        colList.Add(xmlnodes.InnerText);
                    }
                    sr.Close();
                    return(colList);
                }
            }
            catch (SqlException ex)
            {
                SqlHelper.errLog.WriteLog("服务器IP" + account + ex.Message);
                strDesc = "异常";
            }
            return(null);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        public static bool InitDB(IServiceProvider service)
        {
            using (var serviceScope = service.CreateScope())
            {
                var context   = serviceScope.ServiceProvider.GetService <ZhouLiContext>();
                var userAdmin = context.SysUser.Where(t => t.UserName.Equals("zhouli")).SingleOrDefault();
                if (userAdmin == null)
                {
                    using (var tran = context.Database.BeginTransaction())
                    {
                        try
                        {
                            #region 初始化字典表
                            //初始化字典表---------------------------------------------------------开始
                            //添加权限类型
                            context.DictAuthorityType.AddRange(new DictAuthorityType
                            {
                                AuthorityTypeName = "菜单权限",
                                AuthorityTypeId   = Guid.NewGuid().ToString()
                            });

                            //初始化字典表---------------------------------------------------------结束
                            #endregion
                            #region 初始化权限管理数据
                            #region 添加用户
                            //初始化用户(添加超级管理员:zhouli)
                            var entityUser = context.SysUser.Add(new SysUser
                            {
                                UserAvatar   = "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1952694735,1793739098&fm=27&gp=0.jpg",
                                UserName     = "******",
                                UserPwd      = MD5Encrypt.Get32MD5One("123456"),
                                UserEmail    = "*****@*****.**",
                                UserPhone    = "17783042962",
                                UserQq       = "1021907330",
                                UserWx       = "17783042962",
                                UserNikeName = "感谢有梦",
                                CreateTime   = DateTime.Now,
                                CreateUserId = Guid.Empty.ToString(),
                                Note         = "系统初始化自动添加的",
                                UserId       = Guid.NewGuid().ToString()
                            });

                            //这里不对超级管理员做任何授权,因为超级管理没有任何限制
                            ////添加角色
                            //var entityRole = context.SysRole.Add(new SysRole
                            //{
                            //    RoleName = "超级管理员",
                            //    Note = "系统初始化自动添加的"
                            //});
                            ////添加用户角色关联表
                            //context.SysUrRelated.Add(new SysUrRelated
                            //{
                            //    UserId = entityUser.Entity.UserId,
                            //    RoleId = entityRole.Entity.RoleId
                            //});
                            ////添加用户组
                            //var entityUserGroup = context.SysUserGroup.Add(new SysUserGroup
                            //{
                            //    UserGroupName = "超级管理员组",
                            //    Note = "系统初始化自动添加的"

                            //});
                            ////添加用户组与用户关联表
                            //context.SysUuRelated.Add(new SysUuRelated
                            //{
                            //    UserId = entityUser.Entity.UserId,
                            //    UserGroupId = entityUserGroup.Entity.UserGroupId
                            //});
                            ////添加角色与用户组关联表
                            //context.SysUgrRelated.Add(new SysUgrRelated
                            //{
                            //    UserGroupId = entityUserGroup.Entity.UserGroupId,
                            //    RoleId = entityRole.Entity.RoleId
                            //});
                            //添加菜单,权限,权限菜单关联表(因为权限表与权限菜单关联表、权限菜单关联表与菜单表都是一对一的关系,也就是每添加一个菜单,就得同时往这三个表中各插入一条记录)
                            #endregion
                            #region 添加系统菜单
                            //----------------------------系统管理菜单begin
                            var entityMenu = context.SysMenu.Add(new SysMenu
                            {
                                MenuName     = "系统管理",
                                MenuSort     = 1,
                                MenuIcon     = "layui-icon-set",
                                CreateTime   = DateTime.Now,
                                CreateUserId = Guid.Empty.ToString(),
                                ParentMenuId = Guid.Empty.ToString(),
                                MenuId       = Guid.NewGuid().ToString()
                            });
                            var entityAuthority = context.SysAuthority.Add(new SysAuthority
                            {
                                AuthorityType = 1,
                                CreateTime    = DateTime.Now,
                                CreateUserId  = Guid.Empty.ToString(),
                                AuthorityId   = Guid.NewGuid().ToString()
                            });
                            context.SysAmRelated.Add(new SysAmRelated
                            {
                                AmRelatedId = Guid.NewGuid().ToString(),
                                MenuId      = entityMenu.Entity.MenuId,
                                AuthorityId = entityAuthority.Entity.AuthorityId
                            });
                            //----------------------------系统管理菜单end
                            //----------------------------菜单管理菜单begin
                            var entityMenu2 = context.SysMenu.Add(new SysMenu
                            {
                                MenuName     = "菜单管理",
                                MenuUrl      = "/System/Menu/Index",
                                MenuIcon     = "layui-icon-align-left",
                                ParentMenuId = entityMenu.Entity.MenuId,
                                CreateTime   = DateTime.Now,
                                CreateUserId = Guid.Empty.ToString(),
                                MenuId       = Guid.NewGuid().ToString()
                            });
                            var entityAuthority2 = context.SysAuthority.Add(new SysAuthority
                            {
                                AuthorityType = 1,
                                CreateTime    = DateTime.Now,
                                CreateUserId  = Guid.Empty.ToString(),
                                AuthorityId   = Guid.NewGuid().ToString()
                            });
                            context.SysAmRelated.Add(new SysAmRelated
                            {
                                AmRelatedId = Guid.NewGuid().ToString(),
                                MenuId      = entityMenu2.Entity.MenuId,
                                AuthorityId = entityAuthority2.Entity.AuthorityId
                            });
                            //----------------------------菜单管理菜单end
                            //----------------------------角色管理菜单begin
                            var entityMenu3 = context.SysMenu.Add(new SysMenu
                            {
                                MenuName     = "角色管理",
                                MenuUrl      = "/System/Role/Index",
                                ParentMenuId = entityMenu.Entity.MenuId,
                                MenuIcon     = "layui-icon-prev-circle",
                                CreateTime   = DateTime.Now,
                                CreateUserId = Guid.Empty.ToString(),
                                MenuId       = Guid.NewGuid().ToString()
                            });
                            var entityAuthority3 = context.SysAuthority.Add(new SysAuthority
                            {
                                AuthorityType = 1,
                                CreateTime    = DateTime.Now,
                                CreateUserId  = Guid.Empty.ToString(),
                                AuthorityId   = Guid.NewGuid().ToString()
                            });
                            context.SysAmRelated.Add(new SysAmRelated
                            {
                                AmRelatedId = Guid.NewGuid().ToString(),
                                MenuId      = entityMenu3.Entity.MenuId,
                                AuthorityId = entityAuthority3.Entity.AuthorityId
                            });
                            //----------------------------角色管理菜单end
                            //----------------------------用户管理菜单begin
                            var entityMenu4 = context.SysMenu.Add(new SysMenu
                            {
                                MenuName     = "用户管理",
                                MenuUrl      = "/System/User/Index",
                                MenuIcon     = "layui-icon-username",
                                ParentMenuId = entityMenu.Entity.MenuId,
                                CreateTime   = DateTime.Now,
                                CreateUserId = Guid.Empty.ToString(),
                                MenuId       = Guid.NewGuid().ToString()
                            });
                            var entityAuthority4 = context.SysAuthority.Add(new SysAuthority
                            {
                                AuthorityType = 1,
                                CreateTime    = DateTime.Now,
                                CreateUserId  = Guid.Empty.ToString(),
                                AuthorityId   = Guid.NewGuid().ToString()
                            });
                            context.SysAmRelated.Add(new SysAmRelated
                            {
                                AmRelatedId = Guid.NewGuid().ToString(),
                                MenuId      = entityMenu4.Entity.MenuId,
                                AuthorityId = entityAuthority4.Entity.AuthorityId
                            });
                            //----------------------------用户管理菜单end
                            //----------------------------用户组菜单begin
                            var entityMenu5 = context.SysMenu.Add(new SysMenu
                            {
                                MenuName     = "用户组管理",
                                MenuUrl      = "/System/UserGroup/Index",
                                MenuIcon     = "layui-icon-user",
                                ParentMenuId = entityMenu.Entity.MenuId,
                                CreateUserId = Guid.Empty.ToString(),
                                CreateTime   = DateTime.Now,
                                MenuId       = Guid.NewGuid().ToString()
                            });
                            var entityAuthority5 = context.SysAuthority.Add(new SysAuthority
                            {
                                AuthorityType = 1,
                                CreateTime    = DateTime.Now,
                                AuthorityId   = Guid.NewGuid().ToString()
                            });
                            context.SysAmRelated.Add(new SysAmRelated
                            {
                                AmRelatedId = Guid.NewGuid().ToString(),
                                MenuId      = entityMenu5.Entity.MenuId,
                                AuthorityId = entityAuthority5.Entity.AuthorityId
                            });
                            //----------------------------用户组菜单end
                            #endregion
                            #endregion
                            #region 初始化博客管理
                            //----------------------------博客管理菜单begin
                            var entityBlog = context.SysMenu.Add(new SysMenu
                            {
                                MenuName     = "博客管理",
                                MenuSort     = 1,
                                MenuIcon     = "layui-icon-templeate-1",
                                CreateTime   = DateTime.Now,
                                CreateUserId = Guid.Empty.ToString(),
                                ParentMenuId = Guid.Empty.ToString(),
                                MenuId       = Guid.NewGuid().ToString()
                            });
                            var entityBlogAuthority = context.SysAuthority.Add(new SysAuthority
                            {
                                AuthorityType = 1,
                                CreateTime    = DateTime.Now,
                                CreateUserId  = Guid.Empty.ToString(),
                                AuthorityId   = Guid.NewGuid().ToString()
                            });
                            context.SysAmRelated.Add(new SysAmRelated
                            {
                                AmRelatedId = Guid.NewGuid().ToString(),
                                MenuId      = entityBlog.Entity.MenuId,
                                AuthorityId = entityBlogAuthority.Entity.AuthorityId
                            });
                            //----------------------------博客管理菜单end
                            //----------------------------博客友情链接菜单begin
                            var entityBlogYqlj = context.SysMenu.Add(new SysMenu
                            {
                                MenuName     = "友情链接",
                                MenuSort     = 1,
                                MenuIcon     = "layui-icon-share",
                                CreateTime   = DateTime.Now,
                                MenuUrl      = "/Blog/FriendshipLink/Index",
                                CreateUserId = Guid.Empty.ToString(),
                                ParentMenuId = entityBlog.Entity.MenuId,
                                MenuId       = Guid.NewGuid().ToString()
                            });
                            var entityBlogYqljAuthority = context.SysAuthority.Add(new SysAuthority
                            {
                                AuthorityType = 1,
                                CreateTime    = DateTime.Now,
                                CreateUserId  = Guid.Empty.ToString(),
                                AuthorityId   = Guid.NewGuid().ToString()
                            });
                            context.SysAmRelated.Add(new SysAmRelated
                            {
                                AmRelatedId = Guid.NewGuid().ToString(),
                                MenuId      = entityBlogYqlj.Entity.MenuId,
                                AuthorityId = entityBlogYqljAuthority.Entity.AuthorityId
                            });
                            //----------------------------博客友情链接菜单end
                            //----------------------------博客文章菜单begin
                            var entityBlogWz = context.SysMenu.Add(new SysMenu
                            {
                                MenuName     = "文章管理",
                                MenuSort     = 1,
                                MenuIcon     = "layui-icon-read",
                                MenuUrl      = "/Blog/BlogArticle/Index",
                                CreateTime   = DateTime.Now,
                                CreateUserId = Guid.Empty.ToString(),
                                ParentMenuId = entityBlog.Entity.MenuId,
                                MenuId       = Guid.NewGuid().ToString()
                            });
                            var entityBlogWzAuthority = context.SysAuthority.Add(new SysAuthority
                            {
                                AuthorityType = 1,
                                CreateTime    = DateTime.Now,
                                CreateUserId  = Guid.Empty.ToString(),
                                AuthorityId   = Guid.NewGuid().ToString()
                            });
                            context.SysAmRelated.Add(new SysAmRelated
                            {
                                AmRelatedId = Guid.NewGuid().ToString(),
                                MenuId      = entityBlogWz.Entity.MenuId,
                                AuthorityId = entityBlogWzAuthority.Entity.AuthorityId
                            });
                            //----------------------------博客文章菜单end
                            //----------------------------博客标签菜单begin
                            var entityBlogBq = context.SysMenu.Add(new SysMenu
                            {
                                MenuName     = "标签管理",
                                MenuSort     = 1,
                                MenuIcon     = "layui-icon-note",
                                MenuUrl      = "/Blog/BlogLable/Index",
                                CreateTime   = DateTime.Now,
                                CreateUserId = Guid.Empty.ToString(),
                                ParentMenuId = entityBlog.Entity.MenuId,
                                MenuId       = Guid.NewGuid().ToString()
                            });
                            var entityBlogBqAuthority = context.SysAuthority.Add(new SysAuthority
                            {
                                AuthorityType = 1,
                                CreateTime    = DateTime.Now,
                                CreateUserId  = Guid.Empty.ToString(),
                                AuthorityId   = Guid.NewGuid().ToString()
                            });
                            context.SysAmRelated.Add(new SysAmRelated
                            {
                                AmRelatedId = Guid.NewGuid().ToString(),
                                MenuId      = entityBlogBq.Entity.MenuId,
                                AuthorityId = entityBlogBqAuthority.Entity.AuthorityId
                            });
                            //----------------------------博客标签菜单end
                            #endregion
                            context.SaveChanges();
                            tran.Commit();
                        }
                        catch (Exception e)
                        {
                            tran.Rollback();
                            throw e;
                        }
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// 获取用户密码加密的密钥
 /// </summary>
 /// <returns></returns>
 public string GetSecretkey()
 {
     return(MD5Encrypt.GetMD5_16(Utility.CreateNo()));
 }
Ejemplo n.º 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.Request.Files.Count > 0)
            {
                string guid     = Guid.NewGuid().ToString();
                string filePath = "//WorkTime//InputExcelFiles//" + Guid.NewGuid().ToString() + System.IO.Path.GetExtension(Request.Files[0].FileName);
                this.Request.Files[0].SaveAs(Server.MapPath(filePath));
                ExcelProcessor ep = ExcelService.GetProcessor(Server.MapPath(filePath));
                DataSet        ds = ep.GetDataSet();
                InputDatas(ds.Tables[0]);
                Response.Write("{success:true}");
                Response.End();
            }

            id   = RequestData.Get <string>("id", String.Empty);
            type = RequestData.Get <string>("type", String.Empty);

            SysUser usr = null;

            switch (this.RequestAction)
            {
            case RequestActionEnum.Create:
                usr = this.GetPostedData <SysUser>();
                usr.DoCreate();
                this.SetMessage("新建成功!");
                break;

            case RequestActionEnum.Update:
                usr = this.GetMergedData <SysUser>();
                usr.DoUpdate();
                this.SetMessage("保存成功!");
                break;

            case RequestActionEnum.Delete:
                usr = this.GetTargetData <SysUser>();
                usr.DoDelete();
                this.SetMessage("删除成功!");
                break;

            default:
                if (RequestActionString == "clearpass")
                {
                    usr          = SysUser.Find(this.RequestData.Get <string>("UserId"));
                    usr.Password = "";
                    usr.Remark   = "";
                    usr.Save();
                }
                else if (RequestActionString == "setpass")
                {
                    MD5Encrypt encrypt = new MD5Encrypt();
                    SysUser[]  users   = SysUser.FindAll();
                    foreach (SysUser user in users)
                    {
                        Random rnd           = new Random();
                        int    rndNum        = rnd.Next(10000000, 99999999);
                        string encryPassword = encrypt.GetMD5FromString(rndNum.ToString());
                        user.Password = encryPassword;
                        user.Remark   = rndNum.ToString();
                        user.Save();
                    }
                }
                else if (RequestActionString == "checkkey")
                {
                    if (SysUser.FindAllByProperties("Server_IAGUID", this.RequestData.Get <string>("usbguid")).Length > 0)
                    {
                        this.PageState.Add("UserName", SysUser.FindAllByProperties("Server_IAGUID", this.RequestData.Get <string>("usbguid"))[0].Name);
                    }
                    else
                    {
                        this.PageState.Add("UserName", "");
                    }
                }
                else if (RequestActionString == "setkey")
                {
                    SysUser user = SysUser.Find(this.RequestData.Get <string>("userid"));
                    user.Server_IAGUID = this.RequestData.Get <string>("usbguid");
                    user.Server_Seed   = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
                    user.ThreeDESKEY   = "ABCDEFGhijklmn0123456789";
                    user.Save();
                }
                else if (RequestActionString == "sendmail")
                {
                    IList <object> idList = RequestData.GetList <object>("IdList");
                    SysUser[]      tents  = SysUser.FindAll(Expression.In("UserID", idList.ToArray()));

                    foreach (SysUser user in tents)
                    {
                        string body = SysParameter.FindAllByProperties("Code", "MailText")[0].Description + "<br>";
                        body += "您的登录用户名:" + user.LoginName + ";密码:" + user.Remark;
                        string mailAccount       = SysParameter.FindAllByProperties("Code", "MailAccount")[0].Value;
                        string mailPass          = SysParameter.FindAllByProperties("Code", "MailPassword")[0].Value;
                        string mailServer        = SysParameter.FindAllByProperties("Code", "MailSmtpServer")[0].Value;
                        string mailSenderAddress = SysParameter.FindAllByProperties("Code", "MailSenderAddress")[0].Value;
                        MailHelper.SendMail(mailSenderAddress, user.Email, "工时分配系统邮件", body, mailAccount, mailPass, mailServer);
                    }
                }
                else
                {
                    SearchCriterion.AutoOrder = false;
                    SearchCriterion.SetOrder(SysUser.Prop_WorkNo);
                    string dName  = SearchCriterion.GetSearchValue <string>("Name");
                    string workNo = SearchCriterion.GetSearchValue <string>("WorkNo");
                    SearchCriterion.SetOrder(SysUser.Prop_WorkNo);
                    if (dName != null && dName.Trim() != "")
                    {
                        string where = "select * from SysUser where " + GetPinyinWhereString("Name", dName);
                        where       += " and WorkNo like '%" + workNo + "%'";
                        this.PageState.Add("UsrList", DataHelper.QueryDictList(where));
                    }
                    else
                    {
                        users = SysUserRule.FindAll(SearchCriterion);
                        this.PageState.Add("UsrList", users);
                    }
                }
                break;
            }
        }
        /// <summary>
        /// 申请找回密码
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="email">电子邮箱</param>
        /// <param name="userip">用户IP</param>
        /// <param name="checkCode">验证码</param>
        /// <param name="link">找回密码链接</param>
        /// <returns>是否可以申请</returns>
        public static async Task <IMethodResult> RequestResetUserPassword(String userName, String email, String userip, String checkCode, String link)
        {
            if (!CheckCodeStatus.VerifyCheckCode(checkCode))
            {
                return(MethodResult.Failed("The verification code you input didn't match the picture, Please try again!"));
            }

            if (!RegexVerify.IsUserName(userName))
            {
                return(MethodResult.InvalidRequest(RequestType.User));
            }

            if (!RegexVerify.IsEmail(email))
            {
                return(MethodResult.Failed("Email address is INVALID!"));
            }

            UserEntity user = UserManager.InternalGetUserByNameAndEmail(userName, email);

            if (user == null)
            {
                return(MethodResult.Failed("The username \"{0}\" doesn't exist or the email is wrong!", userName));
            }

            if (user.IsLocked)
            {
                return(MethodResult.Failed("The user is locked, please contact the administrator!"));
            }

            if (String.IsNullOrEmpty(user.Email) || "NULL".Equals(user.Email, StringComparison.OrdinalIgnoreCase))
            {
                return(MethodResult.Failed("The user has no email, please contact the administrator!"));
            }

            Random rand = new Random(DateTime.Now.Millisecond);

            UserForgetPasswordEntity ufp = new UserForgetPasswordEntity()
            {
                UserName   = userName,
                SubmitDate = DateTime.Now,
                SubmitIP   = userip,
                HashKey    = MD5Encrypt.EncryptToHexString(String.Format("{0}-{1}-{2}", userName, DateTime.Now.Ticks.ToString(), rand.Next(DateTime.Now.Millisecond)), true)
            };

            Boolean success = UserForgetPasswordRepository.Instance.InsertEntity(ufp) > 0;

            if (!success)
            {
                return(MethodResult.Failed("Failed to process your request!"));
            }

            String url         = ConfigurationManager.DomainUrl + ((link[0] == '/') ? link.Substring(1) : link);
            String mailSubject = ConfigurationManager.OnlineJudgeName + " Password Recovery";
            String mailContent = UserForgetPasswordManager.GetMailContent(userName, url + ufp.HashKey.ToLowerInvariant());

            try
            {
                await MailClient.SendMailAsync(ConfigurationManager.EmailSMTPServer, ConfigurationManager.EmailAddresser, email, mailSubject, mailContent, true, true, ConfigurationManager.EmailUsername, ConfigurationManager.EmailPassword);
            }
            catch
            {
                return(MethodResult.Failed("Failed to send a password reset link to your email address."));
            }

            return(MethodResult.SuccessAndLog("User forget password, name = {0}", userName));
        }
Ejemplo n.º 9
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //保存权限
            if (!VerifyPurview(",SU-EDIT,"))
            {
                Alert.ShowInParent(CHECK_POWER_FAIL_ACTION_MESSAGE);
                return;
            }
            string strErr = String.Empty;
            int    num    = 1;

            if (id <= 0)
            {
                strErr += num + "、参数错误 <br />";
                num++;
            }
            string vName = HttpUtility.HtmlEncode(txtVerityName.Text.Trim());

            if (vName.Length == 0)
            {
                strErr += num + "、真实姓名不能为空 <br />";
            }
            if (strErr.Length > 0)
            {
                Alert.ShowInParent(strErr);
                return;
            }
            UserModel model = new UserModel();

            model.Id = id;
            string pwd = HttpUtility.HtmlEncode(txtPwd.Text.Trim());

            if (pwd.Length > 0)
            {
                model.Encrypt = RandomHelper.CreateRandomStr(6);
                model.Pwd     = MD5Encrypt.GetPass(pwd, model.Encrypt);
            }
            model.RealName = vName;
            model.Email    = HttpUtility.HtmlEncode(txtEmail.Text.Trim());
            model.Mobile   = HttpUtility.HtmlEncode(txtMobile.Text.Trim());
            model.Tel      = HttpUtility.HtmlEncode(txtTel.Text.Trim());
            model.Disabled = chkDisabled.Checked;
            int     result = 0;
            UserBLL bll    = new UserBLL();

            using (DataTable roleDT = new DataTable())
            {
                roleDT.Columns.Add("roleid", typeof(int));
                roleDT.Columns.Add("userid", typeof(int));
                #region 角色用户
                string userRole = hfSelectedRole.Text.Trim();
                if (userRole.Length > 0)
                {
                    string[] userRoleArr = userRole.Split(',');
                    foreach (string s in userRoleArr)
                    {
                        DataRow dr = roleDT.NewRow();
                        dr[0] = Convert.ToInt32(s);
                        dr[1] = model.Id;
                        roleDT.Rows.Add(dr);
                    }
                }
                #endregion
                result = bll.Modify(model, roleDT);
            }
            if (result > 0)
            {
                Alert.ShowInParent("保存成功!", String.Empty, ActiveWindow.GetHidePostBackReference());
            }
            else
            {
                Alert.ShowInParent("保存失败");
            }
        }
Ejemplo n.º 10
0
 public Messages Save(UserParam model)
 {
     if (model != null && model.U_NAME.IsNotNullOrEmpty() && model.U_REALNAME.IsNotNullOrEmpty())
     {
         UserEntity user = new UserEntity();
         user.U_ID   = model.U_ID;
         user.U_NAME = model.U_NAME;
         if (model.U_PWD.IsNotNullOrEmpty())
         {
             string encrypt = RandomHelper.CreateRandomStr(6);
             user.U_ENCRYPT = encrypt;
             user.U_PWD     = MD5Encrypt.GetPass(model.U_PWD, encrypt);
         }
         user.U_REALNAME = model.U_REALNAME;
         user.U_EMAIL    = model.U_EMAIL ?? "";
         user.U_MOBILE   = model.U_MOBILE ?? "";
         user.U_TEL      = model.U_TEL ?? "";
         user.U_PHOTO    = model.U_PHOTO ?? "";
         using (DataTable roleDT = new DataTable())
         {
             roleDT.Columns.Add("roleid", typeof(int));
             roleDT.Columns.Add("userid", typeof(int));
             if (model.RoleIds.IsNotNullOrEmpty())
             {
                 string[] userRoleArr = model.RoleIds.TrimEnd(',').Split(',');
                 if (userRoleArr != null && userRoleArr.Length > 0)
                 {
                     foreach (string s in userRoleArr)
                     {
                         DataRow dr = roleDT.NewRow();
                         dr[0] = Convert.ToInt32(s);
                         dr[1] = model.U_ID;
                         roleDT.Rows.Add(dr);
                     }
                 }
             }
             int result = 0;
             if (model.U_ID > 0)
             {
                 result = userRepository.Modify(user, roleDT);
             }
             else
             {
                 result = userRepository.Add(user, roleDT);
             }
             if (result > 0)
             {
                 messages.Msg     = "保存成功";
                 messages.Success = true;
             }
             else if (result == -10000)
             {
                 messages.Msg = "存在相同用户名的数据";
             }
             else
             {
                 messages.Msg = "保存失败";
             }
         }
     }
     return(messages);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="userPwd">密码</param>
        /// <returns>Task<(bool Succeeded, string Msg)></returns>
        public async Task <(bool Succeeded, string Msg, int UserId)> Login(string userName, string userPwd)
        {
            bool       succeeded = false;
            string     msg       = string.Empty;
            int        userId    = 0;
            UserEntity user      = this.GetModelByUserName(userName);

            if (user != null && user.U_ID > 0)
            {
                userId = user.U_ID;
                int    errorTimes = 0;
                string pwd1       = MD5Encrypt.MD5(userPwd + user.U_ENCRYPT);
                if (user.U_DISABLED == false)
                {
                    //登录错误次数
                    int maxLoginFailedTimes = config.MaxLoginFailedTimes;
                    if (maxLoginFailedTimes <= 0)
                    {
                        maxLoginFailedTimes = 5;
                    }
                    if (user.U_ERRORTIMES < maxLoginFailedTimes)
                    {
                        if (user.U_PWD == pwd1)
                        {
                            succeeded = true;
                            msg       = "登录系统,成功";
                        }
                        else
                        {
                            errorTimes = user.U_ERRORTIMES + 1;
                            int sErrorTimes = maxLoginFailedTimes - errorTimes;
                            if (sErrorTimes > 0)
                            {
                                msg = "密码错误,您今天还可尝试" + sErrorTimes + "次";
                            }
                            else
                            {
                                msg = "您今天登录错误次数过多,今天不可再登录,欢迎明天回来";
                            }
                        }
                    }
                    else
                    {
                        errorTimes = user.U_ERRORTIMES + 1;
                        msg        = "您今天登录错误次数过多,今天不可再登录,欢迎明天回来";
                    }
                    //更新用户登录信息
                    await this.UpdateByLoginAsync(user.U_ID, webHelper.GetCurrentIpAddress(), errorTimes);
                }
                else
                {
                    msg = "登录系统,该用户状态为禁止登录";
                }
            }
            else
            {
                msg = "用户名不存在";
            }
            //记录登录日志
            await logService.AddLogAsync(OperatorLogEnum.Login, msg, userId, userName);

            return(succeeded, msg, userId);
        }
Ejemplo n.º 12
0
        private void btnMD5EncryptString_Click(object sender, RoutedEventArgs e)
        {
            string decryptText = MD5Encrypt.GetEncrptStringByMD5(txtBxEncryptText.Text.Trim());

            txtBxDecryptText.Text = decryptText;
        }
Ejemplo n.º 13
0
        public async Task <IResponseOutput> LoginAsync(AuthLoginParam param)
        {
            #region 验证码校验
            if (Configs.AppSettings.VarifyCode.Enable)
            {
                var verifyCodeKey = string.Format(CacheKey.VerifyCodeKey, param.VerifyCodeKey);
                var exists        = await BaseCache.ExistsAsync(verifyCodeKey);

                if (exists)
                {
                    var verifyCode = await BaseCache.GetAsync(verifyCodeKey);

                    if (string.IsNullOrEmpty(verifyCode))
                    {
                        return(ResponseOutput.NotOk("验证码已过期!"));
                    }
                    if (verifyCode.ToLower() != param.VerifyCode.ToLower())
                    {
                        return(ResponseOutput.NotOk("验证码输入有误!", 2));
                    }
                    await BaseCache.DelAsync(verifyCodeKey);
                }
                else
                {
                    return(ResponseOutput.NotOk("验证码已过期!", 1));
                }
            }
            #endregion

            var user = await _userRepo.FindAsync(a => a.UserName == param.UserName);

            if (string.IsNullOrWhiteSpace(user?.Id))
            {
                return(ResponseOutput.NotOk("账号输入有误!", 3));
            }

            #region 解密
            if (param.PasswordKey.NotNull())
            {
                var passwordEncryptKey = string.Format(CacheKey.PassWordEncryptKey, param.PasswordKey);
                var existsPasswordKey  = await BaseCache.ExistsAsync(passwordEncryptKey);

                if (existsPasswordKey)
                {
                    var secretKey = await BaseCache.GetAsync(passwordEncryptKey);

                    if (secretKey.IsNull())
                    {
                        return(ResponseOutput.NotOk("解密失败!", 1));
                    }
                    param.Password = DesEncrypt.Decrypt(param.Password, secretKey);
                    await BaseCache.DelAsync(passwordEncryptKey);
                }
                else
                {
                    return(ResponseOutput.NotOk("解密失败!", 1));
                }
            }
            #endregion

            var password = MD5Encrypt.Encrypt32(param.Password);
            if (user.Password != password)
            {
                return(ResponseOutput.NotOk("密码输入有误!", 4));
            }

            var authLoginOutput = ObjectMapper.Map <AuthLoginOutput>(user);//user.MapTo<UserEntity, AuthLoginOutput>();

            return(ResponseOutput.Ok(authLoginOutput));
        }
Ejemplo n.º 14
0
        public ActionResult Home()
        {
            var       v     = version;
            Hashtable param = base.GetParameters();

            //if (!param.ContainsKey("controller") || !param.ContainsKey("action"))
            //{
            //TODO:菜单查库
            #region 后期查库

            int            index     = 0;
            List <Tb_Menu> list_menu = new List <Tb_Menu>();



            #endregion 后期查库

            //查询用户所有的菜单权限树
            var userPurview = BusinessFactory.AccountFunction.GetUserMenu(id_user);
            if (userPurview != null)
            {
                var tree      = userPurview.Data as List <Tb_Function_Tree>;
                var role_str  = GetLoginInfo <string>("role_str");
                var isManager = role_str.Split(',').ToList().Any(a => a == "2");
                if (tree != null && tree.Any())
                {
                    var menus = tree[0].children;
                    //遍历菜单权限树
                    foreach (var menu in menus)
                    {
                        if ((menu.version + "").Split(',').All(a => a != v))
                        {
                            continue;
                        }
                        List <Tb_Menu_Item> menuItems = new List <Tb_Menu_Item>();
                        if (menu.children.Any())
                        {
                            foreach (var subItem in menu.children)
                            {
                                if ((subItem.version + "").Split(',').All(a => a != v))
                                {
                                    continue;
                                }

                                //if (!string.IsNullOrEmpty(id_shop)
                                //    && id_shop != id_shop_master
                                //    && (
                                //        subItem.controller_name.ToLower() == "psck"
                                //        || subItem.controller_name.ToLower() == "psfprk"
                                //        || subItem.controller_name.ToLower() == "pscktzd"
                                //        || subItem.controller_name.ToLower() == "psfptzd"
                                //        ) //&& !isManager
                                //    )
                                //{
                                //    continue;
                                //}
                                if (!(id_shop_info.flag_type == 1 || id_shop_info.flag_type == 2) &&
                                    (
                                        subItem.controller_name.ToLower() == "psck" ||
                                        subItem.controller_name.ToLower() == "psfprk" ||
                                        subItem.controller_name.ToLower() == "pscktzd" ||
                                        subItem.controller_name.ToLower() == "psfptzd"
                                    )
                                    )
                                {
                                    continue;
                                }

                                if (id_shop_info.flag_type != 1 &&
                                    subItem.controller_name.ToLower() == "shop" && subItem.action_name.ToLower() == "shopinfo")
                                {
                                    continue;
                                }

                                if (!(id_shop_info.flag_type == 1 || id_shop_info.flag_type == 2) &&
                                    subItem.controller_name.ToLower() == "shop" && subItem.action_name.ToLower() == "list")
                                {
                                    continue;
                                }


                                menuItems.Add(new Tb_Menu_Item()
                                {
                                    ActionName     = subItem.action_name,
                                    ControllerName = subItem.controller_name,
                                    HasRemark      = false,
                                    ID             = subItem.id,
                                    Name           = subItem.name,
                                    Title          = subItem.name,
                                    TabTitle       = subItem.name,
                                    Remark         = subItem.name,
                                    TagName        = subItem.tag_name,
                                    sort_id        = subItem.sort_id == null ? 10000000 : subItem.sort_id.Value
                                });
                            }
                        }
                        list_menu.Add(new Tb_Menu()
                        {
                            ID    = menu.id,
                            Icon  = menu.icon,
                            Name  = menu.name,
                            Title = menu.name,
                            Items = menuItems
                        });
                    }
                }
            }

            ViewData["list_menu"] = list_menu;
            Hashtable ht = new Hashtable();
            ht.Add("id_masteruser", id_user_master);
            ht.Add("id_shop", id_shop);
            var date = DateTime.Now;
            ht.Add("lgrq", new DateTime(date.Year, date.Month, date.Day));
            ht.Add("bgrq", new DateTime(date.Year, date.Month, date.Day, 23, 59, 59, 999));
            ViewData["ShowData"]  = BusinessFactory.Td_Ls_1.Get(ht).Data;
            ViewData["date_type"] = "0";

            param.Clear();
            param.Add("flag_stop", 0);
            param.Add("flag_type", "action");
            ViewData["dialog_tab_ids"] = BusinessFactory.Function.GetAll(param).Data;

            #region 验服务以及获取购买服务地址

            if (PublicSign.flagCheckService == "1")
            {
                var bm = BusinessFactory.Account.GetServiceBM(version);
                if (!string.IsNullOrEmpty(bm))
                {
                    ht.Clear();
                    ht.Add("id_cyuser", id_cyuser);
                    ht.Add("bm", bm);
                    ht.Add("service", "GetService");
                    ht.Add("id_masteruser", id_user_master);
                    ht.Add("rq_create_master_shop", rq_create_master_shop.ToString());
                    var cyServiceHas = BusinessFactory.Account.GetCYService(ht);
                    if (cyServiceHas != null && cyServiceHas.ContainsKey("cyServiceList") && cyServiceHas.ContainsKey("endTime"))
                    {
                        var cyServiceList = (List <Schedule_UserService>)cyServiceHas["cyServiceList"];
                        if (cyServiceList.Count() == 0)
                        {
                            ViewData["vEndData"] = cyServiceHas["endTime"].ToString();
                        }
                        else
                        {
                            DateTime dt = DateTime.Now;
                            if (DateTime.TryParse(cyServiceHas["endTime"].ToString(), out dt))
                            {
                                if (dt > DateTime.Parse("1900-01-01 00:00:00"))
                                {
                                    ViewData["vEndData"] = cyServiceHas["endTime"].ToString();
                                }
                            }
                        }
                    }

                    ht.Clear();
                    ht.Add("id_cyuser", id_cyuser);
                    ht.Add("id", bm);
                    ht.Add("phone", phone_master);
                    ht.Add("service", "Detail");
                    ht.Add("id_masteruser", id_user_master);
                    string buyUrl = BusinessFactory.Tb_Shop.GetBuyServiceUrl(ht);
                    if (string.IsNullOrEmpty(buyUrl))
                    {
                        buyUrl = PublicSign.cyBuyServiceUrl;
                    }
                    ViewData["buyUrl"] = buyUrl;
                }
            }
            #endregion

            ViewData["downUrl"]  = PublicSign.downUrl;
            ViewData["cusName"]  = System.Configuration.ConfigurationManager.AppSettings["CUSTOMER_YUNPOS_CUS"];
            ViewData["cusPhone"] = System.Configuration.ConfigurationManager.AppSettings["CUSTOMER_YUNPOS_PHONE"];
            ViewData["cusTel"]   = System.Configuration.ConfigurationManager.AppSettings["CUSTOMER_YUNPOS_TEL"];
            ViewData["cusQQ"]    = System.Configuration.ConfigurationManager.AppSettings["CUSTOMER_YUNPOS_QQ"];
            ViewData["cusEamil"] = System.Configuration.ConfigurationManager.AppSettings["CUSTOMER_YUNPOS_EMAIL"];

            //生成购买历史的 登录地址
            var paramters = new Dictionary <string, string>();
            paramters.Add("uid", id_cyuser);
            string ps = MD5Encrypt.Encode(Encoding.UTF8, "cy.$" + id_cyuser + "+#" + phone_master + "*" + DateTime.Now.ToString("yyyyMMddHH"));
            paramters.Add("ps", ps);
            string mySign = SignUtils.SignRequestForCyUserSys(paramters, PublicSign.md5KeyBusiness);
            paramters.Add("sign", mySign);
            string url = PublicSign.cyBuyServiceHistoryUrl + "?" + WebUtils.BuildQuery2(paramters);
            ViewData["cyBuyServiceHistoryUrl"] = url;


            int pageIndex = 0;
            int limit     = 10;
            param.Clear();
            param.Add("flag_delete", (int)Enums.FlagDelete.NoDelete);
            param.Add("page", pageIndex);
            param.Add("pageSize", limit);
            param.Add("sort", "rq_create desc");
            param.Add("limit", limit);
            param.Add("start", pageIndex * limit);
            PageNavigate pn = new PageNavigate();
            pn = BusinessFactory.Ts_Notice.GetPage(param);
            var plist = new PageList <Ts_Notice_View>(pn, pageIndex, limit);
            ViewData["notice_list"]   = plist;
            ViewData["cyLoginOutUrl"] = PublicSign.cyLoginOutUrl;

            return(View("Home"));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 用户添加
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public UserAddResponse UserAdd(UserAddRequest request)
        {
            UserAddResponse response = new UserAddResponse();

            //非空判断
            if (string.IsNullOrEmpty(request.User.UserName))
            {
                response.Status  = false;
                response.Message = "用户名为空";
                return(response);
            }
            if (string.IsNullOrEmpty(request.User.UserPassword))
            {
                response.Status  = false;
                response.Message = "密码为空";
                return(response);
            }
            if (string.IsNullOrEmpty(request.User.Email))
            {
                response.Status  = false;
                response.Message = "邮箱为空";
                return(response);
            }
            if (request.User.AddressId <= 0)
            {
                response.Status  = false;
                response.Message = "请选择地址";
                return(response);
            }
            if (request.User.RoleId <= 0)
            {
                response.Status  = false;
                response.Message = "请选择角色";
                return(response);
            }
            if (request.User.CreatorId <= 0)
            {
                response.Status  = false;
                response.Message = "系统繁忙,creatorid<=0";
                return(response);
            }
            //判断用户名是否已被注册
            int uid = UserDal.Instance.UserNameExist(request.User.UserName);

            if (uid > 0)
            {
                response.Status  = false;
                response.Message = "用户名已存在";
                return(response);
            }

            //开始获取盐
            var salt = Generate.GenerateSalt();
            //获取md5加密密码
            var pwd = MD5Encrypt.MD5Encrypt32(request.User.UserPassword + salt);

            request.User.UserPassword = pwd;
            request.User.Salt         = salt;
            var res = UserDal.Instance.UserAdd(request.User);

            if (res < 0)
            {
                response.Status  = false;
                response.Message = "添加失败";
            }
            else
            {
                response.Message = "添加成功";
            }
            return(response);
        }
Ejemplo n.º 16
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);
            }

            IUserAccountService service = DIFactory.GetContainer().Resolve <IUserAccountService>();
            UserAccount         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)CommonEnum.UserState.Frozen)
            {
                return(LoginResult.Frozen);
            }
            else
            {
                //Response,Request,Application,Server,Session

                #region Server
                //辅助类 Server
                string encode       = context.Server.HtmlEncode("<我爱我家>");
                string decode       = context.Server.HtmlDecode(encode);
                string physicalPath = context.Server.MapPath("/home/index");//只能做物理文件的映射
                string encodeUrl    = context.Server.UrlEncode("<我爱我家>");
                string decodeUrl    = context.Server.UrlDecode(encodeUrl);
                #endregion

                #region Application
                context.Application.Lock();//ASP.NET 应用程序内的多个会话和请求之间共享信息
                context.Application.Lock();
                context.Application.Add("try", "die");
                context.Application.UnLock();
                object aValue = context.Application.Get("try");
                aValue = context.Application["try"];
                context.Application.Remove("命名对象");
                context.Application.RemoveAt(0);
                context.Application.RemoveAll();
                context.Application.Clear();

                context.Items["123"] = "123";//单一会话,不同环境都可以用
                #endregion

                #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   = JsonConvert.SerializeObject(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.º 17
0
        private readonly MailService mailService;              //crosscuting de envio de emial

        public AccountController(IUsuarioRepository usuarioRepository, IPerfilRepository perfilRepository, MD5Encrypt mD5Encrypt, MailService mailService)
        {
            this.usuarioRepository = usuarioRepository;
            this.perfilRepository  = perfilRepository;
            this.mD5Encrypt        = mD5Encrypt;
            this.mailService       = mailService;
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            int level = 0;

            try
            {
                var user = new AU_NGUOIDUNG();
                using (var connection = new OracleConnection(ConfigurationManager.ConnectionStrings["Database.Connection"].ConnectionString))
                {
                    await connection.OpenAsync();

                    using (var command = connection.CreateCommand())
                    {
                        command.CommandType = CommandType.Text;
                        command.CommandText =
                            "SELECT * FROM AU_NGUOIDUNG WHERE USERNAME='******' AND PASSWORD='******' AND TRANGTHAI = 10 ";
                        using (var oracleDataReader = command.ExecuteReaderAsync(CommandBehavior.CloseConnection))
                        {
                            if (!oracleDataReader.Result.HasRows)
                            {
                                user = null;
                            }
                            else
                            {
                                while (oracleDataReader.Result.Read())
                                {
                                    user.Username       = oracleDataReader.Result["USERNAME"]?.ToString();
                                    user.TenNhanVien    = oracleDataReader.Result["TENNHANVIEN"]?.ToString();
                                    user.SoDienThoai    = oracleDataReader.Result["SODIENTHOAI"]?.ToString();
                                    user.ChungMinhThu   = oracleDataReader.Result["SOCHUNGMINHTHU"]?.ToString();
                                    user.UnitCode       = oracleDataReader.Result["UNITCODE"]?.ToString();
                                    user.ParentUnitcode = oracleDataReader.Result["PARENT_UNITCODE"]?.ToString();
                                    int.TryParse(oracleDataReader.Result["LEVEL"]?.ToString(), out level);
                                    user.Level = level;
                                }
                            }
                        }
                    }
                }
                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
                    },
                    {
                        "level", level.ToString()
                    }
                });

                AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(identity);
            }
            catch (Exception e)
            {
                context.SetError("invalid_grant", e.Message);
                return;
            }
        }
Ejemplo n.º 19
0
        private byte[] SetCaptch()
        {
            int    codeW    = 80;
            int    codeH    = 30;
            int    fontSize = 16;
            string chkCode  = string.Empty;

            //颜色列表,用于验证码、噪线、噪点
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
            //字体列表,用于验证码
            string[] font = { "Times New Roman" };
            //验证码的字符集,去掉了一些容易混淆的字符
            char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
            Random rnd       = new Random();

            //生成验证码字符串
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }
            //写入Session、验证码加密
            httpContextAccessor.HttpContext.Session.SetString(chkCode.ToUpper(), MD5Encrypt.MD5By16(chkCode.ToLower()));
            //创建画布
            Bitmap   bmp = new Bitmap(codeW, codeH);
            Graphics g   = Graphics.FromImage(bmp);

            g.Clear(Color.White);
            //画噪线
            for (int i = 0; i < 3; i++)
            {
                int   x1  = rnd.Next(codeW);
                int   y1  = rnd.Next(codeH);
                int   x2  = rnd.Next(codeW);
                int   y2  = rnd.Next(codeH);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            }
            //画验证码字符串
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font   ft  = new Font(fnt, fontSize);
                Color  clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0);
            }
            //将验证码图片写入内存流,并将其以 "image/Png" 格式输出
            MemoryStream ms = new MemoryStream();

            try
            {
                bmp.Save(ms, ImageFormat.Png);
                return(ms.ToArray());
            }
            catch (Exception)
            {
                return(null);
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
            }
        }
Ejemplo n.º 20
0
        public async Task <IResultModel> LoginAsync(AuthLoginInput input)
        {
            #region 验证码校验
            //if (_appConfig.VarifyCode.Enable)
            //{
            //    var verifyCodeKey = string.Format(CacheKey.VerifyCodeKey, input.VerifyCodeKey);
            //    var exists = await _cache.ExistsAsync(verifyCodeKey);
            //    if (exists)
            //    {
            //        var verifyCode = await _cache.GetAsync(verifyCodeKey);
            //        if (string.IsNullOrEmpty(verifyCode))
            //        {
            //            return ResponseOutput.NotOk("验证码已过期!", 1);
            //        }
            //        if (verifyCode.ToLower() != input.VerifyCode.ToLower())
            //        {
            //            return ResponseOutput.NotOk("验证码输入有误!", 2);
            //        }
            //        await _cache.DelAsync(verifyCodeKey);
            //    }
            //    else
            //    {
            //        return ResponseOutput.NotOk("验证码已过期!", 1);
            //    }
            //}
            #endregion
            string conditions = "where UserName=@UserName ";
            var    user       = await _userRepository.GetAsync(conditions, new { input.UserName });

            if (!(user?.Id > 0))
            {
                return(ResultModel.Failed("账号输入有误!", 3));
            }

            #region 解密
            //if (input.PasswordKey.NotNull())
            //{
            //    var passwordEncryptKey = string.Format(CacheKey.PassWordEncryptKey, input.PasswordKey);
            //    var existsPasswordKey = await _cache.ExistsAsync(passwordEncryptKey);
            //    if (existsPasswordKey)
            //    {
            //        var secretKey = await _cache.GetAsync(passwordEncryptKey);
            //        if (secretKey.IsNull())
            //        {
            //            return ResponseOutput.NotOk("解密失败!", 1);
            //        }
            //        input.Password = DesEncrypt.Decrypt(input.Password, secretKey);
            //        await _cache.DelAsync(passwordEncryptKey);
            //    }
            //    else
            //    {
            //        return ResponseOutput.NotOk("解密失败!", 1);
            //    }
            //}
            #endregion

            var password = MD5Encrypt.Encrypt32(input.Password);
            if (user.Password != password)
            {
                return(ResultModel.Failed("密码输入有误!", 4));
            }


            var authLoginOutput = _mapper.Map <AuthLoginOutput>(user);
            //await _cache.SetAsync(CacheKey.UserAuthLogin, authLoginOutput, TimeSpan.FromMinutes(5));

            return(ResultModel.Success(authLoginOutput));
        }
Ejemplo n.º 21
0
        public async Task <IResponseOutput> LoginAsync(AuthLoginInput input)
        {
            #region 验证码校验

            if (_appConfig.VarifyCode.Enable)
            {
                var verifyCodeKey = string.Format(CacheKey.VerifyCodeKey, input.VerifyCodeKey);
                var exists        = await Cache.ExistsAsync(verifyCodeKey);

                if (exists)
                {
                    var verifyCode = await Cache.GetAsync(verifyCodeKey);

                    if (string.IsNullOrEmpty(verifyCode))
                    {
                        return(ResponseOutput.NotOk("验证码已过期!", 1));
                    }
                    if (verifyCode.ToLower() != input.VerifyCode.ToLower())
                    {
                        return(ResponseOutput.NotOk("验证码输入有误!", 2));
                    }
                    await Cache.DelAsync(verifyCodeKey);
                }
                else
                {
                    return(ResponseOutput.NotOk("验证码已过期!", 1));
                }
            }

            #endregion 验证码校验

            UserEntity user = null;

            user = await _userRepository.Select.DisableGlobalFilter("Tenant").Where(a => a.UserName == input.UserName).ToOneAsync();

            //user = (await _userRepository.GetAsync(a => a.UserName == input.UserName));

            if (!(user?.Id > 0))
            {
                return(ResponseOutput.NotOk("账号输入有误!", 3));
            }

            #region 解密

            if (input.PasswordKey.NotNull())
            {
                var passwordEncryptKey = string.Format(CacheKey.PassWordEncryptKey, input.PasswordKey);
                var existsPasswordKey  = await Cache.ExistsAsync(passwordEncryptKey);

                if (existsPasswordKey)
                {
                    var secretKey = await Cache.GetAsync(passwordEncryptKey);

                    if (secretKey.IsNull())
                    {
                        return(ResponseOutput.NotOk("解密失败!", 1));
                    }
                    input.Password = DesEncrypt.Decrypt(input.Password, secretKey);
                    await Cache.DelAsync(passwordEncryptKey);
                }
                else
                {
                    return(ResponseOutput.NotOk("解密失败!", 1));
                }
            }

            #endregion 解密

            var password = MD5Encrypt.Encrypt32(input.Password);
            if (user.Password != password)
            {
                return(ResponseOutput.NotOk("密码输入有误!", 4));
            }

            var authLoginOutput = Mapper.Map <AuthLoginOutput>(user);

            if (_appConfig.Tenant)
            {
                var tenant = await _tenantRepository.Select.DisableGlobalFilter("Tenant").WhereDynamic(user.TenantId).ToOneAsync(a => new { a.TenantType, a.DataIsolationType });

                authLoginOutput.TenantType        = tenant.TenantType;
                authLoginOutput.DataIsolationType = tenant.DataIsolationType;
            }

            //登录清空用户缓存
            await Cache.DelAsync(string.Format(CacheKey.UserInfo, user.Id));

            return(ResponseOutput.Ok(authLoginOutput));
        }
Ejemplo n.º 22
0
        public void ProcessRequest(HttpContext Context)
        {
            Context.Response.Clear();
            Context.Response.ClearHeaders();
            Context.Response.ClearContent();
            Context.Response.ContentType = "image/jpeg";

            string static_cache = "/cache/cache_images/";

            //接收参数
            string url = VTSRequest.GetRawUrl();
            //图片名字
            string md5 = MD5Encrypt.DataToMD5(url);

            //////////////开始分文件夹/////////////////
            string folderName = md5.Substring(0, 2);
            string imageDir   = Context.Server.MapPath(static_cache + folderName);

            if (!Directory.Exists(imageDir))
            {
                Directory.CreateDirectory(imageDir);
            }
            //////////////结束分文件夹/////////////////

            //物理地址
            string imageSavePath = string.Concat(imageDir, "\\", md5, ".jpg");

            //分析参数  http://beautify.afuli.mobi
            //示例参数:/https/storage.googleapis.com/140x80/cut/forward/beautify/Pics/1007/005/7A8A25209579C10A943A13E4C27AF54/14.jpg
            string[] urlarrs = url.Replace("http://", "").Replace("https://", "").TrimStart('/').Split('/');

            //urlarrs[0]=thumb.afuli.mobi
            //urlarrs[0]=https

            //urlarrs[1]=storage.googleapis.com
            //urlarrs[2]=140x80

            //urlarrs[3]=cut
            //urlarrs[4]=forward
            //urlarrs[5]=beautify

            //得到原始URL
            string imgUrl = string.Empty;

            //得到相对URL:/Pics/1007/005/7A8A25209579C10A943A13E4C27AF54/14.jpg
            string imgRelUrl = string.Empty;

            int beautify = url.IndexOf("beautify");

            if (beautify != -1)
            {
                //表示找到标识符beautify
                beautify += "beautify".Length;
                imgRelUrl = url.Substring(beautify);
                imgUrl    = string.Concat(urlarrs[0], "://", urlarrs[1], imgRelUrl);

                //Context.Response.Write(imgUrl + "<br />");
            }

            //最终参数
            int    w     = Convert.ToInt32(urlarrs[2].Substring(0, urlarrs[2].IndexOf('x')));
            int    h     = Convert.ToInt32(urlarrs[2].Substring(urlarrs[2].IndexOf('x') + 1));
            string model = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(urlarrs[3]);
            //int zc = VTSRequest.GetQueryInt("zc");
            string src = imgUrl;

            //Context.Response.Write(w + "<br />");
            //Context.Response.Write(h + "<br />");
            //Context.Response.Write(imgUrl + "<br />");
            /***************************************************************************************************************************************************************/

            byte[] b = null;
            if (File.Exists(imageSavePath))
            {
                #region 缓存策略
                //正确显示图片 才设置图片缓存策略
                //配置成一个星期 168小时
                Context.Response.Cache.SetExpires(DateTime.Now.AddHours(168));
                //下面的代码示例演示如何设置 Cache-Control: max-age 标题,为 0 小时,30 分钟和 0 秒。
                TimeSpan ts = new TimeSpan(168, 0, 0);
                Context.Response.Cache.SetMaxAge(ts);

                //设置Etag
                //Context.Response.Cache.SetETag(md5.ToLower());
                #endregion

                #region 响应输出
                b = VTSCommon.GetPictureData(imageSavePath);
                Context.Response.OutputStream.Write(b, 0, b.Length);
                #endregion
            }
            else
            {
                #region 修改类型
                Context.Response.ContentType = "image/gif";
                #endregion

                #region 清除缓存
                Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Context.Response.Cache.SetNoStore();
                #endregion

                #region 后台生成
                ImagePackage image = new ImagePackage();
                image.Src      = src;
                image.SavePath = imageSavePath;
                image.Width    = w;
                image.Height   = h;
                image.Model    = model;

                WaitCallback callBack = new WaitCallback(GeneratePicture);
                ThreadPool.QueueUserWorkItem(callBack, image);
                #endregion

                #region 响应输出
                //随机响应
                //imageSavePath = Context.Server.MapPath(string.Concat("/common/images/random/tb", ImageRandom.GetRandomInt().ToString(), ".jpg"));
                imageSavePath = Context.Server.MapPath("/common/images/process/loading.gif");
                b             = VTSCommon.GetPictureData(imageSavePath);
                Context.Response.OutputStream.Write(b, 0, b.Length);
                #endregion
            }
            Context.ApplicationInstance.CompleteRequest();
        }
Ejemplo n.º 23
0
        protected unsafe void Page_Load(object sender, EventArgs e)
        {
            string   str;
            string   str2;
            bool     flag;
            string   str3;
            string   str4;
            int      num;
            int      num2;
            int      num3;
            int      num4;
            string   str5;
            string   str6;
            string   str7;
            string   str8;
            string   str9;
            UserInfo info;
            string   str10;
            UserInfo info2;
            int      num5;

            UserRoles[]   rolesArray;
            UserRoles     roles;
            int           num6;
            string        str11;
            string        str12;
            string        str13;
            HB_ShiCZTItem item;
            HB_ShiCZTItem item2;
            bool          flag2;
            int           num7;
            string        str14;
            string        str15;
            string        str16;
            Exception     exception;
            bool          flag3;
            int           num8;
            bool          flag4;
            DateTime      time;

            UserRoles[] rolesArray2;
            int         num9;

            str = "";
Label_0007:
            try
            {
                str2 = Util.GetString(base.Request, "act", "");
                flag = 0;
                if (flag != null)
                {
                    goto Label_06E8;
                }
                flag = 1;
                if ((("login" == str2) == 0) != null)
                {
                    goto Label_0206;
                }
                if (((this.Session["global_allportal"] == null) == 0) != null)
                {
                    goto Label_0079;
                }
                this.Session["global_allportal"] = SitePortal.GetAllPortal();
Label_0079:
                str3 = Util.GetString(base.Request, "txtUserName", "");
                str4 = Util.GetString(base.Request, "txtPassword", "");
                num  = Util.GetInt(base.Request, "selPortal", 1);
                if ((string.IsNullOrEmpty(str3) == 0) != null)
                {
                    goto Label_00D3;
                }
                str = "请输入用户名!";
                goto Label_0200;
Label_00D3:
                if ((string.IsNullOrEmpty(str4) == 0) != null)
                {
                    goto Label_00EF;
                }
                str = "请输入用户密码!\ttxtUserName";
                goto Label_01FF;
Label_00EF:
                if (((num < 1) == 0) != null)
                {
                    goto Label_0109;
                }
                str = "请选择登陆角色!\tselPortal";
                goto Label_01FE;
Label_0109:
                this.Session["global_pid"] = &num.ToString();
                num2 = FunUtil.Login(this.Page, SitePortal.GetCurrentPortalId(), str3, str4);
                if (((num2 == 0) == 0) != null)
                {
                    goto Label_01A4;
                }
                this.Session["global_pid"]      = &num.ToString();
                this.Session["global_pid2"]     = &num.ToString();
                this.Session["global_username"] = str3;
                this.Session["global_password"] = str4;
                str = "ok";
                goto Label_01FD;
Label_01A4:
                num8 = num2;
                switch ((num8 - 1))
                {
                case 0:
                    goto Label_01CC;

                case 1:
                    goto Label_01D4;

                case 2:
                    goto Label_01DC;

                case 3:
                    goto Label_01E4;

                case 4:
                    goto Label_01EC;

                case 5:
                    goto Label_01F4;
                }
                goto Label_01FC;
Label_01CC:
                str = "帐号不存在\ttxtUserName";
                goto Label_01FC;
Label_01D4:
                str = "密码错误\ttxtPassword";
                goto Label_01FC;
Label_01DC:
                str = "输入有误\ttxtUserName";
                goto Label_01FC;
Label_01E4:
                str = "本帐号已失效,不能登录!\ttxtUserName";
                goto Label_01FC;
Label_01EC:
                str = "当前IP不能登录本帐号\ttxtUserName";
                goto Label_01FC;
Label_01F4:
                str = "本站点当前不允许帐号登录!\ttxtUserName";
                Label_01FC :;
                Label_01FD :;
                Label_01FE :;
                Label_01FF :;
Label_0200:
                goto Label_06E7;
Label_0206:
                if ((("logout" == str2) == 0) != null)
                {
                    goto Label_026E;
                }
                flag4 = 0;
                PageUtil.SetCookie(this.Page, "GWZKJLMM", &flag4.ToString(), 360);
                PageUtil.SetCookie(this.Page, "GWZKUserInfo", "", 360);
                FunUtil.Logout(this.Page);
                str = "ok";
                goto Label_06E7;
Label_026E:
                if ((("changeportal" == str2) == 0) != null)
                {
                    goto Label_03A5;
                }
                num  = Util.GetInt(base.Request, "pid", PersistenceManager.GlobalPortalId);
                str3 = this.Session["global_username"];
                str4 = this.Session["global_password"];
                num3 = PersistenceManager.GlobalPortalId;
                this.Session["global_pid"] = &num.ToString();
                num2 = FunUtil.Login(this.Page, SitePortal.GetCurrentPortalId(), str3, str4);
                if (((num2 == 0) == 0) != null)
                {
                    goto Label_032E;
                }
                this.Session["global_pid"] = &num.ToString();
                str = "ok";
                goto Label_039F;
Label_032E:
                this.Session["global_pid"] = &num3.ToString();
                num8 = num2;
                switch ((num8 - 1))
                {
                case 0:
                    goto Label_036E;

                case 1:
                    goto Label_0376;

                case 2:
                    goto Label_037E;

                case 3:
                    goto Label_0386;

                case 4:
                    goto Label_038E;

                case 5:
                    goto Label_0396;
                }
                goto Label_039E;
Label_036E:
                str = "帐号不存在";
                goto Label_039E;
Label_0376:
                str = "密码错误";
                goto Label_039E;
Label_037E:
                str = "输入有误";
                goto Label_039E;
Label_0386:
                str = "本帐号已失效,不能登录!";
                goto Label_039E;
Label_038E:
                str = "当前IP不能登录本帐号";
                goto Label_039E;
Label_0396:
                str = "本站点当前不允许帐号登录!";
                Label_039E :;
                Label_039F :
                goto Label_06E7;
Label_03A5:
                if ((("register" == str2) == 0) != null)
                {
                    goto Label_06E5;
                }
                num = Util.GetInt(base.Request, "selPortal", 1);
                if ((num == 3) != null)
                {
                    goto Label_03F3;
                }
                str = string.Format("当前仅开放了电厂端系统的用户注册,请返回首页,选择合适的“登陆角色”!", new object[0]);
                goto Label_06E2;
Label_03F3:
                this.Session["global_pid"] = &num.ToString();
                num4 = SitePortal.GetCurrentPortalId();
                str3 = Util.GetString(base.Request, "txt_UserName", "");
                str5 = Util.GetString(base.Request, "txt_Mobile", "");
                str4 = Util.GetString(base.Request, "txt_PasswordCustom", "");
                str6 = Util.GetString(base.Request, "txt_PasswordCustom2", "");
                str7 = Util.GetString(base.Request, "txtYZM", "");
                str8 = Util.GetString(base.Request, "txt_UserType", "");
                if ((string.IsNullOrEmpty(str3) == 0) != null)
                {
                    goto Label_04C0;
                }
                str = string.Format("请输入用户名!\ttxt_UserName", new object[0]);
                goto Label_052F;
Label_04C0:
                str9 = this.Session["SJCode"];
                if ((string.IsNullOrEmpty(str9) == 0) != null)
                {
                    goto Label_04FD;
                }
                str = string.Format("验证码已改变,请点“刷新”按钮!\ttxtYZM", new object[0]);
                goto Label_052E;
Label_04FD:
                if (((str7.ToLower() != str9.ToLower()) == 0) != null)
                {
                    goto Label_052D;
                }
                str = string.Format("验证码不正确,请改正!\ttxtYZM", new object[0]);
                Label_052D :;
                Label_052E :;
Label_052F:
                if ((string.IsNullOrEmpty(str) == 0) != null)
                {
                    goto Label_0563;
                }
                if ((UserInfo.GetUserInfoByUserName(num4, str3) == null) != null)
                {
                    goto Label_0562;
                }
                str = string.Format("用户名“{0}”已存在,请改正!\ttxt_UserName", str3);
                Label_0562 :;
                Label_0563 :
                if ((string.IsNullOrEmpty(str) == 0) != null)
                {
                    goto Label_05B7;
                }
                if ((str5.Length == 11) != null)
                {
                    goto Label_0595;
                }
                str = string.Format("手机号“{0}”不正确,请改正!\ttxt_Mobile", str5);
                goto Label_05B6;
Label_0595:
                if (((str4 != str6) == 0) != null)
                {
                    goto Label_05B6;
                }
                str = string.Format("两次输入的密码不匹配,请改正!\ttxt_PasswordCustom", str5);
                Label_05B6 :;
                Label_05B7 :
                if ((string.IsNullOrEmpty(str) == 0) != null)
                {
                    goto Label_06E1;
                }
                CommonClassDB.ClearAllCache();
                str10              = MD5Encrypt.PasswordEncrypt(str4);
                info2              = new UserInfo();
                info2.PortalId     = num4;
                info2.IsDelete     = 2;
                info2.IsActive     = 1;
                info2.IsSystemUser = 1;
                info2.Status       = 1;
                info2.CreateTime   = &DateTime.Now.Ticks;
                info2.UserName     = str3;
                info2.RealName     = str3;
                info2.Mobile       = str5;
                info2.Password     = str10;
                num5 = CommonClassDB.Instance(info2).set(info2);
                if (((num5 < 1) == 0) != null)
                {
                    goto Label_0673;
                }
                str = string.Format("创建失败,请与管理员联系!", new object[0]);
                goto Label_06E0;
Label_0673:
                rolesArray = UserRoles.GetUserRolesByUser(num5);
                if ((rolesArray == null) != null)
                {
                    goto Label_06BC;
                }
                rolesArray2 = rolesArray;
                num9        = 0;
                goto Label_06AD;
Label_0693:
                roles = rolesArray2[num9];
                UserRoles.Del(roles.get_id());
                num9 += 1;
Label_06AD:
                if ((num9 < ((int)rolesArray2.Length)) != null)
                {
                    goto Label_0693;
                }
Label_06BC:
                UserRoles.SetUserRole("注册用户", -1, 0, num5);
                FunUtil.AutoLloginUser(this.Page, info2);
                str = "ok";
                Label_06E0 :;
                Label_06E1 :;
Label_06E2:
                goto Label_06E7;
Label_06E5:
                flag = 0;
                Label_06E7 :;
                Label_06E8 :
                if (flag != null)
                {
                    goto Label_0CB6;
                }
                flag = 1;
                if ((("sumbit_ZhuTXX" == str2) == 0) != null)
                {
                    goto Label_095C;
                }
                num6 = FunUtil.GetCurrentUserID();
                if (((num6 < 1) == 0) != null)
                {
                    goto Label_0735;
                }
                str = string.Format("请重新登陆系统!\ttxt_Code", new object[0]);
Label_0735:
                num4  = SitePortal.GetCurrentPortalId();
                str11 = Util.GetString(base.Request, "txt_Code", "");
                str12 = Util.GetString(base.Request, "hidden_YingYZZ", "");
                str13 = Util.GetString(base.Request, "hidden_DianLYWXKZ", "");
                if ((((string.IsNullOrEmpty(str11) != null) || (string.IsNullOrEmpty(str12) != null)) ? 0 : (string.IsNullOrEmpty(str13) == 0)) != null)
                {
                    goto Label_07BA;
                }
                str = string.Format("输入不正确,请改正!\ttxt_Code", new object[0]);
Label_07BA:
                item = HB_ShiCZTItem.GetByUserId(num6);
                if (((item == null) == 0) != null)
                {
                    goto Label_080B;
                }
                item            = new HB_ShiCZTItem();
                item.UserId     = num6;
                item.Creator    = num6;
                item.CreateTime = &DateTime.Now.Ticks;
                item.IsDelete   = 2;
                goto Label_082B;
Label_080B:
                item.Modifier   = num6;
                item.ModifyTime = &DateTime.Now.Ticks;
Label_082B:
                if ((string.IsNullOrEmpty(str) == 0) != null)
                {
                    goto Label_0872;
                }
                item2 = HB_ShiCZTItem.GetByName(str11);
                if (((item2 == null) ? 1 : (item2.Id == item.Id)) != null)
                {
                    goto Label_0871;
                }
                str = string.Format("组织机构名称“{0}”已存在,请改正!\ttxt_Code", str11);
                Label_0871 :;
                Label_0872 :
                if ((string.IsNullOrEmpty(str) == 0) != null)
                {
                    goto Label_0956;
                }
                item.Name         = str11;
                item.RecordStatus = 1;
                num5 = CommonClassDB.Instance(item).set(item);
                if (((num5 > 0) == 0) != null)
                {
                    goto Label_094F;
                }
                item  = HB_ShiCZTItem.Get(num5);
                flag2 = 0;
                if (((str12 != "exist") == 0) != null)
                {
                    goto Label_08FB;
                }
                if ((PageUtil.UploadAttachForBootstrap(this.Page, str12, item, "YingYZZ") == 0) != null)
                {
                    goto Label_08FA;
                }
                flag2 = 1;
                Label_08FA :;
                Label_08FB :
                if (((str13 != "exist") == 0) != null)
                {
                    goto Label_0932;
                }
                if ((PageUtil.UploadAttachForBootstrap(this.Page, str13, item, "DianLYWXKZ") == 0) != null)
                {
                    goto Label_0931;
                }
                flag2 = 1;
                Label_0931 :;
                Label_0932 :
                if ((flag2 == 0) != null)
                {
                    goto Label_094E;
                }
                CommonClassDB.Instance(item).set(item);
                Label_094E :;
                Label_094F :
                str = "ok";
Label_0956:
                goto Label_0CB5;
Label_095C:
                if ((("reject_ZhuTXX" == str2) == 0) != null)
                {
                    goto Label_0AF0;
                }
                num6 = FunUtil.GetCurrentUserID();
                if (((num6 < 1) == 0) != null)
                {
                    goto Label_099C;
                }
                str = string.Format("请重新登陆系统!", new object[0]);
Label_099C:
                if (FunUtil.CanExecEntityAction(num6, "SJ.DesktopModules.HB.主体信息审核自动实体", "DianChang_ShiCZT_ZhuTAudit") != null)
                {
                    goto Label_09C1;
                }
                str = string.Format("当前用户没有执行该功能权限({0})!", str2);
Label_09C1:
                num7  = Util.GetInt(base.Request, "id", -1);
                str14 = Util.GetString(base.Request, "txt_Reason", "");
                if ((string.IsNullOrEmpty(str) == 0) != null)
                {
                    goto Label_0A1D;
                }
                if (((num7 < 1) == 0) != null)
                {
                    goto Label_0A1C;
                }
                str = string.Format("参数错误!", new object[0]);
                Label_0A1C :;
                Label_0A1D :
                item = HB_ShiCZTItem.Get(num7);
                if ((string.IsNullOrEmpty(str) == 0) != null)
                {
                    goto Label_0A58;
                }
                if (((item == null) == 0) != null)
                {
                    goto Label_0A57;
                }
                str = string.Format("参数错误!", new object[0]);
                Label_0A57 :;
                Label_0A58 :
                if ((string.IsNullOrEmpty(str) == 0) != null)
                {
                    goto Label_0AEA;
                }
                item.Modifier     = num6;
                item.ModifyTime   = &DateTime.Now.Ticks;
                item.RecordStatus = 0x1f;
                item.Reason       = str14;
                if (((CommonClassDB.Instance(item).set(item) > 0) == 0) != null)
                {
                    goto Label_0AE3;
                }
                UserRoles.RemoveUserFromRoleName("发电企业", -1, 0, item.UserId);
                UserRoles.SetUserRole("注册用户", -1, 0, item.UserId);
Label_0AE3:
                str = "ok";
Label_0AEA:
                goto Label_0CB5;
Label_0AF0:
                if ((("audit_ZhuTXX" == str2) == 0) != null)
                {
                    goto Label_0CB3;
                }
                num6 = FunUtil.GetCurrentUserID();
                if (((num6 < 1) == 0) != null)
                {
                    goto Label_0B30;
                }
                str = string.Format("请重新登陆系统!", new object[0]);
Label_0B30:
                if (FunUtil.CanExecEntityAction(num6, "SJ.DesktopModules.HB.主体信息审核自动实体", "DianChang_ShiCZT_ZhuTAudit") != null)
                {
                    goto Label_0B55;
                }
                str = string.Format("当前用户没有执行该功能权限({0})!", str2);
Label_0B55:
                num7  = Util.GetInt(base.Request, "id", -1);
                str15 = Util.GetString(base.Request, "txt_DiaoDGX_New", "");
                str16 = Util.GetString(base.Request, "txt_EnterDate_New", "");
                if ((string.IsNullOrEmpty(str) == 0) != null)
                {
                    goto Label_0BC8;
                }
                if (((num7 < 1) == 0) != null)
                {
                    goto Label_0BC7;
                }
                str = string.Format("参数错误!", new object[0]);
                Label_0BC7 :;
                Label_0BC8 :
                item = HB_ShiCZTItem.Get(num7);
                if ((string.IsNullOrEmpty(str) == 0) != null)
                {
                    goto Label_0C03;
                }
                if (((item == null) == 0) != null)
                {
                    goto Label_0C02;
                }
                str = string.Format("参数错误!", new object[0]);
                Label_0C02 :;
                Label_0C03 :
                if ((string.IsNullOrEmpty(str) == 0) != null)
                {
                    goto Label_0CB0;
                }
                item.Modifier     = num6;
                item.ModifyTime   = &DateTime.Now.Ticks;
                item.RecordStatus = 3;
                item.DiaoDGX      = str15;
                item.EnterDate    = &Util.ParseDate(str16, DateTime.Now).Ticks;
                if (((CommonClassDB.Instance(item).set(item) > 0) == 0) != null)
                {
                    goto Label_0CA9;
                }
                UserRoles.RemoveUserFromRoleName("注册用户", -1, 0, item.UserId);
                UserRoles.SetUserRole("发电企业", -1, 0, item.UserId);
Label_0CA9:
                str = "ok";
Label_0CB0:
                goto Label_0CB5;
Label_0CB3:
                flag = 0;
                Label_0CB5 :;
                Label_0CB6 :
                if (flag != null)
                {
                    goto Label_0CCB;
                }
                str = string.Format("未知的操作:{0},请与系统管理员联系!", str2);
Label_0CCB:
                goto Label_0CDC;
            }
            catch (Exception exception1)
            {
Label_0CCE:
                exception = exception1;
                str       = exception.Message;
                goto Label_0CDC;
            }
Label_0CDC:
            this.__Return(str);
            return;
        }
Ejemplo n.º 24
0
        public async Task <IResponseOutput> LoginAsync(AuthLoginInput input)
        {
            #region 验证码校验
            var verifyCodeKey = string.Format(CacheKey.VerifyCodeKey, input.VerifyCodeKey);
            var exists        = await _cache.ExistsAsync(verifyCodeKey);

            if (exists)
            {
                var verifyCode = await _cache.GetAsync(verifyCodeKey);

                if (string.IsNullOrEmpty(verifyCode))
                {
                    return(ResponseOutput.NotOk("验证码已过期!", 1));
                }
                if (verifyCode.ToLower() != input.VerifyCode.ToLower())
                {
                    return(ResponseOutput.NotOk("验证码输入有误!", 2));
                }
                await _cache.DelAsync(verifyCodeKey);
            }
            else
            {
                return(ResponseOutput.NotOk("验证码已过期!", 1));
            }
            #endregion

            var user = (await _userRepository.GetAsync(a => a.UserName == input.UserName));
            if (!(user?.Id > 0))
            {
                return(ResponseOutput.NotOk("账号输入有误!", 3));
            }

            #region 解密
            if (input.PasswordKey.NotNull())
            {
                var passwordEncryptKey = string.Format(CacheKey.PassWordEncryptKey, input.PasswordKey);
                var existsPasswordKey  = await _cache.ExistsAsync(passwordEncryptKey);

                if (existsPasswordKey)
                {
                    var secretKey = await _cache.GetAsync(passwordEncryptKey);

                    if (secretKey.IsNull())
                    {
                        return(ResponseOutput.NotOk("解密失败!", 1));
                    }
                    input.Password = DesEncrypt.Decrypt(input.Password, secretKey);
                    await _cache.DelAsync(passwordEncryptKey);
                }
                else
                {
                    return(ResponseOutput.NotOk("解密失败!", 1));
                }
            }
            #endregion

            var password = MD5Encrypt.Encrypt32(input.Password);
            if (user.Password != password)
            {
                return(ResponseOutput.NotOk("密码输入有误!", 4));
            }

            var authLoginOutput = _mapper.Map <AuthLoginOutput>(user);

            return(ResponseOutput.Ok(authLoginOutput));
        }
Ejemplo n.º 25
0
    private void ProcessLogin()
    {
        string website = txtWebsite.Value;


        DAWebUser      mData       = new DAWebUser();
        DAWebFuncGroup mPermission = new DAWebFuncGroup();

        txtUserName.Value  = txtUserName.Value.Trim();
        txtPassword.Value  = txtPassword.Value.Trim();
        lblError.InnerText = "";

        if (txtUserName.Value == "")
        {
            lblError.InnerText = "Bạn chưa nhập tên đăng nhập!";
            return;
        }
        //if (!Utilities.isEmail(txtUserName.Text))
        //{
        //    lblError.InnerText = string.Format(Message.Show("WARNING"), "Địa chỉ email không hợp lệ!");
        //    return;
        //}
        if (txtPassword.Value == "")
        {
            lblError.InnerText = "Bạn chưa nhập mật khẩu!";
            return;
        }
        //Login sai quá số lần cho phép ==> bật hộp thoại yêu cầu nhập mã kiểm tra.
        //if ((pnlRandom.Visible == true) && (!CaptchaGenerator.IsValidText(txtRandom.Text)))
        //{
        //    lblError.InnerText = "Chuỗi kiểm tra không đúng!";
        //    txtRandom.Text = "";
        //    SetCaptcha();
        //    return;
        //}

        String    sPass = MD5Encrypt.EncryptDataMD5(txtPassword.Value, "CMSVTS");
        DataTable dt    = new DataTable();
        Dictionary <string, string> config     = new Dictionary <string, string>();
        Dictionary <Int32, Boolean> permission = new Dictionary <Int32, Boolean>();
        Dictionary <Int32, String>  navigation = new Dictionary <Int32, String>();

        try
        {
            dt.Load(mData.USP_WebUser_Login(txtUserName.Value, sPass));
            if (dt.Rows.Count > 0)
            {
                String RoleID = dt.Rows[0]["Role"].ToString();
                if (Utilities.IsNullOrEmpty(RoleID) || RoleID == "0")
                {
                    lblError.InnerText = string.Format(Message.Show(MessageText.WARNING), "Bạn chưa được cấp quyền truy cập hệ thống!");
                    return;
                }
                else
                {
                    config.Add("WebSite", website);
                    config.Add("UserID", dt.Rows[0]["UserID"].ToString());
                    config.Add("UserName", dt.Rows[0]["UserName"].ToString());
                    config.Add("FullName", dt.Rows[0]["FullName"].ToString());
                    config.Add("PassWord", dt.Rows[0]["PassWord"].ToString());
                    config.Add("Email", dt.Rows[0]["Email"].ToString());
                    config.Add("Role", dt.Rows[0]["Role"].ToString());

                    // load Config
                    DataTable dtconfig = new DataTable();
                    dtconfig = mPermission.USP_webConfig_GetAll(0, 0).Tables[0];
                    if (dtconfig.Rows.Count > 0)
                    {
                        for (int j = 0; j < dtconfig.Rows.Count; j++)
                        {
                            config.Add(dtconfig.Rows[j]["ConfigKey"].ToString(), dtconfig.Rows[j]["ConfigValue"].ToString());
                        }
                    }

                    Session["USysConfig"] = config;

                    // Load permission menu
                    DataTable dtmenu = new DataTable();
                    dtmenu = mPermission.USP_WebFuncGroup_GetFuncbyGroupID(Convert.ToInt32(RoleID)).Tables[0];
                    for (int j = 0; j < dtmenu.Rows.Count; j++)
                    {
                        permission.Add(Convert.ToInt32(dtmenu.Rows[j]["FuncID"]), Convert.ToBoolean(dtmenu.Rows[j]["pView"]));
                        navigation.Add(Convert.ToInt32(dtmenu.Rows[j]["FuncID"]), dtmenu.Rows[j]["UControl"].ToString());
                    }
                    Session["UPermission"]  = permission;
                    Session["UCNavigation"] = navigation;

                    // + Utils.FuncParam()

                    Response.Redirect(WebConfigurationManager.AppSettings["WebHome"] + "/?module=100");
                }
            }
            else
            {
                //if (Session["LoginFail"] != null)
                //    Session["LoginFail"] = (int)Session["LoginFail"] + 1;
                //else
                //    Session["LoginFail"] = 0;
                //if ((int)Session["LoginFail"] > MaxLogin)
                //{
                //    if (!pnlRandom.Visible)
                //        pnlRandom.Visible = true;
                //    else
                //    {
                //        txtRandom.Text = "";
                //        SetCaptcha();
                //    }
                //}
                lblError.InnerText = "Tài khoản hoặc Mật khẩu không đúng!";
                return;
            }
        }
        catch (Exception ex)
        {
            lblError.InnerText = ex.Message;
            return;
        };
    }
Ejemplo n.º 26
0
        public void Test(string input, string except)
        {
            var result = MD5Encrypt.Encrypt(input);

            Assert.Equal(except, result);
        }
Ejemplo n.º 27
0
        private void btn_save_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txt_OldPwd.Text.Trim()))
                {
                    XtraMessageBox.Show("请输入原始密码!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (string.IsNullOrWhiteSpace(txt_NewPwd.Text.Trim()))
                {
                    XtraMessageBox.Show("请输入新密码!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (string.IsNullOrWhiteSpace(txt_NewPwd2.Text.Trim()))
                {
                    XtraMessageBox.Show("请输入确认新密码!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (txt_NewPwd.Text != txt_NewPwd2.Text)
                {
                    XtraMessageBox.Show("两次密码输入不一致!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                using (var db = SugarDao.GetInstance())
                {
                    var userInfo = db.Queryable <Sys_User>().FirstOrDefault(t => t.Id == UserInfo.UserId);
                    if (userInfo == null || userInfo.Id <= 0)
                    {
                        XtraMessageBox.Show("请您重新登录!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    if (userInfo.Password != MD5Encrypt.Encrypt(txt_OldPwd.Text))
                    {
                        XtraMessageBox.Show("原始密码不正确!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    if (db.Update <Sys_User>($"password='******'",
                                             t => t.Id == UserInfo.UserId))
                    {
                        XtraMessageBox.Show("修改成功,请你重新登录!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Application.Exit();
                        return;
                    }
                    else
                    {
                        XtraMessageBox.Show("修改失败!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// 导入题目(不存在时返回null)
        /// </summary>
        /// <param name="request">Http请求</param>
        /// <param name="fileType">文件类型</param>
        /// <param name="uploadType">上传方式</param>
        /// <param name="content">文件内容</param>
        /// <param name="file">上传文件</param>
        /// <returns>题目数据是否插入成功集合(全部失败时为null)</returns>
        public static IMethodResult AdminImportProblem(HttpRequestBase request, String fileType, String uploadType, String content, HttpPostedFileBase file)
        {
            if (!AdminManager.HasPermission(PermissionType.SuperAdministrator))
            {
                throw new NoPermissionException();
            }

            if (!String.Equals("1", fileType))
            {
                return(MethodResult.FailedAndLog("File type is INVALID!"));
            }

            if (String.Equals("1", uploadType))//从文件上传
            {
                if (file == null)
                {
                    return(MethodResult.FailedAndLog("No file was uploaded!"));
                }

                StreamReader sr = new StreamReader(file.InputStream);

                content = sr.ReadToEnd();
            }

            //转换题库模型
            List <ProblemEntity> problems = null;
            List <Byte[]>        datas    = null;
            List <Dictionary <String, Byte[]> > images     = null;
            Dictionary <String, Byte[]>         imagefiles = new Dictionary <String, Byte[]>();

            if (!ProblemImport.TryImportFreeProblemSet(content, out problems, out datas, out images))
            {
                return(MethodResult.FailedAndLog("File content is INVALID!"));
            }

            if (problems == null || problems.Count == 0)
            {
                return(MethodResult.FailedAndLog("No problem was imported!"));
            }

            //处理题目及图片路径
            for (Int32 i = 0; i < problems.Count; i++)
            {
                problems[i].IsHide   = true;
                problems[i].LastDate = DateTime.Now;

                if (images[i] == null)
                {
                    continue;
                }

                String uploadRoot = ConfigurationManager.UploadDirectoryUrl;

                foreach (KeyValuePair <String, Byte[]> pair in images[i])
                {
                    if (pair.Value == null || !pair.Key.Contains("."))
                    {
                        continue;
                    }

                    String oldUrl      = pair.Key;
                    String fileNewName = MD5Encrypt.EncryptToHexString(oldUrl + DateTime.Now.ToString("yyyyMMddHHmmssffff"), true) + pair.Key.Substring(pair.Key.LastIndexOf('.'));
                    String newUrl      = uploadRoot + fileNewName;

                    problems[i].Description = problems[i].Description.Replace(oldUrl, newUrl);
                    problems[i].Input       = problems[i].Input.Replace(oldUrl, newUrl);
                    problems[i].Output      = problems[i].Output.Replace(oldUrl, newUrl);
                    problems[i].Hint        = problems[i].Hint.Replace(oldUrl, newUrl);

                    imagefiles[fileNewName] = pair.Value;
                }
            }

            //将题目插入到数据库
            List <Int32> pids = ProblemRepository.Instance.InsertEntities(problems);

            if (pids == null || pids.Count == 0)
            {
                return(MethodResult.FailedAndLog("Failed to import problem!"));
            }

            //保存题目数据
            Dictionary <Int32, Boolean> dataadded = new Dictionary <Int32, Boolean>();

            for (Int32 i = 0; i < pids.Count; i++)
            {
                if (pids[i] < 0)
                {
                    continue;
                }

                try
                {
                    if (datas[i] != null)
                    {
                        IMethodResult ret = ProblemDataManager.InternalAdminSaveProblemData(pids[i], datas[i]);

                        if (!ret.IsSuccess)
                        {
                            return(ret);
                        }

                        dataadded[pids[i]] = true;
                    }
                }
                catch
                {
                    dataadded[pids[i]] = false;
                }

                ProblemCache.IncreaseProblemSetCountCache();                      //更新缓存
                ProblemCache.IncreaseProblemIDMaxCache();                         //更新缓存
                ProblemCache.RemoveProblemSetCache(GetProblemPageIndex(pids[i])); //删除缓存
            }

            //保存题目图片
            foreach (KeyValuePair <String, Byte[]> pair in imagefiles)
            {
                try
                {
                    UploadsManager.InternalAdminSaveUploadFile(pair.Value, pair.Key);
                }
                catch { }
            }

            return(MethodResult.SuccessAndLog <Dictionary <Int32, Boolean> >(dataadded, "Admin import problem, id = {0}", String.Join(",", pids)));
        }
        public async Task <IResponseOutput> Login(LoginInput input)
        {
            if (!ModelState.IsValid)
            {
                return(ResponseOutput.NotOk(ModelState.Values.First().Errors[0].ErrorMessage));
            }

            var sw = new Stopwatch();

            sw.Start();

            var context = await _interaction.GetAuthorizationContextAsync(input.ReturnUrl);

            var user = await _userRepository.Select.Where(a => a.UserName == input.UserName)
                       .ToOneAsync(a => new { a.Id, a.Password, a.NickName });

            if (user == null)
            {
                return(ResponseOutput.NotOk("", 1));
            }

            var password = MD5Encrypt.Encrypt32(input.Password);

            if (user.Password != password)
            {
                return(ResponseOutput.NotOk("", 2));
            }


            AuthenticationProperties props = null;

            if (input.RememberLogin)
            {
                props = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(1))
                };
            }
            ;

            var identityServerUser = new IdentityServerUser(user.Id.ToString())
            {
                DisplayName = input.UserName
            };

            await HttpContext.SignInAsync(identityServerUser, props);

            sw.Stop();

            //写登录日志
            var loginLogEntity = new LoginLogEntity()
            {
                CreatedUserId       = user.Id,
                NickName            = user.NickName,
                CreatedUserName     = input.UserName,
                ElapsedMilliseconds = sw.ElapsedMilliseconds,
                Status = true
            };

            await AddLoginLog(loginLogEntity);

            return(ResponseOutput.Ok());
        }
Ejemplo n.º 30
0
 /// <summary>
 /// 获取最终加密后的密码密文。
 /// </summary>
 /// <param name="password">明文密码。</param>
 /// <param name="seed"></param>
 /// <returns></returns>
 public static string GetEncryptPassword(string password, out string seed)
 {
     return(EncryptPassword(MD5Encrypt.GetMD5(password), out seed));
 }
Ejemplo n.º 31
0
 private void btnSave_Click(object sender, EventArgs e)
 {
     if (String.IsNullOrEmpty(txtOperatorName.Text.Trim()))
     {
         MessageBox.Show("操作名称不许为空!", "软件提示");
         txtOperatorName.Focus();
         return;
     }
     if (String.IsNullOrEmpty(txtPassword.Text))
     {
         MessageBox.Show("操作密码不许为空!", "软件提示");
         txtPassword.Focus();
         return;
     }
     if (!(txtPassword.Text == txtAffirmPassword.Text))
     {
         MessageBox.Show("确认密码与操作密码不相同!", "软件提示");
         txtAffirmPassword.Focus();
         return;
     }
     if (this.Tag.ToString() == "Add")
     {
         DataGridViewRow dgvr = cc.AddDataGridViewRow(formOperator.dgvOperator, formOperator.bsOperator);
         dgvr.Cells["OperatorCode"].Value = txtOperatorCode.Text;
         dgvr.Cells["OperatorName"].Value = txtOperatorName.Text.Trim();
         dgvr.Cells["Password"].Value     = MD5Encrypt.GetMD5Password(txtPassword.Text);
         dgvr.Cells["IsFlag"].Value       = "0";
         if (cc.Commit(formOperator.dgvOperator, formOperator.bsOperator))
         {
             if (MessageBox.Show("保存成功,是否继续添加?", "软件提示", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
             {
                 txtOperatorCode.Text   = cc.BuildCode("tb_Operator", "Where OperatorCode <> 'mr'", "OperatorCode", "", 4);
                 txtOperatorName.Text   = "";
                 txtPassword.Text       = "";
                 txtAffirmPassword.Text = "";
             }
             else
             {
                 this.Close();
             }
         }
         else
         {
             MessageBox.Show("保存失败!", "软件提示");
         }
     }
     if (this.Tag.ToString() == "Edit")
     {
         DataGridViewRow dgvr = formOperator.dgvOperator.CurrentRow;
         dgvr.Cells["OperatorName"].Value = txtOperatorName.Text.Trim();
         if (cc.Commit(formOperator.dgvOperator, formOperator.bsOperator))
         {
             MessageBox.Show("保存成功!", "软件提示");
             this.Close();
         }
         else
         {
             MessageBox.Show("保存失败!", "软件提示");
         }
     }
 }