Example #1
0
        public bool HasPrivilege(params string[] privileges)
        {
            var @value = true;

            foreach (var privilegeId in privileges)
            {
                var hasPrivilege = UserPrivilegeMap != null && UserPrivilegeMap.Any(e => e.PrivilegeId == privilegeId);
                if (!hasPrivilege)
                {
                    hasPrivilege = UserRoleMap != null && UserRoleMap.Any(e => e.Role.RolePrivilegeMap != null && e.Role.RolePrivilegeMap.Any(e2 => e2.PrivilegeId == privilegeId));
                    if (!hasPrivilege)
                    {
                        hasPrivilege = UserGroupMap != null && UserGroupMap.Any(e => e.Group.GroupPrivilegeMap != null && e.Group.GroupPrivilegeMap.Any(e2 => e2.PrivilegeId == privilegeId));
                        if (!hasPrivilege)
                        {
                            hasPrivilege = UserGroupMap != null && UserGroupMap.Any(e => e.Group.GroupRoleMap != null && e.Group.GroupRoleMap.Any(e2 => e2.Role.RolePrivilegeMap != null && e2.Role.RolePrivilegeMap.Any(e3 => e3.PrivilegeId == privilegeId)));
                            if (!hasPrivilege)
                            {
                                @value = false;
                                break;
                            }
                        }
                    }
                }
            }
            return(@value);
        }
Example #2
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,UserId,RoleId")] UserRoleMap userRoleMap)
        {
            if (id != userRoleMap.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(userRoleMap);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserRoleMapExists(userRoleMap.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["RoleId"] = new SelectList(_context.Role, "Id", "Id", userRoleMap.RoleId);
            ViewData["UserId"] = new SelectList(_context.User, "Id", "Id", userRoleMap.UserId);
            return(View(userRoleMap));
        }
Example #3
0
        /// <summary>
        /// 设置用户的角色
        /// </summary>
        /// <param name="id">用户编号</param>
        /// <param name="roleIds">角色编号集合</param>
        /// <returns>业务操作结果</returns>
        public async Task <OperationResult> SetUserRoles(int id, int[] roleIds)
        {
            User user = await UserRepository.GetByKeyAsync(id);

            if (user == null)
            {
                return(new OperationResult(OperationResultType.QueryNull, "指定编号的用户信息不存在"));
            }
            int[] existIds  = UserRoleMapRepository.Entities.Where(m => m.User.Id == id).Select(m => m.Role.Id).ToArray();
            int[] addIds    = roleIds.Except(existIds).ToArray();
            int[] removeIds = existIds.Except(roleIds).ToArray();
            UserRoleMapRepository.UnitOfWork.TransactionEnabled = true;
            foreach (int addId in addIds)
            {
                Role role = await RoleRepository.GetByKeyAsync(addId);

                if (role == null)
                {
                    return(new OperationResult(OperationResultType.QueryNull, "指定编号的角色信息不存在"));
                }
                UserRoleMap map = new UserRoleMap()
                {
                    User = user, Role = role
                };
                await UserRoleMapRepository.InsertAsync(map);
            }
            await UserRoleMapRepository.DeleteAsync(m => m.User.Id == id && removeIds.Contains(m.Role.Id));

            return(await UserRoleMapRepository.UnitOfWork.SaveChangesAsync() > 0
                ? new OperationResult(OperationResultType.Success, "用户“{0}”指派角色操作成功".FormatWith(user.UserName))
                : OperationResult.NoChanged);
        }
Example #4
0
        public UserRoleMap MapUserRole(User user, UserRole userRole)
        {
            var userRoleMap = new UserRoleMap();

            userRoleMap.User     = user;
            userRoleMap.UserRole = userRole;// _userRoleRepository.GetById(int.Parse(d));
            return(userRoleMap);
        }
Example #5
0
 static UserRoleMapRepository()
 {
     UserRoleMap entity = new UserRoleMap();
     Type type = entity.GetType();
     AppendDataMap(type, "UserID", () => entity.UserID);
     AppendDataMap(type, "RoleID", () => entity.RoleID);
     ResultMapDelegate<UserRoleMap> queryMap = UsersInRoles_Map;
     QueryMapContainer[entity.GetType()] = queryMap;
 }
Example #6
0
 /// <summary>
 /// 角色实体数据映射
 /// </summary>
 /// <param name="reader"></param>
 /// <returns></returns>
 private static UserRoleMap UsersInRoles_Map(DataReader reader)
 {
     UserRoleMap usersinroles = new UserRoleMap()
     {
         UserID = reader.GetString("UserID"),
         RoleID = reader.GetString("RoleID")
     };
     return usersinroles;
 }
Example #7
0
        public IReadOnlyCollection <User> GetUsers()
        {
            IReadOnlyCollection <User> @value = null;

            if (UserRoleMap != null)
            {
                @value = UserRoleMap.Select(e => e.User).ToList();
            }
            return(@value);
        }
Example #8
0
        /// <summary>
        /// 角色实体数据映射
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private static UserRoleMap UsersInRoles_Map(DataReader reader)
        {
            UserRoleMap usersinroles = new UserRoleMap()
            {
                UserID = reader.GetString("UserID"),
                RoleID = reader.GetString("RoleID")
            };

            return(usersinroles);
        }
Example #9
0
        public IReadOnlyCollection <(Privilege, bool)> GetRolesPrivileges()
        {
            IReadOnlyCollection <(Privilege, bool)> @value = null;

            if (UserRoleMap != null)
            {
                @value = UserRoleMap.SelectMany(e => e.Role.RolePrivilegeMap).Select(e => (e.Privilege, e.IsAllowed)).Distinct().ToList();
            }
            return(@value);
        }
Example #10
0
        public IReadOnlyCollection <Role> GetRoles()
        {
            IReadOnlyCollection <Role> @value = null;

            if (UserRoleMap != null)
            {
                @value = UserRoleMap.Select(e => e.Role).ToList();
            }
            return(@value);
        }
Example #11
0
        public override bool AddUserRole(AUser user, AUserRole userRole)
        {
            var urmap = new UserRoleMap()
            {
                User = user as AppUser, Role = userRole as Role
            };

            context.UserRoleMap.Add(urmap);
            return(true);
        }
Example #12
0
        public async Task <IActionResult> Create([Bind("Id")] UserRoleMap userRoleMap)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userRoleMap);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(userRoleMap));
        }
Example #13
0
        static UserRoleMapRepository()
        {
            UserRoleMap entity = new UserRoleMap();
            Type        type   = entity.GetType();

            AppendDataMap(type, "UserID", () => entity.UserID);
            AppendDataMap(type, "RoleID", () => entity.RoleID);
            ResultMapDelegate <UserRoleMap> queryMap = UsersInRoles_Map;

            QueryMapContainer[entity.GetType()] = queryMap;
        }
Example #14
0
        public async Task <IActionResult> Create([Bind("Id,UserId,RoleId")] UserRoleMap userRoleMap)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userRoleMap);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["RoleId"] = new SelectList(_context.Role, "Id", "Id", userRoleMap.RoleId);
            ViewData["UserId"] = new SelectList(_context.User, "Id", "Id", userRoleMap.UserId);
            return(View(userRoleMap));
        }
Example #15
0
        /// <summary>
        /// 指定したユーザにロールを付与する。
        /// <paramref name="role"/>がシステムロールの場合、<paramref name="userTenantMap"/>はNULLになって、テナントに関係なくそのロールが必ず付与される。
        /// <paramref name="role"/>がテナントロールの場合、<paramref name="userTenantMap"/>は非NULLになる。
        /// その場合、<paramref name="user"/>と<paramref name="userTenantMap"/>のUserIdは一致している必要があり、
        /// <paramref name="role"/>のテナントIDが非NULLなら<paramref name="userTenantMap"/>のテナントIDと一致している必要がある。
        /// </summary>
        /// <param name="user">対象ユーザ</param>
        /// <param name="role">対象ロール</param>
        /// <param name="userTenantMap">テナントマップ</param>
        /// <param name="isCreate">ユーザが新規作成の状態(=ID未割当)ならtrue</param>
        public void AttachRole(User user, Role role, UserTenantMap userTenantMap, bool isCreate)
        {
            if (role.IsSystemRole)
            {
                if (userTenantMap != null)
                {
                    //システムロールの場合、userTenantMapはNULLでないといけない
                    throw new UnauthorizedAccessException($"A system role {role.Id}:{role.Name} is not assigned to specific tenant {userTenantMap.TenantId}.");
                }
            }
            else
            {
                //テナントロールの場合
                if (userTenantMap == null)
                {
                    //userTenantMapはNULLでないといけない
                    throw new UnauthorizedAccessException($"A tenant role {role.Id}:{role.Name} need to be assigned to specific tenant.");
                }
                if (role.TenantId != null && role.TenantId == userTenantMap.TenantId)
                {
                    //ロールがテナント固有のものなら、そのテナントにしか使えない
                    throw new UnauthorizedAccessException($"The tenant role {role.Id}:{role.Name} is only assigned to the tenant {role.TenantId}, not {userTenantMap.TenantId}.");
                }
                if (isCreate && user != userTenantMap.User)
                {
                    //ユーザが一致していないといけない
                    throw new UnauthorizedAccessException($"users are not match. {user.Name} : {userTenantMap.User.Name}.");
                }
                else if (isCreate == false && user.Id != userTenantMap.UserId)
                {
                    //ユーザIDが一致していないといけない
                    throw new UnauthorizedAccessException($"user IDs are not match. {user.Id} : {userTenantMap.UserId}.");
                }
            }
            var model = new UserRoleMap()
            {
                RoleId      = role.Id,
                TenantMapId = userTenantMap?.Id
            };

            if (isCreate)
            {
                model.User = user;
            }
            else
            {
                model.UserId = user.Id;
            }
            AddModel <UserRoleMap>(model);
        }
        public IHttpActionResult Delete([FromBody] UserRoleMap key2)
        {
            var roleMap     = new UserRoleMap();
            var store       = new UserStore <ApplicationUser>(new ApplicationDbContext());
            var userManager = new UserManager <ApplicationUser>(store);

            var result = userManager.RemoveFromRole(roleMap.UserId, roleMap.RoleId);

            if (result.Succeeded)
            {
                return(Created(key2));
            }

            return(InternalServerError());
        }
Example #17
0
        static EntityPostRequest BuildaddRoleRequest(string userid, string roleid)
        {
            UserRoleMap role = new UserRoleMap()
            {
                RoleID = roleid,
                UserID = userid
            };
            EntityPostRequest request = new EntityPostRequest(EntityPostRequest.EntityPostMethod.Create)
            {
                Entity = role
            };

            request.AppendFieldMap(role.UserID, () => role.UserID);
            request.AppendFieldMap(role.RoleID, () => role.RoleID);
            return(request);
        }
Example #18
0
        static EntityPostRequest BuilddeleteRoleRequest(string userid, string roleid)
        {
            UserRoleMap role = new UserRoleMap()
            {
                RoleID = roleid,
                UserID = userid
            };
            EntityPostRequest request = new EntityPostRequest(EntityPostRequest.EntityPostMethod.Delete)
            {
                Entity = role
            };

            request.AppendConditionMap(role.UserID, () => role.UserID);
            request.AppendConditionMap(role.RoleID, () => role.RoleID);
            return(request);
        }
Example #19
0
        private void SetUserRole(UserDTO csDto)
        {
            var userRoleMap = _databaseContext.UserRoleMaps.FirstOrDefault(a => a.UserId == csDto.Id);

            if (userRoleMap != null) //更新
            {
                userRoleMap.RoleId = csDto.RoleDtos[0].Id;
            }
            else //添加
            {
                var newUserRoleMap = new UserRoleMap
                {
                    UserId = csDto.Id,
                    RoleId = csDto.RoleDtos[0].Id
                };
                _databaseContext.UserRoleMaps.Add(newUserRoleMap);
            }
        }
Example #20
0
        public bool EditUserRoles(RequestEditUserRoleDTO dto, out string reason)
        {
            reason = "";
            using (var db = new DBEntities())
            {
                var model = db.Users.Where(t => t.ID == dto.ID && !t.IsDeleted).FirstOrDefault();

                if (model == null)
                {
                    reason = "账号不存在";
                    return(false);
                }
                else
                {
                    if (model.IsSystem)
                    {
                        reason = "系统账号不允许修改";
                        return(false);
                    }

                    var olds = db.UserRoleMaps.Where(t => t.UserID == dto.ID).ToList();
                    foreach (var item in olds)
                    {
                        db.Entry(item).State = System.Data.Entity.EntityState.Deleted;
                    }

                    var rolelist = dto.RoleLists.Where(t => t.Selected).Select(t => t.ID).ToList();

                    var listexit = db.Roles.Where(t => rolelist.Contains(t.ID) && t.State == 0).Select(t => t.ID).ToList();

                    foreach (var item in listexit)
                    {
                        UserRoleMap userRoleMap = new UserRoleMap()
                        {
                            MapID  = Guid.NewGuid().ToString("N"),
                            RoleID = item,
                            UserID = dto.ID
                        };
                        db.UserRoleMaps.Add(userRoleMap);
                    }
                }
                return(db.SaveChanges() > 0);
            }
        }
        public IActionResult ManageUserRole([FromBody] UserRoleMap userRoleDto)
        {
            string      key         = "n";
            string      value       = "Error Updating the User Role";
            string      userId      = AuthSession.GetUserId(HttpContext, "userId");
            UserRoleMap userRoleMap = new UserRoleMap();

            try
            {
                if (userRoleDto != null)
                {
                    bool isUser = Int32.TryParse(userRoleDto.UserIdSystem, out int userid);
                    if (isUser)
                    {
                        UserBasic userBasic = db.UserBasic.Where(x => x.UserIdId == userid).FirstOrDefault();
                        userRoleMap = db.UserRoleMap.Where(x => x.UserIdSystem == userBasic.UserIdSystem).FirstOrDefault();
                        if (userRoleMap != null)
                        {
                            db.UserRoleMap.Remove(userRoleMap);
                        }
                        if (userRoleDto.MapId == 1)
                        {
                            userRoleMap = new UserRoleMap
                            {
                                UserIdSystem = userBasic.UserIdSystem,
                                IsAdmin      = userRoleDto.IsAdmin,
                                UpdateByName = userBasic.FirstName + " " + userBasic.MiddleName + " " + userBasic.LastName,
                                UpdateById   = userId,
                                UpdatedDate  = DateTime.UtcNow
                            };
                            db.UserRoleMap.Attach(userRoleMap);
                            db.UserRoleMap.Add(userRoleMap);
                        }
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception)
            {
                return(Json(new KeyValuePair <string, string>(key, value)));
            }
            return(Json(new KeyValuePair <string, string>("y", "Role Updated Successfully")));
        }
        public IHttpActionResult Post(UserRoleMap userRoleMap)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var store       = new UserStore <ApplicationUser>(new ApplicationDbContext());
            var userManager = new UserManager <ApplicationUser>(store);

            var result = userManager.AddToRole(userRoleMap.UserId, userRoleMap.RoleId);

            if (result.Succeeded)
            {
                return(Created(userRoleMap));
            }

            return(InternalServerError());
        }
Example #23
0
        public IHttpActionResult Logout()
        {
            try
            {
                string userRole = HttpUtilities.GetUserRoleAccessApi(this.Request);
                string token    = HttpUtilities.GetRequestToken(this.Request);
                var    user     = GetLoggedInUser();

                UserRoleMap userRoleMap = _context.UserRoleMaps.FirstOrDefault(i => i.RoleId == userRole && i.UserId == user.Id);
                if (userRoleMap == null)
                {
                    return(BadRequest(ErrorCodes.USER_ROLE_MAP_DOES_NOT_EXISTS.ToString()));
                }
                else
                {
                    userRoleMap.IsPreferredRole = false;
                    //UserRoleMap existingRoles = _context.UserRoleMaps.FirstOrDefault(i => i.UserId == user.Id && i.Id != userRoleMap.Id);
                    //if (existingRoles != null)
                    //{
                    //    existingRoles.IsPreferredRole = false;
                    //}
                    //remove existing preference.
                    _context.SaveChanges();
                    //return Ok();
                }
                UserRoleMap userRoleMapIsAvailable = _context.UserRoleMaps.FirstOrDefault(i => i.UserId == user.Id && i.IsPreferredRole == true);
                if (userRoleMapIsAvailable == null)
                {
                    user.IsLoggedIn = false;
                    //   user.UpdatedAt = DateTimeOffset.UtcNow;
                    _context.SaveChanges();
                }
                DbUtilities.AuditTrialEntry(user, AuditTrialStatus.SUCCESS, AuditTrialOpType.LOGOUT, this.Request, userRole, token);
                return(Ok());
            }
            catch (Exception ex)
            {
                LGSELogger.Error(ex);
                return(InternalServerError());
            }
        }
Example #24
0
        public IHttpActionResult UpdatePreferredRole(PreferredRoleRequest req)
        {
            try
            {
                User   user  = GetLoggedInUser();
                string token = HttpUtilities.GetRequestToken(this.Request);
                if (user == null)
                {
                    return(BadRequest(ErrorCodes.USER_DOES_NOT_EXISTS.ToString()));
                }
                Role role = _context.Roles.FirstOrDefault(i => i.Id == req.RoleId);
                if (role == null)
                {
                    return(BadRequest(ErrorCodes.ROLE_DOES_NOT_EXISTS.ToString()));
                }
                UserRoleMap userRoleMap = _context.UserRoleMaps.FirstOrDefault(i => i.RoleId == req.RoleId && i.UserId == user.Id);
                if (userRoleMap == null)
                {
                    return(BadRequest(ErrorCodes.USER_ROLE_MAP_DOES_NOT_EXISTS.ToString()));
                }
                else
                {
                    userRoleMap.IsPreferredRole = true;
                    //UserRoleMap existingRoles = _context.UserRoleMaps.FirstOrDefault(i => i.UserId == user.Id && i.Id != userRoleMap.Id);
                    //if (existingRoles != null)
                    //{
                    //    existingRoles.IsPreferredRole = false;
                    //}
                    //remove existing preference.
                    _context.SaveChanges();
                    DbUtilities.AuditTrialEntry(user, AuditTrialStatus.SUCCESS, AuditTrialOpType.LOGIN, this.Request, req.RoleId, token);

                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                LGSELogger.Error(ex);
                return(InternalServerError(ex));
            }
        }
        /// <summary>
        /// Handles the Load event of the frmContactUser control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void frmContactUser_Load(object sender, EventArgs e)
        {
            List <Role> userRoles = new List <Role>();

            if (this.User != null)
            {
                this.txtName.Text          = this.User.CommonName;
                this.txtPhoneNumber.Text   = this.User.Mobtel;
                this.txtEmail.Text         = this.User.Email;
                this.txtLoginName.Text     = this.User.LoginName;
                this.txtPassword.Text      = this.User.Password;
                this.txtPasswordAgain.Text = this.User.Password;

                if (this.User.LoginName.Equals(GuiHelper.AdministratorName, StringComparison.OrdinalIgnoreCase))
                {
                    txtLoginName.Enabled = false;
                }

                // Load user roles
                IList <UserRoleMap> userMappings = UserRoleMap.Find(urm => urm.UserId == this.User.Id);
                foreach (UserRoleMap urm in userMappings)
                {
                    Role role = Role.SingleOrDefault(r => r.Id == urm.RoleId);
                    if (role != null)
                    {
                        lstBelongedGroups.Items.Add(BuildDisplayName(role));
                        userRoles.Add(role);
                    }
                }
            }

            List <Role> roles = new List <Role>(Role.All().OrderBy(r => r.Name).AsEnumerable());

            foreach (Role role in roles)
            {
                if (!userRoles.Exists(r => r.Id == role.Id))
                {
                    lstAvailableGroups.Items.Add(BuildDisplayName(role));
                }
            }
        }
Example #26
0
        /// <summary>
        /// Handles the Load event of the frmContactGroup control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void frmContactGroup_Load(object sender, EventArgs e)
        {
            List <User> usersInGroup = new List <User>();

            if (this.Group != null)
            {
                this.Text                = this.Group.Name;
                this.txtName.Text        = this.Group.Name;
                this.txtDescription.Text = this.Group.Desc;

                if (this.Group.Name.Equals(GuiHelper.AdministratorGroupName, StringComparison.OrdinalIgnoreCase))
                {
                    txtName.Enabled = false;
                }

                // Load users in those groups
                IList <UserRoleMap> userList = UserRoleMap.Find(urm => urm.RoleId == this.Group.Id);
                foreach (UserRoleMap urm in userList)
                {
                    User user = User.SingleOrDefault(u => u.Id == urm.UserId);
                    if (user != null)
                    {
                        lstUsersInGroup.Items.Add(BuildDisplayName(user));
                        usersInGroup.Add(user);
                    }
                }
            }

            List <User> users = new List <User>(User.All().OrderBy(u => u.CommonName).AsEnumerable());

            foreach (User user in users)
            {
                if (!usersInGroup.Exists(u => u.Id == user.Id))
                {
                    lstAvailableUsers.Items.Add(BuildDisplayName(user));
                }
            }
        }
Example #27
0
        /// <summary>
        /// 指定したテナントについて、ユーザのロールを変更する。
        /// ユーザIDやテナントIDの存在チェック、および所属済みかのチェックは行わない。
        /// </summary>
        /// <param name="userId">対象ユーザID</param>
        /// <param name="tenantId">対象テナントID</param>
        /// <param name="roles">テナントロール</param>
        /// <exception cref="ArgumentException"><paramref name="roles"/>にシステムロールが含まれていたり、別テナント用のロールが含まれていた場合</exception>
        public void ChangeTenantRole(long userId, long tenantId, IEnumerable <Role> roles)
        {
            UserTenantMap tenantMap = FindModel <UserTenantMap>(map => map.UserId == userId && map.TenantId == tenantId);

            //まずは既存のロールをすべて削除する
            DeleteModelAll <UserRoleMap>(map => map.TenantMapId == tenantMap.Id);

            foreach (var role in roles)
            {
                if (role.IsSystemRole)
                {
                    //Adminロールを特定テナントに所属させようとしている
                    throw new UnauthorizedAccessException($"The tenant role {role.Name} is not assigned to user {userId} as a system role.");
                }
                var roleMap = new UserRoleMap()
                {
                    RoleId      = role.Id,
                    TenantMapId = tenantMap.Id,
                    UserId      = userId
                };
                AddModel <UserRoleMap>(roleMap);
            }
        }
Example #28
0
 /// <summary>
 /// 设置账号的角色
 /// </summary>
 /// <param name="userId"></param>
 /// <param name="roleIds"></param>
 /// <returns></returns>
 private async Task SetUserRoles(int userId, int[] roleIds)
 {
     //获取当前账号所以角色
     int[] userRoles = _userRoleRepository.Entities.Where(o => o.UserId == userId).Select(o => o.RoleId).ToArray();
     int[] addList = roleIds.Except(userRoles).ToArray();//获取添加
     int[] removeList = userRoles.Except(roleIds).ToArray();//获取删除
     foreach (var role in addList)
     {
         var entity = new UserRoleMap() { UserId = userId, RoleId = role };
         await _userRoleRepository.InsertAsync(entity);
     }
     _userRoleRepository.Remove(o => o.UserId == userId && removeList.Contains(o.RoleId));//删除
 }
Example #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            string connectionString = Configuration["SQLiteConnectionString"];

            Tables.CreateBooksTable(connectionString);
            Tables.CreateUsersTable(connectionString);

            List <UserRoleMap> userRoleMap = new List <UserRoleMap>();

            Configuration.GetSection("UserRoleMap").Bind(userRoleMap);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = "GitHub";
            })
            .AddCookie()
            .AddOAuth("GitHub", options =>
            {
                options.ClientId     = Configuration["GitHub:ClientId"];
                options.ClientSecret = Configuration["GitHub:ClientSecret"];
                options.CallbackPath = new PathString("/signin-github");

                options.AuthorizationEndpoint   = "https://github.com/login/oauth/authorize";
                options.TokenEndpoint           = "https://github.com/login/oauth/access_token";
                options.UserInformationEndpoint = "https://api.github.com/user";

                options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
                options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
                options.ClaimActions.MapJsonKey("urn:github:login", "login");
                options.ClaimActions.MapJsonKey("urn:github:url", "html_url");
                options.ClaimActions.MapJsonKey("urn:github:avatar", "avatar_url");

                options.Events = new OAuthEvents
                {
                    OnCreatingTicket = async context =>
                    {
                        var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

                        var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
                        response.EnsureSuccessStatusCode();

                        var user = JObject.Parse(await response.Content.ReadAsStringAsync());

                        context.RunClaimActions(user);

                        string username   = context.Principal.Claims.FirstOrDefault(c => c.Type == "urn:github:login").Value;
                        UserRoleMap roles = userRoleMap.FirstOrDefault(u => u.Username.Equals(username));

                        if (roles != null)
                        {
                            // Update role claims on current user
                            context.Principal.AddIdentity(new ClaimsIdentity(roles.Roles.Select(r => new Claim(ClaimTypes.Role, r)).ToList()));
                        }
                    }
                };
            });

            services.AddLogging(configure => configure.AddDebug());
            services.AddTransient <IDbConnection>(s => new SqliteConnection(connectionString));

            services.AddSingleton <IRepository <LibraryUser> >(s => new UserRepository(s.GetRequiredService <IDbConnection>(), userRoleMap.ToDictionary(kp => kp.Username, kp => kp.Roles.ToList() as IList <string>), s.GetRequiredService <ILogger <UserRepository> >()));
            services.AddSingleton <IRepository <Book> >(s => new BookRepository(s.GetRequiredService <IDbConnection>(), s.GetRequiredService <ILogger <BookRepository> >()));
            services.AddSingleton <IUserBookRepository>(s => new UserBookRepository(s.GetRequiredService <IDbConnection>(), s.GetRequiredService <ILogger <UserBookRepository> >()));

            services.AddSingleton <IUserBookService>(s => new UserBookService(s.GetRequiredService <IUserBookRepository>(), s.GetRequiredService <IRepository <Book> >()));

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }
Example #30
0
        /// <summary>
        /// ユーザをテナントに所属させる。
        /// ユーザIDやテナントIDの存在チェックは行わない。
        /// 結果として、作成したすべての<see cref="UserTenantRegistryMap"/>を返す。
        /// </summary>
        /// <param name="user">対象ユーザ</param>
        /// <param name="tenantId">対象テナントID</param>
        /// <param name="roles">テナントロール</param>
        /// <exception cref="ArgumentException"><paramref name="roles"/>にシステムロールが含まれていたり、別テナント用のロールが含まれていた場合</exception>
        public IEnumerable <UserTenantRegistryMap> AttachTenant(User user, long tenantId, IEnumerable <Role> roles)
        {
            var tenantMap = new UserTenantMap()
            {
                TenantId = tenantId,
                User     = user
            };

            AddModel <UserTenantMap>(tenantMap);
            if (roles != null)
            {
                foreach (var role in roles)
                {
                    if (role == null)
                    {
                        continue;
                    }
                    if (role.IsSystemRole)
                    {
                        //Adminロールを特定テナントに所属させようとしている
                        throw new UnauthorizedAccessException($"The tenant role {role.Name} is not assigned to a user as a system role.");
                    }
                    var roleMap = new UserRoleMap()
                    {
                        RoleId    = role.Id,
                        TenantMap = tenantMap,
                        User      = user
                    };
                    AddModel <UserRoleMap>(roleMap);
                }
            }

            //まずはGitの登録
            //テナントに紐づいているすべてのGitを取得
            var GitMaps = FindModelAll <TenantGitMap>(m => m.TenantId == tenantId).Include(m => m.Git);

            foreach (var GitMap in GitMaps)
            {
                UserTenantGitMap utrMap = new UserTenantGitMap()
                {
                    TenantGitMap = GitMap,
                    UserId       = user.Id
                };

                // 既存の認証情報存在チェック
                var existMap = GetModelAll <UserTenantGitMap>()
                               .Where(m => m.UserId == user.Id && m.TenantGitMapId == GitMap.Id).FirstOrDefault();
                if (existMap != null)
                {
                    // 既存の認証情報が存在する場合、再設定する
                    utrMap.GitToken = existMap.GitToken;
                }
                else
                {
                    // UserTenantGitMap において userId と TenantGitMapId のペアが存在しなければ、エントリ新規追加のためログに出力する
                    LogDebug($"UserTenantGitMap エントリの新規追加 : UserId={user.Id}, TenantGitMapId={GitMap.Id}, TenantId={tenantId}, GitId={GitMap.GitId}");
                }

                AddModel <UserTenantGitMap>(utrMap);
            }

            //続いてレジストリの登録
            //レジストリ登録はクラスタ管理サービスへも影響するので、作成したMapを全て返す

            List <UserTenantRegistryMap> maps = new List <UserTenantRegistryMap>();

            //テナントに紐づいているすべてのレジストリを取得
            var registryMaps = FindModelAll <TenantRegistryMap>(m => m.TenantId == tenantId).Include(m => m.Registry);

            foreach (var registryMap in registryMaps)
            {
                UserTenantRegistryMap utrMap = new UserTenantRegistryMap()
                {
                    TenantRegistryMap = registryMap,
                    UserId            = user.Id
                };

                // 既存の認証情報存在チェック
                var existMap = GetModelAll <UserTenantRegistryMap>()
                               .Where(m => m.UserId == user.Id && m.TenantRegistryMapId == registryMap.Id).FirstOrDefault();
                if (existMap != null)
                {
                    // 既存の認証情報が存在する場合、再設定する
                    utrMap.RegistryUserName = existMap.RegistryUserName;
                    utrMap.RegistryPassword = existMap.RegistryPassword;
                }

                AddModel <UserTenantRegistryMap>(utrMap);
                maps.Add(utrMap);
            }
            return(maps);
        }
        /// <summary>
        /// Handles the Click event of the btnOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            // Name cannot be empty
            if (!FormHelper.ValidateNotEmpty(txtName, Resources.MsgNameRequired))
            {
                return;
            }

            // Login name cannot be empty
            if (!FormHelper.ValidateNotEmpty(txtLoginName, Resources.MsgLoginNameRequired))
            {
                return;
            }

            // Password cannot be empty
            if (!FormHelper.ValidateNotEmpty(txtPassword, Resources.MsgPasswordRequired))
            {
                return;
            }

            if (this.User == null)
            {
                // Login name cannot be the built-in administrator name
                if (GuiHelper.AdministratorName.Equals(txtLoginName.Text, StringComparison.OrdinalIgnoreCase))
                {
                    FormHelper.ShowError(Resources.MsgAdminUserNameNotAllowed);
                    txtLoginName.Focus();
                    return;
                }
            }

            // Validate passwords are the same
            if (!txtPassword.Text.Equals(txtPasswordAgain.Text))
            {
                FormHelper.ShowError(Resources.MsgPasswordNotMatched);
                txtPassword.Focus();
                return;
            }

            using (SharedDbConnectionScope sharedConnectionScope = new SharedDbConnectionScope())
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        if (User == null)
                        {
                            // Login name must be unique
                            if (IsDuplicate())
                            {
                                return;
                            }

                            // Create a new one
                            User user = new User();
                            user.CommonName = txtName.Text;
                            user.Mobtel     = txtPhoneNumber.Text;
                            user.Email      = txtEmail.Text;
                            user.LoginName  = txtLoginName.Text;
                            user.Password   = txtPassword.Text;
                            if (user.LoginName.Equals(GuiHelper.AdministratorName))
                            {
                                user.CanBeDeleted = false;
                            }
                            else
                            {
                                user.CanBeDeleted = true;
                            }
                            user.Save();

                            this.User = user;
                        }
                        else
                        {
                            if (!this.User.LoginName.Equals(txtLoginName.Text.Trim(), StringComparison.OrdinalIgnoreCase))
                            {
                                if (IsDuplicate())
                                {
                                    return;
                                }
                            }

                            // Update an existing one
                            this.User.CommonName = txtName.Text;
                            this.User.Mobtel     = txtPhoneNumber.Text;
                            this.User.Email      = txtEmail.Text;
                            this.User.LoginName  = txtLoginName.Text;
                            this.User.Password   = txtPassword.Text;
                            if (this.User.LoginName.Equals(GuiHelper.AdministratorName))
                            {
                                this.User.CanBeDeleted = false;
                            }
                            else
                            {
                                this.User.CanBeDeleted = true;
                            }
                            this.User.Update();
                        }


                        // Delete groups for this users
                        UserRoleMap.Delete(urm => urm.UserId == this.User.Id);

                        // Save the groups for this user
                        foreach (object item in lstBelongedGroups.Items)
                        {
                            string groupName = item as string;

                            // Get the user id and save the user role mapping
                            Role role = Role.SingleOrDefault(r => r.Name == groupName);
                            if (role != null)
                            {
                                UserRoleMap urm = new UserRoleMap();
                                urm.UserId = this.User.Id;
                                urm.RoleId = role.Id;
                                urm.Save();
                            }
                        }

                        FormHelper.ShowInfo(Resources.MsgUserSaved);
                    }
                    catch (Exception ex)
                    {
                        FormHelper.ShowError(ex.Message);
                    }
                    finally
                    {
                        try
                        {
                            ts.Complete();
                        }
                        catch (Exception) { }
                    }
                }
            }

            this.DialogResult = DialogResult.OK;
        }
Example #32
0
 /// <summary>
 /// 设置用户的角色
 /// </summary>
 /// <param name="id">用户编号</param>
 /// <param name="roleIds">角色编号集合</param>
 /// <returns>业务操作结果</returns>
 public async Task<OperationResult> SetUserRoles(int id, int[] roleIds)
 {
     User user = await UserRepository.GetByKeyAsync(id);
     if (user == null)
     {
         return new OperationResult(OperationResultType.QueryNull, "指定编号的用户信息不存在");
     }
     int[] existIds = UserRoleMapRepository.Entities.Where(m => m.User.Id == id).Select(m => m.Role.Id).ToArray();
     int[] addIds = roleIds.Except(existIds).ToArray();
     int[] removeIds = existIds.Except(roleIds).ToArray();
     UserRoleMapRepository.UnitOfWork.TransactionEnabled = true;
     foreach (int addId in addIds)
     {
         Role role = await RoleRepository.GetByKeyAsync(addId);
         if (role == null)
         {
             return new OperationResult(OperationResultType.QueryNull, "指定编号的角色信息不存在");
         }
         UserRoleMap map = new UserRoleMap(){User = user, Role = role};
         await UserRoleMapRepository.InsertAsync(map);
     }
     await UserRoleMapRepository.DeleteAsync(m => m.User.Id == id && removeIds.Contains(m.Role.Id));
     return await UserRoleMapRepository.UnitOfWork.SaveChangesAsync() > 0
         ? new OperationResult(OperationResultType.Success, "用户“{0}”指派角色操作成功".FormatWith(user.UserName))
         : OperationResult.NoChanged;
 }
Example #33
0
        /// <summary>
        /// Handles the Click event of the btnOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            // Name cannot be empty
            if (!FormHelper.ValidateNotEmpty(txtName, Resources.MsgNameRequired))
            {
                return;
            }

            if (this.Group == null)
            {
                // Name cannot be the built-in administrator group name
                if (GuiHelper.AdministratorGroupName.Equals(txtName.Text, StringComparison.OrdinalIgnoreCase))
                {
                    FormHelper.ShowError(Resources.MsgAdminGroupNameNotAllowed);
                    txtName.Focus();
                    return;
                }
            }

            using (SharedDbConnectionScope sharedConnectionScope = new SharedDbConnectionScope())
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        if (Group == null)
                        {
                            // Name must be unique
                            Role searchRole = Role.SingleOrDefault(r => r.Name.ToLower() == txtName.Text.ToLower());
                            if (searchRole != null)
                            {
                                FormHelper.ShowError(Resources.MsgGroupNameNotUnique);
                                return;
                            }

                            // Create a new one
                            Role role = new Role();
                            role.Name = txtName.Text.Trim();
                            role.Desc = txtDescription.Text;
                            if (role.Name.Equals(GuiHelper.AdministratorGroupName))
                            {
                                role.CanBeDeleted = false;
                            }
                            else
                            {
                                role.CanBeDeleted = true;
                            }
                            role.Save();
                            this.Group = role;
                        }
                        else
                        {
                            if (!this.Group.Name.Equals(txtName.Text.Trim(), StringComparison.OrdinalIgnoreCase))
                            {
                                // Check for duplicate
                                Role searchRole = Role.SingleOrDefault(r => r.Name.ToLower() == txtName.Text.ToLower());
                                if (searchRole != null)
                                {
                                    FormHelper.ShowError(Resources.MsgGroupNameNotUnique);
                                    return;
                                }
                            }

                            // Update an existing one
                            this.Group.Name = txtName.Text.Trim();
                            this.Group.Desc = txtName.Text;
                            if (this.Group.Name.Equals(GuiHelper.AdministratorGroupName))
                            {
                                this.Group.CanBeDeleted = false;
                            }
                            else
                            {
                                this.Group.CanBeDeleted = true;
                            }
                            this.Group.Update();
                        }


                        // Delete user related to existing groups
                        UserRoleMap.Delete(urm => urm.RoleId == this.Group.Id);

                        // Save the users for the existing groups
                        foreach (object item in lstUsersInGroup.Items)
                        {
                            string loginName = GetLoginName(item);

                            // Get the user id and save the user group mapping
                            User user = User.SingleOrDefault(u => u.LoginName == loginName);
                            if (user != null)
                            {
                                UserRoleMap urm = new UserRoleMap();
                                urm.UserId = user.Id;
                                urm.RoleId = this.Group.Id;
                                urm.Save();
                            }
                        }

                        FormHelper.ShowInfo(Resources.MsgGroupSaved);
                    }
                    catch (Exception ex)
                    {
                        FormHelper.ShowError(ex.Message);
                    }
                    finally
                    {
                        try
                        {
                            ts.Complete();
                        }
                        catch (Exception) { }
                    }
                }
            }

            this.DialogResult = DialogResult.OK;
        }
 public Task <int> InsertAsync(UserRoleMap entity)
 {
     return(_repository.InsertAsync(entity));
 }