Beispiel #1
0
        public void Delete(int id)
        {
            using (var db = new DiceGamingDb())
            {
                var user = db.Users.FirstOrDefault(u => u.Id == id);

                if (user == null)
                    throw new NotFoundException();

                db.Users.Remove(user);
                db.SaveChanges();
            }
        }
Beispiel #2
0
        public void Delete(int id)
        {
            using (var db = new DiceGamingDb())
            {
                var login = db.Logins.FirstOrDefault(l => l.Id == id);
                if (login == null)
                {
                    throw new NotFoundException();
                }

                db.Logins.Remove(login);
                db.SaveChanges();
            }
        }
Beispiel #3
0
        public void UpdateMoney(int id, decimal newMoney)
        {
            using (var db = new DiceGamingDb())
            {
                var user = db.Users.FirstOrDefault(u => u.Id == id);
                if (user == null)
                    throw new NotFoundException();

                user.Money = newMoney;

                db.Users.AddOrUpdate(user);
                db.SaveChanges();
            }
        }
Beispiel #4
0
        public UserDto AddMoney(int id, decimal money)
        {
            User user;
            using (var db = new DiceGamingDb())
            {
                user = db.Users.FirstOrDefault(u => u.Id == id);
                if (user == null)
                    throw new NotFoundException();

                user.Money += money;

                db.Users.AddOrUpdate(user);
                db.SaveChanges();
            }

            return CreateUserDTO(user);
        }
Beispiel #5
0
        public void Delete(int id)
        {
            using (var db = new DiceGamingDb())
            {
                var bet = db.Bets.FirstOrDefault(b => b.Id == id);
                if (bet == null)
                {
                    throw new NotFoundException();
                }

                var user = bet.User;
                user.Money = user.Money - bet.Win + bet.Stake;

                db.Users.AddOrUpdate(user);
                db.Bets.Remove(bet);
                db.SaveChanges();
            }
        }
Beispiel #6
0
        public UserDto UpdateNameAndEmail(UserDto user)
        {
            User userForUpdate;
            using (var db = new DiceGamingDb())
            {
                userForUpdate = db.Users.FirstOrDefault(u => u.Id == user.Id);
                if (userForUpdate == null)
                    throw new NotFoundException();

                userForUpdate.FullName = user.FullName;
                userForUpdate.Email = user.Email;

                db.Users.AddOrUpdate(userForUpdate);
                db.SaveChanges();
            }

            return CreateUserDTO(userForUpdate);
        }
Beispiel #7
0
        public LoginDto LoginUser(LoginDto login)
        {
            Login newLogin = new Login();

            using (var db = new DiceGamingDb())
            {
                if (db.Users.FirstOrDefault(u => u.Id == login.UserId) == null)
                {
                    throw new NotFoundException();
                }

                newLogin.UserId = login.UserId;
                newLogin.Token  = login.Token;

                db.Logins.Add(newLogin);
                db.SaveChanges();
            }

            return(CreateLoginDTO(newLogin));
        }
Beispiel #8
0
        public BetDto Create(BetDto bet)
        {
            var newBet = new Bet()
            {
                UserId        = bet.UserId,
                DiceSumBet    = bet.DiceSumBet,
                DiceSumResult = bet.DiceSumResult,
                Stake         = bet.Stake,
                Win           = bet.Win,
                CreationDate  = bet.CreationDate
            };

            using (var db = new DiceGamingDb())
            {
                db.Bets.Add(newBet);
                db.SaveChanges();
            }

            return(CreateBetDTO(newBet));
        }
Beispiel #9
0
        public void UpdatePassword(int id, string oldPassword, string newPassword)
        {
            using (var db = new DiceGamingDb())
            {
                var userForUpdate = db.Users.FirstOrDefault(u => u.Id == id);
                if (userForUpdate == null)
                    throw new NotFoundException();

                var saltedOldPassword = CryptographicManager.GenerateSHA256Hash(oldPassword, userForUpdate.Salt);

                if (!object.Equals(userForUpdate.Password, saltedOldPassword))
                    throw new BadRequestException();

                var saltedNewPassword = CryptographicManager.GenerateSHA256Hash(newPassword, userForUpdate.Salt);

                userForUpdate.Password = saltedNewPassword;

                db.Users.AddOrUpdate(userForUpdate);
                db.SaveChanges();
            }
        }
Beispiel #10
0
        public void TearDown()
        {
            TestHelper.Server?.Dispose();
            TestHelper.Client?.Dispose();

            // Remove all logins of test user
            using (var db = new DiceGamingDb())
            {
                var logins = db.Logins.Where(l => l.UserId == TestHelper.TestUser.Id);

                db.Logins.RemoveRange(logins);
                db.SaveChanges();
            }

            // Remove all bets of test user
            using (var db = new DiceGamingDb())
            {
                var bets = db.Bets.Where(b => b.UserId == TestHelper.TestUser.Id);

                db.Bets.RemoveRange(bets);
                db.SaveChanges();
            }
        }
Beispiel #11
0
        public UserDto Create(UserDto user)
        {
            User newUser;

            using (var db = new DiceGamingDb())
            {
                if (db.Users.FirstOrDefault(u => object.Equals(u.Username, user.Username)) != null)
                    throw new ConflictException();

                newUser = new User()
                {
                    FullName = user.FullName,
                    Email = user.Email,
                    Money = 0
                };

                CryptographicManager.SetNewUserInfo(newUser, user.Username, user.Password);

                db.Users.Add(newUser);
                db.SaveChanges();
            }

            return CreateUserDTO(newUser);
        }
Beispiel #12
0
        public void SetUp()
        {
            // Configure server and client
            var config = new HttpConfiguration();

            WebApiConfig.Register(config);
            TestHelper.Server = new HttpServer(config);
            TestHelper.Client = new HttpClient(TestHelper.Server);

            // Make sure a test user exists in database if not create it
            TestHelper.TestUser = new UserDto()
            {
                Username = "******",
                Password = Convert.ToBase64String(Guid.NewGuid().ToByteArray()),
                FullName = "Test Testov",
                Email    = "*****@*****.**",
                Money    = 9999
            };

            User user;

            using (var db = new DiceGamingDb())
            {
                user = db.Users.FirstOrDefault(u => object.Equals(u.Username, TestHelper.TestUser.Username));

                if (user == null)
                {
                    user = new User();
                }

                CryptographicManager.SetNewUserInfo(user, TestHelper.TestUser.Username, TestHelper.TestUser.Password);
                user.Username = TestHelper.TestUser.Username;
                user.FullName = TestHelper.TestUser.FullName;
                user.Email    = TestHelper.TestUser.Email;
                user.Money    = TestHelper.TestUser.Money;

                db.Users.AddOrUpdate(user);
                db.SaveChanges();
            }

            TestHelper.TestUser.Id = user.Id; // save user id

            // Create test login
            TestHelper.TestLogin = new LoginDto()
            {
                UserId = TestHelper.TestUser.Id,
                Token  = Convert.ToBase64String(Guid.NewGuid().ToByteArray())
            };

            Login login;

            using (var db = new DiceGamingDb())
            {
                login = new Login()
                {
                    UserId = TestHelper.TestLogin.UserId,
                    Token  = TestHelper.TestLogin.Token
                };

                db.Logins.Add(login);
                db.SaveChanges();
            }

            TestHelper.TestLogin.Id = login.Id; // save login id
        }
Beispiel #13
0
        public async Task ChangePasswordOfUserAndLoginAgainWithNewPassword()
        {
            string userIdString = TestHelper.TestUser.Id.ToString();

            // Save user current password and salt, to revert it after test
            string initialPasswordHash;
            string initialPasswordSalt;

            using (var db = new DiceGamingDb())
            {
                var user = db.Users.First(u => u.Id == TestHelper.TestUser.Id);

                initialPasswordHash = user.Password;
                initialPasswordSalt = user.Salt;
            }

            // Change user password
            // Arrange
            var changePasswordRequest = new ChangePasswordRequest()
            {
                OldPassword = TestHelper.TestUser.Password,
                NewPassword = Convert.ToBase64String(Guid.NewGuid().ToByteArray())
            };

            var json    = JsonConvert.SerializeObject(changePasswordRequest);
            var request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/users/" + userIdString + "/password",
                                                            method: HttpMethod.Put,
                                                            token: TestHelper.TestLogin.Token,
                                                            json: json);

            // Act
            var response = await TestHelper.Client.SendAsync(request);

            // Assert
            Assert.IsTrue(response.StatusCode == HttpStatusCode.NoContent);

            // Login with new password

            // Arrange 2
            var loginRequest = new LoginRequest()
            {
                Username = TestHelper.TestUser.Username,
                Password = changePasswordRequest.NewPassword
            };

            json    = JsonConvert.SerializeObject(loginRequest);
            request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/logins/",
                                                        method: HttpMethod.Post,
                                                        json: json);

            // Act 2
            response = await TestHelper.Client.SendAsync(request);

            // Assert 2
            Assert.IsTrue(response.StatusCode == HttpStatusCode.Created);

            var content = await response.Content.ReadAsStringAsync();

            var jsonResponse = JsonConvert.DeserializeObject <Dictionary <string, string> >(content);

            Assert.IsTrue(object.Equals(userIdString, jsonResponse["userId"]));
            string token   = jsonResponse["token"];
            string loginId = jsonResponse["id"];

            // Logout the user from this session

            // Arrange 3
            request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/logins/" + loginId,
                                                        method: HttpMethod.Delete,
                                                        token: token);

            // Act 3
            response = await TestHelper.Client.SendAsync(request);

            // Assert 3
            Assert.IsTrue(response.StatusCode == HttpStatusCode.NoContent);

            // Revert user password and salt
            using (var db = new DiceGamingDb())
            {
                var user = db.Users.First(u => u.Id == TestHelper.TestUser.Id);

                user.Password = initialPasswordHash;
                user.Salt     = initialPasswordSalt;

                db.Users.AddOrUpdate(user);
                db.SaveChanges();
            }
        }
Beispiel #14
0
        public async Task CreateSomeBetsAndGetThemSortedByWinAndByTimeAndCheckSkipAndTakeFunctionality()
        {
            string userIdString = TestHelper.TestUser.Id.ToString();

            List <BetDto> allBets = new List <BetDto>();

            BetRequest          betRequest;
            string              json;
            HttpRequestMessage  request;
            HttpResponseMessage response;

            // Create 10 bets
            for (int i = 0; i < 10; i++)
            {
                // Arrange
                betRequest = new BetRequest()
                {
                    Bet   = 12,
                    Stake = 20
                };

                json    = JsonConvert.SerializeObject(betRequest);
                request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/users/" + userIdString + "/bets",
                                                            method: HttpMethod.Post,
                                                            token: TestHelper.TestLogin.Token,
                                                            json: json);

                // Act
                var timeBeforeBet = DateTime.Now;
                response = await TestHelper.Client.SendAsync(request);

                var timeAfterBet = DateTime.Now;

                // Assert
                Assert.IsTrue(response.StatusCode == HttpStatusCode.Created);
                var cnt = await response.Content.ReadAsStringAsync();

                var jsonResp = JsonConvert.DeserializeObject <Dictionary <string, string> >(cnt);

                allBets.Add(new BetDto()
                {
                    Id           = int.Parse(jsonResp["betId"]),
                    DiceSumBet   = int.Parse(jsonResp["bet"]),
                    Stake        = int.Parse(jsonResp["stake"]),
                    Win          = int.Parse(jsonResp["win"]),
                    UserId       = TestHelper.TestUser.Id,
                    CreationDate = DateTime.Parse(jsonResp["timestamp"])
                });

                Assert.IsTrue(timeBeforeBet < allBets[i].CreationDate);
                Assert.IsTrue(allBets[i].CreationDate < timeAfterBet);
            }

            // Get bets sorted by win

            // Arrange 2
            request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/users/" + userIdString + "/bets?skip=0&take=10&orderby=win",
                                                        method: HttpMethod.Get,
                                                        token: TestHelper.TestLogin.Token);

            // Act 2
            response = await TestHelper.Client.SendAsync(request);

            // Assert 2
            Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
            var content = await response.Content.ReadAsStringAsync();

            var jsonResponse = JsonConvert.DeserializeObject <List <Dictionary <string, string> > >(content);

            decimal lastWin = 0;

            for (int i = 0; i < 10; i++)
            {
                decimal currentWin = decimal.Parse(jsonResponse[i]["win"]);
                Assert.IsTrue(lastWin <= currentWin);
                lastWin = currentWin;
            }
            Assert.IsTrue(jsonResponse.Count == 10);

            // Get bets sorted by time

            // Arrange 3
            request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/users/" + userIdString + "/bets?skip=0&take=10&orderby=time",
                                                        method: HttpMethod.Get,
                                                        token: TestHelper.TestLogin.Token);

            // Act 3
            response = await TestHelper.Client.SendAsync(request);

            // Assert 3
            Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
            content = await response.Content.ReadAsStringAsync();

            var jsonResponseSortedByDateAll = JsonConvert.DeserializeObject <List <Dictionary <string, string> > >(content);

            DateTime lastDate = DateTime.Now.AddYears(-1);

            for (int i = 0; i < 10; i++)
            {
                DateTime currentDate = DateTime.Parse(jsonResponseSortedByDateAll[i]["creationDate"]);
                Assert.IsTrue(lastDate < currentDate);
                lastDate = currentDate;
            }
            Assert.IsTrue(jsonResponseSortedByDateAll.Count == 10);

            // Sort by date but skip 5 and take 3

            // Arrange 4
            request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/users/" + userIdString + "/bets?skip=5&take=3&orderby=time",
                                                        method: HttpMethod.Get,
                                                        token: TestHelper.TestLogin.Token);

            // Act 4
            response = await TestHelper.Client.SendAsync(request);

            // Assert 4
            Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
            content = await response.Content.ReadAsStringAsync();

            jsonResponse = JsonConvert.DeserializeObject <List <Dictionary <string, string> > >(content);

            Assert.IsTrue(jsonResponse.Count == 3);
            for (int i = 0; i < 3; i++)
            {
                var creationDate = DateTime.Parse(jsonResponse[i]["creationDate"]);
                Assert.IsTrue(creationDate == DateTime.Parse(jsonResponseSortedByDateAll[5 + i]["creationDate"]));
            }

            // Restore user money before betting
            using (var db = new DiceGamingDb())
            {
                var user = db.Users.First(u => u.Id == TestHelper.TestUser.Id);

                user.Money = TestHelper.TestUser.Money;

                db.Users.AddOrUpdate(user);
                db.SaveChanges();
            }
        }