<commit_before>﻿using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using static Hl7.Fhir.Model.Practitioner;

namespace GPConnect.Provider.AcceptanceTests.tools
{
    public class JwtHelper
    {
        private static JwtHelper _jwtHelper;
        private DateTime _jwtCreationTime;
        private DateTime _jwtExpiryTime;
        private string _jwtReasonForRequest;
        private string _jwtAuthTokenURL;
        private string _jwtDevice;
        private string _jwtOrganization;
        private string _jwtPractitioner;
        private string _jwtPractitionerId;

        private JwtHelper() {
        }

        public static JwtHelper Instance => _jwtHelper ?? (_jwtHelper = new JwtHelper());

        public void setJwtDefaultValues() {
            _jwtCreationTime = DateTime.UtcNow;
            _jwtExpiryTime = _jwtCreationTime.AddMinutes(5);
            _jwtReasonForRequest = "directcare";
            _jwtAuthTokenURL = "https://authorize.fhir.nhs.net/token";
            _jwtDevice = FhirSerializer.SerializeToJson(
                    new Device()
                    {
                        Id = "1",
                        Model = "v1",
                        Version = "1.1",
                        Identifier = {
                            new Identifier("GPConnectTestSystem", "Client")
                        },
                        Type = new CodeableConcept("DeviceIdentifierSystem","DeviceIdentifier")
                    }
                );
            _jwtOrganization = FhirSerializer.SerializeToJson(
                    new Organization()
                    {
                        Id = "1",
                        Name = "GP Connect Assurance",
                        Identifier = {
                            new Identifier("http://fhir.nhs.net/Id/ods-organization-code", "GPCA0001")
                        }
                    }
                );
            _jwtPractitionerId = getDefaultPractitioner().Id;
            _jwtPractitioner = FhirSerializer.SerializeToJson(getDefaultPractitioner());
        }

        public List<PractitionerRoleComponent> getPractitionerRoleComponent(string system, string value) {
            var practitionerRoleList = new List<PractitionerRoleComponent>();
            PractitionerRoleComponent practitionerRole = new PractitionerRoleComponent()
            {
                Role = new CodeableConcept(system, value)
            };
            practitionerRoleList.Add(practitionerRole);
            return practitionerRoleList;
        }

        public Practitioner getDefaultPractitioner() {
            return new Practitioner
            {
                Id = "1",
                Name = new HumanName()
                {
                    Prefix = new[] { "Mr" },
                    Given = new[] { "AssuranceTest" },
                    Family = new[] { "AssurancePractitioner" }
                },
                Identifier = {
                    new Identifier("http://fhir.nhs.net/sds-user-id", "GCASDS0001"),
                    new Identifier("LocalIdentifierSystem", "1")
                },
                PractitionerRole = getPractitionerRoleComponent("http://fhir.nhs.net/ValueSet/sds-job-role-name-1", "AssuranceJobRole")
            };
        }

        public string buildEncodedHeader() {
            return new JwtHeader().Base64UrlEncode();
        }

        public string buildEncodedPayload(string nhsNumber) {
            return buildPayload(nhsNumber).Base64UrlEncode();
        }

        public JwtPayload buildPayload(string nhsNumber)
        {
            var subject_patient = new Patient
            {
                Identifier = {
                    new Identifier("http://fhir.nhs.net/Id/nhs-number",nhsNumber)
                }
            };

            var subject_organization = new Organization
            {
                Identifier = {
                    new Identifier("http://fhir.nhs.net/Id/ods-organization-code","[OrganizationODSCode]")
                }
            };

            var requesting_system_url = "https://[ConsumerSystemURL]";
            
            var claims = new List<System.Security.Claims.Claim> {
                new System.Security.Claims.Claim("iss", requesting_system_url, ClaimValueTypes.String),
                new System.Security.Claims.Claim("sub", _jwtPractitionerId, ClaimValueTypes.String),
                new System.Security.Claims.Claim("aud", _jwtAuthTokenURL, ClaimValueTypes.String),
                new System.Security.Claims.Claim("exp", EpochTime.GetIntDate(_jwtExpiryTime).ToString(), ClaimValueTypes.Integer64),
                new System.Security.Claims.Claim("iat", EpochTime.GetIntDate(_jwtCreationTime).ToString(), ClaimValueTypes.Integer64),
                new System.Security.Claims.Claim("reason_for_request", _jwtReasonForRequest, ClaimValueTypes.String),
                new System.Security.Claims.Claim("requesting_device", _jwtDevice, JsonClaimValueTypes.Json),
                new System.Security.Claims.Claim("requesting_organization", _jwtOrganization, JsonClaimValueTypes.Json),
                new System.Security.Claims.Claim("requesting_practitioner", _jwtPractitioner, JsonClaimValueTypes.Json)
            };

            if (nhsNumber != null)
            {
                claims.Add(new System.Security.Claims.Claim("requested_record", FhirSerializer.SerializeToJson(subject_patient), JsonClaimValueTypes.Json));
            }
            else {
                claims.Add(new System.Security.Claims.Claim("requested_record", FhirSerializer.SerializeToJson(subject_organization), JsonClaimValueTypes.Json));<commit_msg>Added requested_scope claim to default JWT<commit_after>﻿using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using static Hl7.Fhir.Model.Practitioner;

namespace GPConnect.Provider.AcceptanceTests.tools
{
    public class JwtHelper
    {
        private static JwtHelper _jwtHelper;
        private DateTime _jwtCreationTime;
        private DateTime _jwtExpiryTime;
        private string _jwtReasonForRequest;
        private string _jwtAuthTokenURL;
        private string _jwtDevice;
        private string _jwtOrganization;
        private string _jwtPractitioner;
        private string _jwtPractitionerId;
        private string _jwtRequestScope;

        private JwtHelper() {
        }

        public static JwtHelper Instance => _jwtHelper ?? (_jwtHelper = new JwtHelper());

        public void setJwtDefaultValues() {
            _jwtCreationTime = DateTime.UtcNow;
            _jwtExpiryTime = _jwtCreationTime.AddMinutes(5);
            _jwtReasonForRequest = "directcare";
            _jwtAuthTokenURL = "https://authorize.fhir.nhs.net/token";
            _jwtDevice = FhirSerializer.SerializeToJson(
                    new Device()
                    {
                        Id = "1",
                        Model = "v1",
                        Version = "1.1",
                        Identifier = {
                            new Identifier("GPConnectTestSystem", "Client")
                        },
                        Type = new CodeableConcept("DeviceIdentifierSystem","DeviceIdentifier")
                    }
                );
            _jwtOrganization = FhirSerializer.SerializeToJson(
                    new Organization()
                    {
                        Id = "1",
                        Name = "<NAME>",
                        Identifier = {
                            new Identifier("http://fhir.nhs.net/Id/ods-organization-code", "GPCA0001")
                        }
                    }
                );
            _jwtPractitionerId = getDefaultPractitioner().Id;
            _jwtPractitioner = FhirSerializer.SerializeToJson(getDefaultPractitioner());
            _jwtRequestScope = "organization/*.read";
        }

        public List<PractitionerRoleComponent> getPractitionerRoleComponent(string system, string value) {
            var practitionerRoleList = new List<PractitionerRoleComponent>();
            PractitionerRoleComponent practitionerRole = new PractitionerRoleComponent()
            {
                Role = new CodeableConcept(system, value)
            };
            practitionerRoleList.Add(practitionerRole);
            return practitionerRoleList;
        }

        public Practitioner getDefaultPractitioner() {
            return new Practitioner
            {
                Id = "1",
                Name = new HumanName()
                {
                    Prefix = new[] { "Mr" },
                    Given = new[] { "AssuranceTest" },
                    Family = new[] { "AssurancePractitioner" }
                },
                Identifier = {
                    new Identifier("http://fhir.nhs.net/sds-user-id", "GCASDS0001"),
                    new Identifier("LocalIdentifierSystem", "1")
                },
                PractitionerRole = getPractitionerRoleComponent("http://fhir.nhs.net/ValueSet/sds-job-role-name-1", "AssuranceJobRole")
            };
        }

        public string buildEncodedHeader() {
            return new JwtHeader().Base64UrlEncode();
        }

        public string buildEncodedPayload(string nhsNumber) {
            return buildPayload(nhsNumber).Base64UrlEncode();
        }

        public JwtPayload buildPayload(string nhsNumber)
        {
            var subject_patient = new Patient
            {
                Identifier = {
                    new Identifier("http://fhir.nhs.net/Id/nhs-number",nhsNumber)
                }
            };

            var subject_organization = new Organization
            {
                Identifier = {
                    new Identifier("http://fhir.nhs.net/Id/ods-organization-code","[OrganizationODSCode]")
                }
            };

            var requesting_system_url = "https://[ConsumerSystemURL]";
            
            var claims = new List<System.Security.Claims.Claim> {
                new System.Security.Claims.Claim("iss", requesting_system_url, ClaimValueTypes.String),
                new System.Security.Claims.Claim("sub", _jwtPractitionerId, ClaimValueTypes.String),
                new System.Security.Claims.Claim("aud", _jwtAuthTokenURL, ClaimValueTypes.String),
                new System.Security.Claims.Claim("exp", EpochTime.GetIntDate(_jwtExpiryTime).ToString(), ClaimValueTypes.Integer64),
                new System.Security.Claims.Claim("iat", EpochTime.GetIntDate(_jwtCreationTime).ToString(), ClaimValueTypes.Integer64),
                new System.Security.Claims.Claim("reason_for_request", _jwtReasonForRequest, ClaimValueTypes.String),
                new System.Security.Claims.Claim("requesting_device", _jwtDevice, JsonClaimValueTypes.Json),
                new System.Security.Claims.Claim("requesting_organization", _jwtOrganization, JsonClaimValueTypes.Json),
                new System.Security.Claims.Claim("requesting_practitioner", _jwtPractitioner, JsonClaimValueTypes.Json),
                new System.Security.Claims.Claim("requested_scope", _jwtRequestScope, ClaimValueTypes.String),
            };

            if (nhsNumber != null)
            {
                claims.Add(new System.Security.Claims.Claim("requested_record", FhirSerializer.SerializeToJson(subject_patient), JsonClaimValueTypes.Json));
            }
            else {
                claims.Add(new System.Security.Claims.Claim("requested_record", FhirSerializer.SerializeToJson(subject_organization), JsonClaimValueTypes.Json));
{'fraction_non_alphanumeric': 0.09032476319350474, 'fraction_numerical': 0.004736129905277402, 'mean_word_length': 1.8785296981499513, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 12, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6884101', 'n_tokens_mistral': 3160, 'n_tokens_neox': 2994, 'n_words': 495}