Example #1
0
        public IActionResult Manage(string id)
        {
            int newId = _dataProtector.Unprotect(id);

            ResponseDetails response = _apiHelper.SendApiRequest("", "slot/parkinglot/" + newId, HttpMethod.Get);

            if (response.Success)
            {
                List <SlotViewModel> model = JsonConvert.DeserializeObject <List <SlotViewModel> > (response.Data.ToString());

                PopulateHelperProperties(model);
                _dataProtector.ProtectSlotRouteValues(model);

                ResponseDetails slotTypeResponse = _apiHelper.SendApiRequest("", "slot-type/get-all", HttpMethod.Get);

                ManageSlotModel slotModel = new ManageSlotModel
                {
                    Slots     = model,
                    SlotTypes = JsonConvert.DeserializeObject <List <SlotTypeViewModel> > (slotTypeResponse.Data.ToString())
                };

                return(View(slotModel));
            }
            else
            {
                ErrorViewModel model = new ErrorViewModel
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", model));
            }
        }
        public IActionResult Details(string id)
        {
            int newId = _dataProtector.Unprotect(id);

            ResponseDetails response = _apiHelper.SendApiRequest("", "parkinglot/get/" + newId, HttpMethod.Get);

            if (response.Success)
            {
                ParkingLotViewModel model = JsonConvert.DeserializeObject <ParkingLotViewModel> (response.Data.ToString());

                model = CalculateHourlyRate(model);
                _dataProtector.ProtectParkingLotRouteValues(model);

                return(View(model));
            }
            else
            {
                ErrorViewModel model = new ErrorViewModel
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", model));
            }
        }
        public IActionResult Details(string id)
        {
            int newId = _dataProtector.Unprotect(id);

            ResponseDetails response = _apiHelper.SendApiRequest("", "parkinglot/get/" + newId, HttpMethod.Get);

            if (response.Success)
            {
                ParkingLotViewModel parkingLotViewModel = JsonConvert.DeserializeObject <ParkingLotViewModel>
                                                              (response.Data.ToString());

                _dataProtector.ProtectParkingLotRouteValues(parkingLotViewModel);

                ParkingLotRequestdetailsModel model = new ParkingLotRequestdetailsModel()
                {
                    ParkingLot = parkingLotViewModel
                };

                if (model.ParkingLot.ParkingLotImageViewModels.Any())
                {
                    response = _apiHelper.SendApiRequest("", "parkinglot/all-images/" + newId, HttpMethod.Get);

                    if (response.Success)
                    {
                        model.Images = JsonConvert.DeserializeObject <List <string> > (response.Data.ToString());

                        return(View(model));
                    }
                    else
                    {
                        ErrorViewModel errorModel = new ErrorViewModel
                        {
                            Message = response.Data.ToString()
                        };

                        return(View("Error", errorModel));
                    }
                }
                else
                {
                    return(View(model));
                }
            }
            else
            {
                ErrorViewModel model = new ErrorViewModel
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", model));
            }
        }
Example #4
0
        // Wraps the common logic of working with a DataProtector instance.
        // 'protect' is TRUE if we're calling Protect, FALSE if we're calling Unprotect.
        private byte[] PerformOperation(byte[] data, bool protect)
        {
            // Since the DataProtector might depend on the impersonated context, we must
            // work with it only under app-level impersonation. The idea behind this is
            // that if the cryptographic routine is provided by an OS-level implementation
            // (like DPAPI), any keys will be locked to the account of the web application
            // itself.
            //SOURCE_CHANGED
            DataProtector dataProtector = null;

            try
            {
                dataProtector = _dataProtectorFactory.GetDataProtector(_purpose);
                return((protect) ? dataProtector.Protect(data) : dataProtector.Unprotect(data));
            }
            finally
            {
                // These instances are transient
                IDisposable disposable = dataProtector as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
        }
Example #5
0
        private static void TestEncryption()
        {
            byte[] salt = new byte[] { 65, 61, 53, 222, 105, 5, 199, 241, 213, 56, 19, 120, 251, 37, 66, 185 };
            byte[] data = new byte[255];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }
            byte[] password = new byte[16];
            for (int i = password.Length - 1; i >= 0; i--)
            {
                password[i] = (byte)i;
            }
            byte[] encrypted = CryptoUtility.AesEncryption(data, password, salt);
            byte[] decrypted = CryptoUtility.AesDecryption(encrypted, password, salt);
            if (!decrypted.SequenceEqual(data))
            {
                throw new ApplicationException("AES encryption test fail");
            }

            byte[] protectedData   = DataProtector.Protect(salt);
            byte[] unprotectedData = DataProtector.Unprotect(protectedData);
            if (!unprotectedData.SequenceEqual(salt))
            {
                throw new ApplicationException("Protected data API fail");
            }
        }
        public void DataProtectorWithDifferentEntropy_CannotDecrypt()
        {
            var entropy2 = new byte[] {7, 8, 9, 10};
              var protector2 = new DataProtector(entropy2);

              var cypher = _sut.Protect(_userData);

              Assert.Throws<CryptographicException>(() => protector2.Unprotect(cypher));
        }
Example #7
0
        public void CanUnprotectValue()
        {
            var protector      = new DataProtector();
            var protectedValue = protector.Protect("a value");

            var unprotectedValue = protector.Unprotect(protectedValue);

            Assert.NotNull(protectedValue);
            Assert.That(unprotectedValue, Is.EqualTo("a value"));
        }
Example #8
0
        public IActionResult Index(string userId, string parkingLotId)
        {
            ErrorViewModel errorModel = new ErrorViewModel();

            if (string.IsNullOrEmpty(userId) && string.IsNullOrEmpty(parkingLotId))
            {
                ResponseDetails response = _apiHelper.SendApiRequest("", "booking/get-all", HttpMethod.Get);

                List <BookingViewModel> model = JsonConvert.DeserializeObject <List <BookingViewModel> > (response.Data.ToString());

                _dataProtector.ProtectBookingRouteValues(model);

                return(View(model));
            }

            if (!string.IsNullOrEmpty(parkingLotId))
            {
                int newParkingLotId = _dataProtector.Unprotect(parkingLotId);

                ResponseDetails response = _apiHelper.SendApiRequest("", "booking/get/parkingLot/" + newParkingLotId, HttpMethod.Get);

                List <BookingViewModel> model = JsonConvert.DeserializeObject <List <BookingViewModel> > (response.Data.ToString());

                _dataProtector.ProtectBookingRouteValues(model);

                return(View(model));
            }
            else if (!string.IsNullOrEmpty(userId))
            {
                int newUserId = _dataProtector.Unprotect(userId);

                ResponseDetails response = _apiHelper.SendApiRequest("", "booking/get/user/" + newUserId, HttpMethod.Get);

                List <BookingViewModel> model = JsonConvert.DeserializeObject <List <BookingViewModel> > (response.Data.ToString());

                _dataProtector.ProtectBookingRouteValues(model);

                return(View(model));
            }

            return(View("Error", errorModel));
        }
        public IActionResult RemovePost(string roleId)
        {
            int newId = _dataProtector.Unprotect(roleId);

            ResponseDetails response = _apiHelper.SendApiRequest("", "role/remove/" + newId, HttpMethod.Delete);

            if (response.Success)
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                ErrorViewModel ErrorModel = new ErrorViewModel()
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", ErrorModel));
            }
        }
Example #10
0
        static string ManuallyDecrypt(string encryptedString, IEnumerable <string> purposes = null)
        {
            var entropyCreator = new EntropyCreator();
            var entropy        = entropyCreator.CreateEntropy(purposes);
            var protector      = new DataProtector(entropy);

            var cypher   = Convert.FromBase64String(encryptedString);
            var userData = protector.Unprotect(cypher);

            return(Encoding.UTF8.GetString(userData));
        }
Example #11
0
        public IActionResult ParkingLot(string id)
        {
            int newId = _dataProtector.Unprotect(id);

            ResponseDetails response = _apiHelper.SendApiRequest("", "parkinglot/get/" + newId, HttpMethod.Get);

            if (response.Success)
            {
                ParkingLotViewModel model = JsonConvert.DeserializeObject <ParkingLotViewModel>
                                                (response.Data.ToString());

                _dataProtector.ProtectParkingLotRouteValues(model);

                model.SlotViewModels = model.SlotViewModels.Select(x =>
                {
                    // populate can book property logic
                    x.CanBook = CanBookSlot(x);

                    _dataProtector.ProtectSlotRouteValues(x);

                    return(x);
                }).ToList();

                return(View(model));
            }
            else
            {
                ErrorViewModel model = new ErrorViewModel
                {
                    Message = response.Data.ToString()
                };

                return(View("Error", model));
            }
        }
Example #12
0
        public IActionResult UpdatePassword(UpdatePasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                string OTP      = HttpContext.Session.GetString("OTP");
                int    plainOTP = _dataProtector.Unprotect(OTP);

                HttpContext.Session.Remove("OTP");

                if (plainOTP != Convert.ToInt32(model.OTP))
                {
                    ModelState.AddModelError("", "Invalid OTP.");
                    return(View(model));
                }

                ChangePasswordModel changePasswordModel = new ChangePasswordModel
                {
                    Email    = TempData["Email"].ToString(),
                    Password = model.Password
                };

                ResponseDetails response = _apiHelper.SendApiRequest(changePasswordModel, "user/change-password", HttpMethod.Post);

                if (response.Success)
                {
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ErrorViewModel errorModel = new ErrorViewModel
                    {
                        Message = response.Data.ToString()
                    };

                    return(View("Error", errorModel));
                }
            }
            else
            {
                ModelState.AddModelError("", "Validation error.");
            }

            return(View(model));
        }
        public void AESEncryption()
        {
            byte[] salt = new byte[] { 65, 61, 53, 222, 105, 5, 199, 241, 213, 56, 19, 120, 251, 37, 66, 185 };
            byte[] data = new byte[255];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }
            byte[] password = new byte[16];
            for (int i = password.Length - 1; i >= 0; i--)
            {
                password[i] = (byte)i;
            }
            byte[] encrypted = CryptoUtility.AesEncryption(data, password, salt);
            byte[] decrypted = CryptoUtility.AesDecryption(encrypted, password, salt);
            Assert.IsTrue(decrypted.SequenceEqual(data));

            byte[] protectedData   = DataProtector.Protect(salt);
            byte[] unprotectedData = DataProtector.Unprotect(protectedData);
            Assert.IsTrue(unprotectedData.SequenceEqual(salt));
        }
 private byte[] PerformOperation(byte[] data, bool protect)
 {
     byte[] result;
     //using (new ApplicationImpersonationContext())
     {
         DataProtector dataProtector = null;
         try
         {
             dataProtector = this._dataProtectorFactory.GetDataProtector(this._purpose);
             result        = (protect ? dataProtector.Protect(data) : dataProtector.Unprotect(data));
         }
         finally
         {
             IDisposable disposable = dataProtector as IDisposable;
             if (disposable != null)
             {
                 disposable.Dispose();
             }
         }
     }
     return(result);
 }
Example #15
0
        public IActionResult ConfirmEmail(ConfirmEmailModel model)
        {
            ErrorViewModel errorModel = new ErrorViewModel();

            if (model.Id == _tokenDecoder.UserId)
            {
                string OTP      = HttpContext.Session.GetString("OTP");
                int    plainOTP = _dataProtector.Unprotect(OTP);

                HttpContext.Session.Remove("OTP");

                if (plainOTP == Convert.ToInt32(model.OTP))
                {
                    ResponseDetails response = _apiHelper.SendApiRequest("", "user/confirm-email/" + _tokenDecoder.UserId, HttpMethod.Post);

                    if (response.Success)
                    {
                        return(RedirectToAction("EmailConfirmed"));
                    }
                    else
                    {
                        errorModel.Message = response.Data.ToString();
                    }
                }
                else
                {
                    errorModel.Message = "Invalid OTP.";
                }
            }
            else
            {
                errorModel.Message = "It seems like someone is trying to bypass the security";
            }

            return(View("Error", model));
        }
Example #16
0
        public async Task Register(string @event)
        {
            Logger.LogInformation(@event);
            try
            {
                var httpContext = Context.GetHttpContext();
                var query       = httpContext.Request.Query;

                if (!query.TryGetValue("api_key", out var values))
                {
                    throw new ArgumentException("Не найден api_key");
                }

                var apiKey   = values.First();
                var tenantId = DataProtector.Unprotect(apiKey);

                var message = new EventMessage
                {
                    TenantId = Guid.Parse(tenantId),
                    Event    = @event
                };

                var headers = new CapHeaders
                {
                    MessageKey        = tenantId,
                    EnableIdempotence = true
                };

                await CapPublisher.PublishAsync(KafkaTopics.Events, message, headers);
            }
            catch (Exception e)
            {
                Logger.LogError(e.Message);
                throw new Exception("Не удалось обработать эвент", e);
            }
        }
        public async Task <IActionResult> ConfirmCode(
            ConfirmCodeViewModel confirmCodeViewModel,
            CancellationToken cancellationToken)
        {
            if (confirmCodeViewModel == null)
            {
                throw new ArgumentNullException(nameof(confirmCodeViewModel));
            }

            var user = await SetUser().ConfigureAwait(false);

            if (user?.Identity != null && user.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "User", new { Area = "pwd" }));
            }

            var authenticatedUser = await _authenticationService
                                    .GetAuthenticatedUser(this, CookieNames.PasswordLessCookieName)
                                    .ConfigureAwait(false);

            if (authenticatedUser?.Identity == null || !authenticatedUser.Identity.IsAuthenticated)
            {
                var message = "SMS authentication cannot be performed";
                _logger.LogError(message);
                return(SetRedirection(message, Strings.InternalServerError, ErrorCodes.UnhandledExceptionCode));
            }

            var authenticatedUserClaims = authenticatedUser.Claims.ToArray();
            var subject     = authenticatedUserClaims.First(c => c.Type == OpenIdClaimTypes.Subject).Value;
            var phoneNumber = authenticatedUserClaims.First(c => c.Type == OpenIdClaimTypes.PhoneNumber);

            if (confirmCodeViewModel.Action == "resend") // Resend the confirmation code.
            {
                _ = await _generateAndSendSmsCodeOperation.Execute(phoneNumber.Value, cancellationToken)
                    .ConfigureAwait(false);

                return(Ok(confirmCodeViewModel));
            }

            // Check the confirmation code.
            if (confirmCodeViewModel.ConfirmationCode == null ||
                !await _validateConfirmationCode
                .Execute(confirmCodeViewModel.ConfirmationCode, subject, cancellationToken)
                .ConfigureAwait(false))
            {
                ModelState.AddModelError("message_error", "Confirmation code is not valid");
                return(Ok(confirmCodeViewModel));
            }

            await _authenticationService.SignOutAsync(
                HttpContext,
                CookieNames.PasswordLessCookieName,
                new AuthenticationProperties())
            .ConfigureAwait(false);

            var resourceOwnerOption =
                await _getUserOperation.Execute(authenticatedUser, cancellationToken).ConfigureAwait(false);

            if (resourceOwnerOption is Option <ResourceOwner> .Error e)
            {
                return(SetRedirection(e.Details.Detail, e.Details.Status.ToString(), e.Details.Title));
            }

            var resourceOwner = (resourceOwnerOption as Option <ResourceOwner> .Result) !.Item;

            if (!string.IsNullOrWhiteSpace(resourceOwner.TwoFactorAuthentication)) // Execute TWO Factor authentication
            {
                try
                {
                    await SetTwoFactorCookie(authenticatedUserClaims).ConfigureAwait(false);

                    await _generateAndSendSmsCodeOperation.Execute(phoneNumber.Value, cancellationToken)
                    .ConfigureAwait(false);

                    return(RedirectToAction("SendCode", new { code = confirmCodeViewModel.Code }));
                }
                catch (ClaimRequiredException)
                {
                    return(RedirectToAction("SendCode", new { code = confirmCodeViewModel.Code }));
                }
                catch (Exception)
                {
                    ModelState.AddModelError("message_error", "Two factor authenticator is not properly configured");
                    return(Ok(confirmCodeViewModel));
                }
            }

            if (!string.IsNullOrWhiteSpace(confirmCodeViewModel.Code)) // Execute OPENID workflow
            {
                var request = DataProtector.Unprotect <AuthorizationRequest>(confirmCodeViewModel.Code);
                await SetLocalCookie(authenticatedUserClaims, request.session_id !).ConfigureAwait(false);

                var issuerName   = Request.GetAbsoluteUriWithVirtualPath();
                var actionResult = await _authenticateHelper.ProcessRedirection(
                    request.ToParameter(),
                    confirmCodeViewModel.Code,
                    subject,
                    authenticatedUserClaims,
                    issuerName,
                    cancellationToken)
                                   .ConfigureAwait(false);

                var result = actionResult.CreateRedirectionFromActionResult(request, _logger);
                if (result != null)
                {
                    await LogAuthenticateUser(resourceOwner !.Subject !, actionResult.Amr !).ConfigureAwait(false);

                    return(result);
                }
            }

            await SetLocalCookie(authenticatedUserClaims, Id.Create())
            .ConfigureAwait(false);     // Authenticate the resource owner

            var modelCode = string.IsNullOrWhiteSpace(confirmCodeViewModel.Code)
                ? confirmCodeViewModel.ConfirmationCode
                : confirmCodeViewModel.Code;

            if (!string.IsNullOrWhiteSpace(modelCode))
            {
                await _confirmationCodeStore.Remove(modelCode, subject, cancellationToken).ConfigureAwait(false);
            }

            return(RedirectToAction("Index", "User", new { Area = "pwd" }));
        }
        public async Task <IActionResult> LocalLoginOpenId(
            OpenidLocalAuthenticationViewModel viewModel,
            CancellationToken cancellationToken)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException(nameof(viewModel));
            }

            if (string.IsNullOrWhiteSpace(viewModel.Code))
            {
                throw new ArgumentException(Strings.MissingValues, nameof(viewModel));
            }

            await SetUser().ConfigureAwait(false);

            // 1. Decrypt the request
            var request = DataProtector.Unprotect <AuthorizationRequest>(viewModel.Code);

            // 3. Check the state of the view model
            if (!ModelState.IsValid)
            {
                await SetIdProviders(viewModel).ConfigureAwait(false);

                RouteData.Values["view"] = "OpenId";
                return(Ok(viewModel));
            }

            // 4. Local authentication
            var issuerName = Request.GetAbsoluteUriWithVirtualPath();

            var actionResult = await _localOpenIdAuthentication.Execute(
                new LocalAuthenticationParameter { UserName = viewModel.Login, Password = viewModel.Password },
                request.ToParameter(),
                viewModel.Code,
                issuerName,
                cancellationToken)
                               .ConfigureAwait(false);

            if (actionResult.ErrorMessage == null)
            {
                var subject = actionResult.Claims.First(c => c.Type == OpenIdClaimTypes.Subject).Value;

                // 5. Two factor authentication.
                if (!string.IsNullOrWhiteSpace(actionResult.TwoFactor))
                {
                    try
                    {
                        await SetTwoFactorCookie(actionResult.Claims).ConfigureAwait(false);
                        await SendCode(subject, cancellationToken).ConfigureAwait(false);

                        return(RedirectToAction("SendCode", new { code = viewModel.Code }));
                    }
                    catch (ClaimRequiredException cre)
                    {
                        await _eventPublisher.Publish(
                            new SimpleAuthError(
                                Id.Create(),
                                cre.Code,
                                cre.Message,
                                string.Empty,
                                DateTimeOffset.UtcNow))
                        .ConfigureAwait(false);

                        return(RedirectToAction("SendCode", new { code = viewModel.Code }));
                    }
                    catch (Exception ex)
                    {
                        await _eventPublisher.Publish(
                            new SimpleAuthError(
                                Id.Create(),
                                ex.Message,
                                ex.Message,
                                string.Empty,
                                DateTimeOffset.UtcNow))
                        .ConfigureAwait(false);

                        ModelState.AddModelError(
                            InvalidCredentials,
                            "Two factor authenticator is not properly configured");
                    }
                }
                else
                {
                    // 6. Authenticate the user by adding a cookie
                    await SetLocalCookie(actionResult.Claims, request.session_id !).ConfigureAwait(false);

                    // 7. Redirect the user agent
                    var endpointResult = actionResult.EndpointResult !;
                    var result         = endpointResult.CreateRedirectionFromActionResult(request, _logger);
                    if (result != null)
                    {
                        await LogAuthenticateUser(subject, endpointResult.Amr !).ConfigureAwait(false);

                        return(result);
                    }
                }
            }
            else
            {
                await _eventPublisher.Publish(
                    new SimpleAuthError(
                        Id.Create(),
                        ErrorCodes.InvalidRequest,
                        actionResult.ErrorMessage,
                        string.Empty,
                        DateTimeOffset.UtcNow))
                .ConfigureAwait(false);

                ModelState.AddModelError(InvalidCredentials, actionResult.ErrorMessage);
            }

            await SetIdProviders(viewModel).ConfigureAwait(false);

            RouteData.Values["view"] = "OpenId";
            return(Ok(viewModel));
        }
Example #19
0
        public void UnprotectNullValueReturnsNull()
        {
            var protector = new DataProtector();

            Assert.IsNull(protector.Unprotect(null));
        }
Example #20
0
 private string UnprotectString(string str)
 {
     return(Encoding.UTF8.GetString(DataProtector.Unprotect(Convert.FromBase64String(str))));
 }