ERP登录(八)
登录的存储过程:
ALTER PROCEDURE [dbo].[UserLogin] @userid int output, @LoginName nvarchar(50), @Password nvarchar(50) AS BEGIN SET NOCOUNT ON; DECLARE @count int --查询指定表,返回符合条件的个数 SELECT @count=count(*) FROM UserManager WHERE LoginName=@LoginName AND Password=@Password -- PRINT '行数:'+convert(varchar(10),@count) --判断是否有用户,如果有则返回用户ID,否则返回0 IF (@count!=0) begin select @userid=UserId FROM UserManager WHERE LoginName=@LoginName AND Password=@Password END ELSE BEGIN SET @userid=0 END END
业务层的代码:
/// <summary> /// 用户登录,返回符合登录名和密码的用户的条数 /// </summary> /// <param name="LoginName">登录名</param> /// <param name="Pwd">登录密码</param> /// <returns>int</returns> public int UserLogin(string LoginName, string Pwd) { SqlParameter []pars = new SqlParameter[]{ new SqlParameter("@userid",SqlDbType.Int), new SqlParameter("@LoginName",LoginName), new SqlParameter("@Password",Pwd) };
//指定为输出参数 pars[0].Direction = ParameterDirection.Output; DataBaseHelper.SelectSQLReturnObject("UserLogin", CommandType.StoredProcedure, pars); //object count = DataBaseHelper.SelectSQLReturnObject("UserLogin", CommandType.StoredProcedure, pars); //if (count != null) //{ // return int.Parse(count.ToString()); //} //return 0; if (pars[0].Value.ToString() != "0") { return int.Parse(pars[0].Value.ToString()); } else { return 0; } }
前台代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserLogin.aspx.cs" Inherits="BioErpWeb.Web.UserLogin" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <link rel="stylesheet" type="text/css" href="css/Login.css" /> <script src="js/jquery.js" type="text/javascript"></script> <script src="js/jquery-cookieplug.js" type="text/javascript"></script> <style type="text/css"> TABLE { font-size: 12px; color: #333333; line-height: 150%; font-family: "宋体"; } BODY { margin: 0px; } .style1 { width: 50px; } .style2 { width: 155px; } .style3 { width: 50px; height: 60px; } .style4 { width: 155px; height: 60px; } .fl{ clear:left;} </style> </head> <body leftmargin="0" background="images/bg.gif" topmargin="0"> <form id="form1" runat="server"> <div align="center"> <table cellspacing="0" cellpadding="0" width="913" border="0"> <tbody> <tr> <td width="461" style="height: 465px" valign="top"> <table cellspacing="0" cellpadding="0" width="100%" border="0"> <tbody> <tr> <td> <div align="left"> <img height="80" src="images/log_mykd_n.gif" width="212"></div> </td> </tr> <tr> <td> <img height="110" src="images/ren1_n.gif" width="461"> </td> </tr> <tr> <td> <img height="230" src="images/ren2.jpg" width="461"> </td> </tr> </tbody> </table> </td> <td valign="top" style="height: 465px"> <table cellspacing="0" cellpadding="0" width="100%" border="0"> <tbody> <tr> <td valign="bottom" height="190"> <img height="32" src="images/pic_text.gif" width="381"> </td> </tr> </tbody> </table> <table cellspacing="0" cellpadding="0" width="100%" border="0"> <tbody> <tr> <td valign="top" background="images/con1.gif"> <table style="margin-top: 37px; margin-left: 8px" cellspacing="0" cellpadding="0" width="100%" border="0"> <tbody> <tr> <td> <img height="34" src="images/pic_text_login.gif" width="253"> </td> </tr> <tr> <td> <table style="margin-top: 10px; width: 379px;" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr> <td nowrap class="style1"> 用户: </td> <td style="text-align:left;" class="style2"> <asp:TextBox ID="txtUserName" runat="server" Width="100px"></asp:TextBox> <label> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtUserName" ErrorMessage='<img src="images/false.gif">'></asp:RequiredFieldValidator></label> </td> </tr> <tr style="padding-top: 5px"> <td class="style1"> 密码: </td> <td style="text-align:left;" class="style2"> <asp:TextBox ID="txtPwd" Width="100px" TextMode="Password" runat="server"></asp:TextBox> <label> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtPwd" ErrorMessage='<img src="images/false.gif">'></asp:RequiredFieldValidator></label> </td> </tr> <tr> <td> 验证码: </td> <td style="text-align:left;"> <asp:TextBox ID="txtValidate" Width="100px" runat="server"></asp:TextBox> <asp:ImageButton ID="imgbtnValidate" Width="150px" ImageUrl="~/Web/ViewImg.aspx" runat="server" onclick="imgbtnValidate_Click" CausesValidation="false" /> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" Width="10px" runat="server" ControlToValidate="txtValidate" ErrorMessage='<img src="images/false.gif">'></asp:RequiredFieldValidator> </td> </tr> <tr> <td> </td> <td style=" padding:3px;"> <table cellspacing="0" cellpadding="0" width="100%" border="0"> <tbody> <tr> <td> <div align="left"> <asp:ImageButton ID="LoginButton" ImageUrl="images/but1.gif" runat="server" onclick="LoginButton_Click" /> </div> </td> </tr> <tr> <td> <div align="left"> <img height="18" src="images/but1_y.gif" width="83"></div> </td> </tr> <tr> <td> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> <td width="22"> <img height="229" src="images/con2.gif" width="22"> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <table cellspacing="0" cellpadding="0" width="913" align="center" border="0"> <tbody> <tr> <td style="padding-bottom: 10px" valign="bottom" height="180"> <div align="center"> <font color="#999999">成都Bio公司ERP系统.版权所有 2011-2012<br> 请使用IE6.0 SP1以上浏览器,最佳显示分辨率1024×768</font></div> </td> </tr> </tbody> </table> </div> </form> </body> </html>
验证码的流程图:
验证码的代码:
public partial class ViewImg : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string chcode = ""; //颜色列表,用于验证码,噪线,躁点的绘制 Color[] colors = { Color.Black, Color.Red, Color.Green, Color.Orange, Color.Yellow, Color.DarkBlue }; //字体列表,用于验证码 string[] font = { "Times New Roman", "MS MinCho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" }; //验证码的字符集,去掉容易混淆的字符 char[] Character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' }; Random random = new Random(); //随机生成验证码 for (int i = 0; i < 4; i++) { chcode += Character[random.Next(Character.Length)]; } //保存验证码 Cookie HttpCookie anycookie = new HttpCookie("ValidateCookie"); anycookie.Values.Add("Chcode", chcode); HttpContext.Current.Response.Cookies["ValidateCookie"].Values["Chcode"] = chcode; Bitmap bmp = new Bitmap(150, 30); Graphics g = Graphics.FromImage(bmp); //清空内容 g.Clear(Color.White); //画噪音线 for (int i = 0; i < 5; i++) { int x1 = random.Next(150); int y1 = random.Next(30); int x2 = random.Next(150); int y2 = random.Next(30); Color clr = colors[random.Next(colors.Length)]; g.DrawLine(new Pen(clr), x1, y1, x2, y2); } //画验证码字符串 for (int i = 0; i < chcode.Length; i++) { string fontsytle = font[random.Next(font.Length)]; Font fnt = new Font(fontsytle, 16); Color fcolor = colors[random.Next(colors.Length)]; g.DrawString(chcode[i].ToString(), fnt, new SolidBrush(fcolor), i * 20 + 20, 6); } //画噪点 for (int i = 0; i < 100; i++) { int x = random.Next(bmp.Width); int y = random.Next(bmp.Height); Color fcolor = colors[random.Next(colors.Length)]; bmp.SetPixel(x, y, fcolor); } //清除该页输出缓存,设置该页无缓存 Response.Buffer = true; Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0); Response.Expires = 0; Response.CacheControl = "no-cache"; Response.AppendHeader("Pragma", "No-Cache"); //把验证码图片写入到内存中,并以图片格式输出("imgae/png"); MemoryStream stream = new MemoryStream(); try { bmp.Save(stream, ImageFormat.Png); Response.ClearContent(); Response.ContentType = "Image/png"; Response.BinaryWrite(stream.ToArray()); } finally { bmp.Dispose(); g.Dispose(); } } }
登录的代码:
public partial class UserLogin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void LoginButton_Click(object sender, ImageClickEventArgs e) { if (Request.Cookies["ValidateCookie"].Values["Chcode"].ToString().ToLower() != this.txtValidate.Text.Trim().ToLower()) { ClientScript.RegisterStartupScript(this.GetType(), "test", "<script>alert('请输入正确的验证码')</script>"); imgbtnValidate.ImageUrl = "ViewImg.aspx"; return; } string Username = this.txtUserName.Text; string Pwd = this.txtPwd.Text; UserManagerBLL userbll = new UserManagerBLL(); int userid= userbll.UserLogin(Username, Comm.MD5(Pwd)); if (userid != 0) { //获取用户iD Session["Userid"] = userid.ToString(); ClientScript.RegisterStartupScript(this.GetType(), "test", "<script>alert('" + Session["Userid"] + "')</script>"); Response.Redirect("Index.aspx"); } } /// <summary> /// 给验证码注册一个点击跳转事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void imgbtnValidate_Click(object sender, ImageClickEventArgs e) { imgbtnValidate.ImageUrl = "ViewImg.aspx"; } }
用户权限绑定菜单:
设计方案:
-- Description: 根据权限id获取权限信息 -- ============================================= ALTER PROCEDURE [dbo].[getRightById] @id int AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; SELECT ID, RightName, ReMark FROM tbRight WHERE ID=@id END
BLL层:
/// <summary> /// 根据指定ID返回其对象 /// </summary> /// <param name="id">userid</param> /// <returns>UserManager</returns> public UserManager getuserbyId(string id) { UserManager user = new UserManager(); SqlParameter[] pars = new SqlParameter[]{ new SqlParameter("@userid",id) }; SqlDataReader reader = DataBaseHelper.SelectSQLReturnReader("getUserByid", CommandType.StoredProcedure, pars); while (reader.Read()) { user.LoginName = reader["LoginName"].ToString(); user.UserName = reader["UserName"].ToString(); user.DepartmentId =int.Parse(reader["DepartmentId"].ToString()); user.RoleId = int.Parse(reader["RoleId"].ToString()); user.Birthday =Convert.ToDateTime(reader["Birthday"].ToString()); user.Mobile = reader["Mobile"].ToString(); user.Email = reader["Email"].ToString(); user.Photo = reader["Photo"].ToString(); user.Address = reader["Address"].ToString(); user.LastLoginDate = Convert.ToDateTime(reader["LastLoginDate"].ToString()); user.Sex = reader["Sex"].ToString() == "True" ? true : false; user.DisplayOrder =int.Parse( reader["DisplayOrder"].ToString()); user.Sate = reader["Sate"].ToString() == "True" ? true : false; } reader.Close(); return user; }
创建菜单的时候进行权限的筛选:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { CreateTreeVeiw(); TreeView1.NodeStyle.Font.Size = FontUnit.Parse("13px"); } } DataSet ds; DataTable dt; private void CreateTreeVeiw() { UserRightMangerBLL userrightbll=new UserRightMangerBLL(); DataTable RightList=userrightbll.getUserRightListByUserID(Session["Userid"].ToString()); string UserRightList=""; for(int i=0;i<RightList.Rows.Count;i++) { UserRightList +=RightList.Rows[i]["RightID"].ToString()+","; } //0 修改自己密码权限 UserRightList=UserRightList+"0"; ds = SqlComm.GetDataByCondition("TreeMenu", "NodeId,ParentId,Text,Url,Duty", " Duty in (" + UserRightList + ")"); dt = new DataTable(); dt = ds.Tables[0]; DataView dv = new DataView(dt, "ParentId=0", "NodeId", DataViewRowState.CurrentRows); //遍历父节点 foreach (DataRowView d in dv) { TreeNode n = new TreeNode(d["Text"].ToString(), d["Url"].ToString()); n.NavigateUrl = d["Url"].ToString(); n.ImageToolTip = dt.TableName; n.Target = "MainFrame"; TreeView1.Nodes.Add(n); n.Expanded = false; //根据父节点筛选出对应的子节点 dv = new DataView(dt, "ParentId='" + d["NodeId"] + "'", "NodeId", DataViewRowState.CurrentRows); if (dv.Count>0) { CreateSubTreeView(n, dv); } } }
先加载Index页面:
protected void Page_Load(object sender, EventArgs e) { if (Session["Userid"] == null) { Server.Transfer("UserLogin.aspx"); return; } }
创建外键约束的方法:
.