Пример #1
0
        public async Task RenderUpdate()
        {
            NewCompanies          = TempService.NewCompanies;
            QualifiedCompanies    = TempService.QualifiedCompanies;
            NotQualifiedCompanies = TempService.NotQualifiedCompanies;
            countries             = TempService.Countries;
            SelectedId            = TempService.GetSelectedId();
            if (SelectedId != 0)
            {
                SelectedCompany = TempService.CompanyModels.Where(p => p.Id == SelectedId).FirstOrDefault();
                await InvokeAsync(StateHasChanged);

                contacts = await TempService.GetCompanyContacts(SelectedId);
            }
            else
            {
                SelectedCompany = null;
            }
            if (TempService.CurrentUser != null)
            {
                currentUser = TempService.CurrentUser;
                var logTemp = TempService.logs;
                if (logTemp != null)
                {
                    logs = TempService.logs.Where(p => p.UserId == currentUser.Id);
                }
            }
            SelectedCompany = TempService.CompanyModels.Where(p => p.Id == SelectedId).FirstOrDefault();
            Linkedins       = TempService.Linkedins;
        }
        public async Task <GetUserDTO> UpdateUser(GetUserDTO UserDTO)
        {
            var  mapper = new MapperConfiguration(cfg => cfg.CreateMap <User, GetUserDTO>()).CreateMapper();
            User model  = mapper.Map <GetUserDTO, User>(UserDTO);
            await _userManager.UpdateAsync(model);

            return(UserDTO);
        }
        public async Task <GetUserDTO> GetCurrent(string currentUserName)
        {
            User user = await _userManager.FindByNameAsync(currentUserName);

            var        mapper = new MapperConfiguration(cfg => cfg.CreateMap <User, GetUserDTO>()).CreateMapper();
            GetUserDTO DTO    = mapper.Map <User, GetUserDTO>(user);

            return(DTO);
        }
Пример #4
0
        public async Task DeleteUserAsync(GetUserDTO item)
        {
            User user = await _unitOfWork.UserRepository.GetByIdAsync(item.Id);

            User itemToRemove = _mapper.Map(item, user);

            _unitOfWork.UserRepository.Remove(itemToRemove);

            await _unitOfWork.SaveAsync();
        }
        public async Task <string> GetUserFullName(string userId)
        {
            if (userId == null)
            {
                return("Lead не назначен");
            }
            GetUserDTO user = await GetUser(userId);

            return(user.FirstName + " " + user.LastName);
        }
        public async Task <GetUserDTO> GetUser(string UserId)
        {
            User model = await _userManager.FindByIdAsync(UserId);

            var        config = new MapperConfiguration(cfg => cfg.CreateMap <User, GetUserDTO>());
            var        mapper = new Mapper(config);
            GetUserDTO DTO    = mapper.Map <GetUserDTO>(model);

            return(DTO);
        }
Пример #7
0
        public async Task <ActionResult <UserViewModel> > GetUser(string id)
        {
            GetUserDTO user = await userService.GetUser(id);

            var mapper = new MapperConfiguration(cfg => cfg.CreateMap <GetUserDTO, UserViewModel>()
                                                 .ForMember(p => p.RoleNames, p => p.MapFrom(s => userService.GetUserRoles(s.Id).Result.ToList()))).CreateMapper();
            UserViewModel userView = mapper.Map <GetUserDTO, UserViewModel>(user);

            return(Ok(userView));
        }
Пример #8
0
        public async Task <ActionResult <UserDTO> > GetUser(GetUserDTO getUserDTO)
        {
            if (!await Helpers.CheckAccessToken(userRepository, getUserDTO.UserId, getUserDTO.Token))
            {
                return(new UnauthorizedResult());
            }

            var user = await userRepository.GetUser(getUserDTO.UserId);

            return(new ActionResult <UserDTO>(Mapper.ToUserDTO(user)));
        }
        protected override async Task <IActionResult> ExecuteAction(GetUserByIdQuery command)
        {
            GetUserDTO user = await _userService.GetUserAsync(command.Id);

            if (user == null)
            {
                return(NotFound());
            }

            return(Ok(user));
        }
Пример #10
0
        protected override async Task <IActionResult> ExecuteAction(DeleteUserCommand command)
        {
            GetUserDTO user = await _userService.GetUserAsync(command.Id);

            if (user != null)
            {
                await _userService.DeleteUserAsync(user);
            }

            return(Ok(user));
        }
Пример #11
0
        public async Task <ReceivedUserLoginDTO> LoginUser(GetUserDTO incomingLoginDTO)
        {
            var hashChecker = new VerifyPasswordHashEngine();

            var receivedUser = await _userLoginInvoker.InvokeLoginUserCommand(_mapper.Map <GetUserRAO>(incomingLoginDTO));

            if (hashChecker.VerifyPasswordHash(incomingLoginDTO.Password, receivedUser.PasswordHash, receivedUser.PasswordSalt))
            {
                return(_mapper.Map <ReceivedUserLoginDTO>(receivedUser));
            }
            return(null);
        }
Пример #12
0
        public async Task <GetUserDTO> GetAsync(Guid id)
        {
            var user = await _repository.GetAsync(id);

            if (user != null)
            {
                return(GetUserDTO.FromEntity(user));
            }
            else
            {
                return(null);
            }
        }
Пример #13
0
        public List <GetUserDTO> GetUsersWhichAreNotFriendsOfUser(int id)
        {
            List <GetUserDTO>    notFriends = GetUsers();
            List <FriendUserDTO> friends    = this.GetFriendsOfUser(id);

            foreach (FriendUserDTO f in friends)
            {
                GetUserDTO user = notFriends.Where(nf => nf.Id == f.UserId).FirstOrDefault();
                if (user != null)
                {
                    notFriends.Remove(user);
                }
            }
            return(notFriends);
        }
Пример #14
0
        public async Task <IActionResult> Login([FromBody] CheckCredentialsDTO credentialsDTO)
        {
            try
            {
                GetUserDTO user = await _userService.CheckCredentials(credentialsDTO);

                return(Ok(new UserTokenDTO()
                {
                    Email = user.Email,
                    AccessToken = _jwtGeneraror.CreateToken(user)
                }));
            }
            catch (System.Exception ex)
            {
                return(BadRequest(ErrorDTO.Create(ex.Message)));
            }
        }
Пример #15
0
        public async Task <ActionResult <GetUserDTO> > GetUser(string email, [FromQuery(Name = "password")] string password, [FromQuery(Name = "accessToken")] string accessToken)
        {
            var userToGet = await _context.Users.Where(user => user.Email == email).FirstAsync();

            if (userToGet == null)
            {
                return(BadRequest(this.GetError(Error.INVALID_TOKEN)));
            }

            if (password == null && accessToken == null)
            {
                return(BadRequest(this.GetError(Error.INVALID_TOKEN)));
            }
            if (!userToGet.Password.Equals(new AES().EncryptToBase64String(password)))
            {
                return(BadRequest(this.GetError(Error.INVALID_PASSWORD)));
            }
            if (accessToken != null && !accessToken.Equals(userToGet.AccessToken))
            {
                return(BadRequest(this.GetError(Error.INVALID_TOKEN)));
            }
            if (accessToken != null && userToGet.tokenExpired())
            {
                return(BadRequest(this.GetError(Error.EXPIRED_TOKEN)));
            }

            var expiresTimestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() + 60 * 60 * 24;

            userToGet.TokenExpires = expiresTimestamp.ToString();

            _context.Entry(userToGet).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                throw;
            }

            GetUserDTO getUserDTO = new GetUserDTO(userToGet);

            return(getUserDTO);
        }
Пример #16
0
 public IActionResult LoginUser([FromBody] LoginUserDTO loginUserDTO)
 {
     if (!ModelState.IsValid)
     {
         return(StatusCode(400, "bad data!"));
     }
     try
     {
         GetUserDTO getUserDTO = _userService.LoginUser(loginUserDTO);
         return(Ok(getUserDTO));
     }
     catch (APIException ex)
     {
         ErrorMessage err = new ErrorMessage {
             message = ex.Message
         };
         return(StatusCode(ex.StatusCode, err));
     }
 }
Пример #17
0
        public async Task <LoginRespone> Login(User user)
        {
            var result = await _signInManager.PasswordSignInAsync(user.UserName, user.Password, false, false);

            if (result.Succeeded)
            {
                var myUser = await _userManager.FindByNameAsync(user.UserName);

                if (user != null)
                {
                    var role = await _userManager.GetRolesAsync(myUser);

                    string userRole = role.FirstOrDefault();

                    var token = GenergateToken(new User {
                        UserName = myUser.UserName, Role = userRole
                    }, myUser.Id);

                    if (token.Success)
                    {
                        GetUserDTO authUser = _mapper.Map <GetUserDTO>(myUser);

                        authUser.Role = userRole;

                        return(new LoginRespone {
                            Success = true, Token = token.Token, User = authUser, Error = ""
                        });
                    }
                    return(new LoginRespone {
                        Success = false, Token = "", Error = token.error, User = null
                    });
                }
                return(new LoginRespone {
                    Success = false, Token = "", Error = "User have not found.", User = null
                });
            }
            return(new LoginRespone {
                Success = false, Token = "", Error = "Username or Password are not correct", User = null
            });
        }
Пример #18
0
        public string CreateToken(GetUserDTO user)
        {
            var jwtTokenHandler = new JwtSecurityTokenHandler();

            var key = Encoding.UTF8.GetBytes("stsaznzgt%@df1231%AFG35GS647GaetUIA46IjRTH5e");

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email),
                    new Claim(ClaimsIdentity.DefaultRoleClaimType, user.isAdmin ? "Admin": ""),
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token    = jwtTokenHandler.CreateToken(tokenDescriptor);
            var jwtToken = jwtTokenHandler.WriteToken(token);

            return(jwtToken);
        }
Пример #19
0
        public IActionResult GetUser([FromQuery] string phoneNumber, [FromQuery] int userId)
        {
            if (phoneNumber != null)
            {
                try
                {
                    GetUserDTO getUserDTO = _userService.GetUserDTOByPhoneNumber(phoneNumber);
                    return(Ok(getUserDTO));
                }
                catch (APIException ex)
                {
                    ErrorMessage err = new ErrorMessage {
                        message = ex.Message
                    };
                    return(StatusCode(ex.StatusCode, err));
                }
            }

            if (userId != 0)
            {
                try
                {
                    GetUserDTO getUserDTO = _userService.GetUserById(userId);
                    return(Ok(getUserDTO));
                }
                catch (APIException ex)
                {
                    ErrorMessage err = new ErrorMessage {
                        message = ex.Message
                    };
                    return(StatusCode(ex.StatusCode, err));
                }
            }

            return(StatusCode(StatusCodes.Status400BadRequest));
        }
Пример #20
0
        public async Task <ActionResult <GetUserDTO> > EditUser(GetUserDTO GetUserDTO)
        {
            await userService.UpdateUser(GetUserDTO);

            return(Ok(GetUserDTO));
        }
Пример #21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //----------------------------------------------------
            IConfigService configService     = new XMLConfigService("Config.xml");
            IMessenger     messenger_sms     = new SmsMessenger();
            IMessenger     messenger_email   = new EmailMessenger();
            IPassHasher    passHasher        = new SHA256Hasher();
            IKeyGenerator  smallKeyGenerator = new SmallKeyGenerator();
            IKeyGenerator  bigKeyGenerator   = new BigKeyGenerator();
            IRegValidator  regValidator      = new RegValidator();
            IUOWFactory    UOWFactory        = new EFUOWFactory(configService.ConnectionString);
            IGetUserDTO    getUserDTO        = new GetUserDTO();

            //----------------------------------------------------
            IClaimService claimService = new ClaimService(UOWFactory);

            //----------------------------------------------------
            services.AddSingleton <IConfigService, IConfigService>(
                serviceProvider =>
            {
                return(configService);
            }
                );
            //----------------------------------------------------
            services.AddSingleton <IGetUserDTO, IGetUserDTO>(
                serviceProvider =>
            {
                return(getUserDTO);
            }
                );
            //----------------------------------------------------
            services.AddSingleton <IUOWFactory, IUOWFactory>(
                serviceProvider =>
            {
                return(UOWFactory);
            }
                );

            services.AddSingleton <IClaimService, ClaimService>();
            //-----------------------------------------------------

            services.AddSingleton <IUserService, UserAuthService>(
                serviceProvider =>
            {
                return(new UserAuthService(
                           UOWFactory,
                           new AuthKeyService(smallKeyGenerator, messenger_sms),
                           new AuthKeyService(smallKeyGenerator, messenger_email),
                           passHasher,
                           regValidator,
                           claimService,
                           bigKeyGenerator,
                           getUserDTO
                           ));
            }
                );

            services.AddSingleton <IProfileService, ProfileService>(
                serviceProvider =>
            {
                IConfirmService emailCS = new ConfirmService(
                    new ConfirmKeyService(bigKeyGenerator, messenger_email)
                    );
                IConfirmService phoneCS = new ConfirmService(
                    new ConfirmKeyService(smallKeyGenerator, messenger_sms)
                    );
                return(new ProfileService(
                           UOWFactory,
                           regValidator,
                           emailCS,
                           phoneCS,
                           passHasher,
                           claimService,
                           getUserDTO
                           ));
            }
                );

            services.AddSingleton <IRestorePasswordService, RestorePasswordService>(
                serviceProvider =>
            {
                var emaiCKS  = new ConfirmKeyService(bigKeyGenerator, messenger_email);
                var phoneCKS = new ConfirmKeyService(smallKeyGenerator, messenger_sms);
                return(new RestorePasswordService(UOWFactory, emaiCKS, phoneCKS, new RegValidator(), passHasher));
            }
                );
            //---------Forum Services--------------------------------
            IGroupRules     groupRules     = new GroupRules();
            ISectionRules   sectionRules   = new SectionRules(groupRules);
            IThemeRules     themeRules     = new ThemeRules(sectionRules);
            IMessageRules   messageRules   = new MessageRules(themeRules, sectionRules);
            IDTOHelper      dtoHelper      = new DTOHelper();
            IForumDTOHelper forumDTOHelper = new ForumDTOHelper(messageRules, themeRules, sectionRules, groupRules, dtoHelper);

            services.AddSingleton <IGroupService, GroupService>(
                serviceProvider =>
            {
                return(new GroupService(groupRules, getUserDTO, UOWFactory, forumDTOHelper));
            }
                );

            services.AddSingleton <ISectionService, SectionService>(
                serviceProvider =>
            {
                return(new SectionService(sectionRules, getUserDTO, UOWFactory, forumDTOHelper));
            }
                );

            services.AddSingleton <IThemeService, ThemeService>(
                serviceProvider =>
            {
                return(new ThemeService(themeRules, getUserDTO, UOWFactory, forumDTOHelper));
            }
                );

            services.AddSingleton <IMessageService, MessageService>(
                serviceProvider =>
            {
                return(new MessageService(messageRules, getUserDTO, UOWFactory, forumDTOHelper));
            }
                );

            services.AddSingleton <IForumService, ForumService>(
                serviceProvider =>
            {
                return(new ForumService(getUserDTO, UOWFactory, forumDTOHelper, groupRules));
            }
                );
            //--------------------Page Services--------------------
            IPageRules pageRules = new PageRules();
            INoteRules noteRules = new NoteRules();

            services.AddSingleton <IPageService, PageService>(
                serviceProvider =>
            {
                return(new PageService(pageRules, UOWFactory, getUserDTO, dtoHelper));
            }
                );

            services.AddSingleton <IBlogService, BlogService>(
                serviceProvider =>
            {
                return(new BlogService(noteRules, UOWFactory, getUserDTO, dtoHelper));
            }
                );

            //-------------------------------------------------------
            services.AddSingleton <IImageService, ImageService>(
                serviceProvider =>
            {
                return(new ImageService(UOWFactory, getUserDTO));
            }
                );
            //-------------------------------------------
            services.AddSingleton <IAdminService, AdminService>(
                serviceProvider =>
            {
                return(new AdminService(getUserDTO, UOWFactory));
            }
                );

            services.Configure <FormOptions>(x =>
            {
                x.ValueCountLimit          = int.MaxValue;
                x.MemoryBufferThreshold    = int.MaxValue;
                x.ValueLengthLimit         = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
            });
            //------------------------------------------------------
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath  = new Microsoft.AspNetCore.Http.PathString("/Account/Login");
                options.LogoutPath = new Microsoft.AspNetCore.Http.PathString("/Account/Logout");
                options.Events.OnValidatePrincipal = PrincipalValidator.ValidateAsync;
            });

            services.AddMvc();
        }
Пример #22
0
        public void GivenIMadeARequestToGetAnUserWithUserId(int userId)
        {
            var dtoHelper = new TfLAPITest.DTOHelper();

            getUserDTO = dtoHelper.GetUser("/api/users/" + userId);
        }