public UserDto Create(UserDto user) { User newUser; using (var db = new OnlineCasinoDb()) { 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)); }
public void UpdatePassword(int id, string oldPassword, string newPassword) { using (var db = new OnlineCasinoDb()) { 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(); } }
public bool HasLoginAndToken(int loginId, string token) { using (var db = new OnlineCasinoDb()) { if (db.Logins.FirstOrDefault(l => l.Id == loginId && object.Equals(l.Token, token)) == null) { return(false); } } return(true); }
public IEnumerable <LoginDto> GetUserLogins(int userId) { IQueryable <Login> logins; using (var db = new OnlineCasinoDb()) { logins = db.Logins.Where(l => l.UserId == userId); } foreach (var login in logins) { yield return(CreateLoginDTO(login)); } }
public void Delete(int id) { using (var db = new OnlineCasinoDb()) { var login = db.Logins.FirstOrDefault(l => l.Id == id); if (login == null) { throw new NotFoundException(); } db.Logins.Remove(login); db.SaveChanges(); } }
public void Delete(int id) { using (var db = new OnlineCasinoDb()) { var user = db.Users.FirstOrDefault(u => u.Id == id); if (user == null) { throw new NotFoundException(); } db.Users.Remove(user); db.SaveChanges(); } }
public bool IsPasswordCorrect(int id, string password) { using (var db = new OnlineCasinoDb()) { var user = db.Users.FirstOrDefault(u => u.Id == id); if (user == null) { throw new BadRequestException(); } var saltedPassword = CryptographicManager.GenerateSHA256Hash(password, user.Salt); return(object.Equals(user.Password, saltedPassword)); } }
public void UpdateMoney(int id, decimal newMoney) { using (var db = new OnlineCasinoDb()) { var user = db.Users.FirstOrDefault(u => u.Id == id); if (user == null) { throw new NotFoundException(); } user.Money = newMoney; db.Users.AddOrUpdate(user); db.SaveChanges(); } }
public LoginDto Get(int id) { Login login; using (var db = new OnlineCasinoDb()) { login = db.Logins.FirstOrDefault(l => l.Id == id); if (login == null) { throw new NotFoundException(); } } return(CreateLoginDTO(login)); }
public UserDto Get(int id) { User user; using (var db = new OnlineCasinoDb()) { user = db.Users.FirstOrDefault(u => u.Id == id); if (user == null) { throw new NotFoundException(); } } return(CreateUserDTO(user)); }
public RouletteBetDto Get(int id) { RouletteBet bet; using (var db = new OnlineCasinoDb()) { bet = db.RouletteBets.FirstOrDefault(b => b.Id == id); if (bet == null) { throw new NotFoundException(); } } return(CreateBetDTO(bet)); }
public IEnumerable <RouletteBetDto> GetBets(int userId, int skip, int take, string orderby, string filter) { Func <RouletteBet, bool> betFilter; if (object.Equals(filter, "win")) { betFilter = new Func <RouletteBet, bool>(b => b.UserId == userId && b.Win != 0); } else if (object.Equals(filter, "lose")) { betFilter = new Func <RouletteBet, bool>(b => b.UserId == userId && b.Win == 0); } else { betFilter = new Func <RouletteBet, bool>(b => b.UserId == userId); } List <RouletteBet> bets; using (var db = new OnlineCasinoDb()) { var user = db.Users.FirstOrDefault(u => u.Id == userId); if (user == null) { throw new NotFoundException(); } if (object.Equals(orderby, "win")) { bets = (from b in db.RouletteBets.Where(betFilter) orderby b.Win select b).Skip(skip).Take(take).ToList(); } else { bets = (from b in db.RouletteBets.Where(betFilter) orderby b.CreationDate select b).Skip(skip).Take(take).ToList(); } } foreach (var bet in bets) { yield return(CreateBetDTO(bet)); } }
public static bool IsTokenPresent(string token) { if (token == null) { return(false); } using (var db = new OnlineCasinoDb()) { if (db.Logins.FirstOrDefault(l => object.Equals(l.Token, token)) == null) { return(false); } } return(true); }
public void Delete(int id) { using (var db = new OnlineCasinoDb()) { var bet = db.DiceBets.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.DiceBets.Remove(bet); db.SaveChanges(); } }
public DiceBetDto Create(DiceBetDto bet) { var newBet = new DiceBet() { UserId = bet.UserId, DiceSumBet = bet.DiceSumBet, DiceSumResult = bet.DiceSumResult, Stake = bet.Stake, Win = bet.Win, CreationDate = bet.CreationDate }; using (var db = new OnlineCasinoDb()) { db.DiceBets.Add(newBet); db.SaveChanges(); } return(CreateBetDTO(newBet)); }
public RouletteBetDto Create(RouletteBetDto bet) { var newBet = new RouletteBet() { UserId = bet.UserId, BetValues = bet.BetValues.ToArray(), SpinResult = bet.SpinResult, Stake = bet.Stake, Win = bet.Win, CreationDate = bet.CreationDate }; using (var db = new OnlineCasinoDb()) { db.RouletteBets.Add(newBet); db.SaveChanges(); } return(CreateBetDTO(newBet)); }
public LoginDto LoginUser(LoginDto login) { Login newLogin = new Login(); using (var db = new OnlineCasinoDb()) { 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)); }
public UserDto AddMoney(int id, decimal money) { User user; using (var db = new OnlineCasinoDb()) { 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)); }
public UserDto UpdateNameAndEmail(UserDto user) { User userForUpdate; using (var db = new OnlineCasinoDb()) { 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)); }
public UserDto Get(string username, string password) { User user; using (var db = new OnlineCasinoDb()) { user = db.Users.FirstOrDefault(u => object.Equals(u.Username, username)); if (user == null) { throw new NotFoundException(); } var saltedPassword = CryptographicManager.GenerateSHA256Hash(password, user.Salt); if (!object.Equals(user.Password, saltedPassword)) { throw new BadRequestException(); } } return(CreateUserDTO(user)); }
public void TearDown() { TestHelper.Server?.Dispose(); TestHelper.Client?.Dispose(); // Remove all logins of test user using (var db = new OnlineCasinoDb()) { 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 OnlineCasinoDb()) { var bets = db.DiceBets.Where(b => b.UserId == TestHelper.TestUser.Id); db.DiceBets.RemoveRange(bets); db.SaveChanges(); } }
public async Task CreateSomeBetsAndGetThemSortedByWinAndByTimeAndCheckSkipAndTakeFunctionality() { string userIdString = TestHelper.TestUser.Id.ToString(); List <DiceBetDto> allBets = new List <DiceBetDto>(); DiceBetRequest betRequest; string json; HttpRequestMessage request; HttpResponseMessage response; // Create 10 bets for (int i = 0; i < 10; i++) { // Arrange betRequest = new DiceBetRequest() { Bet = 12, Stake = 20 }; json = JsonConvert.SerializeObject(betRequest); request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/users/" + userIdString + "/dicebets", 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 DiceBetDto() { Id = int.Parse(jsonResp["betId"]), DiceSumBet = int.Parse(jsonResp["bet"]), Stake = decimal.Parse(jsonResp["stake"]), Win = decimal.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 + "/dicebets?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 + "/dicebets?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 + "/dicebets?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 OnlineCasinoDb()) { var user = db.Users.First(u => u.Id == TestHelper.TestUser.Id); user.Money = TestHelper.TestUser.Money; db.Users.AddOrUpdate(user); db.SaveChanges(); } }
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 OnlineCasinoDb()) { 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 OnlineCasinoDb()) { 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 }
public async Task MakeABetWithValidDataThenGetTheNewBetToCheckInfoAndDeleteIt() { string userIdString = TestHelper.TestUser.Id.ToString(); // Make a bet decimal initialUserMoney = TestHelper.TestUser.Money; // Arrange var betRequest = new DiceBetRequest() { Bet = 12, Stake = 20 }; var json = JsonConvert.SerializeObject(betRequest); var request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/users/" + userIdString + "/dicebets", method: HttpMethod.Post, token: TestHelper.TestLogin.Token, json: json); // Act var timeBeforeBet = DateTime.Now; var response = await TestHelper.Client.SendAsync(request); var timeAfterBet = DateTime.Now; // Assert Assert.IsTrue(response.StatusCode == HttpStatusCode.Created); var content = await response.Content.ReadAsStringAsync(); var jsonResponse = JsonConvert.DeserializeObject <Dictionary <string, string> >(content); var bet = new DiceBetDto() { Id = int.Parse(jsonResponse["betId"]), DiceSumBet = int.Parse(jsonResponse["bet"]), Stake = decimal.Parse(jsonResponse["stake"]), Win = decimal.Parse(jsonResponse["win"]), UserId = TestHelper.TestUser.Id, CreationDate = DateTime.Parse(jsonResponse["timestamp"]) }; Assert.IsTrue(timeBeforeBet < bet.CreationDate); Assert.IsTrue(bet.CreationDate < timeAfterBet); // update new test user money using (var db = new OnlineCasinoDb()) { var user = db.Users.First(u => u.Id == TestHelper.TestUser.Id); TestHelper.TestUser.Money = user.Money; } Assert.IsTrue(bet.Win > 0 ? TestHelper.TestUser.Money > initialUserMoney - betRequest.Stake : TestHelper.TestUser.Money == initialUserMoney - betRequest.Stake); // Get bet info // Arrange 2 request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/users/" + userIdString + "/dicebets/" + bet.Id.ToString(), method: HttpMethod.Get, token: TestHelper.TestLogin.Token); // Act 2 response = await TestHelper.Client.SendAsync(request); // Assert 2 Assert.IsTrue(response.StatusCode == HttpStatusCode.OK); content = await response.Content.ReadAsStringAsync(); jsonResponse = JsonConvert.DeserializeObject <Dictionary <string, string> >(content); Assert.IsTrue(int.Parse(jsonResponse["bet"]) == bet.DiceSumBet); Assert.IsTrue(decimal.Parse(jsonResponse["stake"]) == bet.Stake); Assert.IsTrue(decimal.Parse(jsonResponse["win"]) == bet.Win); Assert.IsTrue(DateTime.Parse(jsonResponse["creationDate"]) == bet.CreationDate); // Delete bet // Arrange 3 request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/users/" + userIdString + "/dicebets/" + bet.Id.ToString(), method: HttpMethod.Delete, token: TestHelper.TestLogin.Token); // Act 3 response = await TestHelper.Client.SendAsync(request); // Assert 3 Assert.IsTrue(response.StatusCode == HttpStatusCode.NoContent); using (var db = new OnlineCasinoDb()) { var deletedBet = db.DiceBets.FirstOrDefault(b => b.Id == bet.Id); Assert.IsTrue(deletedBet == null); } }
public async Task RegisterNewUserAndLoginAndDeleteAccount() { var user = new UserDto() { Username = "******", Password = "******", FullName = "Fast Tester", Email = "*****@*****.**" }; // Register new user // Arrange var registerRequest = new RegisterRequest() { Username = user.Username, Password = user.Password, FullName = user.FullName, Email = user.Email }; var json = JsonConvert.SerializeObject(registerRequest); var request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/users/", method: HttpMethod.Post, json: json); // Act var response = await TestHelper.Client.SendAsync(request); // Assert Assert.IsTrue(response.StatusCode == HttpStatusCode.Created); string content = await response.Content.ReadAsStringAsync(); var jsonResponse = JsonConvert.DeserializeObject <Dictionary <string, string> >(content); Assert.IsTrue(object.Equals(jsonResponse["username"], user.Username)); Assert.IsTrue(object.Equals(jsonResponse["fullName"], user.FullName)); Assert.IsTrue(object.Equals(jsonResponse["email"], user.Email)); user.Id = int.Parse(jsonResponse["userId"]); //Login into account // Arrange 2 var loginRequest = new LoginRequest() { Username = user.Username, Password = user.Password }; 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); content = await response.Content.ReadAsStringAsync(); jsonResponse = JsonConvert.DeserializeObject <Dictionary <string, string> >(content); string token = jsonResponse["token"]; // Delete account // Arrange 3 var deleteRequest = new DeleteAccountRequest() { Password = user.Password }; json = JsonConvert.SerializeObject(deleteRequest); request = TestHelper.GenerateRequestMessage(url: "http://localhost/api/users/" + user.Id.ToString(), method: HttpMethod.Delete, token: token, json: json); // Act 3 response = await TestHelper.Client.SendAsync(request); // Assert 3 Assert.IsTrue(response.StatusCode == HttpStatusCode.NoContent); using (var db = new OnlineCasinoDb()) { var deletedUser = db.Users.FirstOrDefault(u => u.Id == user.Id); Assert.IsTrue(deletedUser == null); } }
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 OnlineCasinoDb()) { 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 OnlineCasinoDb()) { var user = db.Users.First(u => u.Id == TestHelper.TestUser.Id); user.Password = initialPasswordHash; user.Salt = initialPasswordSalt; db.Users.AddOrUpdate(user); db.SaveChanges(); } }