【无私分享:从入门到精通ASP.NET MVC】从0开始,一起搭框架、做项目(5.4) 登录功能的实现,创建与登录用户相关的接口和实现类

索引

【无私分享:从入门到精通ASP.NET MVC】从0开始,一起搭框架、做项目 目录索引

简述

今天我们创建几个与登录用户相关的数据表的接口和实现类

项目准备

我们用的工具是:VS 2013 + SqlServer 2012 + IIS7.5

希望大家对ASP.NET MVC有一个初步的理解,理论性的东西我们不做过多解释,有些地方不理解也没关系,会用就行了,用的多了,用的久了,自然就理解了。

项目开始

一、新建登录用户类Account

我们在(5.2)中我们登录验证直接返回了管理员实体类Domain.SYS_USER,但是在实际的后台操作验证中,我们并不需要SYS_USER的许多属性,同时我们需要它的一些扩展属性,我们来新建一个管理员类,来具体的描述这个管理员,我们在Service类库下面新建一个管理类Account.cs

 

 

代码:

 1 using System.Collections.Generic;
 2 
 3 namespace Service
 4 {
 5     /// <summary>
 6     /// 通用用户登录类,简单信息
 7     /// </summary>
 8     public class Account
 9     {
10         #region Attribute
11         /// <summary>
12         /// 主键
13         /// </summary>
14         public int Id { get; set; }
15         /// <summary>
16         /// 姓名
17         /// </summary>
18         public string Name { get; set; }
19         /// <summary>
20         /// 登录的用户名
21         /// </summary>
22         public string LogName { get; set; }
23         /// <summary>
24         /// 登录密码
25         /// </summary>
26         public string PassWord { get; set; }
27         /// <summary>
28         /// 是否管理员
29         /// </summary>
30         public bool IsAdmin { get; set; }
31         /// <summary>
32         /// 用户头像
33         /// </summary>
34         public string Face_Img { get; set; }
35         /// <summary>
36         /// 用户主部门
37         /// </summary>
38         public Domain.SYS_DEPARTMENT DptInfo { get; set; }
39         /// <summary>
40         /// 用户所在部门集合
41         /// </summary>
42         public List<Domain.SYS_DEPARTMENT> Dpt { get; set; }
43         /// <summary>
44         /// 权限集合
45         /// </summary>
46         public List<Domain.SYS_PERMISSION> Permissions { get; set; }
47         /// <summary>
48         /// 角色的集合
49         /// </summary>
50         public List<Domain.SYS_ROLE> Roles { get; set; }
51         /// <summary>
52         /// 用户岗位集合
53         /// </summary>
54         public List<Domain.SYS_POST_USER> PostUser { get; set; }
55         /// <summary>
56         /// 用户可操作的模块集合
57         /// </summary>
58         public List<Domain.SYS_MODULE> Modules { get; set; }
59         #endregion
60     }
61 }
View Code

 

 

二、修改我们的用户管理接口IUserManage

修改我们的用户管理接口IUserManage 添加几个方法:根据用户ID获取本职部门名称、 删除用户、根据用户构造用户基本信息、从Cookie中获取用户信息

 

代码:

 1  /// <summary>
 2         /// 根据用户ID获取本职部门名称
 3         /// </summary>
 4         string GetUserDptName(int id);
 5         /// <summary>
 6         /// 删除用户
 7         /// </summary>
 8         bool Remove(int userId);
 9         /// <summary>
10         /// 根据用户构造用户基本信息
11         /// </summary>
12         Account GetAccountByUser(Domain.SYS_USER user);
13         /// <summary>
14         /// 从Cookie中获取用户信息
15         /// </summary>
16         Account GetAccountByCookie();
View Code

 

三、我们分别创建几个关联表的接口和实现类

创建SYS_USERINFO(用户档案)、SYS_USER_ROLE(用户角色)、SYS_USER_PERMISSION(用户权限)、SYS_POST_USER(用户岗位)、SYS_USER_DEPARTMENT(用户部门)、SYS_PERMISSION(权限表)、SYS_DEPARTMENT(部门表)、SYS_MODULE(模块表)的接口和实现类

这两天没怎么发布东西,一是工作太忙,二是我提前把这些东西都写好了,测试了一下,可能写的会有些不合理,希望大家指正,我先贴出来,注释我都写了,大家可以先预想一下这些都是干什么用的,下一篇我们完成我们的登录功能,使用到了这些东西就一目了然了。

IUserInfoManage、UserInfoManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Service.IService
 8 {
 9     public interface IUserInfoManage:IRepository<Domain.SYS_USERINFO>
10     {
11     }
12 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.ServiceImp
 7 {
 8     /// <summary>
 9     /// Service层用户拓展信息接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public class UserInfoManage : RepositoryBase<Domain.SYS_USERINFO>,IService.IUserInfoManage
13     {
14     }
15 }
View Code

 

IUserRoleManage、UserRoleManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Service.IService
 8 {
 9     /// <summary>
10     /// Service层用户与角色关系接口
11     /// add yuangang by 2016-05-19
12     /// </summary>
13     public interface IUserRoleManage:IRepository<Domain.SYS_USER_ROLE>
14     {
15         /// <summary>
16         /// 设置用户角色
17         /// add yuangang by 2016-05-19
18         /// </summary>
19         /// <param name="userId">用户ID</param>
20         /// <param name="roleId">角色ID字符串</param>
21         /// <returns></returns>
22         bool SetUserRole(int userId, string roleId);
23     }
24 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.ServiceImp
 7 {
 8     /// <summary>
 9     /// Service层用户与角色关系接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public class UserRoleManage : RepositoryBase<Domain.SYS_USER_ROLE>,IService.IUserRoleManage
13     {
14         /// <summary>
15         /// 设置用户角色
16         /// add yuangang by 2016-05-19
17         /// </summary>
18         /// <param name="userId">用户ID</param>
19         /// <param name="roleId">角色ID字符串</param>
20         public bool SetUserRole(int userId, string roleId)
21         {
22             try
23             {
24                 //1、删除用户角色
25                 this.Delete(p => p.FK_USERID == userId);
26                 //2、设置当前用户的角色
27                 if (string.IsNullOrEmpty(roleId)) return true;
28                 foreach (var entity in roleId.Split(',').Select(t => new Domain.SYS_USER_ROLE()
29                 {
30                     FK_USERID = userId,
31                     FK_ROLEID = int.Parse(t)
32                 }))
33                 {
34                     this.dbSet.Add(entity);
35                 }
36                 return this.Context.SaveChanges() > 0;
37             }
38             catch (Exception e) { throw e; }
39         }
40     }
41 }
View Code

 

IUserPermissionManage、UserPermissionManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// Service层用户授权接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public interface IUserPermissionManage : IRepository<Domain.SYS_USER_PERMISSION>
13     {
14         /// <summary>
15         /// 设置用户权限
16         /// add yuangang by 2016-05-19
17         /// </summary>
18         /// <param name="userId">用户ID</param>
19         /// <param name="newper">权限字符串</param>
20         /// <param name="sysId">系统ID</param>
21         /// <returns></returns>
22         bool SetUserPermission(int userId, string newper, string sysId);
23     }
24 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using Service.IService;
 6 
 7 namespace Service.ServiceImp
 8 {
 9     /// <summary>
10     /// Service层用户授权接口
11     /// add yuangang by 2016-05-19
12     /// </summary>
13     public class UserPermissionManage : RepositoryBase<Domain.SYS_USER_PERMISSION>,IService.IUserPermissionManage
14     {
15         IPermissionManage PermissionManage { get; set; }
16         /// <summary>
17         /// 保存用户权限
18         /// </summary>
19         public bool SetUserPermission(int userId, string newper, string sysId)
20         {
21             try
22             {
23                 //1、获取当前系统的模块ID集合
24                 var permissionId = this.PermissionManage.GetPermissionIdBySysId(sysId).Cast<int>().ToList();
25                 //2、获取用户权限,是否存在,存在即删除
26                 if (this.IsExist(p => p.FK_USERID == userId && permissionId.Any(e => e == p.FK_PERMISSIONID)))
27                 {
28                     //3、删除用户权限
29                     this.Delete(p => p.FK_USERID == userId && permissionId.Any(e => e == p.FK_PERMISSIONID));
30                 }
31                 //4、添加用户权限
32                 var str = newper.Trim(',').Split(',');
33                 foreach (var per in str.Select(t => new Domain.SYS_USER_PERMISSION()
34                 {
35                     FK_USERID = userId,
36                     FK_PERMISSIONID = int.Parse(t)
37                 }))
38                 {
39                     this.dbSet.Add(per);
40                 }
41                 //5、Save
42                 return this.Context.SaveChanges() > 0;
43             }
44             catch (Exception e) { throw e; }
45         }
46     }
47 }
View Code

 

IPostUserManage、PostUserManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// 岗位用户关系业务接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public interface IPostUserManage : IRepository<Domain.SYS_POST_USER>
13     {
14         /// <summary>
15         /// 根据岗位ID获取人员集合,可传递多个岗位ID
16         /// </summary>
17         List<Domain.SYS_USER> GetUserListByPostId(string postId);
18         /// <summary>
19         /// 根据人员ID获取岗位集合,可传递多个
20         /// </summary>
21         List<Domain.SYS_POST> GetPostListByUserId(string userId);
22         /// <summary>
23         /// 添加岗位人员关系
24         /// </summary>
25         /// <param name="userId">人员ID</param>
26         /// <param name="postId">岗位ID集合</param>
27         /// <returns></returns>
28         bool SavePostUser(int userId, string postId);
29         /// <summary>
30         /// 根据岗位集合获取岗位名称,部门-岗位模式        
31         /// </summary>
32         dynamic GetPostNameBySysPostUser(ICollection<Domain.SYS_POST_USER> collection);
33 
34     }
35 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.ServiceImp
 7 {
 8     /// <summary>
 9     /// 岗位人员关系业务实现类
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public class PostUserManage : RepositoryBase<Domain.SYS_POST_USER>, IService.IPostUserManage
13     {
14         /// <summary>
15         /// 根据岗位ID获取人员列表
16         /// </summary>
17         public List<Domain.SYS_USER> GetUserListByPostId(string postId)
18         {
19             try
20             {
21                 string sql = @"select * from sys_user t where exists(select u.fk_userid from sys_post_user u
22                                 inner join sys_post_department p
23                                 on u.fk_post_departmentid=p.id
24                                 where t.id=u.fk_userid and p.fk_post_id in (" + postId + ")  group by u.fk_userid)";
25                 return this.SelectBySql<Domain.SYS_USER>(sql);
26             }
27             catch (Exception e) { throw e.InnerException; }
28         }
29         /// <summary>
30         /// 根据用户ID获取所持有的岗位集合
31         /// </summary>
32         public List<Domain.SYS_POST> GetPostListByUserId(string userId)
33         {
34             return this.LoadAll(p => userId.Contains(p.FK_USERID.ToString())).Select(p => p.SYS_POST_DEPARTMENT.SYS_POST).ToList();
35         }
36 
37         /// <summary>
38         /// 添加岗位人员关系
39         /// </summary>
40         /// <param name="userId">人员ID</param>
41         /// <param name="postId">岗位ID集合</param>
42         /// <returns></returns>
43         public bool SavePostUser(int userId, string postId)
44         {
45             try
46             {
47                 if (this.IsExist(p => p.FK_USERID == userId))
48                 {
49                     //存在之后再对比是否一致 
50                     var oldCount = this.LoadAll(p => p.FK_USERID == userId).Select(p => p.FK_POST_DEPARTMENTID).ToList().Cast<int>().ToList();
51                     var newpostId = postId.Trim(',').Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToList();
52                     if (oldCount.Count == newpostId.Count && oldCount.All(newpostId.Contains)) return true;
53                     //删除原有关系
54                     this.Delete(p => p.FK_USERID == userId);
55                 }
56                 if (!string.IsNullOrEmpty(postId))
57                 {
58                     //添加现有关系
59                     var list = postId.Split(',').Select(item => new Domain.SYS_POST_USER()
60                     {
61                         FK_USERID = userId,
62                         FK_POST_DEPARTMENTID =int.Parse(item)
63                     }).ToList();
64                     return this.SaveList(list) > 0;
65                 }
66                 return true;
67             }
68             catch (Exception e) { throw e.InnerException; }
69         }
70 
71         /// <summary>
72         /// 根据岗位集合获取岗位名称,部门-岗位模式        
73         /// </summary>
74         public dynamic GetPostNameBySysPostUser(ICollection<Domain.SYS_POST_USER> collection)
75         {
76             //岗位部门关系ID集合
77             string post_departmentid = collection.Select(p => p.FK_POST_DEPARTMENTID).Aggregate(string.Empty, (current, t) => current + "'" + t + "',").TrimEnd(',');
78             try
79             {
80                 string sql = @"select d.name+'-'+p.postname as postname,s.id from sys_department d inner join
81                         sys_post_department s on d.id=s.fk_department_id
82                         inner join sys_post p on p.id=s.fk_post_id 
83                         where s.id in (" + post_departmentid + ")";
84                 return this.ExecuteSqlQuery(sql);
85             }
86             catch (Exception e) { throw e.InnerException; }
87         }
88     }
89 }
View Code

 

IUserDepartmentManage、UserDepartmentManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// 用户部门关系业务接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public interface IUserDepartmentManage : IRepository<Domain.SYS_USER_DEPARTMENT>
13     {
14         /// <summary>
15         /// 根据部门ID获取当前部门的所有用户集合
16         /// </summary>
17         List<Domain.SYS_USER> GetUserListByDptId(List<string> dptId);
18         /// <summary>
19         /// 根据用户ID获取所在的部门集合
20         /// </summary>
21         List<Domain.SYS_DEPARTMENT> GetDptListByUserId(int userId);
22         /// <summary>
23         /// 保存用户部门关系
24         /// </summary>
25         /// <param name="userId">用户ID</param>
26         /// <param name="dptId">部门ID集合</param>
27         /// <returns></returns>
28         bool SaveUserDpt(int userId, string dptId);
29     }
30 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.ServiceImp
 7 {
 8     /// <summary>
 9     /// 用户部门关系业务实现类
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public class UserDepartmentManage:RepositoryBase<Domain.SYS_USER_DEPARTMENT>,IService.IUserDepartmentManage
13     {
14         /// <summary>
15         /// 根据部门ID获取当前部门的所有用户ID集合
16         /// </summary>
17         public List<Domain.SYS_USER> GetUserListByDptId(List<string> dptId)
18         {
19             return this.LoadAll(p => dptId.Contains(p.DEPARTMENT_ID)).Select(p => p.SYS_USER).ToList();
20         }
21         /// <summary>
22         /// 根据用户ID获取所在的部门ID集合
23         /// </summary>
24         public List<Domain.SYS_DEPARTMENT> GetDptListByUserId(int userId)
25         {
26             return this.LoadAll(p => p.USER_ID == userId).Select(p=>p.SYS_DEPARTMENT).ToList();
27         }
28 
29         /// <summary>
30         /// 保存用户部门关系
31         /// </summary>
32         /// <param name="userId">用户ID</param>
33         /// <param name="dptId">部门ID集合</param>
34         public bool SaveUserDpt(int userId, string dptId)
35         {
36             try
37             {
38                 //原始部门人员关系是否与当前设置一致,不一致重新构造
39                 if (this.IsExist(p => p.USER_ID == userId))
40                 {
41                     //存在之后再对比是否一致 
42                     var oldCount = this.LoadAll(p => p.USER_ID == userId && dptId.Contains(p.DEPARTMENT_ID)).Select(p => p.DEPARTMENT_ID).ToList();
43                     var newdptid = dptId.Split(',').OrderBy(c => c).ToList();
44                     if (oldCount.Count == newdptid.Count && oldCount.All(newdptid.Contains)) return true;
45                     //删除原有关系
46                     this.Delete(p => p.USER_ID == userId);
47                 }
48                 if (!string.IsNullOrEmpty(dptId))
49                 {
50                     //添加现有关系
51                     var list = dptId.Split(',').Select(item => new Domain.SYS_USER_DEPARTMENT()
52                     {
53                         DEPARTMENT_ID = item,
54                         USER_ID = userId
55                     }).ToList();
56                     return this.SaveList(list) > 0;
57                 }
58                 return true;
59             }
60             catch (Exception e) { throw e.InnerException; }
61         }
62     }
63 }
View Code

 

IPermissionManage、PermissionManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// Service 授权验证模块对应接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public interface IPermissionManage : IRepository<Domain.SYS_PERMISSION>
13     {
14         /// <summary>
15         /// 根据系统ID获取所有模块的权限ID集合
16         /// </summary>
17         List<int> GetPermissionIdBySysId(string sysId);
18     }
19 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Data.Common;
 4 using System.Data.SqlClient;
 5 using System.Linq;
 6 using System.Text;
 7 
 8 namespace Service.ServiceImp
 9 {
10     /// <summary>
11     /// Service 授权模块关系处理类
12     /// add yuangang by 2016-05-19
13     /// </summary>
14     public class PermissionManage : RepositoryBase<Domain.SYS_PERMISSION>, IService.IPermissionManage
15     {
16         /// <summary>
17         /// 根据系统ID获取所有模块的权限ID集合
18         /// </summary>
19         public List<int> GetPermissionIdBySysId(string sysId)
20         {
21             try
22             {
23                 string sql = "select p.id from sys_permission p where exists(select 1 from sys_module t where t.fk_belongsystem=@sysid and t.id=p.moduleid)";
24                 DbParameter para = new SqlParameter("@sysid", sysId);
25                 return this.SelectBySql<int>(sql, para);
26             }
27             catch (Exception e)
28             {
29                 throw e;
30             }
31         }
32     }
33 }
View Code

 

IDepartmentManage、DepartmentManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// Service层部门管理接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public interface IDepartmentManage : IRepository<Domain.SYS_DEPARTMENT>
13     {
14         /// <summary>
15         /// 递归部门列表,返回按级别排序
16         /// add yuangang by 2016-05-19
17         /// </summary>
18         /// <param name="list"></param>
19         /// <returns></returns>
20         List<Domain.SYS_DEPARTMENT> RecursiveDepartment(List<Domain.SYS_DEPARTMENT> list);
21 
22         /// <summary>
23         /// 根据部门ID递归部门列表,返回子部门+本部门的对象集合
24         /// add yuangang by 2016-05-19
25         /// </summary>
26         List<Domain.SYS_DEPARTMENT> RecursiveDepartment(string parentId);
27         /// <summary>
28         /// 自动创建部门编号
29         /// add yuangang by 2016-05-19
30         /// </summary>
31         string CreateCode(string parentCode);
32 
33         /// <summary>
34         /// 部门是否存在下级部门
35         /// add huafg by 2015-06-03
36         /// </summary>
37         bool DepartmentIsExists(string idlist);
38 
39         /// <summary>
40         /// 根据部门ID获取部门名称,不存在返回空
41         /// </summary>
42         string GetDepartmentName(string id);
43         /// <summary>
44         /// 显示错层方法
45         /// </summary>
46         object GetDepartmentName(string name, decimal? level);
47         /// <summary>
48         /// 获取部门父级列表
49         /// </summary>
50         System.Collections.IList GetDepartmentByDetail();
51 
52     }
53 }
View Code
  1 using System;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 using System.Linq;
  5 using System.Text;
  6 
  7 namespace Service.ServiceImp
  8 {
  9     /// <summary>
 10     /// Service层部门管理
 11     /// add yuangang by 2016-05-19
 12     /// </summary>
 13     public class DepartmentManage : RepositoryBase<Domain.SYS_DEPARTMENT>,IService.IDepartmentManage
 14     {
 15         /// <summary>
 16         /// 自动创建部门编号
 17         /// add yuangang by 2016-05-19
 18         /// <param name="parentId">上级部门ID 注:ID不是Code,数据表已改</param>
 19         /// </summary>
 20         public string CreateCode(string parentId)
 21         {
 22             string _strCode = string.Empty;
 23 
 24             #region 验证上级部门code是否为空,为空返回,第一级部门的Code
 25             if (string.IsNullOrEmpty(parentId))
 26             {
 27                 //注意:Oracle存储值为空=null MsSql 空=空 null=null
 28                 var query = this.LoadAll(p => p.PARENTID == null || p.PARENTID == "").OrderBy(p => p.CODE).ToList();
 29                 if (!query.Any())
 30                 {
 31                     return "001";
 32                 }
 33                 //按照之前的逻辑,查漏补缺
 34                 for (int i = 1; i <= query.Count; i++)
 35                 {
 36                     string code = query[i - 1].CODE;
 37                     if (string.IsNullOrEmpty(code))
 38                     {
 39                         return FormatCode(i);
 40                     }
 41                     if (i != int.Parse(code))
 42                     {
 43                         return  FormatCode(i);
 44                     }
 45                 }
 46                 return  FormatCode(query.Count + 1);
 47             }
 48             #endregion
 49             
 50             #region 上级部门不为空,返回当前上级部门下的部门Code
 51             
 52             /* *根据部门编号获取下级部门 查询条件为:
 53              * 1.下级部门编号长度=当前部门编号+3 
 54              * 2.下级部门上级部门ID=当前部门ID
 55              * */
 56             var parentDpt = this.Get(p => p.ID == parentId);
 57             if (parentDpt != null)//上级部门存在
 58             {
 59                 //查询同等级部门下的所有数据
 60                 var queryable = this.LoadAll(p => p.CODE.Length == parentDpt.CODE.Length + 3 && p.PARENTID == parentId).OrderBy(p=>p.CODE).ToList();
 61                 if (queryable.Any())
 62                 {
 63                     //需要验证是否存在编号缺失的情况 方法:遍历下级部门列表,
 64                     //用部门编号去掉上级部门编号,然后转化成数字和for循环的索引进行对比,遇到第一个不相等时,返回此编号,并跳出循环
 65                     for (int i = 1; i <= queryable.Count; i++)
 66                     {
 67                         string _code = queryable[i - 1].CODE;
 68                         _code = _code.Substring(parentDpt.CODE.Length);
 69                         int _intCode = 0;
 70                         Int32.TryParse(_code, out _intCode);
 71                         //下级部门编号中不存在
 72                         if (i != _intCode)
 73                         {
 74                             //返回此编号,并退出循环
 75                             _strCode = parentDpt.CODE + FormatCode(i);
 76                             return _strCode;
 77                         }
 78                     }
 79                     //不存在编号缺失情况
 80                     _strCode = parentDpt.CODE + FormatCode(queryable.Count + 1);
 81                 }
 82                 else
 83                 {
 84                     _strCode = parentDpt.CODE + FormatCode(1);
 85                     return _strCode;
 86                 }
 87             }//上级部门不存在,返回空,这种情况基本不会出现
 88             #endregion
 89 
 90             return _strCode;
 91         }
 92         /// <summary>
 93         /// 功能描述:根据传入的数字 返回补码后的3位部门编号
 94         /// 创建标号:add yuangang by 2016-05-19
 95         /// </summary>
 96         public string FormatCode(int dptCode)
 97         {
 98             try
 99             {
100                 string _strCode = string.Empty;
101                 //<=9 一位数
102                 if (dptCode <= 9 && dptCode >= 1)
103                 {
104                     return "00" + dptCode;
105                 }
106                 //<=99 两位数
107                 else if (dptCode <= 99 && dptCode > 9)
108                 {
109                     return "0" + dptCode;
110                 }
111                 //<==999 三位数
112                 else if (dptCode <= 999 && dptCode > 99)
113                 {
114                     return _strCode;
115                 }
116                 return string.Empty;
117             }
118             catch (Exception ex)
119             {
120                 throw ex;
121             }
122         }
123 
124         /// <summary>
125         /// 验证当前删除的部门是否存在下级部门
126         /// </summary>
127         public bool DepartmentIsExists(string idlist)
128         {
129             return this.IsExist(p => idlist.Contains(p.PARENTID));
130         }
131 
132         /// <summary>
133         /// 递归部门列表,返回排序后的对象集合
134         /// add yuangang by 2016-05-19
135         /// </summary>
136         public List<Domain.SYS_DEPARTMENT> RecursiveDepartment(List<Domain.SYS_DEPARTMENT> list) 
137         {
138             var result = new List<Domain.SYS_DEPARTMENT>();
139             if (list.Count>0)
140             {
141                 ChildDepartment(list, result, null);
142             }
143             return result;
144         }
145 
146         /// <summary>
147         /// 根据部门ID递归部门列表,返回子部门+本部门的对象集合
148         /// add yuangang by 2016-05-19
149         /// </summary>
150         public List<Domain.SYS_DEPARTMENT> RecursiveDepartment(string parentId)
151         {
152             //原始数据
153             var list = this.LoadAll(null);
154             //新数据
155             var result = new List<Domain.SYS_DEPARTMENT>();
156             if (list.Any())
157             {
158                 result.AddRange(list.Where(p => p.ID == parentId).ToList());
159                 if(!string.IsNullOrEmpty(parentId))
160                     ChildDepartment(list.ToList(),result, parentId);
161                 else
162                     ChildDepartment(list.ToList(),result, null);//oracle使用null sql使用空
163             }
164             return result;
165         }
166 
167         private void ChildDepartment(List<Domain.SYS_DEPARTMENT> newlist ,List<Domain.SYS_DEPARTMENT> list,string id) 
168         {
169             var result = newlist.Where(p => p.PARENTID == id).OrderBy(p => p.CODE).ThenBy(p => p.SHOWORDER).ToList();
170             if (result.Any())
171             {
172                 for (int i = 0; i < result.Count(); i++)
173                 {
174                     list.Add(result[i]);
175                     ChildDepartment(newlist,list, result[i].ID);
176                 }
177             }
178         }
179 
180         /// <summary>
181         /// 根据部门ID获取部门名称,不存在返回空
182         /// </summary>
183         public string GetDepartmentName(string id)
184         {
185             var query = this.LoadAll(p => p.ID == id);
186             if (query == null || !query.Any())
187                 return "";
188             return query.First().NAME;
189         }
190 
191         /// <summary>
192         /// 显示错层方法
193         /// </summary>
194         public object GetDepartmentName(string name, decimal? level)
195         {
196             if (level > 1)
197             {
198                 string nbsp = "&nbsp;&nbsp;";
199                 for (int i = 0; i < level; i++)
200                 {
201                     nbsp += "&nbsp;&nbsp;";
202                 }
203                 name = nbsp + "|--" + name;
204             }
205             return name;
206         }
207 
208         /// <summary>
209         /// 获取父级列表
210         /// </summary>
211         public IList GetDepartmentByDetail()
212         {
213             var list = RecursiveDepartment(this.LoadAll(null).ToList())
214                 .Select(p => new
215                 {
216                     id = p.ID,
217                     code=p.CODE,
218                     name = GetDepartmentName(p.NAME, p.BUSINESSLEVEL)
219                 }).ToList();
220 
221             return Common.JsonConverter.JsonClass(list);
222         }
223     }
224 }
View Code

 

IModuleManage、ModuleManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// Service模型处理接口
10     /// add yuangang by 2015-05-22
11     /// </summary>
12     public interface IModuleManage : IRepository<Domain.SYS_MODULE>
13     {
14         /// <summary>
15         /// 获取用户权限模块集合
16         /// add yuangang by 2015-05-30
17         /// </summary>
18         /// <param name="userId">用户ID</param>
19         /// <param name="permission">用户授权集合</param>
20         /// <param name="siteId">站点ID</param>
21         /// <returns></returns>
22         List<Domain.SYS_MODULE> GetModule(int userId, List<Domain.SYS_PERMISSION> permission, string siteId);
23         /// <summary>
24         /// 递归模块列表,返回按级别排序
25         /// add yuangang by 2015-06-03
26         /// </summary>
27         List<Domain.SYS_MODULE> RecursiveModule(List<Domain.SYS_MODULE> list);
28 
29         /// <summary>
30         /// 批量变更当前模块下其他模块的级别
31         /// </summary>
32         bool MoreModifyModule(int moduleId, int levels);
33     }
34 }
View Code
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 
  6 namespace Service.ServiceImp
  7 {
  8     /// <summary>
  9     /// Service模型处理类
 10     /// add yuangang by 2015-05-22
 11     /// </summary>
 12     public class ModuleManage : RepositoryBase<Domain.SYS_MODULE>, IService.IModuleManage
 13     {
 14         /// <summary>
 15         /// 获取用户权限模块集合
 16         /// add yuangang by 2015-05-30
 17         /// </summary>
 18         /// <param name="userId">用户ID</param>
 19         /// <param name="permission">用户授权集合</param>
 20         /// <param name="siteId">站点ID</param>
 21         /// <returns></returns>
 22         public List<Domain.SYS_MODULE> GetModule(int userId, List<Domain.SYS_PERMISSION> permission,string siteId)
 23         {
 24             //返回模块
 25             var retmodule = new List<Domain.SYS_MODULE>();
 26             var permodule = new List<Domain.SYS_MODULE>();
 27             //权限转模块
 28             if (permission != null)
 29             {
 30                 permodule.AddRange(permission.Select(p => p.SYS_MODULE));
 31                 //去重
 32                 permodule = permodule.Distinct(new ModuleDistinct()).ToList();
 33             }
 34             //检索显示与系统
 35             //permodule = permodule.Where(p => p.ISSHOW == 1 && p.FK_BELONGSYSTEM.ToString() == siteId).ToList();
 36             //商城系统融入本系统不再区分系统
 37             permodule = permodule.Where(p => p.ISSHOW == 1 ).ToList();
 38             //构造上级导航模块
 39             //var prevModule = this.LoadListAll(p => p.FK_BELONGSYSTEM.ToString() == siteId);
 40             //商城系统融入本系统不再区分系统
 41             var prevModule = this.LoadListAll(null);
 42             //反向递归算法构造模块带上级上上级模块
 43             if (permodule.Count > 0)
 44             {
 45                 foreach (var item in permodule)
 46                 {
 47                     RecursiveModule(prevModule, retmodule, item.PARENTID);
 48                     retmodule.Add(item);
 49                 }
 50             }
 51             //去重
 52             retmodule = retmodule.Distinct(new ModuleDistinct()).ToList();
 53             //返回模块集合
 54             return retmodule.OrderBy(p => p.LEVELS).ThenBy(p => p.SHOWORDER).ToList();
 55         }
 56 
 57         /// <summary>
 58         /// 反向递归模块集合,可重复模块数据,最后去重
 59         /// </summary>
 60         /// <param name="PrevModule">总模块</param>
 61         /// <param name="retmodule">返回模块</param>
 62         /// <param name="parentId">上级ID</param>
 63         private void RecursiveModule(List<Domain.SYS_MODULE> PrevModule, List<Domain.SYS_MODULE> retmodule, int? parentId)
 64         {
 65            var result = PrevModule.Where(p => p.ID == parentId);
 66             if (result != null)
 67             {
 68                 foreach (var item in result)
 69                 {
 70                     retmodule.Add(item);
 71                     RecursiveModule(PrevModule, retmodule, item.PARENTID);
 72                 }
 73             }
 74         }
 75 
 76         /// <summary>
 77         /// 递归模块列表,返回按级别排序
 78         /// add yuangang by 2015-06-03
 79         /// </summary>
 80         public List<Domain.SYS_MODULE> RecursiveModule(List<Domain.SYS_MODULE> list)
 81         {
 82             List<Domain.SYS_MODULE> result = new List<Domain.SYS_MODULE>();
 83             if (list!=null && list.Count>0)
 84             {
 85                 ChildModule(list, result, 0);
 86             }
 87             return result;
 88         }
 89         /// <summary>
 90         /// 递归模块列表
 91         /// add yuangang by 2015-06-03
 92         /// </summary>
 93         private void ChildModule(List<Domain.SYS_MODULE> list, List<Domain.SYS_MODULE> newlist, int parentId)
 94         {
 95             var result = list.Where(p => p.PARENTID == parentId).OrderBy(p => p.LEVELS).OrderBy(p => p.SHOWORDER).ToList();
 96             if (result.Count() > 0)
 97             {
 98                 for (int i = 0; i < result.Count(); i++)
 99                 {
100                     newlist.Add(result[i]);
101                     ChildModule(list, newlist, result[i].ID);
102                 }
103             }
104         }
105 
106         /// <summary>
107         /// 批量变更下级模块的级别
108         /// </summary>
109         public bool MoreModifyModule(int moduleId, int levels)
110         {
111            //根据当前模块ID获取下级模块的集合
112             var ChildModule = this.LoadAll(p => p.PARENTID == moduleId).ToList();
113             if (ChildModule.Any())
114             {
115                 foreach (var item in ChildModule)
116                 {
117                     item.LEVELS = levels + 1;
118                     this.Update(item);
119                     MoreModifyModule(item.ID, item.LEVELS);
120                 }
121             }
122             return true;
123         }
124 
125         /// <summary>
126         /// 获取模板列表
127         /// </summary>
128         public dynamic LoadModuleInfo(int id)
129         {
130             return Common.JsonConverter.JsonClass(this.LoadAll(p=>p.PARENTID==id).OrderBy(p => p.ID).Select(p => new { p.ID, p.NAME }).ToList());
131         }
132     }
133   /// <summary>
134     /// 模型去重,非常重要
135     /// add yuangang by 2015-08-03
136     /// </summary>
137     public class ModuleDistinct : IEqualityComparer<Domain.SYS_MODULE> 
138     {
139         public bool Equals(Domain.SYS_MODULE x, Domain.SYS_MODULE y)
140         {
141             return x.ID == y.ID; 
142         }
143 
144         public int GetHashCode(Domain.SYS_MODULE obj)
145         {
146             return obj.ToString().GetHashCode();
147         }
148     }
149 }
View Code

 

三、我们分修改UserManage实现类

修改我们UserManage的IsAdmin方法

 1  /// <summary>
 2         /// 是否超级管理员
 3         /// </summary>
 4         public bool IsAdmin(int userId)
 5         {
 6             //通过用户ID获取角色
 7             Domain.SYS_USER entity = this.Get(p => p.ID == userId);
 8             if (entity == null) return false;
 9             var roles = entity.SYS_USER_ROLE.Select(p => new Domain.SYS_ROLE
10             {
11                 ID = p.SYS_ROLE.ID
12             });
13             return roles.ToList().Any(item => item.ID == ClsDic.DicRole["超级管理员"]);
14         }
View Code


/// 根据用户ID删除用户相关记录
/// 删除原则:1、删除用户档案
/// 2、删除用户角色关系
/// 3、删除用户权限关系
/// 4、删除用户岗位关系
/// 5、删除用户部门关系
/// 6、删除用户

 1 /// <summary>
 2         /// 根据用户ID删除用户相关记录
 3         /// 删除原则:1、删除用户档案
 4         ///           2、删除用户角色关系
 5         ///           3、删除用户权限关系
 6         ///           4、删除用户岗位关系
 7         ///           5、删除用户部门关系
 8         ///           6、删除用户
 9         /// </summary>
10         public bool Remove(int userId)
11         {
12             try
13             {
14                 //档案
15                 if (this.UserInfoManage.IsExist(p => p.USERID == userId))
16                 {
17                     this.UserInfoManage.Delete(p => p.USERID == userId);
18                 }
19                 //用户角色
20                 if (this.UserRoleManage.IsExist(p => p.FK_USERID == userId))
21                 {
22                     this.UserRoleManage.Delete(p => p.FK_USERID == userId);
23                 }
24                 //用户权限
25                 if (this.UserPermissionManage.IsExist(p => p.FK_USERID == userId))
26                 {
27                     this.UserPermissionManage.Delete(p => p.FK_USERID == userId);
28                 }
29                 //用户岗位
30                 if (this.PostUserManage.IsExist(p => p.FK_USERID == userId))
31                 {
32                     this.PostUserManage.Delete(p => p.FK_USERID == userId);
33                 }
34                 //用户部门
35                 if (this.UserDepartmentManage.IsExist(p => p.USER_ID == userId))
36                 {
37                     this.UserDepartmentManage.Delete(p => p.USER_ID == userId);
38                 }
39                 //用户自身
40                 if (this.IsExist(p => p.ID == userId))
41                 {
42                     this.Delete(p => p.ID == userId);
43                 }
44                 return true;
45             }
46             catch (Exception e) { throw e.InnerException; }
47         }
View Code

 

从Cookie中获取用户信息

 1 /// <summary>
 2         /// 从Cookie中获取用户信息
 3         /// </summary>
 4         public Account GetAccountByCookie()
 5         {
 6             var cookie = CookieHelper.GetCookie("cookie_rememberme");
 7             if (cookie != null)
 8             {
 9                 //验证json的有效性
10                 if (!string.IsNullOrEmpty(cookie.Value))
11                 {
12                     //解密
13                     var cookievalue = new Common.CryptHelper.AESCrypt().Decrypt(cookie.Value);
14                     //是否为json
15                     if (!JsonSplit.IsJson(cookievalue)) return null;
16                     try
17                     {
18                         var jsonFormat = Common.JsonConverter.ConvertJson(cookievalue);
19                         if (jsonFormat != null)
20                         {
21                             var users = UserLogin(jsonFormat.username, new Common.CryptHelper.AESCrypt().Decrypt(jsonFormat.password));
22                             if (users != null)
23                                 return GetAccountByUser(users);
24                         }
25                     }
26                     catch { return null; }
27                 }
28             }
29             return null;
30         }
View Code

 

根据用户构造用户基本信息

 1  /// <summary>
 2         /// 根据用户构造用户基本信息
 3         /// </summary>
 4         public Account GetAccountByUser(Domain.SYS_USER users)
 5         {
 6             if (users == null) return null;
 7             //用户授权--->注意用户的授权是包括角色权限与自身权限的
 8             var permission = GetPermissionByUser(users);
 9             //用户角色
10             var role = users.SYS_USER_ROLE.Select(p => p.SYS_ROLE).ToList();
11             //用户部门
12             var dpt = users.SYS_USER_DEPARTMENT.Select(p => p.SYS_DEPARTMENT).ToList();
13             //用户岗位
14             var post = users.SYS_POST_USER.ToList();
15             //用户主部门
16             var dptInfo = this.DepartmentManage.Get(p => p.ID == users.DPTID);
17             //用户模块
18             var module = permission.Select(p => p.SYS_MODULE).ToList().Distinct(new ModuleDistinct()).ToList();
19             Account account = new Account()
20             {
21                 Id = users.ID,
22                 Name = users.NAME,
23                 LogName = users.ACCOUNT,
24                 PassWord = users.PASSWORD,
25                 IsAdmin = IsAdmin(users.ID),
26                 DptInfo = dptInfo,
27                 Dpt = dpt,
28                 Face_Img = users.FACE_IMG,
29                 Permissions = permission,
30                 Roles = role,
31                 PostUser = post,
32                 Modules = module
33             };
34             return account;
35         }
View Code

 

根据用户信息获取用户所有的权限

 1 /// <summary>
 2         /// 根据用户信息获取用户所有的权限
 3         /// </summary>
 4         private List<Domain.SYS_PERMISSION> GetPermissionByUser(Domain.SYS_USER users)
 5         {
 6             //1、超级管理员拥有所有权限
 7             if (IsAdmin(users.ID))
 8                 return PermissionManage.LoadListAll(null);
 9             //2、普通用户,合并当前用户权限与角色权限
10             var perlist = new List<Domain.SYS_PERMISSION>();
11             //2.1合并用户权限
12             perlist.AddRange(users.SYS_USER_PERMISSION.Select(p => p.SYS_PERMISSION).ToList());
13             //2.2合同角色权限
14             ////todo:经典多对多的数据查询Linq方法
15             perlist.AddRange(users.SYS_USER_ROLE.Select(p => p.SYS_ROLE.SYS_ROLE_PERMISSION.Select(c => c.SYS_PERMISSION)).SelectMany(c => c.Select(e => e)).Cast<Domain.SYS_PERMISSION>().ToList());
16             //3、去重
17             ////todo:通过重写IEqualityComparer<T>实现对象去重
18             perlist = perlist.Distinct(new PermissionDistinct()).ToList();
19             return perlist;
20         }
View Code

 

根据用户ID获取部门名称

 1  /// <summary>
 2         /// 根据用户ID获取部门名称
 3         /// </summary>
 4         public string GetUserDptName(int id)
 5         {
 6             if (id <= 0)
 7                 return "";
 8             var dptid = this.Get(p => p.ID == id).DPTID;
 9             return this.DepartmentManage.Get(p => p.ID == dptid).NAME;
10         }
View Code

 

三、权限去重,非常重要

 1  /// <summary>
 2     /// 权限去重,非常重要
 3     /// add yuangang by 2015-08-03
 4     /// </summary>
 5     public class PermissionDistinct : IEqualityComparer<Domain.SYS_PERMISSION>
 6     {
 7         public bool Equals(Domain.SYS_PERMISSION x, Domain.SYS_PERMISSION y)
 8         {
 9             return x.ID == y.ID;
10         }
11 
12         public int GetHashCode(Domain.SYS_PERMISSION obj)
13         {
14             return obj.ToString().GetHashCode();
15         }
16     }
View Code

 

需要的帮助类:【C#公共帮助类】 WebHelper帮助类

 

原创文章 转载请尊重劳动成果 http://yuangang.cnblogs.com

posted @ 2016-05-19 10:12 果冻布丁喜之郎 阅读(...) 评论(...) 编辑 收藏