예제 #1
0
        public Result <List <Base> > List4Filter()
        {
            UserRoleEnum role = (UserRoleEnum)int.Parse(UserRA.Get(user_id.ToString(), "role"));
            List <Base>  lst  = UserDA.List <Base>(role == UserRoleEnum.Administrator ? 0 : user_id);

            return(Result(lst));
        }
예제 #2
0
        public User Update(User dto)
        {
            Fullname = Fullname;
            Role     = dto.Role;

            return(this);
        }
예제 #3
0
        public Result <List <Base> > List4Undirected()
        {
            UserRoleEnum             role = (UserRoleEnum)int.Parse(UserRA.Get(user_id.ToString(), "role"));
            List <Model.Common.Base> lst  = UnitDA.List4Undirected(role == UserRoleEnum.Administrator ? 0 : user_id);

            return(Result(lst));
        }
예제 #4
0
        public Result <List <Model.DB.User> > List()
        {
            UserRoleEnum         role = (UserRoleEnum)int.Parse(UserRA.Get(user_id.ToString(), "role"));
            List <Model.DB.User> lst  = UserDA.List <Model.DB.User>(role == UserRoleEnum.Administrator ? 0 : user_id);

            return(Result(lst));
        }
        public async Task <IActionResult> UpdateUserRoleThen(int id, UserRoleEnum userRoleEnum)
        {
            var user = await _userManager.FindByNameAsync(User.Identity.Name);

            switch (userRoleEnum)
            {
            case UserRoleEnum.Basic:
                await _userManager.AddToRoleAsync(user, UserRoleEnum.Basic.ToString());

                await _userManager.RemoveFromRoleAsync(user, UserRoleEnum.Admin.ToString());

                break;

            case UserRoleEnum.Admin:
                await _userManager.AddToRoleAsync(user, UserRoleEnum.Admin.ToString());

                await _userManager.AddToRoleAsync(user, UserRoleEnum.Basic.ToString());

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(userRoleEnum), userRoleEnum, null);
            }

            return(RedirectToAction("Index"));
        }
예제 #6
0
        public static void CreateBranchAdminUsersForNewBranch(Branch branch, UserRoleEnum role)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            CreateBranchAdminUsersForNewBranch(db, branch, role);
            db.Dispose();
        }
예제 #7
0
        public void JwtGenerator_Generate_ReturnsToken(long userId, UserRoleEnum role)
        {
            // Arrange
            var tokenHandler = new JwtSecurityTokenHandler();
            var hmac         = new HMACSHA256();
            var key          = Convert.ToBase64String(hmac.Key);

            var configuration = Substitute.For <IOptions <JwtConfig> >();

            configuration.Value.Returns(new JwtConfig {
                SeacretKey = key
            });

            var sut = new JwtGenerator(configuration, _systemClock);

            // Act
            var token = sut.Generate(new User {
                UserId = userId, Role = role
            });

            // Assert
            Assert.NotNull(token);
            var securityToken = tokenHandler.ReadJwtToken(token);

            Assert.Contains(securityToken.Claims, c => c.Type == "unique_name" && c.Value == userId.ToString());
            Assert.Contains(securityToken.Claims, c => c.Type == "role" && c.Value == ((int)role).ToString());
            //Assert.DoesNotContain(securityToken.Claims, c => c.Type == "exp");
        }
예제 #8
0
        private LoginRequest MountLoginRequest(UserRoleEnum userRole)
        {
            var consumerDefault = new LoginRequest
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            switch (userRole)
            {
            case UserRoleEnum.Consumer:
                return(consumerDefault);

            case UserRoleEnum.Partner:
                return(new LoginRequest
                {
                    Email = "*****@*****.**",
                    Password = "******"
                });

            case UserRoleEnum.Admin:
                return(new LoginRequest
                {
                    Email = "*****@*****.**",
                    Password = "******"
                });

            default:
                return(consumerDefault);
            }
        }
예제 #9
0
 public UserModel(User db)
 {
     Id       = db.Id;
     Login    = db.Login;
     Password = db.Password;
     Role     = (UserRoleEnum)db.Role;
 }
예제 #10
0
        public async Task <IActionResult> UpdateUserRole(int id, UserRoleEnum userRoleEnum)
        {
            ;
            var userEntity = await _userLogic.Update(id, x => x.Role = userRoleEnum);

            switch (userRoleEnum)
            {
            case UserRoleEnum.Basic:
                await _userManager.AddToRoleAsync(userEntity, UserRoleEnum.Basic.ToString());

                await _userManager.RemoveFromRoleAsync(userEntity, UserRoleEnum.Admin.ToString());

                break;

            case UserRoleEnum.Admin:
                await _userManager.AddToRoleAsync(userEntity, UserRoleEnum.Admin.ToString());

                await _userManager.AddToRoleAsync(userEntity, UserRoleEnum.Basic.ToString());

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(userRoleEnum), userRoleEnum, null);
            }

            return(RedirectToAction("Index"));
        }
예제 #11
0
        private void ConfigurarSegunModo(UserRoleEnum mode)
        {
            string text;


            switch (mode)
            {
            case UserRoleEnum.JefeDepartamento:
                text = "Modo Jefe Grupo";
                ConfigurarModoJefeGrupo();
                break;

            case UserRoleEnum.Supervisor:
                text = "Modo Supervisor RR HH";
                ConfigurarModoSupervisor();
                break;

            case UserRoleEnum.Administrador:
            default:
                text = "Modo Administrador";
                ConfigurarModoAdministrador();
                break;
            }

            tslbInfo.Text = text;
        }
예제 #12
0
        public static void UpdateBranchUserRoleForAllBranches(Guid appUserId, UserRoleEnum userRole)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            UpdateBranchUserRoleForAllBranches(db, appUserId, userRole);
            db.Dispose();
        }
예제 #13
0
        internal static CurrentUser BuildPortalUser(int kioskId, UserRoleEnum portalUserRole, int customerId, bool isSystemCustomer, string timeZoneName)
        {
            UserRoleEnum userRole;

            switch (portalUserRole)
            {
            case UserRoleEnum.CustomerAdmin:
                userRole = isSystemCustomer ? UserRoleEnum.GlobalAdmin : UserRoleEnum.CustomerAdmin;
                break;

            case UserRoleEnum.CustomerSupport:
                userRole = isSystemCustomer ? UserRoleEnum.GlobalSupport : UserRoleEnum.CustomerSupport;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(portalUserRole), portalUserRole, null);
            }

            return(new CurrentUser()
            {
                Id = kioskId,
                Role = userRole,
                CustomerId = customerId,
                TimeZoneName = timeZoneName
            });
        }
예제 #14
0
        public async Task VolunteersController_CantDelete_RemoveVolunteerAssign(UserRoleEnum role)
        {
            // Arrange
            IntegrationTestsFixture.SetUserContext(new User {
                Role = role
            });
            var dream = _fixture.DreamBuilder().WithNewCategory().Create();
            var user  = _fixture.VolunteerBuilder().Create();

            await IntegrationTestsFixture.DatabaseContext.Dreams.AddAsync(dream);

            await IntegrationTestsFixture.DatabaseContext.Users.AddAsync(user);

            await IntegrationTestsFixture.DatabaseContext.AssignedDreams.AddAsync(new AssignedDreams { Dream = dream, Volunteer = user });

            await IntegrationTestsFixture.DatabaseContext.SaveChangesAsync();

            // Act
            var response = await Client.DeleteAsync(CreateDeleteUrl(user.UserId, dream.DreamId));

            var existingAssign = await IntegrationTestsFixture.DatabaseContext.AssignedDreams.FirstOrDefaultAsync();

            // Assert
            response.IsSuccessStatusCode.Should().BeFalse();
            existingAssign.Should().NotBeNull();
        }
예제 #15
0
        public static BranchUser UpdateBranchUserRole(Guid branchUserId, UserRoleEnum userRole)
        {
            ApplicationDbContext db = new ApplicationDbContext();
            BranchUser           updateBranchUser = UpdateBranchUserRole(db, branchUserId, userRole);

            db.Dispose();
            return(updateBranchUser);
        }
예제 #16
0
 public DefaultUser(string name, string surname, UserRoleEnum role, string email, string password)
 {
     FirstName = name;
     Surname   = surname;
     Email     = email;
     Password  = password;
     Role      = role;
 }
예제 #17
0
        public static ApplicationUser UpdateUserRole(IPrincipal user, UserRoleEnum role)
        {
            ApplicationDbContext db = new ApplicationDbContext();
            ApplicationUser      applicationUser = UpdateUserRole(db, user, role);

            db.Dispose();
            return(applicationUser);
        }
예제 #18
0
 public static IEnumerable <UserRoleEnum> SubRoles(this UserRoleEnum userRoleEnum)
 {
     return((userRoleEnum switch
     {
         UserRoleEnum.Basic => Enumerable.Empty <UserRoleEnum>(),
         UserRoleEnum.Admin => ImmutableList.Create <UserRoleEnum>()
         .Add(UserRoleEnum.Basic),
         _ => Enumerable.Empty <UserRoleEnum>()
     }).Concat(new[] { userRoleEnum }).ToHashSet());
 public void Create(UserRoleEnum role, int RedirectID, RedirectType type, string format, params string[] args)
 {
     var roleInt = (int)role;
     var users = db.Users.Where(u => (u.Role.RoleEnum & roleInt) == u.Role.RoleEnum).ToList();
     foreach (var u in users)
     {
         Create(u, RedirectID, type, format, args);
     }
 }
예제 #20
0
        public UserRoleViewModel(RoleRequirementViewModel viewModel, UserRoleEnum role)
        {
            this.viewModel = viewModel;
            this.Role      = role;

            this.DeleteAdvancedRoleCommand = this.CreateCommand(() =>
            {
                this.viewModel.SelectedAdvancedRoles.Remove(this);
            });
        }
 public ConsumablesActionModel(StreamPassModel streamPass, ConsumablesActionTypeEnum actionType, string amount, string username = null, UserRoleEnum usersToApplyTo = UserRoleEnum.User, bool deductFromUser = false)
     : base(ActionTypeEnum.Consumables)
 {
     this.StreamPassID   = streamPass.ID;
     this.ActionType     = actionType;
     this.Amount         = amount;
     this.Username       = username;
     this.UsersToApplyTo = usersToApplyTo;
     this.DeductFromUser = deductFromUser;
 }
예제 #22
0
        public bool HasPermissionsTo(UserRoleEnum checkRole)
        {
            Logger.Log($"Checking role permission for user: {this.PrimaryRole} - {checkRole}");

            if (checkRole == UserRoleEnum.Subscriber && this.IsEquivalentToSubscriber())
            {
                return(true);
            }
            return(this.PrimaryRole >= checkRole);
        }
 public ConsumablesActionModel(CurrencyModel currency, ConsumablesActionTypeEnum actionType, string amount, string username = null, UserRoleEnum usersToApplyTo = UserRoleEnum.User, bool deductFromUser = false)
     : base(ActionTypeEnum.Consumables)
 {
     this.CurrencyID     = currency.ID;
     this.ActionType     = actionType;
     this.Amount         = amount;
     this.Username       = username;
     this.UsersToApplyTo = usersToApplyTo;
     this.DeductFromUser = deductFromUser;
 }
예제 #24
0
 /// <summary>
 /// Ctor - service channel id validator.
 /// </summary>
 /// <param name="model">Service channel id</param>
 /// <param name="channelService">Service channel service</param>
 /// <param name="userRole">Current user role.</param>
 /// <param name="propertyName">Property name</param>
 /// <param name="propertyItemName"></param>
 /// <param name="publishedVersion">Indicates if published or latest version should be fetched.</param>
 public ServiceChannelIdValidator(Guid model, IChannelService channelService, UserRoleEnum userRole, string propertyName, string propertyItemName = null, bool publishedVersion = true) : base(model, propertyName)
 {
     this.channelService   = channelService;
     this.userRole         = userRole;
     this.publishedVersion = publishedVersion;
     if (!string.IsNullOrEmpty(propertyItemName))
     {
         PropertyName = $"{propertyName}.{propertyItemName}";
     }
 }
        public override ActionBase GetAction()
        {
            if (this.CurrencyTypeComboBox.SelectedIndex >= 0 && this.CurrencyActionTypeComboBox.SelectedIndex >= 0)
            {
                CurrencyModel          currency   = this.GetSelectedCurrency();
                InventoryModel         inventory  = this.GetSelectedInventory();
                StreamPassModel        streamPass = this.GetSelectedStreamPass();
                CurrencyActionTypeEnum actionType = (CurrencyActionTypeEnum)this.CurrencyActionTypeComboBox.SelectedItem;

                if (actionType == CurrencyActionTypeEnum.ResetForAllUsers || actionType == CurrencyActionTypeEnum.ResetForUser || !string.IsNullOrEmpty(this.CurrencyAmountTextBox.Text))
                {
                    if (actionType == CurrencyActionTypeEnum.AddToSpecificUser)
                    {
                        if (string.IsNullOrEmpty(this.CurrencyUsernameTextBox.Text))
                        {
                            return(null);
                        }
                    }

                    UserRoleEnum roleRequirement = UserRoleEnum.User;
                    if (actionType == CurrencyActionTypeEnum.AddToAllChatUsers || actionType == CurrencyActionTypeEnum.SubtractFromAllChatUsers)
                    {
                        if (this.CurrencyPermissionsAllowedComboBox.SelectedIndex < 0)
                        {
                            return(null);
                        }
                        roleRequirement = (UserRoleEnum)this.CurrencyPermissionsAllowedComboBox.SelectedItem;
                    }

                    if (currency != null)
                    {
                        return(new CurrencyAction(currency, actionType, this.CurrencyAmountTextBox.Text, username: this.CurrencyUsernameTextBox.Text,
                                                  roleRequirement: roleRequirement, deductFromUser: this.DeductFromUserToggleButton.IsChecked.GetValueOrDefault()));
                    }
                    else if (inventory != null)
                    {
                        if (actionType == CurrencyActionTypeEnum.ResetForAllUsers || actionType == CurrencyActionTypeEnum.ResetForUser)
                        {
                            return(new CurrencyAction(inventory, actionType));
                        }
                        else if (!string.IsNullOrEmpty(this.InventoryItemNameComboBox.Text))
                        {
                            return(new CurrencyAction(inventory, actionType, this.InventoryItemNameComboBox.Text, this.CurrencyAmountTextBox.Text,
                                                      username: this.CurrencyUsernameTextBox.Text, roleRequirement: roleRequirement, deductFromUser: this.DeductFromUserToggleButton.IsChecked.GetValueOrDefault()));
                        }
                    }
                    else if (streamPass != null)
                    {
                        return(new CurrencyAction(streamPass, actionType, this.CurrencyAmountTextBox.Text, username: this.CurrencyUsernameTextBox.Text,
                                                  roleRequirement: roleRequirement, deductFromUser: this.DeductFromUserToggleButton.IsChecked.GetValueOrDefault()));
                    }
                }
            }
            return(null);
        }
예제 #26
0
        public async Task <string> Add(AddUserRequest model, UserRoleEnum userRole)
        {
            if (String.IsNullOrEmpty(model.Username))
            {
                throw new ArgumentException("Username not valid");
            }
            if (String.IsNullOrEmpty(model.Password))
            {
                throw new ArgumentException("Password not valid");
            }

            var isUsed = await IsUsernameUsed(model.Username);

            if (isUsed)
            {
                throw new ArgumentException("Username already in use");
            }

            using (IDbConnection connection = _factory.Connection( )) {
                Guid userId    = Guid.NewGuid( );
                Guid profileId = Guid.NewGuid( );

                var sql = @"INSERT INTO users(
	                            id, username, password, role, is_deleted)
	                            VALUES (uuid( @id), @username, @password, @role, 0);"    ;


                await connection.ExecuteAsync(sql,
                                              new {
                    id       = userId.ToString( ),
                    username = model.Username,
                    password = _passwordService.Encrypt(model.Password),
                    role     = (int)userRole
                });

                var profileSql = @"INSERT INTO user_profiles(
	                                id, user_id, email, phone, address)
	                                VALUES (uuid(@id), uuid(@userId), @email, @phone, @address);"    ;


                await connection.ExecuteAsync(profileSql,
                                              new {
                    id      = profileId.ToString( ),
                    userId  = userId.ToString( ),
                    email   = model.Email ?? "",
                    phone   = model.Phone ?? "",
                    address = model.Address ?? ""
                });



                return(userId.ToString( ));
            }
        }
예제 #27
0
        public void TestConvertEnumToIList()
        {
            var value1 = new UserRoleEnum().FromEnum();
            var value2 = UserRoleEnum.User.FromEnum();

            Assert.AreEqual(string.Join(",", value1), string.Join(",", value2), "Error getting list from enum, expected same");

            var count = ((UserRoleEnum[])System.Enum.GetValues(typeof(UserRoleEnum))).Count();

            Assert.AreEqual(count, value1.Count, "Error getting list from enum, expected same");
        }
예제 #28
0
        public Task <IdentityResult> Create(User user, string password, UserRoleEnum role)
        {
            //add claims & roles
            var ir = _userManager.CreateAsync(user, password);

            ir = _userManager.AddToRoleAsync(user, role.ToString());
            var newClaim = new Claim(role.ToString(), role.ToString(), ClaimValueTypes.String);

            ir = _userManager.AddClaimAsync(user, newClaim);
            return(ir);
        }
 public ConsumablesActionModel(InventoryModel inventory, ConsumablesActionTypeEnum actionType, string itemName = null, string amount = null, string username = null, UserRoleEnum usersToApplyTo = UserRoleEnum.User, bool deductFromUser = false)
     : base(ActionTypeEnum.Consumables)
 {
     this.InventoryID    = inventory.ID;
     this.ActionType     = actionType;
     this.ItemName       = itemName;
     this.Amount         = amount;
     this.Username       = username;
     this.UsersToApplyTo = usersToApplyTo;
     this.DeductFromUser = deductFromUser;
 }
예제 #30
0
 public static IHtmlContent PartialWithRole(this IHtmlHelper helper, string partialName, object model, ClaimsPrincipal user, UserRoleEnum userRole)
 {
     if (user.IsInRole(userRole.ToString()))
     {
         return helper.Partial(partialName, model: model);
     }
     else
     {
         return helper.Raw(string.Empty);
     }
 }
예제 #31
0
 public CurrencyAction(CurrencyModel currency, CurrencyActionTypeEnum currencyActionType, string amount, string username = null,
                       UserRoleEnum roleRequirement = UserRoleEnum.User, bool deductFromUser = false)
     : this()
 {
     this.CurrencyID         = currency.ID;
     this.CurrencyActionType = currencyActionType;
     this.Amount             = amount;
     this.Username           = username;
     this.RoleRequirement    = roleRequirement;
     this.DeductFromUser     = deductFromUser;
 }
예제 #32
0
 public BidGameCommandModel(string name, HashSet <string> triggers, UserRoleEnum starterRole, int timeLimit, CustomCommandModel startedCommand, CustomCommandModel newTopBidderCommand,
                            CustomCommandModel notEnoughPlayersCommand, CustomCommandModel gameCompleteCommand)
     : base(name, triggers, GameCommandTypeEnum.Bid)
 {
     this.StarterRole             = starterRole;
     this.TimeLimit               = timeLimit;
     this.StartedCommand          = startedCommand;
     this.NewTopBidderCommand     = newTopBidderCommand;
     this.NotEnoughPlayersCommand = notEnoughPlayersCommand;
     this.GameCompleteCommand     = gameCompleteCommand;
 }
 public static bool IsUserInRole(UserRoleEnum role)
 {
     return IsUserInRole(new[] { role });
 }
        public bool ValidatePermissions(string controller, string action, string user, UserIndentity userIndentity, UserRoleEnum role)
        {
            if (userIndentity == null)
            {
                return false;
            }
            bool result = false;

            try
            {
                result = userIndentity.User.UserRole == (int)role;
            }
            catch (Exception)
            {
                result = false;
            }

            //if (user == "user1" && controller == "Home")
            //{
            //    switch (action)
            //    {
            //        case "Test":
            //            isUserAccess = true;
            //            break;
            //    }
            //}

            //if (user == "user2" && controller == "Home")
            //{
            //    switch (action)
            //    {
            //        case "Edit":
            //            isUserAccess = true;
            //            break;
            //    }
            //}

            //// Незарегистрированных ползователей пускаем на главную и "О проекте"
            //if (controller == "Home" && (action == "Index" || action == "About"))
            //{
            //    isUserAccess = true;
            //}

            return result;
        }
예제 #35
0
        public void TestConvertEnumToIList()
        {
            var value1 = new UserRoleEnum().FromEnum();
            var value2 = UserRoleEnum.User.FromEnum();
            Assert.AreEqual(string.Join(",", value1), string.Join(",", value2), "Error getting list from enum, expected same");

            var count = ((UserRoleEnum[]) System.Enum.GetValues(typeof (UserRoleEnum))).Count();
            Assert.AreEqual(count, value1.Count, "Error getting list from enum, expected same");
        }