Esempio n. 1
0
        public async Task <IActionResult> ChangeUser(EditUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                string path = model.PicturePath;

                if (model.PictureFile != null)
                {
                    path = await _blobHelper.UploadBlobAsync(model.PictureFile, "users");
                }

                UserEntity user = await _userHelper.GetUserAsync(User.Identity.Name);

                user.Document    = model.Document;
                user.FirstName   = model.FirstName;
                user.LastName    = model.LastName;
                user.Address     = model.Address;
                user.PhoneNumber = model.PhoneNumber;
                user.PicturePath = path;
                user.Team        = await _context.Teams.FindAsync(model.TeamId);

                await _userHelper.UpdateUserAsync(user);

                return(RedirectToAction("Index", "Home"));
            }

            model.Teams = _combosHelper.GetComboTeams();
            return(View(model));
        }
        public async Task <IActionResult> Create(CategoryViewModel model)
        {
            if (ModelState.IsValid)
            {
                Guid imageId = Guid.Empty;
                if (model.ImageFile != null)
                {
                    imageId = await _blobHelper.UploadBlobAsync(model.ImageFile, "categories");
                }
                try
                {
                    var category = _converterHelper.ToCategory(model, imageId, true);
                    _context.Add(category);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException UpdateException)
                {
                    if (UpdateException.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, "There are a record with the same name.");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, UpdateException.InnerException.Message);
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);
                }
            }
            return(View(model));
        }
Esempio n. 3
0
        private async Task AddProductAsync(Category category, string description, string name, decimal price, string[] images, User user)
        {
            Product product = new Product
            {
                Category       = category,
                Description    = description,
                IsActive       = true,
                Name           = name,
                Price          = price,
                ProductImages  = new List <ProductImage>(),
                Qualifications = GetRandomQualifications(description, user)
            };

            foreach (string image in images)
            {
                string path    = Path.Combine(Directory.GetCurrentDirectory(), $"wwwroot\\images", $"{image}.png");
                Guid   imageId = await _blobHelper.UploadBlobAsync(path, "products");

                product.ProductImages.Add(new ProductImage {
                    ImageId = imageId
                });
            }

            _context.Products.Add(product);
        }
Esempio n. 4
0
        public async Task <IActionResult> Create(TeamViewModel teamViewModel)
        {
            if (ModelState.IsValid)
            {
                string path = string.Empty;

                if (teamViewModel.LogoFile != null)
                {
                    path = await _blobHelper.UploadBlobAsync(teamViewModel.LogoFile, "teams");
                }

                TeamEntity teamEntity = _converterHelper.ToTeamEntity(teamViewModel, path, true);
                _context.Add(teamEntity);
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (Exception ex)
                {
                    if (ex.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, "Already exists a team with the same name.");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, ex.InnerException.Message);
                    }
                }
            }

            return(View(teamViewModel));
        }
Esempio n. 5
0
        private async Task <User> CheckUserAsync(
            string document,
            string email,
            UserType userType)
        {
            RandomUsers randomUsers;

            do
            {
                randomUsers = await _apiService.GetRandomUser("https://randomuser.me", "api");
            } while (randomUsers == null);

            Guid       imageId    = Guid.Empty;
            RandomUser randomUser = randomUsers.Results.FirstOrDefault();
            string     imageUrl   = randomUser.Picture.Large.ToString().Substring(22);
            Stream     stream     = await _apiService.GetPictureAsync("https://randomuser.me", imageUrl);

            if (stream != null)
            {
                imageId = await _blobHelper.UploadBlobAsync(stream, "users");
            }

            int  cityId = _random.Next(1, _context.Cities.Count());
            User user   = await _userHelper.GetUserAsync(email);

            if (user == null)
            {
                user = new User
                {
                    FirstName   = randomUser.Name.First,
                    LastName    = randomUser.Name.Last,
                    Email       = email,
                    UserName    = email,
                    PhoneNumber = randomUser.Cell,
                    Address     = $"{randomUser.Location.Street.Number}, {randomUser.Location.Street.Name}",
                    Document    = document,
                    UserType    = userType,
                    City        = await _context.Cities.FindAsync(cityId),
                    ImageId     = imageId,
                    Latitude    = double.Parse(randomUser.Location.Coordinates.Latitude),
                    Logitude    = double.Parse(randomUser.Location.Coordinates.Longitude)
                };

                await _userHelper.AddUserAsync(user, "123456");

                await _userHelper.AddUserToRoleAsync(user, userType.ToString());

                string token = await _userHelper.GenerateEmailConfirmationTokenAsync(user);

                await _userHelper.ConfirmEmailAsync(user, token);
            }

            return(user);
        }
Esempio n. 6
0
        public async Task <IActionResult> PutUser([FromBody] UserRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string email = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
            User   user  = await _userHelper.GetUserAsync(email);

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

            City city = await _context.Cities.FindAsync(request.CityId);

            if (city == null)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Error004"
                }));
            }

            Guid imageId = user.ImageId;

            if (request.ImageArray != null)
            {
                imageId = await _blobHelper.UploadBlobAsync(request.ImageArray, "users");
            }

            user.FirstName   = request.FirstName;
            user.LastName    = request.LastName;
            user.Address     = request.Address;
            user.PhoneNumber = request.Phone;
            user.Document    = request.Phone;
            user.City        = city;
            user.ImageId     = imageId;

            IdentityResult respose = await _userHelper.UpdateUserAsync(user);

            if (!respose.Succeeded)
            {
                return(BadRequest(respose.Errors.FirstOrDefault().Description));
            }

            User updatedUser = await _userHelper.GetUserAsync(email);

            return(Ok(updatedUser));
        }
Esempio n. 7
0
        public async Task <IActionResult> Register(AddUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                Guid imageId = Guid.Empty;

                if (model.ImageFile != null)
                {
                    imageId = await _blobHelper.UploadBlobAsync(model.ImageFile, "users");
                }

                User user = await _userHelper.AddUserAsync(model, imageId, UserType.User);

                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "This email is already used.");
                    model.Fields      = _combosHelper.GetComboFields();
                    model.Districts   = _combosHelper.GetComboDistricts(model.FieldId);
                    model.Churches    = _combosHelper.GetComboChurches(model.DistrictId);
                    model.Professions = _combosHelper.GetComboProfessions();
                    return(View(model));
                }

                string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user);

                string tokenLink = Url.Action("ConfirmEmail", "Account", new
                {
                    userid = user.Id,
                    token  = myToken
                }, protocol: HttpContext.Request.Scheme);

                Response response = _mailHelper.SendMail(model.Username, "Email confirmation", $"<h1>Email Confirmation</h1>" +
                                                         $"To allow the user, " +
                                                         $"plase click in this link:<p><a href = \"{tokenLink}\">Confirm Email</a></p>");
                if (response.IsSuccess)
                {
                    ViewBag.Message = "The instructions to allow your user has been sent to email.";
                    return(View(model));
                }

                ModelState.AddModelError(string.Empty, response.Message);
            }

            model.Fields      = _combosHelper.GetComboFields();
            model.Districts   = _combosHelper.GetComboDistricts(model.FieldId);
            model.Churches    = _combosHelper.GetComboChurches(model.DistrictId);
            model.Professions = _combosHelper.GetComboProfessions();
            return(View(model));
        }
Esempio n. 8
0
        public async Task <IActionResult> Register(AddUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                Guid imageId = Guid.Empty; //no se sabe si subieron imàgen

                if (model.ImageFile != null)
                {
                    imageId = await _blobHelper.UploadBlobAsync(model.ImageFile, "users"); //subimos la imàgen
                }

                User user = await _userHelper.AddUserAsync(model, imageId, UserType.User);

                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "This email is already used.");
                    model.Countries   = _combosHelper.GetComboCountries();
                    model.Departments = _combosHelper.GetComboDepartments(model.CountryId);
                    model.Cities      = _combosHelper.GetComboCities(model.DepartmentId);
                    return(View(model));
                }

                string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user);

                string tokenLink = Url.Action("ConfirmEmail", "Account", new
                {
                    userid = user.Id, //se envìa
                    token  = myToken  //se envìa
                }, protocol: HttpContext.Request.Scheme);

                //envìa email al correo del user
                Response response = _mailHelper.SendMail(model.Username, "Email confirmation", $"<h1>Email Confirmation</h1>" +
                                                         $"To allow the user, " +
                                                         $"plase click in this link:</br></br><a href = \"{tokenLink}\">Confirm Email</a>");
                if (response.IsSuccess)
                {
                    ViewBag.Message = "The instructions to allow your user has been sent to email.";
                    return(View(model));
                }

                ModelState.AddModelError(string.Empty, response.Message);
            }

            model.Countries   = _combosHelper.GetComboCountries();
            model.Departments = _combosHelper.GetComboDepartments(model.CountryId);
            model.Cities      = _combosHelper.GetComboCities(model.DepartmentId);
            return(View(model));
        }
Esempio n. 9
0
        public async Task <IActionResult> Create(ProductViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    Product product = await _converterHelper.ToProductAsync(model, true);

                    if (model.ImageFile != null)
                    {
                        //Guid, devuelve el còdigo de la imàgen
                        //lìnea de còdigo que sube la imàgen a l contendero products del blobstorage
                        Guid imageId = await _blobHelper.UploadBlobAsync(model.ImageFile, "products");

                        product.ProductImages = new List <ProductImage> //crea una lista de imàgenes
                        {
                            new ProductImage {
                                ImageId = imageId
                            }                                      //la primera ImageId va ser iagual a imageId que le pasaron
                        };
                    }

                    _context.Add(product); //adiciona al contexto el producto
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException dbUpdateException)
                {
                    if (dbUpdateException.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, "There are a record with the same name.");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, dbUpdateException.InnerException.Message);
                    }
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError(string.Empty, exception.Message);
                }
            }

            model.Categories = _combosHelper.GetComboCategories();
            return(View(model));
        }
Esempio n. 10
0
        public async Task <IActionResult> Create(ProductViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    Product product = await _converterHelper.ToProductAsync(model, true);

                    if (model.ImageFile != null)
                    {
                        Guid imageId = await _blobHelper.UploadBlobAsync(model.ImageFile, "products");

                        product.ProductImages = new List <ProductImage>
                        {
                            new ProductImage {
                                ImageId = imageId
                            }
                        };
                    }

                    _context.Add(product);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateException dbUpdateException)
                {
                    if (dbUpdateException.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, "There are a record with the same name.");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, dbUpdateException.InnerException.Message);
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);
                }
            }

            model.Categories = _combosHelper.GetComboCategories();

            return(View(model));
        }
Esempio n. 11
0
        public async Task <IActionResult> PutUser([FromBody] UserRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            CultureInfo cultureInfo = new CultureInfo(request.CultureInfo);

            Resource.Culture = cultureInfo;

            UserEntity userEntity = await _userHelper.GetUserAsync(request.Email);

            if (userEntity == null)
            {
                return(BadRequest(Resource.UserNotFoundError));
            }

            string picturePath = userEntity.PicturePath;

            if (request.PictureArray != null && request.PictureArray.Length > 0)
            {
                picturePath = await _blobHelper.UploadBlobAsync(request.PictureArray, "users");
            }

            userEntity.FirstName   = request.FirstName;
            userEntity.LastName    = request.LastName;
            userEntity.Address     = request.Address;
            userEntity.PhoneNumber = request.Phone;
            userEntity.Document    = request.Phone;
            userEntity.PicturePath = picturePath;

            IdentityResult respose = await _userHelper.UpdateUserAsync(userEntity);

            if (!respose.Succeeded)
            {
                return(BadRequest(respose.Errors.FirstOrDefault().Description));
            }

            UserEntity updatedUser = await _userHelper.GetUserAsync(request.Email);

            return(Ok(updatedUser));
        }
Esempio n. 12
0
        public async Task <IActionResult> Register(AddUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                string path = string.Empty;

                if (model.PictureFile != null)
                {
                    path = await _blobHelper.UploadBlobAsync(model.PictureFile, "users");
                }

                UserEntity user = await _userHelper.AddUserAsync(model, path);

                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "This email is already used.");
                    model.UserTypes = _combosHelper.GetComboRoles();
                    return(View(model));
                }

                var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user);

                var tokenLink = Url.Action("ConfirmEmail", "Account", new
                {
                    userid = user.Id,
                    token  = myToken
                }, protocol: HttpContext.Request.Scheme);

                var response = _mailHelper.SendMail(model.Username, "Email confirmation", $"<h1>Email Confirmation</h1>" +
                                                    $"To allow the user, " +
                                                    $"plase click in this link:</br></br><a href = \"{tokenLink}\">Confirm Email</a>");
                if (response.IsSuccess)
                {
                    ViewBag.Message = "The instructions to allow your user has been sent to email.";
                    return(View(model));
                }

                ModelState.AddModelError(string.Empty, response.Message);
            }

            model.UserTypes = _combosHelper.GetComboRoles();
            return(View(model));
        }
Esempio n. 13
0
        public async Task <IActionResult> Create(TournamentViewModel model)
        {
            if (ModelState.IsValid)
            {
                string path = string.Empty;

                if (model.LogoFile != null)
                {
                    path = await _blobHelper.UploadBlobAsync(model.LogoFile, "tournaments");
                }

                TournamentEntity tournament = _converterHelper.ToTournamentEntity(model, path, true);
                _context.Add(tournament);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            return(View(model));
        }
Esempio n. 14
0
        public async Task <IActionResult> PostEstablishment([FromBody] EstablishmentRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Bad request",
                    Result = ModelState
                }));
            }

            UserEntity userEntity = await _userHelper.GetUserAsync(request.UserId);

            if (userEntity == null)
            {
                return(BadRequest("User doesn't exists."));
            }

            EstablishmentEntity establishment = await _context.Establishments.FirstOrDefaultAsync(e => e.Name == request.Name);

            if (establishment != null)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Establishment exist"
                }));
            }

            string picturePath = string.Empty;

            if (request.PictureEstablishmentArray != null && request.PictureEstablishmentArray.Length > 0)
            {
                picturePath = await _blobHelper.UploadBlobAsync(request.PictureEstablishmentArray, "establishments");
            }

            establishment = new EstablishmentEntity
            {
                Name = request.Name,
                LogoEstablishmentPath = picturePath,
                User = userEntity
            };

            _context.Establishments.Add(establishment);
            await _context.SaveChangesAsync();

            return(Ok(_converterHelper.ToEstablishmentResponse(establishment)));
        }
        public async Task <IActionResult> Register(AddUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                Guid imageId = Guid.Empty;

                if (model.ImageFile != null)
                {
                    imageId = await _blobHelper.UploadBlobAsync(model.ImageFile, "users");
                }

                User user = await _userHelper.AddUserAsync(model, imageId, UserType.User);

                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "Este correo electrónico ya está en uso.");
                    model.Countries   = _combosHelper.GetComboCountries();
                    model.Departments = _combosHelper.GetComboDepartments(model.CountryId);
                    model.Cities      = _combosHelper.GetComboCities(model.DepartmentId);
                    return(View(model));
                }

                LoginViewModel loginViewModel = new LoginViewModel
                {
                    Password   = model.Password,
                    RememberMe = false,
                    Username   = model.Username
                };

                var result2 = await _userHelper.LoginAsync(loginViewModel);

                if (result2.Succeeded)
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }

            model.Countries   = _combosHelper.GetComboCountries();
            model.Departments = _combosHelper.GetComboDepartments(model.CountryId);
            model.Cities      = _combosHelper.GetComboCities(model.DepartmentId);
            return(View(model));
        }
Esempio n. 16
0
        public async Task <IActionResult> Register(AddUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                Guid imageId = Guid.Empty;

                if (model.ImageFile != null)
                {
                    imageId = await _blobHelper.UploadBlobAsync(model.ImageFile, "users");
                }

                User user = await _userHelper.AddUserAsync(model, imageId, UserType.User);

                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "This email is already used.");
                    model.Countries   = _combosHelper.GetComboCountries();
                    model.Departments = _combosHelper.GetComboDepartments(model.CountryId);
                    model.Cities      = _combosHelper.GetComboCities(model.DepartmentId);
                    return(View(model));
                }
                string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user);

                string tokenLink = Url.Action("ConfirmEmail", "Account", new
                {
                    userid = user.Id,
                    token  = myToken
                }, protocol: HttpContext.Request.Scheme);

                Response response = _mailHelper.SendMail(model.Username, "Email confirmation", $"<h1>Email Confirmation</h1>" +
                                                         $"To allow the user, " +
                                                         $"plase click in this link:</br></br><a href = \"{tokenLink}\">Confirm Email</a>");
                if (response.IsSuccess)
                {
                    ViewBag.Message = "The instructions to allow your user has been sent to email.";
                    return(View(model));
                }

                ModelState.AddModelError(string.Empty, response.Message);


                //LoginViewModel loginViewModel = new LoginViewModel
                //{
                //    Password = model.Password,
                //    RememberMe = false,
                //    Username = model.Username
                //};

                //var result2 = await _userHelper.LoginAsync(loginViewModel);

                //if (result2.Succeeded)
                //{
                //    return RedirectToAction("Index", "Home");
                //}
            }

            model.Countries   = _combosHelper.GetComboCountries();
            model.Departments = _combosHelper.GetComboDepartments(model.CountryId);
            model.Cities      = _combosHelper.GetComboCities(model.DepartmentId);
            return(View(model));
        }
        public async Task <IActionResult> PostUser([FromBody] UserRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Bad request",
                    Result = ModelState
                }));
            }

            var user = await _userHelper.GetUserByEmailAsync(request.Email);

            if (user != null)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Error003"
                }));
            }

            //City city = await _context.Cities.FindAsync(request.CityId);
            //if (city == null)
            //{
            //    return BadRequest(new Response
            //    {
            //        IsSuccess = false,
            //        Message = "Error004"
            //    });
            //}

            Guid imageId = Guid.Empty;

            if (request.ImageArray != null)
            {
                imageId = await _blobHelper.UploadBlobAsync(request.ImageArray, "users");
            }

            user = new ApplicationUser
            {
                Address = request.Address,
                Email   = request.Email,
                //  Name = request.Name,
                PhoneNumber = request.Phone,
                UserName    = request.Email,
                // ImageId = imageId,
                // UserType = UserType.User,
                // Latitude = request.Latitude,
                //  Logitude = request.Logitude
            };

            IdentityResult result = await _userHelper.AddUserAsync(user, request.Password);

            if (result != IdentityResult.Success)
            {
                return(BadRequest(result.Errors.FirstOrDefault().Description));
            }

            var userNew = await _userHelper.GetUserByEmailAsync(request.Email);

            //  await _userHelper.AddUserToRoleAsync(userNew, user.UserType.ToString());

            string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user);

            string tokenLink = Url.Action("ConfirmEmail", "Account", new
            {
                userid = user.Id,
                token  = myToken
            }, protocol: HttpContext.Request.Scheme);

            _mailHelper.SendMail(request.Email, "Email Confirmation", $"<h1>Email Confirmation</h1>" +
                                 $"To confirm your email please click on the link<p><a href = \"{tokenLink}\">Confirm Email</a></p>");

            return(Ok(new Response {
                IsSuccess = true
            }));
        }
Esempio n. 18
0
        public async Task <IActionResult> PostUser([FromBody] UserRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Bad request",
                    Result = ModelState
                }));
            }

            UserEntity user = await _userHelper.GetUserAsync(request.Email);

            if (user != null)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "User exist"
                }));
            }

            string picturePath = string.Empty;

            if (request.PictureUserArray != null && request.PictureUserArray.Length > 0)
            {
                picturePath = await _blobHelper.UploadBlobAsync(request.PictureUserArray, "users");
            }

            user = new UserEntity
            {
                Document        = request.Document,
                Email           = request.Email,
                FirstName       = request.FirstName,
                LastName        = request.LastName,
                UserName        = request.Email,
                PicturePathUser = picturePath,
                UserType        = request.UserTypeId == 1 ? UserType.Owner : UserType.User
            };

            IdentityResult result = await _userHelper.AddUserAsync(user, request.Password);

            if (result != IdentityResult.Success)
            {
                return(BadRequest(result.Errors.FirstOrDefault().Description));
            }

            UserEntity userNew = await _userHelper.GetUserAsync(request.Email);

            await _userHelper.AddUserToRoleAsync(userNew, user.UserType.ToString());

            string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user);

            string tokenLink = Url.Action("ConfirmEmail", "Account", new
            {
                userid = user.Id,
                token  = myToken
            }, protocol: HttpContext.Request.Scheme);

            _mailHelper.SendMail(request.Email, "Email Confimation", $"<h1>Email</h1>" +
                                 $"Welcome to Just In Case Travels</br></br><a href = \"{tokenLink}\"> Please clic Here for Confirm Email</a>");

            return(Ok(new Response
            {
                IsSuccess = true,
                Message = "Send message for confirm Email"
            }));
        }
Esempio n. 19
0
        public async Task <IActionResult> PostFood([FromBody] FoodRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Bad request",
                    Result = ModelState
                }));
            }

            EstablishmentLocationEntity establishmentLocationEntity = await _context
                                                                      .EstablishmentLocations
                                                                      .FirstOrDefaultAsync(el => el.Id == request.EstablishmentLocationId);

            FoodEntity foodEntity = await _context.Foods.FirstOrDefaultAsync(f => f.FoodName == request.FoodName);

            TypeFoodEntity typeFoodEntity = await _context.TypeFoods.FirstOrDefaultAsync(f => f.Id == request.TypeFoodsId);

            UserEntity userEntity = await _userHelper.GetUserAsync(request.UserId);

            if (userEntity == null)
            {
                return(BadRequest("User doesn't exists."));
            }

            if (foodEntity != null)
            {
                if (establishmentLocationEntity.Id == foodEntity.EstablishmentLocations.Id)
                {
                    return(BadRequest(new Response
                    {
                        IsSuccess = false,
                        Message = "This food exist in this place"
                    }));
                }
            }

            string picturePath = string.Empty;

            if (request.PictureFoodArray != null && request.PictureFoodArray.Length > 0)
            {
                picturePath = await _blobHelper.UploadBlobAsync(request.PictureFoodArray, "foods");
            }

            FoodEntity food = new FoodEntity
            {
                FoodName                = request.FoodName,
                PicturePathFood         = picturePath,
                Qualification           = request.Qualification,
                Remarks                 = request.Remarks,
                TypeFoods               = typeFoodEntity,
                EstablishmentLocationId = establishmentLocationEntity.Id.ToString(),
                EstablishmentLocations  = establishmentLocationEntity,
                User = userEntity
            };

            _context.Foods.Add(food);
            await _context.SaveChangesAsync();

            return(Ok(_converterHelper.ToFoodResponse(food)));
        }
Esempio n. 20
0
        public async Task <IActionResult> PostUser([FromBody] UserRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Bad request",
                    Result = ModelState
                }));
            }

            CultureInfo cultureInfo = new CultureInfo(request.CultureInfo);

            Resource.Culture = cultureInfo;

            UserEntity user = await _userHelper.GetUserAsync(request.Email);

            if (user != null)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = Resource.UserAlreadyExists
                }));
            }

            string picturePath = string.Empty;

            if (request.PictureArray != null && request.PictureArray.Length > 0)
            {
                picturePath = await _blobHelper.UploadBlobAsync(request.PictureArray, "users");
            }

            user = new UserEntity
            {
                Address     = request.Address,
                Document    = request.Document,
                Email       = request.Email,
                FirstName   = request.FirstName,
                LastName    = request.LastName,
                PhoneNumber = request.Phone,
                UserName    = request.Email,
                PicturePath = picturePath,
                UserType    = request.UserTypeId == 1 ? UserType.User : UserType.Driver
            };

            IdentityResult result = await _userHelper.AddUserAsync(user, request.Password);

            if (result != IdentityResult.Success)
            {
                return(BadRequest(result.Errors.FirstOrDefault().Description));
            }

            UserEntity userNew = await _userHelper.GetUserAsync(request.Email);

            await _userHelper.AddUserToRoleAsync(userNew, user.UserType.ToString());

            string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user);

            string tokenLink = Url.Action("ConfirmEmail", "Account", new
            {
                userid = user.Id,
                token  = myToken
            }, protocol: HttpContext.Request.Scheme);

            _mailHelper.SendMail(request.Email, Resource.EmailConfirmationSubject, $"<h1>{Resource.EmailConfirmationSubject}</h1>" +
                                 $"{Resource.EmailConfirmationBody}</br></br><a href = \"{tokenLink}\">{Resource.ConfirmEmail}</a>");

            return(Ok(new Response
            {
                IsSuccess = true,
                Message = Resource.EmailConfirmationSent
            }));
        }