// DELETE id /// <summary> /// Removing a product /// </summary> /// <param name="id">Id of the product</param> public IHttpActionResult Delete(int id) { System.Web.Http.Results.StatusCodeResult status; using (IUMdbEntities entities = new IUMdbEntities()) { Products deletedProduct = entities.Products.Find(id); if (deletedProduct == null) { status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.NotFound, this); return(status); } List <Prices> pricesOfDeletedProduct = entities.Prices.Where(price => price.ProductId == deletedProduct.Id).ToList(); foreach (Prices price in pricesOfDeletedProduct) { entities.Prices.Remove(price); } entities.SaveChanges(); entities.Products.Remove(deletedProduct); entities.SaveChanges(); status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.OK, this); return(status); } }
// GET id /// <summary> /// Return data of specific product. /// </summary> /// <param name="id">Id of the product</param> /// <returns>Specific product data</returns> public Products Get(int id, string CountryContext = "PLN") { using (IUMdbEntities entities = new IUMdbEntities()) { Products searchedProduct = entities.Products.Find(id); if (searchedProduct == null) { return(null); } Countries requestedCountry = entities.Countries.FirstOrDefault(country => country.CountryTag == CountryContext); Prices priceForProduct = entities.Prices.FirstOrDefault(price => price.ProductId == searchedProduct.Id && price.CountryId == requestedCountry.Id); if (priceForProduct == null) { searchedProduct.Price = decimal.MinusOne; } else { searchedProduct.Price = priceForProduct.Price; } return(searchedProduct); } }
// PUT id?quantityChange /// <summary> /// Change quantity of given product /// </summary> /// <param name="id">Id of the product</param> /// <param name="quantityChange">Change in quantity</param> public IHttpActionResult Put(int id, int quantityChange) { System.Web.Http.Results.StatusCodeResult status; using (IUMdbEntities entities = new IUMdbEntities()) { Products changedProduct = entities.Products.Find(id); if (changedProduct == null) { status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.NotFound, this); return(status); } if ((changedProduct.Quantity + quantityChange) < 0) { status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.Conflict, this); return(status); } if (changedProduct != null) { changedProduct.Quantity += quantityChange; entities.Products.AddOrUpdate(changedProduct); entities.SaveChanges(); status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.OK, this); return(status); } else { status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.NotFound, this); return(status); } } }
public IHttpActionResult Register([FromBody] Users user) { System.Web.Http.Results.StatusCodeResult status; using (IUMdbEntities entities = new IUMdbEntities()) { #region Validation #region checkIfUserIsNull if (user == null) { status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.Conflict, this); return(status); } #endregion #region checkIfUsernameIsTaken bool checkIfUsernameIsTaken = entities.Users .Any(e => e.Username == user.Username); if (checkIfUsernameIsTaken) { status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.Conflict, this); return(status); } #endregion #endregion CryptoService cryptoService = new CryptoService(); string hashedPassword = cryptoService.GetHashedString(user.Password); Users newUser = new Users() { Username = user.Username, Password = hashedPassword, GoogleId = user.GoogleId }; entities.Users.Add(newUser); entities.SaveChanges(); Users dbUser = entities.Users .Where(e => e.Username == user.Username) .First(); UserRoles employeeRole = entities.UserRoles .Where(e => e.RoleName == "Employee") .First(); Workplaces newWorkplace = new Workplaces() { UserId = dbUser.Id, UserRoleId = employeeRole.Id }; entities.Workplaces.Add(newWorkplace); entities.SaveChanges(); status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.Created, this); return(status); } }
// GET /// <summary> /// List all supported countries currencies /// </summary> /// <returns>List all supported countries currencies</returns> public IEnumerable <Countries> Get() { using (IUMdbEntities entities = new IUMdbEntities()) { List <Countries> supportedCountries = entities.Countries.ToList(); return(supportedCountries); } }
// PUT /// <summary> /// Edit all availble product fields (exluding Quantiy) /// </summary> /// <param name="product">Updated product</param> public IHttpActionResult Put([FromBody] Products product, string CountryContext = "PLN") { System.Web.Http.Results.StatusCodeResult status; using (IUMdbEntities entities = new IUMdbEntities()) { Products changedProduct = entities.Products.Find(product.Id); if (changedProduct == null) { status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.NotFound, this); return(status); } Countries requestedCountry = entities.Countries.FirstOrDefault(country => country.CountryTag == CountryContext); Prices changedPrice = entities.Prices.FirstOrDefault(price => price.ProductId == changedProduct.Id && price.CountryId == requestedCountry.Id); if (changedPrice == null) { changedPrice = new Prices() { ProductId = changedProduct.Id, CountryId = requestedCountry.Id }; } changedPrice.Price = product.Price.Value; entities.Prices.AddOrUpdate(changedPrice); entities.SaveChanges(); product.Price = null; product.Quantity = changedProduct.Quantity; if (product.OriginCountry == null) { product.OriginCountry = changedProduct.OriginCountry; } entities.Products.AddOrUpdate(product); entities.SaveChanges(); status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.OK, this); return(status); } }
// POST /// <summary> /// Add new product. New products should be added with Quantity=0 /// </summary> /// <param name="product">Product to add to database</param> public IHttpActionResult Post([FromBody] Products product, string CountryContext = "PLN") { System.Web.Http.Results.StatusCodeResult status; product.Quantity = 0; using (IUMdbEntities entities = new IUMdbEntities()) { bool checkIfProductExist = entities.Products.Any(e => e.ManufacturerName == product.ManufacturerName && e.ModelName == product.ModelName); /* * bool checkIfCountryContextIsSupported = entities.Countries.Any(e => * e.CountryTag == CountryContext); */ if (checkIfProductExist) { status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.Conflict, this); return(status); } entities.Products.Add(product); entities.SaveChanges(); Countries requestedCountry = entities.Countries.FirstOrDefault(country => country.CountryTag == CountryContext); Prices price = new Prices() { Price = product.Price.Value, CountryId = requestedCountry.Id, ProductId = product.Id }; PricesController pc = new PricesController(); pc.Post(price); status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.Created, this); return(status); } }
// POST /// <summary> /// Add new price for a product. /// </summary> /// <param name="product">Price to add to database</param> public IHttpActionResult Post([FromBody] Prices price) { System.Web.Http.Results.StatusCodeResult status; using (IUMdbEntities entities = new IUMdbEntities()) { bool checkIfPriceExist = entities.Prices.Any(e => e.ProductId == price.ProductId && e.CountryId == price.Id); if (checkIfPriceExist) { status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.Conflict, this); return(status); } entities.Prices.Add(price); entities.SaveChanges(); status = new System.Web.Http.Results.StatusCodeResult(HttpStatusCode.Created, this); return(status); } }
// GET /// <summary> /// List all products in the database /// </summary> /// <returns>List of products data in database</returns> public IEnumerable <Products> Get(string CountryContext = "PLN") { using (IUMdbEntities entities = new IUMdbEntities()) { List <Products> requestedProducts = entities.Products.ToList(); Countries requestedCountry = entities.Countries.FirstOrDefault(country => country.CountryTag == CountryContext); foreach (Products product in requestedProducts) { Prices priceForProduct = entities.Prices.FirstOrDefault(price => price.ProductId == product.Id && price.CountryId == requestedCountry.Id); if (priceForProduct == null) { product.Price = decimal.MinusOne; } else { product.Price = priceForProduct.Price; } } return(requestedProducts); } }
private void TryToSynchronize(List <OfflineRequestModel> offlineChanges, List <HttpResponseMessage> results, string CountryContext) { foreach (OfflineRequestModel offlineChange in offlineChanges) { Products syncProduct = offlineChange.data; if (offlineChange.changeType == OfflineChangeType.Create) { int oldId = syncProduct.Id; HttpResponseMessage status = Post(syncProduct, CountryContext) .ExecuteAsync(System.Threading.CancellationToken.None).GetAwaiter().GetResult(); if (status.IsSuccessStatusCode) { int newId; using (IUMdbEntities entities = new IUMdbEntities()) { newId = entities.Products.FirstOrDefault(e => e.ManufacturerName == syncProduct.ManufacturerName && e.ModelName == syncProduct.ModelName).Id; } foreach (OfflineRequestModel offChn in offlineChanges) { Products currentProduct = offChn.data; if (currentProduct.Id == oldId) { currentProduct.Id = newId; } } } results.Add(status); } else if (offlineChange.changeType == OfflineChangeType.Update) { HttpResponseMessage status = Put(syncProduct, CountryContext) .ExecuteAsync(System.Threading.CancellationToken.None).GetAwaiter().GetResult(); results.Add(status); } else if (offlineChange.changeType == OfflineChangeType.ChangeQuantity) { int quantityChange = Int32.Parse(offlineChange.requestURL.Split('=')[1]); HttpResponseMessage status = Put(syncProduct.Id, quantityChange) .ExecuteAsync(System.Threading.CancellationToken.None).GetAwaiter().GetResult(); results.Add(status); } else if (offlineChange.changeType == OfflineChangeType.Delete) { string token = Request.Headers.Authorization.Parameter; JWTService service = new JWTService(DefaultSecretKey.key); if (!service.IsTokenValid(token)) { results.Add(new HttpResponseMessage(HttpStatusCode.Forbidden)); continue; } string tokenType; //username, password, List <string> userRoles; List <Claim> tokenClaims = service.GetTokenClaims(token).ToList(); userRoles = tokenClaims.FirstOrDefault(e => e.Type.Equals(MyClaimsTypes.Roles)).Value.Split(',').ToList(); if (!userRoles.Any(e => e == "Manager")) { results.Add(new HttpResponseMessage(HttpStatusCode.Forbidden)); continue; } HttpResponseMessage status = Delete(syncProduct.Id) .ExecuteAsync(System.Threading.CancellationToken.None).GetAwaiter().GetResult(); results.Add(status); } } }
public TokenModel LogIn([FromBody] Users user) { using (IUMdbEntities entities = new IUMdbEntities()) { #region Validation #region checkIfUserIsNull if (user == null) { return(null); } #endregion #region checkIfUserExist bool checkIfUserExist = entities.Users .Any(e => e.Username == user.Username); if (!checkIfUserExist) { return(null); } #endregion string dbUserHashedPassword = entities.Users .Where(e => e.Username == user.Username) .Select(e => e.Password) .First(); CryptoService cryptoService = new CryptoService(); #region checkIfUserPasswordMatches bool checkIfUserPasswordMatches = cryptoService.CompareStringToHash(user.Password, dbUserHashedPassword); if (!checkIfUserPasswordMatches) { return(null); } #endregion #endregion Users dbUser = entities.Users .First(e => e.Username == user.Username); List <string> userRoles = entities.Workplaces .Where(e => e.UserId == dbUser.Id) .Select(e => e.UserRoles.RoleName) .ToList(); JWTContainerModel newRefreshTokenJWTContainerModel = JWTContainerModel.GetUserJWTContainerModel( user.Username, user.Password, userRoles, MyTokenTypes.RefreshToken); JWTService serviceJWT = new JWTService(DefaultSecretKey.key); string newRefreshToken = serviceJWT.GenerateToken(newRefreshTokenJWTContainerModel); Users newUser = new Users() { Id = dbUser.Id, Username = dbUser.Username, Password = dbUser.Password, RefreshToken = newRefreshToken, GoogleId = dbUser.GoogleId }; entities.Users.AddOrUpdate(newUser); entities.SaveChanges(); return(new TokenModel(newRefreshToken)); } }
public TokenModel StartSession([FromBody] TokenModel refreshToken) { using (IUMdbEntities entities = new IUMdbEntities()) { #region Validation #region CheckIfRefreshTokenIsNull if (refreshToken == null) { return(null); } #endregion JWTService serviceJWT = new JWTService(DefaultSecretKey.key); #region checkIfTokenIsValid if (!serviceJWT.IsTokenValid(refreshToken.Token)) { return(null); } #endregion string username, password, tokenType; List <string> userRoles; List <Claim> tokenClaims = serviceJWT.GetTokenClaims(refreshToken.Token).ToList(); username = tokenClaims.FirstOrDefault(e => e.Type.Equals(MyClaimsTypes.Username)).Value; password = tokenClaims.FirstOrDefault(e => e.Type.Equals(MyClaimsTypes.Password)).Value; userRoles = tokenClaims.FirstOrDefault(e => e.Type.Equals(MyClaimsTypes.Roles)).Value.Split(',').ToList(); tokenType = tokenClaims.FirstOrDefault(e => e.Type.Equals(MyClaimsTypes.TokenType)).Value; #region checkTokenType if (!tokenType.Equals(MyTokenTypes.RefreshToken)) { return(null); } #endregion #region checkIfRefreshTokenMatches bool checkIfRefreshTokenMatches = entities.Users .Any(e => e.Username == username && e.RefreshToken == refreshToken.Token); if (!checkIfRefreshTokenMatches) { return(null); } #endregion string dbUserHashedPassword = entities.Users .Where(e => e.Username == username) .Select(e => e.Password) .First(); CryptoService cryptoService = new CryptoService(); #region checkIfUserPasswordMatches bool checkIfUserPasswordMatches = cryptoService.CompareStringToHash(password, dbUserHashedPassword); if (!checkIfUserPasswordMatches) { return(null); } #endregion #endregion Users dbUser = entities.Users .Where(e => e.Username == username) .First(); JWTContainerModel newBearerTokenJWTContainerModel = JWTContainerModel.GetUserJWTContainerModel( username, password, userRoles, MyTokenTypes.BearerToken); string newBearerToken = serviceJWT.GenerateToken(newBearerTokenJWTContainerModel, true); Users newUser = new Users() { Id = dbUser.Id, Username = dbUser.Username, Password = dbUser.Password, RefreshToken = dbUser.RefreshToken, BearerToken = newBearerToken, GoogleId = dbUser.GoogleId }; entities.Users.AddOrUpdate(newUser); entities.SaveChanges(); return(new TokenModel(newBearerToken)); } }