コード例 #1
0
        public IActionResult ChangeImage([FromBody] ChangeImage model)
        {
            string image = null;

            var userId = User.Claims.ToList()[0].Value;
            var user   = _context.BaseProfiles.FirstOrDefault(u => u.Id == userId);

            if (user != null)
            {
                string imageName      = user.Image ?? Guid.NewGuid().ToString() + ".jpg";
                string pathSaveImages = InitStaticFiles
                                        .CreateImageByFileName(_env, _configuration,
                                                               new string[] { "ImagesPath", "ImagesUserPath" },
                                                               imageName, model.Image);

                if (pathSaveImages != null)
                {
                    image      = imageName;
                    user.Image = image;
                    _context.SaveChanges();
                }
                else
                {
                    image = user.Image;
                }
            }

            string path      = $"{_configuration.GetValue<string>("UserUrlImages")}/250_";
            string imagePath = image != null ? path + image :
                               path + _configuration.GetValue <string>("DefaultImage");

            return(Ok(imagePath));
        }
コード例 #2
0
        public async Task <IActionResult> RegisterTeacher([FromBody] TeacherRegisterVM model)
        {
            return(await HandleRequestAsync(async() =>
            {
                string imageName = Path.GetRandomFileName() + ".jpg";
                var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Uploaded\Users");

                string pathSaveImages = InitStaticFiles
                                        .CreateImageByFileName(_env, _configuration,
                                                               new string[] { Directory.GetCurrentDirectory(), @"wwwroot", "Uploaded", "Users" },
                                                               imageName,
                                                               model.Photo);

                //+38 (098) 665 34 18
                model.Photo = imageName;

                var rezult = await _teacherService.Create(model);
                if (rezult)
                {
                    var user = _userManager.FindByEmailAsync(model.Email).Result;
                    var teacher = await _teacherService.GetTeacherById(user.Id);
                    JwtInfo jwtInfo;
                    if (teacher != null)
                    {
                        // Return token
                        jwtInfo = new JwtInfo()
                        {
                            Token = _jwtTokenService.CreateToken(user),
                            RefreshToken = _jwtTokenService.CreateRefreshToken(user),
                            SchoolId = teacher.SchoolId.ToString()
                        };
                    }
                    else
                    {
                        // Return token
                        jwtInfo = new JwtInfo()
                        {
                            Token = _jwtTokenService.CreateToken(user),
                            RefreshToken = _jwtTokenService.CreateRefreshToken(user),
                        };
                    }

                    this._logger.LogDebug("End method LoginUser...");

                    return Ok(jwtInfo);
                }
                else
                {
                    var invalid = new Dictionary <string, string>
                    {
                        { "email", "Користувач з даною електронною поштою уже зареєстрований" }
                    };
                    return BadRequest(invalid);
                }
            }));
        }
コード例 #3
0
        public IActionResult ChangeUserProfile([FromBody] UserProfileModel model)
        {
            if (!ModelState.IsValid)
            {
                var errrors = CustomValidator.GetErrorsByModel(ModelState);
                return(BadRequest(errrors));
            }

            var userid = (User.Claims.ToList()[0].Value).ToString();
            // var i = "fe623d77-2603-4787-99f6-e13337cc4083";
            var user = _context.UserProfile.SingleOrDefault(a => a.User.Id == userid);

            string image = null;

            if (user != null)
            {
                string imageName = "";
                if (user.Avatar == "")
                {
                    imageName = Guid.NewGuid().ToString() + ".jpg";
                }
                else
                {
                    imageName = user.Avatar + ".jpg";
                }
                string pathSaveImages = InitStaticFiles
                                        .CreateImageByFileName(_env, _configuration,
                                                               new string[] { "ImagesPath", "ImagesPathUsers" },
                                                               imageName,
                                                               model.Avatar);
                if (pathSaveImages != null)
                {
                    image       = imageName;
                    user.Avatar = image;
                    _context.SaveChanges();
                }
                else
                {
                    image = user.Avatar;
                }
            }

            //string imageName = user.Avatar ?? Guid.NewGuid().ToString() + ".jpg";
            //string path = $"{_configuration.GetValue<string>("UserUrlImages")}/600_";
            //string imagePath = image != null ?
            //    path + image :
            //    _configuration.GetValue<string>("UrlImages") +
            //    "300_" + _configuration.GetValue<string>("DefaultImage");
            //return Ok(imagePath);

            _context.Users.Where(a => a.Id == user.Id).SingleOrDefault().Email           = model.Email;
            _context.Users.Where(a => a.Id == user.Id).SingleOrDefault().NormalizedEmail = model.Email.ToUpper();
            _context.SaveChanges();
            return(Ok());
        }
コード例 #4
0
        public async Task <ActionResult <Product> > Edit(int id, [FromBody] ProductModel model)
        {
            Product product = _context.Products.Include("Photos").FirstOrDefault(x => x.ID == id);

            using (CTX db = _context)
            {
                if (product != null)
                {
                    List <Photo> added_photos = new List <Photo>();
                    try
                    {
                        foreach (var x in product.Photos)
                        {
                            InitStaticFiles.DeleteImageByFileName(_env, _configuration,
                                                                  new string[] { "ImagesPath", "ImagesPathProduct" },
                                                                  x.Path);
                        }
                        foreach (var photo in model.ImgsBase64)
                        {
                            string imageName = Path.GetRandomFileName() + ".jpg";

                            string pathSaveImages = InitStaticFiles
                                                    .CreateImageByFileName(_env, _configuration,
                                                                           new string[] { "ImagesPath", "ImagesPathProduct" },
                                                                           imageName,
                                                                           photo);
                            added_photos.Add(new Photo
                            {
                                Path = imageName
                            });
                        }
                    }
                    catch (Exception)
                    {
                        return(BadRequest());
                    }

                    product.Name        = model.Name;
                    product.Description = model.Description;
                    product.Price       = model.Price;
                    product.Photos.Clear();
                    product.Photos = added_photos;


                    db.SaveChanges();
                    return(Ok(product));
                }
                else
                {
                    return(BadRequest());
                }
            }
        }
コード例 #5
0
        public IActionResult ChangeImage([FromBody] ChangeImageModel model)
        {
            string image = null;

            if (User.Identity.IsAuthenticated)
            {
                var userId = User.Claims.ToList()[0].Value.ToString();
                var user   = _context.UserProfile.SingleOrDefault(c => c.Id == userId);
                if (user != null)
                {
                    string imageName = "";
                    if (user.Avatar == "")
                    {
                        imageName = Guid.NewGuid().ToString() + ".jpg";
                    }
                    else
                    {
                        imageName = user.Avatar + ".jpg";
                    }

                    string pathSaveImages = InitStaticFiles
                                            .CreateImageByFileName(_env, _configuration,
                                                                   new string[] { "ImagesPath", "ImagesPathUsers" },
                                                                   imageName,
                                                                   model.Avatar);
                    if (pathSaveImages != null)
                    {
                        image       = imageName;
                        user.Avatar = image;
                        _context.SaveChanges();
                    }
                    else
                    {
                        image = user.Avatar;
                    }
                }
            }

            string path      = $"{_configuration.GetValue<string>("UserUrlImages")}/300_";
            string imagePath = image != "" ?
                               path + image :
                               _configuration.GetValue <string>("UrlImages") +
                               "300_" + _configuration.GetValue <string>("DefaultImage");

            return(Ok(imagePath));
        }
コード例 #6
0
        public async Task <ActionResult <Product> > AddProduct([FromBody] ProductModel product)
        {
            Product p;

            try
            {
                List <Photo> added_photos = new List <Photo>();
                foreach (var photo in product.ImgsBase64)
                {
                    string imageName = Path.GetRandomFileName() + ".jpg";

                    string pathSaveImages = InitStaticFiles
                                            .CreateImageByFileName(_env, _configuration,
                                                                   new string[] { "ImagesPath", "ImagesPathProduct" },
                                                                   imageName,
                                                                   photo);
                    added_photos.Add(new Photo
                    {
                        Path = imageName
                    });
                }
                p = new Product
                {
                    Name        = product.Name,
                    Category    = _context.Categories.FirstOrDefault(x => x.Name == product.Category),
                    Description = product.Description,
                    Price       = product.Price,
                    Photos      = added_photos
                };
                _context.Products.Add(p);
                _context.SaveChanges();
            }
            catch (Exception)
            {
                return(BadRequest());
            }
            return(p);
        }
コード例 #7
0
        public async Task <IActionResult> RegisterUser([FromBody] RegisterDTO model)
        {
            // Auto return errors from viewModel and other global errors
            return(await HandleRequestAsync(async() =>
            {
                if (!CaptchaHelper.VerifyAndExpireSolution(this.HttpContext,
                                                           model.CaptchaKey,
                                                           model.CaptchaText))
                {
                    var invalid = new Dictionary <string, string>();
                    invalid.Add("captchaText", "Помилка вводу зображення на фото");
                    return BadRequest(invalid);
                }
                var user = _userManager.FindByEmailAsync(model.Email).Result;
                if (user != null)
                {
                    var invalid = new Dictionary <string, string>();
                    invalid.Add("email", "Користувач з даною електронною поштою уже зареєстрований");
                    return BadRequest(invalid);
                }

                string imageName = Path.GetRandomFileName() + ".jpg";

                try
                {
                    this._logger.LogDebug("Start register method RegisterUser...");
                    string pathSaveImages = InitStaticFiles
                                            .CreateImageByFileName(_env, _configuration,
                                                                   new string[] { "ImagesPath", "ImagesPathUser" },
                                                                   imageName,
                                                                   model.Photo);
                    this._logger.LogDebug("Save image complete method RegisterUser...");
                    if (pathSaveImages != null)
                    {
                        var profile = new UserProfile()
                        {
                            RegistrationDate = DateTime.Now,
                            FirstName = model.FirstName,
                            LastName = model.LastName,
                            Photo = imageName,
                        };
                        user = new DbUser()
                        {
                            UserName = model.Email,
                            Email = model.Email,
                            PhoneNumber = model.Phone,
                            UserProfile = profile
                        };
                        var result = _userManager.CreateAsync(user, model.Password).Result;
                        if (!result.Succeeded)
                        {
                            var errors = CustomValidator.GetErrorsByIdentityResult(result);
                            return BadRequest(errors);
                        }
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        // Return token
                        JwtInfo jwtInfo = new JwtInfo()
                        {
                            Token = _jwtTokenService.CreateToken(user),
                            RefreshToken = _jwtTokenService.CreateRefreshToken(user)
                        };

                        this._logger.LogDebug("End method RegisterUser...");

                        return Ok(jwtInfo);
                    }
                    else
                    {
                        throw new Exception("Помила додавання фото в БД");
                    }
                }
                catch (Exception ex)
                {
                    InitStaticFiles.DeleteImageByFileName(_env, _configuration,
                                                          new string[] { "ImagesPath", "ImagesPathUser" },
                                                          imageName);
                    var errors = new Dictionary <string, string>();
                    errors.Add("invalid", ex.Message);
                    return BadRequest(errors);
                }
            }));
        }