Пример #1
0
        public async Task <ApplicationUserEntity> CreateUser(ApplicationUserDto dto, string password)
        {
            var user = new ApplicationUserEntity()
            {
                UserName           = dto.UserName,
                NormalizedUserName = dto.NormalizedUserName,
                Email                = dto.Email,
                EmailConfirmed       = dto.EmailConfirmed,
                PhoneNumber          = dto.PhoneNumber,
                PhoneNumberConfirmed = dto.PhoneNumberConfirmed
            };

            try {
                var result = await _userManager.CreateAsync(user, password);

                if (result.Succeeded)
                {
                    // Add user to new roles
                    // var roleNames = await _roleManager.Roles.Where(x => model.Roles.Contains(x.Id)).Select(x => x.Name).ToArrayAsync();
                    //var res2 = await _userManager.AddToRolesAsync(user.Id, roleNames);
                    return(user);
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        //ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            } catch (Exception er) {
                System.Console.WriteLine(er.Message);
            }
            return(null);
        }
        public void DeleteUser(ApplicationUserEntity userEntity)
        {
            var user   = mapper.Map <ApplicationUserEntity, ApplicationUserSearch>(userEntity);
            var client = clients.GetValueOrDefault(typeof(ApplicationUserSearch))();

            client.Delete <ApplicationUserSearch>(user.Id, a => a.Index("user").Type("object"));
        }
Пример #3
0
        private async Task <List <Claim> > GetClaimsAsync(ApplicationUserEntity user)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            };

            IList <Claim> userClaims = await _userManager.GetClaimsAsync(user);

            IList <string> userRoles = await _userManager.GetRolesAsync(user);

            claims.AddRange(userClaims);

            foreach (var userRole in userRoles)
            {
                claims.Add(new Claim(ClaimTypes.Role, userRole));

                IdentityRole role = await _roleManager.FindByNameAsync(userRole);

                if (role != null)
                {
                    IList <Claim> roleClaims = await _roleManager.GetClaimsAsync(role);

                    claims.AddRange(roleClaims);
                }
            }

            return(claims);
        }
        public async Task <IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var info = await Authentication.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(InternalServerError());
            }

            var user = new ApplicationUserEntity()
            {
                UserName = model.Email, Email = model.Email
            };

            IdentityResult result = await UserManager.CreateAsync(user);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            result = await UserManager.AddLoginAsync(user.Id, info.Login);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }
            return(Ok());
        }
        public IActionResult Edit(UserModel model)
        {
            var entity = this.dbContext.Users.FirstOrDefault(x => x.Id == model.Id);

            if (entity == null)
            {
                entity = new ApplicationUserEntity();
                this.dbContext.Users.Add(entity);
            }
            var assignedRoles = this.dbContext.UserRoles.Where(x => x.UserId == model.Id);

            foreach (var assignedRole in assignedRoles)
            {
                this.dbContext.UserRoles.Remove(assignedRole);
            }
            this.dbContext.SaveChanges();

            foreach (var modelSelectedRole in model.SelectedRoles)
            {
                ApplicationRoleEntity role = this.dbContext.Roles.FirstOrDefault(x => x.Id == modelSelectedRole);
                this.dbContext.UserRoles.Add(new IdentityUserRole <long>
                {
                    RoleId = role.Id,
                    UserId = model.Id
                });
            }

            this.dbContext.SaveChanges();

            return(RedirectToAction("Index"));
        }
Пример #6
0
        public async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>();

            ApplicationUserEntity user = await userManager.FindAsync(context.UserName, context.Password);

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",
                                                     new[] { "http://localhost:52613" }); //todo: change to config

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Пример #7
0
        public async Task Login_UserAndPasswordAreValid_GeneratesJwt()
        {
            var loginDto = new LoginDto
            {
                Email    = "email",
                Password = "******"
            };
            var userEntity = new ApplicationUserEntity
            {
                Email = loginDto.Email
            };
            var expectedResult = new JwtDto();

            _userManagerMock.Setup(p => p.FindByNameAsync(loginDto.Email))
            .ReturnsAsync(userEntity);
            _userManagerMock.Setup(p => p.CheckPasswordAsync(userEntity, loginDto.Password)).ReturnsAsync(true);
            _jwtServiceMock.Setup(p => p.GenerateJwtAsync(userEntity)).ReturnsAsync(expectedResult);

            JwtDto actualResult = await _accountService.Login(loginDto);

            Assert.AreEqual(expectedResult, actualResult);
            _userManagerMock.Verify(p => p.FindByNameAsync(loginDto.Email), Times.Once);
            _userManagerMock.Verify(p => p.CheckPasswordAsync(userEntity, loginDto.Password), Times.Once);
            _jwtServiceMock.Verify(p => p.GenerateJwtAsync(userEntity), Times.Once);
        }
Пример #8
0
        /// <inheritdoc />
        public async Task UpdateAccountInfoAsync(AccountDto account)
        {
            ApplicationUserEntity currentUserEntity = await _userManager.FindByIdAsync(_userHelper.UserId);

            IdentityResult result;

            if (!string.IsNullOrEmpty(account.Password))
            {
                string token = await _userManager.GeneratePasswordResetTokenAsync(currentUserEntity);

                result = await _userManager.ResetPasswordAsync(currentUserEntity, token, account.Password);

                if (!result.Succeeded)
                {
                    throw new ValidationException("password", result.Errors);
                }
            }

            currentUserEntity.UserName = account.Email;
            currentUserEntity.Email    = account.Email;
            result = await _userManager.UpdateAsync(currentUserEntity);

            if (!result.Succeeded)
            {
                throw new ValidationException(result.Errors);
            }
        }
Пример #9
0
        public async Task UpdateAccountInfoAsync_UserAndPasswordAreValid_SavesChanges()
        {
            var userId     = Guid.NewGuid().ToString();
            var userEntity = new ApplicationUserEntity();
            var account    = new AccountDto
            {
                Email    = "email",
                Password = "******"
            };
            string token = Guid.NewGuid().ToString();

            _userHelperMock.SetupGet(p => p.UserId).Returns(userId);
            _userManagerMock.Setup(p => p.FindByIdAsync(userId)).ReturnsAsync(userEntity);
            _userManagerMock.Setup(p => p.GeneratePasswordResetTokenAsync(userEntity)).ReturnsAsync(token);
            _userManagerMock.Setup(p => p.ResetPasswordAsync(userEntity, token, account.Password))
            .ReturnsAsync(IdentityResult.Success);
            _userManagerMock.Setup(p =>
                                   p.UpdateAsync(
                                       It.Is <ApplicationUserEntity>(u => u.Email == account.Email && u.UserName == account.Email)))
            .ReturnsAsync(IdentityResult.Success);

            await _accountService.UpdateAccountInfoAsync(account);

            _userHelperMock.VerifyAll();
            _userManagerMock.VerifyAll();
        }
Пример #10
0
        public UserMiniViewModel GetUserMiniViewModel(ApplicationUserEntity applicationUserPost)
        {
            var userMiniViewModel = mapper.Map <ApplicationUserEntity, UserMiniViewModel>(applicationUserPost);

            userMiniViewModel.Role = GetUserRole(applicationUserPost).Result;
            return(userMiniViewModel);
        }
Пример #11
0
        public async Task <UserRole> GetUserRole(ApplicationUserEntity applicationUser)
        {
            var roles = repositoryOfRole.ReadMany().ToList();
            var role  = (await userManager.GetRolesAsync(applicationUser)).Select(a => roles.Where(b => b.Name == a).FirstOrDefault()).FirstOrDefault();

            return(mapper.Map <RoleEntity, UserRole>(role));
        }
Пример #12
0
        public IEnumerable <BaseCommentViewModel> GetMany(string type, ApplicationUserEntity applicationUser, int?skip, int?take, string applicationUserIdCurrent)
        {
            var commentEntities = repositoryOfComment.ReadMany(new System.Linq.Expressions.Expression <Func <CommentEntity, bool> >[] { a => a.UserProfileId == applicationUser.UserProfileId }, null);

            commentEntities = commentEntities.OrderBy(a => a.Created).Reverse();
            return(GetMany(type, commentEntities, skip, take, applicationUserIdCurrent));
        }
Пример #13
0
        public ApplicationUser CreateUser(ApplicationUser user)
        {
            byte[] passwordHash;
            byte[] passwordSalt;
            _userPasswordService.CreateHash(user.Password, out passwordHash, out passwordSalt);

            var userEntity = new ApplicationUserEntity
            {
                FirstName    = user.FirstName,
                LastName     = user.LastName,
                Username     = user.Username,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                IsActive     = true
            };

            userEntity.Roles = user.Roles.Select(r =>
                                                 new ApplicationUserRoleEntity
            {
                ApplicationUserId = userEntity.Id,
                ApplicationRoleId = r.ApplicationRoleId
            }).ToList();

            var result = _userRepository.Insert(userEntity);

            return(_mapper.Map <ApplicationUser>(result));
        }
Пример #14
0
        public async Task Update(ApplicationUserEntity applicationUserCurrent, PostUpdateViewModel postCreateEditViewModel, PostEntity lastPostEntity = null)
        {
            lastPostEntity = (lastPostEntity == null) ? repositoryOfPost.Read(a => a.Id == postCreateEditViewModel.PostId, a => a.Tags, a => a.UserProfile, a => a.Images) : lastPostEntity;
            var postEntity = mapper.Map <PostUpdateViewModel, PostEntity>(postCreateEditViewModel);

            if (!await serviceOfUser.IsThereAccess(new[] { 2, 3 }, applicationUserCurrent, lastPostEntity.UserProfile.ApplicationUserId, true))
            {
                return;
            }
            if (postCreateEditViewModel.Section != null)
            {
                var section = repositoryOfSection.Read(a => a.Name == postCreateEditViewModel.Section);
                postEntity.Section   = section;
                postEntity.SectionId = section.Id;
            }
            if (postEntity.IsFinished == false && lastPostEntity.IsFinished == true)
            {
                postEntity.IsFinished = true;
            }
            postEntity.CountOfScore = lastPostEntity.CountOfScore;
            postEntity.SumOfScore   = lastPostEntity.SumOfScore;
            postEntity.Created      = lastPostEntity.Created;
            postEntity.Tags         = serviceOfTag.TagsPostUpdate(postCreateEditViewModel.Tags, lastPostEntity.Tags, postCreateEditViewModel.PostId);
            repositoryOfPost.Update(postEntity);
        }
Пример #15
0
 public LogActionEntity(ApplicationUserEntity performedBy, string action, string controller, string description)
 {
     PerformedBy = performedBy;
     Action      = action;
     Controller  = controller;
     Description = description;
     PerformedAt = DateTime.Now;
 }
Пример #16
0
        private PostMiniViewModel GetPostMiniViewModel(PostEntity postEntity, ApplicationUserEntity applicationUserCurrent)
        {
            var postViewModel       = mapper.Map <PostEntity, PostMiniViewModel>(postEntity);
            var applicationUserPost = repositoryOfApplicationUser.Read(a => a.UserProfileId == postEntity.UserProfileId);

            postViewModel.BelongsToUser = (applicationUserCurrent == null)
                ? false
                : applicationUserCurrent.UserProfileId == postEntity.UserProfileId;
            return(postViewModel);
        }
Пример #17
0
        private async Task SignInAsync(ApplicationUserEntity user, bool isPersistent)
        {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await _applicationManager.UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            AuthenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = isPersistent
            }, identity);
        }
Пример #18
0
        private PostUpdateViewModel GetPostUpdateViewModel(PostEntity postEntity, ApplicationUserEntity applicationUserCurrent)
        {
            var postViewModel = mapper.Map <PostEntity, PostUpdateViewModel>(postEntity);

            postViewModel.Tags          = serviceOfTag.GetTagsForPost(postEntity);
            postViewModel.Images        = repositoryOfImage.ReadMany(new Expression <Func <ImageEntity, bool> >[] { a => a.PostId == postEntity.Id }, null).Select(a => a.Path).ToList();
            postViewModel.BelongsToUser = (applicationUserCurrent == null)
                ? false
                : applicationUserCurrent.UserProfileId == postEntity.UserProfileId;
            return(postViewModel);
        }
Пример #19
0
        public ClaimsIdentity Authenticate(ApplicationUserDTO userDto)
        {
            ClaimsIdentity        claim = null;
            ApplicationUserEntity user  = _userRepository.Find(userDto.UserName, userDto.Password);

            if (user != null)
            {
                claim = _userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
            }
            return(claim);
        }
Пример #20
0
        private CommentViewModel GetCommentViewModel(CommentEntity commentEntity, ApplicationUserEntity applicationUserCurrent)
        {
            var commentViewModel                = mapper.Map <CommentEntity, CommentViewModel>(commentEntity);
            var applicationUserForComment       = repositoryOfUserProfile.Read(a => a.Id == commentEntity.UserProfileId, a => a.ApplicationUser).ApplicationUser;
            UserMiniViewModel userMiniViewModel = mapper.Map <ApplicationUserEntity, UserMiniViewModel>(applicationUserForComment);

            commentViewModel.BelongsToUser           = (applicationUserCurrent == null) ? false : applicationUserCurrent.UserProfileId == commentEntity.UserProfileId;
            commentViewModel.AuthorUserMiniViewModel = serviceOfUser.GetUserMiniViewModel(applicationUserForComment);
            commentViewModel.IsUserLiked             = (applicationUserCurrent == null) ? false : IsCommentLike(commentEntity, applicationUserCurrent.UserProfileId.Value);
            return(commentViewModel);
        }
Пример #21
0
        /// <inheritdoc />
        public async Task DeleteAsync(string id)
        {
            ApplicationUserEntity userEntity = await _userManager.FindByIdAsync(id);

            if (userEntity == null)
            {
                throw new NotFoundException();
            }

            await _userManager.DeleteAsync(userEntity);
        }
Пример #22
0
        public OperationDetails DeleteUser(ApplicationUserDTO user)
        {
            ApplicationUserEntity appUser = _userRepository.FindByName(user.UserName);

            if (appUser != null)
            {
                _userRepository.Delete(appUser);
                _uow.Commit();
                return(new OperationDetails(true, "Удаление прошло успешно", ""));
            }
            return(new OperationDetails(false, "Пользователь, который должен быть удален не существует", ""));
        }
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            ApplicationUserEntity user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                                       externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            return(Ok());
        }
Пример #24
0
        /// <inheritdoc />
        public async Task <JwtDto> Login(LoginDto model)
        {
            ApplicationUserEntity user = await _userManager.FindByNameAsync(model.Email) ?? await _userManager.FindByEmailAsync(model.Email);

            if (user != null)
            {
                if (await _userManager.CheckPasswordAsync(user, model.Password))
                {
                    return(await _jwtService.GenerateJwtAsync(user));
                }
            }

            throw new ValidationException("Incorrect email and/or password.");
        }
Пример #25
0
        /// <inheritdoc />
        public async Task UpdateAsync(UserDto userDto)
        {
            ApplicationUserEntity userEntity = await _userManager.FindByIdAsync(userDto.Id);

            if (userEntity == null)
            {
                throw new NotFoundException();
            }

            IdentityResult result;

            if (!string.IsNullOrEmpty(userDto.Password))
            {
                string token = await _userManager.GeneratePasswordResetTokenAsync(userEntity);

                result = await _userManager.ResetPasswordAsync(userEntity, token, userDto.Password);

                if (!result.Succeeded)
                {
                    throw new ValidationException("password", result.Errors);
                }
            }

            userEntity.UserName = userDto.Email;
            userEntity.Email    = userDto.Email;
            result = await _userManager.UpdateAsync(userEntity);

            if (!result.Succeeded)
            {
                throw new ValidationException("email", result.Errors);
            }

            IList <string> existingRoles = await _userManager.GetRolesAsync(userEntity);

            List <string> rolesToAdd    = userDto.Roles.Where(r => !existingRoles.Contains(r)).ToList();
            List <string> rolesToRemove = existingRoles.Where(r => !userDto.Roles.Contains(r)).ToList();

            result = await _userManager.RemoveFromRolesAsync(userEntity, rolesToRemove);

            if (!result.Succeeded)
            {
                throw new ValidationException("roles", result.Errors);
            }
            result = await _userManager.AddToRolesAsync(userEntity, rolesToAdd);

            if (!result.Succeeded)
            {
                throw new ValidationException("roles", result.Errors);
            }
        }
Пример #26
0
        private PostCompactViewModel GetPostCompactViewModel(PostEntity postEntity, ApplicationUserEntity applicationUserCurrent)
        {
            var postViewModel       = mapper.Map <PostEntity, PostCompactViewModel>(postEntity);
            var applicationUserPost = repositoryOfApplicationUser.Read(a => a.UserProfileId == postEntity.UserProfileId);

            postViewModel.AuthorUserMiniViewModel = serviceOfUser.GetUserMiniViewModel(applicationUserPost);
            postViewModel.BelongsToUser           = (applicationUserCurrent == null)
                ? false
                : applicationUserCurrent.UserProfileId == postEntity.UserProfileId;
            postViewModel.FirstImage = (postEntity.Images == null)
                ? repositoryOfImage.ReadMany(new Expression <Func <ImageEntity, bool> >[] { a => a.PostId == postEntity.Id }, null).FirstOrDefault()?.Path
                : postEntity.Images.FirstOrDefault().Path;
            return(postViewModel);
        }
Пример #27
0
        public async Task <AuthorizedUserModel> LoginUser(ApplicationUserEntity userForLogin)
        {
            var refreshToken = GenerateRefreshToken();

            authorizedUserModel.Token = await GenerateToken(userForLogin.Email);

            authorizedUserModel.RefreshToken = refreshToken;

            await userManager.RemoveAuthenticationTokenAsync(userForLogin, "UniversityApp", "RefreshToken");

            await userManager.SetAuthenticationTokenAsync(userForLogin, "UniversityApp", "RefreshToken", refreshToken);

            return(authorizedUserModel);
        }
Пример #28
0
        private async Task <List <Claim> > GetClaims(ApplicationUserEntity user)
        {
            var claims = new List <Claim> {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.Email, user.Email)
            };
            var roles = await userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }
            return(claims);
        }
Пример #29
0
        public async Task ChangeRole(ApplicationUserEntity applicationUser, UserRole newRole)
        {
            var roleName = (await userManager.GetRolesAsync(applicationUser)).FirstOrDefault();
            var role     = repositoryOfRole.Read(a => a.Name == roleName);

            if (newRole.Name != role.Name)
            {
                repositoryOfIdentityUserRole.Delete(new IdentityUserRole <string> {
                    UserId = applicationUser.Id, RoleId = role.Id
                });
                repositoryOfIdentityUserRole.Create(new IdentityUserRole <string> {
                    UserId = applicationUser.Id, RoleId = newRole.Id
                });
            }
        }
Пример #30
0
        private PostViewModel GetPostViewModel(PostEntity postEntity, ApplicationUserEntity applicationUserCurrent)
        {
            var postViewModel       = mapper.Map <PostEntity, PostViewModel>(postEntity);
            var applicationUserPost = repositoryOfApplicationUser
                                      .Read(a => a.UserProfileId == postEntity.UserProfileId);

            postViewModel.Tags = serviceOfTag.GetTagsForPost(postEntity);
            postViewModel.AuthorUserMiniViewModel = serviceOfUser.GetUserMiniViewModel(applicationUserPost);
            postViewModel.Comments      = serviceOfComment.GetMany(nameof(CommentViewModel), postEntity.Id, null, null, applicationUserCurrent) as List <CommentViewModel>;
            postViewModel.CurrentUserId = (applicationUserCurrent == null) ? null : applicationUserCurrent.Id;
            postViewModel.BelongsToUser = (applicationUserCurrent == null)
                ? false
                : applicationUserCurrent.UserProfileId == postEntity.UserProfileId;
            return(postViewModel);
        }