예제 #1
0
        public async Task <IActionResult> PutCertificate(long id, CertificateViewModel certificateViewModel)
        {
            if (!ModelState.IsValid)
            {
                var errorMessages = ModelState.Values
                                    .SelectMany(modelStateEntry => modelStateEntry.Errors.Select(b => b.ErrorMessage)).ToList();
                return(BadRequest(errorMessages));
            }

            if (id != certificateViewModel.Id)
            {
                return(BadRequest(new List <string>()
                {
                    "Certificate ID mismatch"
                }));
            }

            if (!await certificateRepository.Exists(id))
            {
                return(NotFound(new List <string>()
                {
                    $"Certificate with ID = {id} not found"
                }));
            }

            var citizenUser = citizenUserRepository.GetUserByLogin(certificateViewModel.OwnerLogin);

            if (citizenUser == null)
            {
                return(NotFound(new List <string>()
                {
                    $"CitizenUser with Login = {certificateViewModel.OwnerLogin} not found"
                }));
            }

            var validCertificate = citizenUser.Certificates.SingleOrDefault(c =>
                                                                            string.Equals(c.Name, certificateViewModel.Name, StringComparison.OrdinalIgnoreCase) &&
                                                                            c.Status == CertificateStatus.Valid) ?? new Certificate();

            // Check if the valid certificate is not the input certificate.
            if (validCertificate.Id != 0 && validCertificate.Id != certificateViewModel.Id)
            {
                return(BadRequest(new List <string>()
                {
                    $"The citizen {certificateViewModel.OwnerLogin} already has a valid certificate."
                }));
            }

            mapper.Map(certificateViewModel, validCertificate);
            validCertificate.Owner = citizenUser;
            await certificateRepository.SaveAsync(validCertificate);

            return(NoContent());
        }