public IActionResult MyMatches()
        {
            DeserializeUser deserializable = new DeserializeUser(new HttpContextAccessor());
            UserReadDto     loggedUser     = deserializable.GetLoggedUser();

            if (loggedUser == null)
            {
                return(RedirectToAction("LoginView", "Login", new { area = "" }));
            }

            if (loggedUser.Role == Role.TournamentDirector)
            {
                return(RedirectToAction("GetAllTournaments", "Tournament", new { area = "" }));
            }

            var matches    = _matchRepository.GetMatchesByUserId(loggedUser.Id);
            var matchesDto = _mapper.Map <List <MatchDto> >(matches);

            //problem with autoMapper (not mapping tournament)
            for (int i = 0; i < matchesDto.Count; i++)
            {
                matchesDto[i].TournamentDto = _mapper.Map <TournamentReadDto>(matches[i].Tournament);
            }

            return(matchesDto.Count == 0 ?
                   View("NoMatches", loggedUser) : View("/Views/UserAchievements/PlayerMatches.cshtml", new UserMatchesDto(matchesDto, loggedUser)));
        }
        public ActionResult MyTournaments()
        {
            DeserializeUser deserializable = new DeserializeUser(new HttpContextAccessor());
            UserReadDto     loggedUser     = deserializable.GetLoggedUser();

            if (loggedUser == null)
            {
                return(RedirectToAction("LoginView", "Login", new { area = "" }));
            }

            if (loggedUser.Role == Role.TournamentDirector)
            {
                return(RedirectToAction("GetAllTournaments", "Tournament", new { area = "" }));
            }

            List <TournamentReadDto> tournaments = _mapper.Map <List <TournamentReadDto> >(
                _tournamentRepository.GetTournamentByUserId(loggedUser.Id).ToList());

            foreach (var tournament in tournaments.Where(tournament => !tournament.Completed))
            {
                tournament.Started = _tournamentRepository.IsTournamentStarted(tournament.Id);
            }
            return(tournaments.Any()
                ? View("/Views/Tournament/GetAllTournaments.cshtml",
                       _mapper.Map <IEnumerable <TournamentReadDto> >(tournaments))
                : View("NoTournaments", loggedUser));
        }
        public ActionResult DeleteTournament(int id)
        {
            DeserializeUser deserializable = new DeserializeUser(new HttpContextAccessor());
            UserReadDto     loggedUser     = deserializable.GetLoggedUser();

            if (loggedUser == null)
            {
                return(RedirectToAction("LoginView", "Login", new { area = "" }));
            }

            if (loggedUser.Role == Role.Player)
            {
                return(RedirectToAction("GetAllTournaments", "Tournament", new { area = "" }));
            }

            var tournamentModelFromRepository = _repository.GetTournamentById(id);

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

            if (_matchRepository.IsAnyMatchInTheTournament(id))
            {
                TempData["CantDelete"] = tournamentModelFromRepository.Name;
                return(RedirectToAction(nameof(GetAllTournaments)));
            }

            _repository.DeleteTournament(tournamentModelFromRepository);
            _repository.SaveChanges();
            TempData["deleted"] = tournamentModelFromRepository.Name;
            return(RedirectToAction(nameof(GetAllTournaments))); //return to GetAllTournaments
        }
Esempio n. 4
0
        public ActionResult GetToken([FromBody] UserReadDto credentials)
        {
            var identity = GetIdentity(credentials.Username, credentials.Password);

            if (identity == null)
            {
                return(BadRequest(new { errorText = "Invalid username or password" }));
            }

            var now = DateTime.UtcNow;
            // create a jwt-token
            var jwt = new JwtSecurityToken(
                issuer: AuthOptions.ISSUER,
                audience: AuthOptions.AUDIENCE,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                username     = identity.Name
            };

            return(Ok(response));
        }
Esempio n. 5
0
 public MatchDto(TournamentReadDto tournamentDto, UserReadDto player1, UserReadDto player2, int round)
 {
     TournamentDto = tournamentDto;
     Player1       = player1;
     Player2       = player2;
     Round         = round;
 }
        public ActionResult UpdateTournamentView(int id /*[FromForm] TournamentCreateDto tournamentCreateDto*/)
        {
            DeserializeUser deserializable = new DeserializeUser(new HttpContextAccessor());
            UserReadDto     loggedUser     = deserializable.GetLoggedUser();

            if (loggedUser == null)
            {
                return(RedirectToAction("LoginView", "Login", new { area = "" }));
            }

            if (loggedUser.Role == Role.Player)
            {
                return(RedirectToAction("GetAllTournaments", "Tournament", new { area = "" }));
            }
            var tournamentModelFromRepository = _repository.GetTournamentById(id);

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

            TournamentCreateDto tournamentCreateDto = _mapper.Map <TournamentCreateDto>(tournamentModelFromRepository);

            //_mapper.Map(tournamentCreateDto, tournamentModelFromRepository); //updating

            //_repository.UpdateTournament(tournamentModelFromRepository);
            //_repository.SaveChanges();

            return(View("CreateTournamentView", tournamentCreateDto));
        }
        public ActionResult GetIncomingTournament()
        {
            DeserializeUser deserializable = new DeserializeUser(new HttpContextAccessor());
            UserReadDto     loggedUser     = deserializable.GetLoggedUser();

            IEnumerable <TournamentReadDto> tournamentsReadDto =
                _mapper.Map <IEnumerable <TournamentReadDto> >(_repository.GetIncomingTournament());

            List <TournamentParticipants> tournamentUserReadDtos = new List <TournamentParticipants>();

            foreach (var tournamentDto in tournamentsReadDto)
            {
                var usersDto     = _mapper.Map <List <UserReadDto> >(_userRepository.GetUsersByTournament(tournamentDto.Id));
                var isRegistered = loggedUser != null && _userRepository.IsUserRegisteredForTournamentById(loggedUser.Id,
                                                                                                           tournamentDto.Id);

                if (!_matchRepository.IsAnyMatchInTheTournament(tournamentDto.Id))
                {
                    tournamentUserReadDtos.Add(new TournamentParticipants(tournamentDto, usersDto, isRegistered));
                }
            }

            //return View((_mapper.Map<IEnumerable<TournamentReadDto>>(tournaments)));
            return(View(tournamentUserReadDtos));
        }
        public ActionResult CreateUser([FromForm] UserCreateDto userCreateDto, IFormFile upload)
        {
            if (upload != null)
            {
                using var ms = new MemoryStream();
                upload.CopyTo(ms);
                userCreateDto.Photo = ms.ToArray();
            }


            User user = _repository.GetUserByEMail(userCreateDto.EMail);

            if (user != null) //the same e-mail
            {
                ModelState.AddModelError("EMailExists", "E-Mail already exists");
                return(View("/Views/Register/RegisterView.cshtml", userCreateDto));
            }


            var userModel = _mapper.Map <User>(userCreateDto);

            userModel.Password = BCrypt.Net.BCrypt.HashPassword(userCreateDto.Password); //hash password

            _repository.CreateUser(userModel);
            _repository.SaveChanges();

            UserReadDto userSession = _mapper.Map <UserReadDto>(userModel);

            userSession.AvatarPhoto();
            HttpContext.Session.SetString("SessionUser", JsonConvert.SerializeObject(userSession));

            return(RedirectToAction("GetAllTournaments", "Tournament", new { area = "" }));
        }
Esempio n. 9
0
        public void Test_Equals_Positive()
        {
            var userOne = new UserReadDto(Id, Username);
            var userTwo = new UserReadDto(Id, Username);

            Assert.True(userOne.Equals(userTwo));
            Assert.True(userTwo.Equals(userOne));
        }
Esempio n. 10
0
        public ActionResult <UserReadDto> GetProfileData()
        {
            int userId = Convert.ToInt32(HttpContext.Items["id"]);

            UserReadDto result = _service.Get(userId);

            return(Ok(result));
        }
 public TournamentCourse(List <UserReadDto> users, TournamentReadDto tournamentDto, UserReadDto byeUser)
 {
     UsersDto      = users;
     TournamentDto = tournamentDto;
     _byeUser      = byeUser;
     RoundsNumber  = (int)Math.Ceiling(Math.Log2(TournamentDto.DrawSize));
     InitNameOfRound();
     DrawFirstRound();
 }
Esempio n. 12
0
        public ActionResult <UserReadDto> CreateUser(UserCreateDto user)
        {
            User userModel = _mapper.Map <User>(user);

            _userRepo.CreateUser(userModel);
            _userRepo.SaveChanges();
            UserReadDto userReadDto = _mapper.Map <UserReadDto>(userModel);

            return(CreatedAtRoute(nameof(GetUserById), new { id = userModel.Id }, userReadDto));
        }
Esempio n. 13
0
 public UserReadDtoTest()
 {
     _readDto = new UserReadDto()
     {
         UserID   = 1,
         Name     = "Test User",
         Username = "******",
         Email    = "*****@*****.**"
     };
 }
Esempio n. 14
0
        public UserReadDto VerifyUser(string email, string password)
        {
            UserReadDto user = _mapper.Map <UserReadDto>(_context.Users.FirstOrDefault(user => user.Email == email && user.Password == password));

            if (user == null)
            {
                return(null);
            }
            return(tokenGenerator(user));
        }
Esempio n. 15
0
 public MatchDto(int id, TournamentReadDto tournamentDto, UserReadDto player1, UserReadDto player2,
                 Winner winner, string result, int round)
 {
     Id            = id;
     TournamentDto = tournamentDto;
     Player1       = player1;
     Player2       = player2;
     Winner        = winner;
     Result        = result;
     Round         = round;
 }
        //todo drawing
        private void DrawFirstRound()
        {
            CurrentRound = 1;
            int sizeDraw            = TournamentDto.DrawSize;
            List <UserReadDto> draw = new List <UserReadDto>();

            for (int i = 0; i < sizeDraw; i++)
            {
                draw.Add(new UserReadDto(-1));
            }

            for (int i = UsersDto.Count; i < sizeDraw; i++)
            {
                UsersDto.Add(new UserReadDto(-1));
            }

            List <MatchDto> matchesTmp = new List <MatchDto>();

            for (int i = 0; i < sizeDraw / 2; i++)
            {
                matchesTmp.Add(new MatchDto(TournamentDto, UsersDto[i], UsersDto[UsersDto.Count - 1 - i], CurrentRound));
            }


            var upperHalf  = 0;
            var bottomHalf = sizeDraw - 1;

            for (int i = 0; i < sizeDraw / 2; i++)
            {
                MatchDto match = matchesTmp[i];
                if (i % 2 == 0)
                {
                    draw[upperHalf]     = match.Player1;
                    draw[upperHalf + 1] = match.Player2;
                    upperHalf          += 2;
                }
                else
                {
                    draw[bottomHalf]     = match.Player1;
                    draw[bottomHalf - 1] = match.Player2;
                    bottomHalf          -= 2;
                }
            }


            Matches = new List <MatchDto>();
            for (int i = 0; i < draw.Count; i += 2)
            {
                UserReadDto p1 = draw[i].Id == -1 ? _byeUser : draw[i];
                UserReadDto p2 = draw[i + 1].Id == -1 ? _byeUser : draw[i + 1];
                Matches.Add(new MatchDto(TournamentDto, p1, p2, CurrentRound));
            }
        }
Esempio n. 17
0
        public void Test_Equals_Negative()
        {
            var userOne   = new UserReadDto(Id, Username);
            var userTwo   = new UserReadDto(213312, Username);
            var userThree = new UserReadDto(Id, "sddadas");

            Assert.False(userOne.Equals(userTwo));
            Assert.False(userTwo.Equals(userOne));

            Assert.False(userOne.Equals(userThree));
            Assert.False(userThree.Equals(userOne));
        }
 public ActionResult <UserReadDto> Post(UserCreateDto user)
 {
     try
     {
         UserReadDto newUser = _userService.Create(user);
         return(CreatedAtAction("Get", new { id = newUser.Id }, newUser));
     }
     catch (ApiException ex)
     {
         return(StatusCode(ex.StatusCode, new { error = true, message = ex.Message }));
     }
 }
Esempio n. 19
0
        public ActionResult EditAccountView()
        {
            DeserializeUser deserializable = new DeserializeUser(new HttpContextAccessor());
            UserReadDto     loggedUser     = deserializable.GetLoggedUser();

            if (loggedUser == null)
            {
                return(RedirectToAction("LoginView", "Login", new { area = "" }));
            }
            User user = _repository.GetUserById(loggedUser.Id);

            return(View(_mapper.Map <UserEditDto>(user)));
        }
        private ClaimsIdentity GetIdentity(UserReadDto user)
        {
            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email),
                new Claim("UserId", user.Id),
            };
            ClaimsIdentity claimsIdentity =
                new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType,
                                   ClaimsIdentity.DefaultRoleClaimType);

            return(claimsIdentity);
        }
Esempio n. 21
0
        public UserReadDto SignUpUser(UserCore user)
        {
            if (_context.Users.Any(users => users.Email == user.Email))
            {
                return(null);
            }
            // user.UserRole = "user";
            // user.DateCreated = DateTime.Now;
            _context.Add(_mapper.Map <User>(user));
            _context.SaveChanges();
            UserReadDto newUser = _mapper.Map <UserReadDto>(_context.Users.FirstOrDefault(u => u.Email == user.Email && u.Password == user.Password));

            return(tokenGenerator(newUser));
        }
        public ActionResult CreateTournamentView()
        {
            DeserializeUser deserializable = new DeserializeUser(new HttpContextAccessor());
            UserReadDto     loggedUser     = deserializable.GetLoggedUser();

            if (loggedUser == null)
            {
                return(RedirectToAction("LoginView", "Login"));
            }
            if (loggedUser.Role == Role.Player)
            {
                return(RedirectToAction("GetAllTournaments", "Tournament", new { area = "" }));
            }
            return(View());
        }
        public async Task <UserReadDto> GetUserById(int id)
        {
            var user = await _context.Users.FirstOrDefaultAsync(s => s.ID == id);

            UserReadDto userDto = new UserReadDto()
            {
                Email    = user.Email,
                Phone    = user.Phone,
                Username = user.Username,
                ID       = id,
                Fullname = user.Name + " " + user.Surname
            };

            return(userDto);
        }
Esempio n. 24
0
        public ActionResult LoggedIn([FromForm] UserReadDto userReadDto)
        {
            var user = _repository.GetUserByEMail(userReadDto.EMail);

            if (user == null || !BCrypt.Net.BCrypt.Verify(userReadDto.Password, user.Password))
            {
                ModelState.AddModelError("WrongEMailOrPassword", "Wrong e-mail or password");
                return(View("/Views/Login/LoginView.cshtml", userReadDto));
            }

            UserReadDto toSaving = _mapper.Map <UserReadDto>(user);

            toSaving.AvatarPhoto();
            HttpContext.Session.SetString("SessionUser", JsonConvert.SerializeObject(toSaving));
            return(RedirectToAction("GetAllTournaments", "Tournament", new { area = "" }));
        }
Esempio n. 25
0
        public IActionResult WithdrawTournament(int id)
        {
            DeserializeUser deserializable = new DeserializeUser(new HttpContextAccessor());
            UserReadDto     loggedUser     = deserializable.GetLoggedUser();

            if (loggedUser == null)
            {
                return(RedirectToAction("LoginView", "Login", new { area = "" }));
            }

            var enrolment = _repository.FindEnrolment(loggedUser.Id, id);

            _repository.DeleteEnrolment(enrolment);
            _repository.SaveChanges();

            return(RedirectToAction("GetIncomingTournament", "Tournament"));
        }
Esempio n. 26
0
        public IActionResult EnrolTournament(int id)
        {
            DeserializeUser deserializable = new DeserializeUser(new HttpContextAccessor());
            UserReadDto     loggedUser     = deserializable.GetLoggedUser();

            if (loggedUser == null)
            {
                return(RedirectToAction("LoginView", "Login", new { area = "" }));
            }

            var enrolmentDto   = new EnrolmentDto(id, loggedUser.Id);
            var enrolmentModel = _mapper.Map <Enrolment>(enrolmentDto);

            _repository.SaveEnrolment(enrolmentModel);
            _repository.SaveChanges();

            return(RedirectToAction("GetIncomingTournament", "Tournament"));
        }
        private void CreateNextMatches()
        {
            List <MatchDto> matchesPrevRound = Matches.Where(m => m.Round == CurrentRound).ToList();

            CurrentRound += 1;
            for (int i = 0; i < matchesPrevRound.Count; i += 2)
            {
                UserReadDto winner1 = matchesPrevRound[i].Winner == Winner.One
                    ? matchesPrevRound[i].Player1
                    : matchesPrevRound[i].Player2;

                UserReadDto winner2 = matchesPrevRound[i + 1].Winner == Winner.One
                    ? matchesPrevRound[i + 1].Player1
                    : matchesPrevRound[i + 1].Player2;

                Matches.Add(new MatchDto(TournamentDto, winner1, winner2, CurrentRound));
            }
        }
        public async Task <ICollection <UserReadDto> > GetUnvalidated()
        {
            var unvalidatedAccounts = (await _context.Users.Where(u => !u.IsValidated).ToListAsync());
            var unvalidatedDtos     = new List <UserReadDto>();

            foreach (User user in unvalidatedAccounts)
            {
                UserReadDto userReadDto = new UserReadDto()
                {
                    Id        = user.Id,
                    FirstName = user.FirstName,
                    LastName  = user.LastName
                };

                unvalidatedDtos.Add(userReadDto);
            }
            return(unvalidatedDtos);
        }
Esempio n. 29
0
        public void Test_GetUserById()
        {
            // preparation
            var userReadDto = new UserReadDto(IdOne, UsernameOne);

            _mockUserRepo.Setup(x => x.GetUserById(IdOne)).Returns(_userOne);
            _mockMapper.Setup(x => x.Map <UserReadDto>(_userOne)).Returns(userReadDto);

            // actions
            var response     = _usersController.GetUserById(IdOne);
            var returnedUser = (response.Result as OkObjectResult)?.Value;

            // asserts
            Assert.Equal(200, ((OkObjectResult)response.Result).StatusCode);
            Assert.Equal(userReadDto, returnedUser);
            _mockUserRepo.Verify(x => x.GetUserById(IdOne), Times.Once());
            _mockUserRepo.VerifyNoOtherCalls();
            _mockMapper.Verify(x => x.Map <UserReadDto>(_userOne), Times.Once());
            _mockMapper.VerifyNoOtherCalls();
        }
        public async Task <ICollection <UserReadDto> > GetUsersByRole(string role)
        {
            var companyRoleId        = (await _context.Roles.FirstOrDefaultAsync(x => x.NormalizedName == role.ToUpper())).Id;
            var UserIdsFromCompanies = await _context.UserRoles.Where(x => x.RoleId == companyRoleId).Select(x => x.UserId).ToListAsync();

            var DtoList = new List <UserReadDto>();

            foreach (var id in UserIdsFromCompanies)
            {
                var dto = new UserReadDto
                {
                    Id        = id,
                    FirstName = (await _context.FindAsync <User>(id)).FirstName,
                    LastName  = (await _context.FindAsync <User>(id)).LastName
                };

                DtoList.Add(dto);
            }
            return(DtoList);
        }