Beispiel #1
0
        public async Task <IdentityResult <UserWithRoles> > GetUserByKey(string key)
        {
            var res = new IdentityResult <UserWithRoles>();

            var apiKeyResult = await _context.ApiKeys.SingleOrDefaultAsync(apiKey => apiKey.Key == key && apiKey.Active);

            if (apiKeyResult == null)
            {
                res.Errors    = new[] { "Invalid key" };
                res.ErrorType = ErrorType.InvalidParameters;
                return(res);
            }

            var user = await _userManager.FindByNameAsync(apiKeyResult.User.UserName);

            if (user == null)
            {
                res.Errors    = new[] { "User with this username not found" };
                res.ErrorType = ErrorType.NotFound;
                return(res);
            }

            var details = new UserWithRoles
            {
                User  = user,
                Roles = await _userManager.GetRolesAsync(user)
            };

            res.Object  = details;
            res.Success = true;

            return(res);
        }
        public JsonResult SaveUserWithRoles(UserWithRoles userWithRoles)
        {
            ReturnUserWithRoles returnResult = new ReturnUserWithRoles();

            returnResult.Code = "00";
            //validate
            if (userWithRoles == null)
            {
                returnResult.Code    = "99";
                returnResult.Message = "Không có dữ liệu/No data.";
                return(Json(returnResult, JsonRequestBehavior.AllowGet));
            }
            UserRoleDB          userRoleDB = new UserRoleDB();
            ReturnUserWithRoles returnUserWith_aRole;

            foreach (Role role in userWithRoles.Roles)
            {
                returnUserWith_aRole = userRoleDB.SaveUserWith_aRole(userWithRoles.UserID, role);
                if (returnUserWith_aRole.Code == "99")
                {
                    returnResult.Code     = "99";
                    returnResult.Message += "Lỗi phân quyền : " + role.RoleName + "; ";
                }
            }
            return(Json(returnResult, JsonRequestBehavior.AllowGet));
        }
Beispiel #3
0
        async public Task UpdateAsync(UserWithRoles entity)
        {
            var mappedUser = _mapper.Map <ApplicationUser>(entity.User);

            var mappedRoles   = _mapper.Map <IEnumerable <ApplicationRole> >(entity.Roles);
            var mappedRoleIds = mappedRoles.Select(role => role.Id);

            var userRoles = await GetUserRolesAsync(mappedUser);

            var userRoleIds = userRoles.Select(role => role.Id);

            foreach (string role in userRoleIds.Except(mappedRoleIds))
            {
                var identityRole = mappedUser.Roles.ToList().Find(item => item.RoleId == role);
                mappedUser.Roles.Remove(identityRole);
            }

            mappedUser.Roles.Clear();
            foreach (var role in mappedRoleIds)
            {
                mappedUser.Roles.Add(new IdentityUserRole <string>
                {
                    UserId = entity.User.Id,
                    RoleId = role
                });
            }

            await _userUnitOfWork.UserRepository.UpdateAsync(mappedUser);

            await _userUnitOfWork.SaveAsync();
        }
Beispiel #4
0
        public async Task <IActionResult> OnGetAsync()
        {
            Users = await _userManager.Users.ToListAsync();

            Roles = await _roleManager.Roles.ToListAsync();

            foreach (var user in Users)
            {
                var roles = await _userManager.GetRolesAsync(user);

                if (Role != null && roles.Contains(Role.Name))
                {
                    var userWithRoles = new UserWithRoles(user, roles.ToList());
                    UsersWithRole.Add(userWithRoles);
                }
                else if (Role == null)
                {
                    var userWithRoles = new UserWithRoles(user, roles.ToList());
                    UsersWithRole.Add(userWithRoles);
                }
            }


            return(Page());
        }
Beispiel #5
0
        /// <summary>
        /// Validate user by username and password
        /// </summary>
        /// <param name="username">username</param>
        /// <param name="password">password</param>
        /// <param name="lockoutOnFailure">to disable the lockout feature, use false</param>
        /// <returns></returns>
        public async Task <IdentityResult <UserWithRoles> > GetUserByUsername(string username, string password, bool lockoutOnFailure)
        {
            var res = new IdentityResult <UserWithRoles>();

            var user = await _userManager.FindByNameAsync(username);

            if (user == null)
            {
                res.Errors    = new[] { "User with this username not found" };
                res.ErrorType = ErrorType.NotFound;
                return(res);
            }


            var userHasValidPassword = await _userManager.CheckPasswordAsync(user, password);

            if (!userHasValidPassword)
            {
                res.Errors = new[] { "Invalid password" };

                if (_userManager.SupportsUserLockout && lockoutOnFailure)
                {
                    // If lockout is requested, increment access failed count which might lock out the user
                    await _userManager.AccessFailedAsync(user);

                    if (await _userManager.IsLockedOutAsync(user))
                    {
                        res.Errors = new[] { "Invalid password", "Account is locked out" };
                    }
                }

                res.ErrorType = ErrorType.InvalidParameters;
                return(res);
            }

            // account is still in lockout period
            if (_userManager.SupportsUserLockout && user.LockoutEnabled && user.LockoutEnd.HasValue)
            {
                if (user.LockoutEnd.Value.DateTime > DateTime.UtcNow)
                {
                    res.Errors    = new[] { "Account is still locked out" };
                    res.ErrorType = ErrorType.InvalidParameters;
                    return(res);
                }
            }

            await _userManager.ResetLockout(user);

            var details = new UserWithRoles
            {
                User  = user,
                Roles = await _userManager.GetRolesAsync(user)
            };

            res.Object  = details;
            res.Success = true;

            return(res);
        }
Beispiel #6
0
        private UserDetailsResponse GetUserToReturn(UserWithRoles userWithRoles)
        {
            var userToReturn = _mapper.Map <UserDetailsResponse>(userWithRoles.User);

            userToReturn.Roles = string.Join(';', userWithRoles.Roles);

            return(userToReturn);
        }
        internal static UserWithRoles GetDetailsObject(ApplicationUser info, IEnumerable <ApplicationRole> roles)
        {
            var userWithRoles = new UserWithRoles
            {
                User  = info,
                Roles = roles.Select(role => role.Name)
            };

            return(userWithRoles);
        }
Beispiel #8
0
        protected override async Task OnParametersSetAsync()
        {
            if (!string.IsNullOrEmpty(userId))
            {
                Title         = "Edit";
                userWithRoles = await Http.GetJsonAsync <UserWithRoles>("/api/User/" + userId);
            }

            await GetRoles();
        }
Beispiel #9
0
        public UserDto GetUser(IPrincipal principal)
        {
            // It's certain that the user exists and the principal is not null
            // because the request wouldn't arrive here if the user doesn't exist

            UserWithRoles user = _membershipService
                                 .GetUser(principal.Identity.Name);

            return(user.ToUserDto());
        }
Beispiel #10
0
        public async Task <ActionResult <UserModel> > GetCurrentUser()
        {
            UserWithRoles <ApplicationUser> user =
                await _repository.GetUserAsync(User.Identity.Name);

            if (user == null)
            {
                return(NotFound());
            }
            return(Ok(UserToModel(user.User, user.Roles)));
        }
Beispiel #11
0
        public async Task <ActionResult <UserModel> > GetUser([FromRoute] string name)
        {
            UserWithRoles <ApplicationUser> user =
                await _repository.GetUserAsync(name);

            if (user == null)
            {
                return(NotFound());
            }
            return(Ok(UserToModel(user.User, user.Roles)));
        }
Beispiel #12
0
        public async Task <IActionResult> OnGetAsync()
        {
            Users = await _userManager.Users.ToListAsync();

            Roles = await _roleManager.Roles.ToListAsync();

            foreach (var user in Users)
            {
                var roles = await _userManager.GetRolesAsync(user);

                var userWithRoles = new UserWithRoles(user, roles.ToList());
                UsersWithRoles.Add(userWithRoles);
            }


            return(Page());
        }
Beispiel #13
0
        protected async Task SaveUser()
        {
            var userWithRolesToSave = new UserWithRoles
            {
                User  = this.userWithRoles.User,
                Roles = editableRoles.Where(role => role.Selected)
            };

            if (!string.IsNullOrWhiteSpace(this.userWithRoles.User.Id))
            {
                await Http.SendJsonAsync(HttpMethod.Put, "api/User/", userWithRolesToSave);
            }
            else
            {
                await Http.SendJsonAsync(HttpMethod.Post, "/api/User/", userWithRolesToSave);
            }

            Cancel();
        }
Beispiel #14
0
        public static void Seed <T>(T context)
            where T : Data.TenderSearchDb
        {
            Seeder.Execute("Users", () =>
            {
                Seeder.Execute("Users", () =>
                {
                    const string EMAIL_DOMAIN = "tendersearch.com";

                    var emlIdentityMigration = context.CreateIdentityMigration <ApplicationUser>();
                    var hans      = new UserWithRoles("Hans", new[] { UserRoles.Admins.ToString(), UserRoles.UserManagers.ToString(), UserRoles.Users.ToString() }, EMAIL_DOMAIN);
                    var kyle      = new UserWithRoles("Kyle", new[] { UserRoles.UserManagers.ToString() }, EMAIL_DOMAIN);
                    var kitkat    = new UserWithRoles("KitKat", new[] { UserRoles.Users.ToString() }, EMAIL_DOMAIN);
                    var withRoles = new List <UserWithRoles>(new[] { hans, kyle, kitkat });

                    emlIdentityMigration.CreateUsers(withRoles);
                    context.DoSave("Users");
                });
            });
        }
Beispiel #15
0
 public static SysUserDto ToSysUserDto(this UserWithRoles ur)
 {
     return(new SysUserDto
     {
         UserName = ur.User.USERNAME,
         //Sn = ur.User.VT_SYSTEM.FirstOrDefault().SYS_SN,
         Address = ur.User.ADDRESS,
         CellPhone = ur.User.CELLPHONE,
         CityCode = ur.User.CITYCODE,
         ContactUser = ur.User.LINKMAN,
         CountryCode = ur.User.COUNTRYCODE,
         Email = ur.User.EMAIL,
         Id = ur.User.Key,
         LanguageCode = ur.User.LANGUAGECODE,
         PostCode = ur.User.POSTCODE,
         UserType = ur.User.USERTYPE,
         LicenseNo = ur.User.LICNO,
         StateCode = ur.User.STATECODE
     });
 }
Beispiel #16
0
        async public Task InsertAsync(UserWithRoles entity)
        {
            entity.User.Id = Guid.NewGuid().ToString();

            var mappedUser  = _mapper.Map <ApplicationUser>(entity.User);
            var mappedRoles = _mapper.Map <IEnumerable <ApplicationRole> >(entity.Roles);

            var roles = mappedRoles.Select(role => role.Id);

            foreach (var role in roles)
            {
                mappedUser.Roles.Add(new IdentityUserRole <string>
                {
                    UserId = entity.User.Id,
                    RoleId = role
                });
            }

            await _userUnitOfWork.UserRepository.InsertAsync(mappedUser);

            await _userUnitOfWork.SaveAsync();
        }
Beispiel #17
0
        public async Task <IdentityResult <UserWithRoles> > GetUserByUsername(string username)
        {
            var user = await _userManager.FindByNameAsync(username);

            if (user == null)
            {
                return(new IdentityResult <UserWithRoles>("User with this username not found", errorType: ErrorType.NotFound));
            }

            var details = new UserWithRoles
            {
                User  = user,
                Roles = await _userManager.GetRolesAsync(user)
            };

            var res = new IdentityResult <UserWithRoles>
            {
                Object  = details,
                Success = true
            };

            return(res);
        }
        internal static UserDto ToUserDto(this UserWithRoles userWithRoles)
        {
            if (userWithRoles == null)
            {
                throw new ArgumentNullException("userWithRoles");
            }

            if (userWithRoles.User == null)
            {
                throw new ArgumentNullException("userWithRoles.User");
            }

            return(new UserDto {
                Key = userWithRoles.User.Key,
                Name = userWithRoles.User.Name,
                Email = userWithRoles.User.Email,
                IsLocked = userWithRoles.User.IsLocked,
                CreatedOn = userWithRoles.User.CreatedOn,
                LastUpdatedOn = userWithRoles.User.LastUpdatedOn,
                Roles = userWithRoles.Roles.Select(
                    role => role.ToRoleDto()
                    )
            });
        }
Beispiel #19
0
        public override Task OnDisconnected()
        {
            string userName     = Context.User.Identity.Name;
            string connectionId = Context.ConnectionId;

            UserWithRoles userWithRoles = _membershipService.GetUser(userName);

            if (userWithRoles != null)
            {
                HubConnection hubConnection = _hubConnectionRepository.GetAll().FirstOrDefault(conn => conn.ConnectionId == connectionId);
                if (hubConnection != null)
                {
                    _hubConnectionRepository.Delete(hubConnection);
                    _hubConnectionRepository.Save();
                }

                if (!_hubConnectionRepository.GetAll().Any())
                {
                    Clients.Others.userDisconnected(userName);
                }
            }

            return(base.OnDisconnected());
        }
Beispiel #20
0
 async public Task Post([FromBody] UserWithRoles userWithRoles)
 {
     await _userService.InsertAsync(userWithRoles);
 }
Beispiel #21
0
        private UserDetailsShortResponse GetUserToReturnShort(UserWithRoles userWithRoles)
        {
            var userToReturn = _mapper.Map <UserDetailsShortResponse>(userWithRoles.User);

            return(userToReturn);
        }
Beispiel #22
0
 async public Task Put([FromBody] UserWithRoles userWithRoles)
 {
     await _userService.UpdateAsync(userWithRoles);
 }