Пример #1
0
        //erişebilir oldugu  zamn
        private void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
            try
            {
                //FormsAuthentication.FormsCookieName isminle bir cookie oluşturacagımız soylemsıtık
                var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

                //bos sa dondur
                if (authCookie == null)
                {
                    return;
                }

                var encticket = authCookie.Value;

                //bos sa dondur
                if (String.IsNullOrEmpty(encticket))
                {
                    return;
                }

                var ticket           = FormsAuthentication.Decrypt(encticket);
                var securityUrlities = new SecurityUtilities();
                var identity         = securityUrlities.FormsAuthTicketToIdentity(ticket);
                var principal        = new GenericPrincipal(identity, identity.Roles);

                //backend ve fronted tarafında erişim işlemleri için
                HttpContext.Current.User = principal;
                Thread.CurrentPrincipal  = principal;
            }
            catch (Exception)
            {
            }
        }
Пример #2
0
        public void Say(string token, string text)
        {
            try
            {
                string userId = SecurityUtilities.VerifyToken(token);

                if (NoahService.NoahBotHandle != null)
                {
                    NoahService.NoahBotHandle.Invoke(new Request
                    {
                        Input     = text,
                        SessionId = userId,
                        UserId    = userId
                    });
                }
            }
            catch (SecurityTokenInvalidSignatureException ex)
            {
                Logger.Error(ex);
                throw new HubException("Ingen adgang.");
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw new HubException(ex.Message);
            }
        }
Пример #3
0
        string UpdateStatusAction(string sessionID, string action)
        {
            string result = "";

            try
            {
                //action = approve, deny or hold.
                string         computerName = SecurityUtilities.GetComputerName();
                string         userName     = SecurityUtilities.GetUserName();
                Authentication auth;
                if (Utilities.Auth == null)
                {
                    auth = SecurityUtilities.GetAuthentication(serviceName);
                }
                else
                {
                    auth = Utilities.Auth;
                }
                HttpsClient client      = new HttpsClient();
                Uri         fhirAddress = new Uri(UpdatePendingStatusUri);
                result = client.UpdatePendingStatus(fhirAddress, auth, sessionID, action, computerName, userName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }
Пример #4
0
        //TODO: Update function in JavaScript and C# to postUnknownDOBExistingPatient
        public bool postUnknownDOBExistingpatient(string passedLocalNoID)
        {
            bool result = false;

            try
            {
                Authentication auth;
                if (Utilities.Auth == null)
                {
                    auth = SecurityUtilities.GetAuthentication(serviceName);
                }
                else
                {
                    auth = Utilities.Auth;
                }
                localNoID = passedLocalNoID;
                HttpsClient client         = new HttpsClient();
                Uri         endpoint       = new Uri(IdentityChallengeUri);
                string      resultResponse = client.SendIdentityChallenge(endpoint, auth, passedLocalNoID, "failedchallenge", "", SecurityUtilities.GetComputerName(), ClinicArea);

                if (resultResponse.ToLower() == "yes")
                {
                    result = true;
                }
                else if (resultResponse.ToLower().Contains("error") == true)
                {
                    errorDescription = "Error in PatientBridge::postUnknownDOBExistingPatient: " + resultResponse.Substring(3);
                }
            }
            catch (Exception ex)
            {
                errorDescription = "Error in PatientBridge::postUnknownDOBExistingPatient: " + ex.Message;
            }
            return(result);
        }
        public void SignFile(string inputFileName, X509Certificate2 certificate, string timestampServer,
                             SignFileRequest signFileRequest, SignFileResponse signFileResponse)
        {
            SignFileResponseResult successResult = SignFileResponseResult.FileSigned;

            if (IsFileSigned(inputFileName))
            {
                if (signFileRequest.OverwriteSignature)
                {
                    UnsignFile(inputFileName);
                    successResult = SignFileResponseResult.FileResigned;
                }
                else
                {
                    signFileResponse.Result = SignFileResponseResult.FileAlreadySigned;
                    return;
                }
            }

            SecurityUtilities.SignFile(certificate, new Uri(timestampServer), inputFileName);

            signFileResponse.Result      = successResult;
            signFileResponse.FileContent = new FileStream(inputFileName, FileMode.Open, FileAccess.Read);
            signFileResponse.FileSize    = signFileResponse.FileContent.Length;
        }
Пример #6
0
    private void RegisterEmail(string email, string storeID)
    {
        bool isCorrectFormat = checkEmailFormat(email, storeID);

        if (isCorrectFormat)
        {
            string emailHash =
                SecurityUtilities.HashMD5(email + WebConfiguration.SecretKey);

            Store      store      = DataAccessContext.StoreRepository.GetOne(storeID);
            NewsLetter newsLetter = DataAccessContext.NewsLetterRepository.GetOne(email, store);
            if (newsLetter.IsNull)
            {
                newsLetter.Email     = email;
                newsLetter.EmailHash = emailHash;
                newsLetter.JoinDate  = DateTime.Now;
                newsLetter.StoreID   = storeID;
                DataAccessContext.NewsLetterRepository.Create(newsLetter);
                uxMessage.DisplayMessage(Resources.NewsletterManager.RegisterSuccess);
                ClearField();
            }
            else
            {
                uxMessage.DisplayError(Resources.NewsletterManager.RegisterAlready);
            }
        }
        else
        {
            uxMessage.DisplayError(Resources.NewsletterManager.RegisterInvalidEmail);
        }
    }
Пример #7
0
        /// <summary>
        /// The method to be overriden in inheriting tasks.
        /// Throw an exception in case of an errror.
        /// </summary>
        protected override void ExecuteTask()
        {
            // Keyfile password
            var password = new SecureString();

            foreach (char c in BagGet(AttributeName.Password, ""))
            {
                password.AppendChar(c);
            }

            // Timestamping server
            string sTimestampServer   = BagGet(AttributeName.TimestampingServer, "");
            Uri    uriTimestampServer = string.IsNullOrEmpty(sTimestampServer) ? null : new Uri(sTimestampServer);

            if (uriTimestampServer == null)
            {
                Log.LogWarning("It would be better to specify the Timestamping Server Uri.");
            }

            // Sign each file
            foreach (ITaskItem item in BagGet <ITaskItem[]>(AttributeName.InputFiles))
            {
                SecurityUtilities.SignFile(GetStringValue(AttributeName.KeyFile), password, uriTimestampServer, item.GetMetadata("FullPath"));
            }
        }
Пример #8
0
        public async Task <Permissions> GetPermissions(HttpResponseMessage response)
        {
            string      json        = string.Empty;
            Permissions permissions = Permissions.NONE;

            try
            {
                json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                _logger?.LogDebug("GetPermisions returned json: {0}", SecurityUtilities.SanitizeInput(json));

                var result = JsonConvert.DeserializeObject <Dictionary <string, object> >(json);

                if (result.TryGetValue(READ_SENSITIVE_DATA, out object perm))
                {
                    bool boolResult = (bool)perm;
                    permissions = boolResult ? Permissions.FULL : Permissions.RESTRICTED;
                }
            }
            catch (Exception e)
            {
                _logger?.LogError("Exception {0} extracting permissions from {1}", e, SecurityUtilities.SanitizeInput(json));
                throw;
            }

            _logger?.LogDebug("GetPermisions returning: {0}", permissions);
            return(permissions);
        }
        private void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
            try
            {
                var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie == null)
                {
                    return;
                }

                var encTicket = authCookie.Value;
                if (String.IsNullOrEmpty(encTicket))
                {
                    return;
                }

                var ticket            = FormsAuthentication.Decrypt(encTicket);              // bileti çöz.
                var securityUtilities = new SecurityUtilities();
                var identity          = securityUtilities.FormsAuthTicketToIdentity(ticket); // Çözülmüþ ticket'dan identity oluþturuyoruz.
                var principal         = new GenericPrincipal(identity, identity.Roles);      // principal oluþturuyoruz.

                HttpContext.Current.User = principal;                                        // Web'de kullaným için.
                Thread.CurrentPrincipal  = principal;                                        // Back-end' de kullaným için.
            }
            catch (Exception)
            {
            }
        }
        public ActionResult Login(LoginViewModel LoginVM)
        {
            if (ModelState.IsValid)
            {
                var patient = db.Patients.Where(u => u.Email == LoginVM.Email).FirstOrDefault();
                if (patient != null)
                {
                    //valid email address
                    if (string.Compare(SecurityUtilities.Hash(LoginVM.PW), patient.PW) == 0)
                    {
                        //valid login password, reset access faild counter and create FormAuthentication Cookie
                        Response.Cookies.Add(SecurityUtilities.CreateAuthenticationCookie(patient.FName, patient.ID.ToString()));

                        //redirect to home page
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        //invalid password
                        ModelState.AddModelError("InvalidPassword", "Invalid Password. ");
                    }
                }
                else
                {
                    //wrong email address
                    ModelState.AddModelError("InvalidEmail", "Invalid Email Address. ");
                }
            }
            else
            {
                ModelState.AddModelError("loginerror", "An error occured while sign in .");
            }
            // If we got this far, something failed, redisplay form
            return(View(LoginVM));
        }
Пример #11
0
 private void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
 {
     //Web için gerekli olan cookie de ki bilgileri alıp role karşılaştırması ile principal oluşturduk artık kullanıcımızın bilgilerine erişebiliriz.
     try
     {
         var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
         if (authCookie == null)
         {
             return;
         }
         var encTicket = authCookie.Value;
         if (String.IsNullOrEmpty(encTicket))
         {
             return;
         }
         var ticket            = FormsAuthentication.Decrypt(encTicket);
         var securityUtilities = new SecurityUtilities();
         var identity          = securityUtilities.FormsAuthTicketToIdentity(ticket);
         var principal         = new GenericPrincipal(identity, identity.Roles);
         HttpContext.Current.User = principal;
         Thread.CurrentPrincipal  = principal;
     }
     catch (Exception)
     {
     }
 }
Пример #12
0
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            try
            {
                var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

                var encTicket = authCookie?.Value;
                if (String.IsNullOrEmpty(encTicket))
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary {
                        { "controller", "Account" },
                        { "action", "SignIn" }
                    });
                    return;
                }
                var ticket            = FormsAuthentication.Decrypt(encTicket);
                var securityUtilities = new SecurityUtilities();
                var identity          = securityUtilities.FormsAuthTicketToIdentity(ticket);
                var principal         = new GenericPrincipal(identity, identity.Roles);
                HttpContext.Current.User = principal;
                Thread.CurrentPrincipal  = principal;
            }
            catch
            {
                // ignored
            }
        }
Пример #13
0
        public void SetUp()
        {
            engine = new Fakes.FakeEngine(new Type[] { typeof(ContentHandlerTestsPage), typeof(ContentHandlerTestsPart), typeof(Fakes.FakeNodeAdapter) });
            //engine.Resolve<Fakes.FakeNodeAdapter>().Engine = engine;
            handler = new ContentHandler(engine);
            context = new Fakes.FakeWebContextWrapper();
            context.HttpContext.User = SecurityUtilities.CreatePrincipal("Admin");

            startPage = new ContentHandlerTestsPage {
                Title = "Start page"
            };
            engine.Persister.Save(startPage);
            page = new ContentHandlerTestsPage {
                Title = "Page in question"
            };
            page.AddTo(startPage);
            engine.Persister.Save(page);

            engine.AddComponentInstance <IWebContext>(context);
            engine.AddComponentInstance <IUrlParser>(new Fakes.FakeUrlParser(startPage: startPage));
            var persister         = engine.Persister;
            var activator         = engine.Resolve <ContentActivator>();
            var versionRepository = TestSupport.CreateVersionRepository(ref persister, ref activator, new Type[] { typeof(ContentHandlerTestsPage), typeof(ContentHandlerTestsPart) });

            engine.AddComponentInstance <ContentVersionRepository>(versionRepository);
            engine.AddComponentInstance <VersionManager>(versionManager = TestSupport.SetupVersionManager(engine.Persister, versionRepository));
            (engine.Resolve <IContentAdapterProvider>() as N2.Plugin.IAutoStart).Start();
            engine.Resolve <IContentAdapterProvider>().ResolveAdapter <N2.Edit.NodeAdapter>(typeof(ContentItem)).Engine = engine;
            engine.AddComponentInstance(new HtmlSanitizer(new N2.Configuration.HostSection()));
            engine.AddComponentInstance <IEditUrlManager>(new FakeEditUrlManager());
            engine.AddComponentInstance(new ConfigurationManagerWrapper());
            engine.AddComponentInstance <ILanguageGateway>(new FakeLanguageGateway());

            engine.AddComponentInstance(new DraftRepository(versionRepository, new FakeCacheWrapper()));
        }
        private void MvcApplication_PostAuthenticateRequest(object sender, System.EventArgs e)
        {
            try
            {
                var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

                if (authCookie == null)/*Böyle bir çerez bulunmamaktadır*/
                {
                    return;
                }

                var encpTicket = authCookie.Value;
                if (String.IsNullOrEmpty(encpTicket))/*Boş gönderilip gönderilmediği kontrol ediliyor*/
                {
                    return;
                }

                var ticket = FormsAuthentication.Decrypt(encpTicket);
                SecurityUtilities utilies = new SecurityUtilities();
                var identity  = utilies.FormAuthTicketToIdentity(ticket);/* Kimlik oluşturuldu */
                var principal = new GenericPrincipal(identity, identity.Roles);

                HttpContext.Current.User = principal;
                Thread.CurrentPrincipal  = principal;/*Başka katmanlarda erişim sağlandı*/
            }
            catch
            {
                /*Olası bir hata karşısında önlem alındı.*/
            }
        }
Пример #15
0
        private void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
            try
            {
                var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie == null)
                {
                    return;
                }

                var encTicket = authCookie.Value;
                if (String.IsNullOrEmpty(encTicket))
                {
                    return;
                }

                var ticket = FormsAuthentication.Decrypt(encTicket);

                var securityUtilities = new SecurityUtilities();
                var identity          = securityUtilities.FormsAuthTicketToIdentity(ticket);

                var principal = new GenericPrincipal(identity, identity.Roles);

                HttpContext.Current.User = principal;

                Thread.CurrentPrincipal = principal;
            }
            catch (Exception ex)
            {
            }
        }
Пример #16
0
        private void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
            try
            {
                var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie == null)
                {
                    return;
                }

                var encTicket = authCookie.Value;
                if (string.IsNullOrEmpty(encTicket))
                {
                    return;
                }

                var ticket    = FormsAuthentication.Decrypt(encTicket);
                var identity  = SecurityUtilities.FormsAuthenticationTicketToIdentity(ticket);
                var principal = new CustomPrincipal(identity);

                HttpContext.Current.User = principal;   // for Web
                Thread.CurrentPrincipal  = principal;   // for Back-end
            }
            catch
            {
                // ignored
            }
        }
Пример #17
0
        internal static bool Sign(string file, Project project)
        {
            if (project.CertificateSource.Value is null)
            {
                return(false);
            }

            try
            {
                var certificateSource = project.CertificateSource.Value;
                var timestampUrl      = project.TimestampUrl.Value is null ? null : new Uri(project.TimestampUrl.Value, UriKind.Absolute);

                if (certificateSource.Length == 40 && Regex.IsMatch(certificateSource, "[a-fA-F0-9]*"))
                {
                    SecurityUtilities.SignFile(certificateSource, timestampUrl, file);
                }
                else
                {
                    SecurityUtilities.SignFile(Path.Combine(project.Source.Value, project.CertificateSource.Value), project.CertificatePassword.Value, timestampUrl, file);
                }

                return(true);
            }
            catch
            {
                throw new ApplicationException($"An error occurred signing the manifest. Check that all signature parameters are correct.");
            }
        }
        public new ActionResult Profile(Patient patient)
        {
            if (ModelState.IsValid)
            {
                var isExist = SecurityUtilities.IsEmailExists(patient.Email);
                if (isExist)
                {
                    if (db.Patients.Where(p => p.ID == patient.ID).Select(p => p.Email).FirstOrDefault() != patient.Email)
                    {
                        //username is registered before
                        ModelState.AddModelError("EmailExist", "Email already exists .");
                        ViewBag.BloodGroupID = new SelectList(db.BloodGroups, "ID", "Name", patient.BloodGroupID);
                        return(View(patient));
                    }
                }

                // saving data
                patient.PW = SecurityUtilities.Hash(patient.PW);
                db.Entry(patient).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index", "Home"));
            }
            //if we reach here something went wrong
            ModelState.AddModelError("ProfileError", "An error occured while editing profile");
            ViewBag.BloodGroupID = new SelectList(db.BloodGroups, "ID", "Name", patient.BloodGroupID);
            return(View(patient));
        }
Пример #19
0
    private void RegisterEmailUpdate(string email, string emailOld, string storeID, string storeIDOld)
    {
        bool isCorrectFormat = checkEmailFormat(email, storeID);

        if (isCorrectFormat)
        {
            string emailHash =
                SecurityUtilities.HashMD5(email + WebConfiguration.SecretKey);
            string emailOldHash =
                SecurityUtilities.HashMD5(emailOld + WebConfiguration.SecretKey);

            Store      store      = DataAccessContext.StoreRepository.GetOne(storeID);
            Store      storeOld   = DataAccessContext.StoreRepository.GetOne(storeIDOld);
            NewsLetter newsLetter = DataAccessContext.NewsLetterRepository.GetOne(email, store);
            if (newsLetter.IsNull)
            {
                NewsLetter newsLetterOld = DataAccessContext.NewsLetterRepository.GetOne(emailOld, storeOld);
                newsLetterOld.EmailHash = emailHash;
                DataAccessContext.NewsLetterRepository.Update(newsLetterOld, email, storeID);
            }
            else
            {
                uxMessage.DisplayError(Resources.NewsletterManager.RegisterAlready);
            }
        }
        else
        {
            uxMessage.DisplayError(Resources.NewsletterManager.RegisterInvalidEmail);
        }
    }
Пример #20
0
        public UserModel RegisterMembership(UserModel userModel, Guid userId)
        {
            try
            {
                MailAddress mailAddress = new MailAddress(userModel.Email);

                var membership = new User()
                {
                    CreatedById = userId,
                    FirstName   = userModel.FirstName,
                    LastName    = userModel.LastName,
                    NationalIdentificationNumber = userModel.NationalIdentificationNumber,
                    TaxNumber    = userModel.TaxNumber,
                    UserType     = Common.Enum.Enum.UserType.Membership,
                    EntityType   = userModel.EntityType,
                    Email        = userModel.Email,
                    PasswordHash = SecurityUtilities.HashPassword(userModel.Password),
                    UserName     = mailAddress.User
                };

                var membershipRoleId = _identityRepository.GetAllRoles().Where(m => m.Name.Contains("Membership")).Select(m => m.Id).FirstOrDefault();

                /* adding membership role */
                membership.Roles.Add(new UserRole
                {
                    RoleId      = membershipRoleId,
                    CreatedById = userId
                });

                /* adding deposit record */
                membership.AccrualLoans.Add(new AccrualLoan
                {
                    Type              = Common.Enum.Enum.AccrualLoanType.Deposit,
                    Amount            = 100m,
                    ExpiryDate        = DateTime.UtcNow,
                    CreatedById       = userId,
                    CreatedAt         = DateTime.UtcNow,
                    CollectionRecords = new List <CollectionRecord>()
                    {
                        new CollectionRecord()
                        {
                            Amount      = 100m,
                            CreatedById = userId,
                            CreatedAt   = DateTime.UtcNow,
                        }
                    }
                });

                membership = _identityRepository.AddUser(membership);

                var mappedMembership = ObjectMapper.Mapper.Map <UserModel>(membership);

                return(mappedMembership);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public override bool Execute()
        {
            TrustInfo info = new TrustInfo {
                IsFullTrust = false
            };
            FrameworkName name = null;
            string        str  = string.Empty;

            if (!string.IsNullOrEmpty(this.TargetFrameworkMoniker))
            {
                name = new FrameworkName(this.TargetFrameworkMoniker);
                str  = name.Version.ToString();
            }
            if ((this.BaseManifest != null) && File.Exists(this.BaseManifest.ItemSpec))
            {
                try
                {
                    info.ReadManifest(this.BaseManifest.ItemSpec);
                }
                catch (Exception exception)
                {
                    base.Log.LogErrorWithCodeFromResources("GenerateManifest.ReadInputManifestFailed", new object[] { this.BaseManifest.ItemSpec, exception.Message });
                    return(false);
                }
            }
            if (!string.IsNullOrEmpty(this.ExcludedPermissions))
            {
                base.Log.LogWarningFromResources("GenerateManifest.ExcludedPermissionsNotSupported", new object[0]);
            }
            try
            {
                if ((!string.IsNullOrEmpty(this.targetZone) && (info.PermissionSet != null)) && ((info.PermissionSet.Count > 0) && !string.Equals(this.targetZone, "Custom", StringComparison.OrdinalIgnoreCase)))
                {
                    base.Log.LogErrorFromResources("GenerateManifest.KnownTargetZoneCannotHaveAdditionalPermissionType", new object[0]);
                    return(false);
                }
                info.PermissionSet = SecurityUtilities.ComputeZonePermissionSetHelper(this.TargetZone, info.PermissionSet, this.applicationDependencies, this.TargetFrameworkMoniker);
                if (info.PermissionSet == null)
                {
                    base.Log.LogErrorWithCodeFromResources("GenerateManifest.NoPermissionSetForTargetZone", new object[] { str });
                    return(false);
                }
            }
            catch (ArgumentNullException)
            {
                base.Log.LogErrorWithCodeFromResources("GenerateManifest.NoPermissionSetForTargetZone", new object[] { str });
                return(false);
            }
            catch (ArgumentException exception2)
            {
                if (!string.Equals(exception2.ParamName, "TargetZone", StringComparison.OrdinalIgnoreCase))
                {
                    throw;
                }
                base.Log.LogWarningWithCodeFromResources("GenerateManifest.InvalidItemValue", new object[] { "TargetZone", this.TargetZone });
            }
            info.Write(this.TrustInfoFile.ItemSpec);
            return(true);
        }
Пример #22
0
        static void Main(string[] args)
        {
            #region Number to Words

            var numberToWords = NumberUtilities.ToWords(1234);

            #endregion

            #region Twilio Sms

            SmsUtilities.ConfigureService(container =>
            {
                container.Add("twilio", new TwilioSmsService("+10000000000", "sid", "token"));
            });

            var text = "Test Sms!";
            SmsUtilities.SendSms(text, "+8801815000000", "t");

            #endregion

            #region Encription/Decryption

            SecurityUtilities.ConfigureOptions(x =>
            {
                x.Key    = "";
                x.Secret = "";
            });

            string str             = "Normal String";
            string encryptedString = str.Encrypt();

            #endregion

            #region Dynamic Search

            var users = new List <User>
            {
                new User {
                    Id = 1, Name = "A"
                },
                new User {
                    Id = 2, Name = "B"
                },
                new User {
                    Id = 3, Name = "B"
                },
            }.AsQueryable();

            var searchOptions = new SearchOptions
            {
                Search = new string[] { "name eq B" }
            };

            var result = users.ApplySearch(searchOptions).ToList();

            #endregion

            Console.ReadLine();
        }
        public new ActionResult Profile()
        {
            int     id      = SecurityUtilities.GetAuthenticatedUserID();
            Patient patient = db.Patients.Where(p => p.ID == id).FirstOrDefault();

            ViewBag.BloodGroupID = new SelectList(db.BloodGroups, "ID", "Name", patient.BloodGroupID);
            return(View(patient));
        }
Пример #24
0
        private static void SendJSON(Patient payload)
        {
            Authentication auth     = SecurityUtilities.GetAuthentication(NoIDServiceName);
            Uri            endpoint = new Uri(PatentCheckinUri);
            HttpsClient    client   = new HttpsClient();

            client.SendFHIRPatientProfile(endpoint, auth, payload);
            Console.WriteLine(client.ResponseText);
        }
Пример #25
0
        private static void SendJSON(Media payload)
        {
            Authentication auth     = SecurityUtilities.GetAuthentication(NoIDServiceName);
            Uri            endpoint = new Uri(SearchBiometricsUri);
            HttpsClient    client   = new HttpsClient();

            client.SendFHIRMediaProfile(endpoint, auth, payload);
            Console.WriteLine(client.ResponseText);
        }
Пример #26
0
        public async Task <SecurityResult> GetPermissionsAsync(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return(new SecurityResult(HttpStatusCode.Unauthorized, AUTHORIZATION_HEADER_INVALID));
            }

            string checkPermissionsUri     = _options.CloudFoundryApi + "/v2/apps/" + _options.ApplicationId + "/permissions";
            var    request                 = new HttpRequestMessage(HttpMethod.Get, checkPermissionsUri);
            AuthenticationHeaderValue auth = new AuthenticationHeaderValue("bearer", token);

            request.Headers.Authorization = auth;

            // If certificate validation is disabled, inject a callback to handle properly
            HttpClientHelper.ConfigureCertificateValidation(
                _options.ValidateCertificates,
                out SecurityProtocolType prevProtocols,
                out RemoteCertificateValidationCallback prevValidator);
            try
            {
                _logger?.LogDebug("GetPermissions({0}, {1})", checkPermissionsUri, SecurityUtilities.SanitizeInput(token));

                // If certificate validation is disabled, inject a callback to handle properly
                HttpClientHelper.ConfigureCertificateValidation(
                    _options.ValidateCertificates,
                    out prevProtocols,
                    out prevValidator);
                using (var client = HttpClientHelper.GetHttpClient(_options.ValidateCertificates, DEFAULT_GETPERMISSIONS_TIMEOUT))
                {
                    using (HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false))
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            _logger?.LogInformation(
                                "Cloud Foundry returned status: {HttpStatus} while obtaining permissions from: {PermissionsUri}",
                                response.StatusCode,
                                checkPermissionsUri);

                            return(response.StatusCode == HttpStatusCode.Forbidden
                                ? new SecurityResult(HttpStatusCode.Forbidden, ACCESS_DENIED_MESSAGE)
                                : new SecurityResult(HttpStatusCode.ServiceUnavailable, CLOUDFOUNDRY_NOT_REACHABLE_MESSAGE));
                        }

                        return(new SecurityResult(await GetPermissions(response).ConfigureAwait(false)));
                    }
                }
            }
            catch (Exception e)
            {
                _logger?.LogError("Cloud Foundry returned exception: {SecurityException} while obtaining permissions from: {PermissionsUri}", e, checkPermissionsUri);
                return(new SecurityResult(HttpStatusCode.ServiceUnavailable, CLOUDFOUNDRY_NOT_REACHABLE_MESSAGE));
            }
            finally
            {
                HttpClientHelper.RestoreCertificateValidation(_options.ValidateCertificates, prevProtocols, prevValidator);
            }
        }
Пример #27
0
        public ActionResult Index()
        {
            ChatModel model = new ChatModel
            {
                ServerUrl   = WebAppSettings.ServerUrl.Value,
                ServerToken = SecurityUtilities.GenerateServerToken(HttpContext.GetOwinContext().Authentication),
                UserName    = new MvcHtmlString(JavaScriptStringEncode(User.Identity.Name))
            };

            return(View(model));
        }
Пример #28
0
 public override bool Execute()
 {
     if (!NativeMethodsShared.IsWindows)
     {
         Log.LogErrorWithCodeFromResources("General.TaskRequiresWindows", nameof(SignFile));
         return(false);
     }
     try
     {
         SecurityUtilities.SignFile(
             CertificateThumbprint,
             TimestampUrl == null ? null : new Uri(TimestampUrl),
             SigningTarget.ItemSpec,
             TargetFrameworkVersion,
             TargetFrameworkIdentifier,
             DisallowMansignTimestampFallback);
         return(true);
     }
     catch (ArgumentException ex) when(ex.ParamName.Equals("certThumbprint"))
     {
         Log.LogErrorWithCodeFromResources("SignFile.CertNotInStore");
         return(false);
     }
     catch (FileNotFoundException ex)
     {
         Log.LogErrorWithCodeFromResources("SignFile.TargetFileNotFound", ex.FileName);
         return(false);
     }
     catch (ApplicationException ex)
     {
         Log.LogErrorWithCodeFromResources("SignFile.SignToolError", ex.Message.Trim());
         return(false);
     }
     catch (WarningException ex)
     {
         Log.LogWarningWithCodeFromResources("SignFile.SignToolWarning", ex.Message.Trim());
         return(true);
     }
     catch (CryptographicException ex)
     {
         Log.LogErrorWithCodeFromResources("SignFile.SignToolError", ex.Message.Trim());
         return(false);
     }
     catch (Win32Exception ex)
     {
         Log.LogErrorWithCodeFromResources("SignFile.SignToolError", ex.Message.Trim());
         return(false);
     }
     catch (UriFormatException ex)
     {
         Log.LogErrorWithCodeFromResources("SignFile.SignToolError", ex.Message.Trim());
         return(false);
     }
 }
Пример #29
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // ... log stuff before execution
            if (System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated == false)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {
                    { "controller", "Account" },
                    { "action", "Index" }
                });
                return;
            }
            try
            {
                var authCookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie == null)
                {
                    return;
                }

                var encTicket = authCookie.Value;
                if (string.IsNullOrEmpty(encTicket))
                {
                    return;
                }

                var ticket = FormsAuthentication.Decrypt(encTicket);

                var securityUtilies = new SecurityUtilities();
                var identity        = securityUtilies.FormsAuthTicketToIdentity(ticket);
                var principal       = new GenericPrincipal(identity, identity.Roles);

                if (!string.IsNullOrEmpty(identity.Name) && !string.IsNullOrEmpty(identity.Email))
                {
                    IUserService userService = IstanceFactory.GetIstance <IUserService>();
                    var          result      = userService.GetByUserForId(identity.Id);
                    if (result != null)
                    {
                        _BaseUser = new User
                        {
                            FirstName = result.FirstName,
                            LastName  = result.LastName,
                            Email     = identity.Email,
                            Id        = result.Id
                        };

                        ViewBag.UserFirstName = _BaseUser.FirstName;
                        ViewBag.UserLastName  = _BaseUser.LastName;
                    }
                }
            }
            catch (Exception)
            {
            }
        }
Пример #30
0
        private static IList <PatientProfile> GetCheckinList()
        {
            IList <PatientProfile> PatientProfiles = null;

            Authentication auth     = SecurityUtilities.GetAuthentication(NoIDServiceName);
            Uri            endpoint = new Uri(PendingPatientsUri);
            HttpsClient    client   = new HttpsClient();

            PatientProfiles = client.RequestPendingQueue(endpoint, auth);
            Console.WriteLine(client.ResponseText);
            return(PatientProfiles);
        }