Exemplo n.º 1
0
        public async Task <IActionResult> PutFeedback(string j, string r, [FromBody] CapturedFeedback model, CancellationToken cancellationToken)
        {
            int          jobId       = Base64Utils.Base64DecodeToInt(j);
            RequestRoles requestRole = (RequestRoles)Base64Utils.Base64DecodeToInt(r);

            if (!_authService.GetUrlIsSessionAuthorised(HttpContext))
            {
                return(StatusCode((int)HttpStatusCode.Unauthorized));
            }
            if (!ModelState.IsValid)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }

            model.JobId = jobId;
            model.RoleSubmittingFeedback = requestRole;

            var user = await _authService.GetCurrentUser(HttpContext, cancellationToken);

            var result = await _feedbackService.PostRecordFeedback(user, model);

            if (result == Result.Success || result == Result.Failure_FeedbackAlreadyRecorded)
            {
                return(StatusCode((int)HttpStatusCode.OK));
            }
            else
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
        }
Exemplo n.º 2
0
        public void Execute(IHost host)
        {
            host.Show("Select an option:");
            host.Show("1. Encode");
            host.Show("2. Decode");
            var option = host.Read <int>();
            var data   = host.Read <string>("Enter a string");

            var result = string.Empty;

            if (option == 1)
            {
                result = Base64Utils.ToBase64(data);
            }
            else if (option == 2)
            {
                result = Base64Utils.FromBase64(data);
            }
            else
            {
                host.Show($"Option '{option}' is not recognized.");
            }

            host.Show($"Result: {result}");
        }
Exemplo n.º 3
0
        public async Task <IActionResult> PostTaskFeedbackCapture(string j, string r, FeedbackCaptureEditModel model, CancellationToken cancellationToken)
        {
            int          jobId       = Base64Utils.Base64DecodeToInt(j);
            RequestRoles requestRole = (RequestRoles)Base64Utils.Base64DecodeToInt(r);

            if (!_authService.GetUrlIsSessionAuthorised(HttpContext))
            {
                return(Redirect("/Error/401"));
            }
            if (!ModelState.IsValid)
            {
                throw new Exception($"Invalid model state in PostTaskFeedbackCapture for job {jobId}");
            }

            model.JobId = jobId;
            model.RoleSubmittingFeedback = requestRole;

            var user = await _authService.GetCurrentUser(HttpContext, cancellationToken);

            var job = await _requestService.GetJobSummaryAsync(jobId, cancellationToken);

            var result = await _feedbackService.PostRecordFeedback(user, model);

            return(ShowMessage(result, job.ReferringGroupID, model));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> PrintJobDetails(string j, CancellationToken cancellationToken)
        {
            var  jobID = Base64Utils.Base64DecodeToInt(j);
            User user  = await _authService.GetCurrentUser(HttpContext, cancellationToken);

            return(ViewComponent("JobDetail", new { JobID = jobID, User = user, Jobset = JobSet.UserMyRequests, ToPrint = true }));
        }
Exemplo n.º 5
0
        public async Task <IActionResult> PostTaskFeedbackCapture(string j, string r, string f, CancellationToken cancellationToken)
        {
            if (!_authService.GetUrlIsSessionAuthorised(HttpContext))
            {
                return(Redirect("/Error/401"));
            }

            int            jobId          = Base64Utils.Base64DecodeToInt(j);
            RequestRoles   requestRole    = (RequestRoles)Base64Utils.Base64DecodeToInt(r);
            FeedbackRating feedbackRating = string.IsNullOrEmpty(f) ? 0 : (FeedbackRating)Base64Utils.Base64DecodeToInt(f);
            var            job            = await _requestService.GetJobSummaryAsync(jobId, cancellationToken);

            var user = await _authService.GetCurrentUser(HttpContext, cancellationToken);

            if (job.JobStatus.Incomplete())
            {
                return(ShowMessage(Result.Failure_IncorrectJobStatus, job.ReferringGroupID));
            }

            if (await _feedbackService.GetFeedbackExists(jobId, requestRole, user?.ID))
            {
                return(ShowMessage(Result.Failure_FeedbackAlreadyRecorded, job.ReferringGroupID));
            }

            return(View(new FeedbackCaptureViewComponentParameters()
            {
                JobId = jobId, RequestRole = requestRole, FeedbackRating = feedbackRating
            }));
        }
Exemplo n.º 6
0
        public static byte[] Decrypt(byte[] secretKeyBytes, JweObject jweObject)
        {
            // Extract the encryption key
            byte[] aesKey = new byte[16];
            Array.Copy(secretKeyBytes, 16, aesKey, 0, aesKey.Length);

            byte[] plaintext;
            using (var aes = Aes.Create())
            {
                aes.Key     = aesKey;
                aes.Mode    = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                aes.IV      = Base64Utils.URLDecode(jweObject.Iv);

                byte[] ciphertext = Base64Utils.URLDecode(jweObject.CipherText);
                using (var decryptor = aes.CreateDecryptor())
                {
                    using (var memoryStream = new MemoryStream(ciphertext))
                    {
                        using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                        {
                            var output    = new MemoryStream();
                            var decrypted = new byte[Math.Min(1024, ciphertext.Length)];
                            int byteCount;
                            while ((byteCount = cryptoStream.Read(decrypted, 0, decrypted.Length)) > 0)
                            {
                                output.Write(decrypted, 0, byteCount);
                            }
                            plaintext = output.ToArray();
                        }
                    }
                }
            }
            return(plaintext);
        }
Exemplo n.º 7
0
        public DataRecordCollection GetFileContents(bool b64encode = false)
        {
            DataRecordCollection result = null;

            using (StreamReader file = File.OpenText(path))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    JObject obj1 = (JObject)JToken.ReadFrom(reader);
                    foreach (JObject obj in obj1.Children <JObject>())
                    {
                        Dictionary <String, String> dictObj = obj1.ToObject <Dictionary <string, string> >();
                        List <String> schema = dictObj.Keys.Cast <String>().ToList();
                        List <String> values = dictObj.Values.Cast <String>().ToList();
                        if (b64encode)
                        {
                            values = Base64Utils.MakeB64(values);
                        }
                        if (result == null)
                        {
                            result = new DataRecordCollection(schema.ToArray(), values.ToArray());
                        }
                        else
                        {
                            result.AddRecord(values.ToArray());
                        }
                    }
                }
            return(result);
        }
Exemplo n.º 8
0
        public async Task <IActionResult> EmailJobDetails(string j, CancellationToken cancellationToken)
        {
            var jobID = Base64Utils.Base64DecodeToInt(j);

            User user = await _authService.GetCurrentUser(HttpContext, cancellationToken);

            if (user == null)
            {
                return(Unauthorized());
            }

            var commsResponse = await _communicationService.RequestCommunication(null, user.ID, jobID, new CommunicationJob()
            {
                CommunicationJobType = CommunicationJobTypes.TaskDetail
            });

            if (commsResponse)
            {
                return(Ok());
            }
            else
            {
                return(new StatusCodeResult(500));
            }
        }
Exemplo n.º 9
0
        public async Task <ActionResult <SetJobStatusResult> > SetJobStatus(string j, string rq, JobStatuses s, string r, string u, CancellationToken cancellationToken)
        {
            try
            {
                var user = await _authService.GetCurrentUser(HttpContext, cancellationToken);

                UpdateJobStatusOutcome?outcome;
                bool requestFeedback = false;

                if (string.IsNullOrEmpty(j))
                {
                    int requestId = Base64Utils.Base64DecodeToInt(rq);
                    outcome = await _requestService.UpdateRequestStatusAsync(requestId, s, user.ID, cancellationToken);
                }
                else
                {
                    RequestRoles requestRole  = (RequestRoles)Base64Utils.Base64DecodeToInt(r);
                    int?         targetUserId = null;
                    if (s == JobStatuses.Accepted || s == JobStatuses.InProgress)
                    {
                        targetUserId = (requestRole == RequestRoles.Volunteer ? user.ID : Base64Utils.Base64DecodeToInt(u));
                    }

                    int jobId = Base64Utils.Base64DecodeToInt(j);
                    outcome = await _requestService.UpdateJobStatusAsync(jobId, s, user.ID, targetUserId, cancellationToken);

                    var job = await _requestService.GetJobSummaryAsync(jobId, cancellationToken);

                    if (job.RequestType.Equals(RequestType.Task))
                    {
                        requestFeedback = (await GetJobFeedbackStatus(jobId, user.ID, requestRole, cancellationToken)).FeedbackDue;
                    }
                }

                switch (outcome)
                {
                case UpdateJobStatusOutcome.AlreadyInThisStatus:
                case UpdateJobStatusOutcome.Success:
                    return(new SetJobStatusResult
                    {
                        NewStatus = s.FriendlyName(),
                        RequestFeedback = requestFeedback
                    });

                case UpdateJobStatusOutcome.BadRequest:
                    return(StatusCode(400));

                case UpdateJobStatusOutcome.Unauthorized:
                    return(StatusCode(401));

                default:
                    return(StatusCode(500));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Exception in SetRequestStatus", ex);
                return(StatusCode(500));
            }
        }
Exemplo n.º 10
0
        public async Task <IActionResult> RequestId(string encodedRequestId, CancellationToken cancellationToken)
        {
            int  requestId = Base64Utils.Base64DecodeToInt(encodedRequestId);
            User user      = await _authService.GetCurrentUser(HttpContext, cancellationToken);

            if (user == null)
            {
                throw new UnauthorizedAccessException("No user in session");
            }

            var jobLocation = await _requestService.LocateRequest(requestId, user.ID, cancellationToken);

            encodedRequestId = Base64Utils.Base64Encode(requestId);

            string destination = jobLocation?.JobSet switch
            {
                JobSet.UserOpenRequests_MatchingCriteria => $"/account/open-requests/r/{encodedRequestId}",
                JobSet.UserOpenRequests_NotMatchingCriteria => $"/account/open-requests/r/{encodedRequestId}",
                JobSet.UserMyRequests => $"/account/my-requests/r/{encodedRequestId}",
                JobSet.GroupRequests => $"/account/g/{jobLocation.GroupKey}/requests/r/{encodedRequestId}",
                JobSet.UserOpenShifts => $"/account/open-shifts/r/{encodedRequestId}",
                JobSet.UserMyShifts => $"/account/my-shifts/r/{encodedRequestId}",
                JobSet.GroupShifts => $"/account/g/{jobLocation.GroupKey}/shifts/r/{encodedRequestId}",
                _ => LINK_EXPIRED_URL,
            };

            return(Redirect(destination));
        }
Exemplo n.º 11
0
        internal static char[] GetCryptoKey(string dynamicSuffix = null)
        {
            if (generatedCryptoKey == null)
            {
                var savedKey = PlayerPrefs.GetString(PrefsKey);
                if (!string.IsNullOrEmpty(savedKey))
                {
                    generatedCryptoKey = Base64Utils.FromBase64ToChars(savedKey);
                }
                else
                {
                    generatedCryptoKey = ObscuredString.GenerateKey();
                    var b64 = Base64Utils.ToBase64(generatedCryptoKey);
                    PlayerPrefs.SetString(PrefsKey, b64);
                    PlayerPrefs.Save();
                }
            }

            if (string.IsNullOrEmpty(dynamicSuffix))
            {
                return(generatedCryptoKey);
            }

            var suffixChars = dynamicSuffix.ToCharArray();
            var result      = new char[generatedCryptoKey.Length + suffixChars.Length];

            Buffer.BlockCopy(generatedCryptoKey, 0, result, 0, generatedCryptoKey.Length);
            Buffer.BlockCopy(suffixChars, 0, result, generatedCryptoKey.Length + 1, suffixChars.Length);

            return(result);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Base64编码验证
        /// </summary>
        /// <param name="httpMessage"></param>
        /// <param name="baseRequest"></param>
        /// <param name="data"></param>
        /// <param name="signdata"></param>
        /// <returns></returns>
        private bool Base64Verify(out HttpMessage httpMessage, out BaseRequest baseRequest, string data = null, string signdata = null)
        {
            httpMessage = new HttpMessage();
            baseRequest = new BaseRequest();
            if (data == null || signdata == null)
            {
                var base64 = ReadRequestXml();
                if (string.IsNullOrEmpty(base64))
                {
                    return(false);
                }
                //httpMessage = JsonUtils.Deserialize<HttpMessage>(base64);
                httpMessage = GetHttpMessage(base64);
            }
            else
            {
                httpMessage = new HttpMessage()
                {
                    data     = data,
                    signdata = signdata
                };
            }

            if (httpMessage == null)
            {
                return(false);
            }
            httpMessage.data     = Base64Utils.DecodeBase64String(httpMessage.data);
            httpMessage.signdata = Base64Utils.DecodeBase64String(httpMessage.signdata);

            baseRequest = JsonUtils.Deserialize <BaseRequest>(httpMessage.data);
            loger.Debug(string.Format("Base64解码后的请求数据为:{0}", httpMessage.data));
            loger.Debug(string.Format("Base64解码后的较验码为:{0}", httpMessage.signdata));
            return(true);
        }
Exemplo n.º 13
0
        public string Decrypt(JweConfig config)
        {
            byte[] unwrappedKey = RsaEncryption.UnwrapSecretKey(config, Base64Utils.URLDecode(EncryptedKey), "SHA-256");
            if (unwrappedKey == null)
            {
                throw new EncryptionException(String.Format("Failed to unwrap key {0}", EncryptedKey));
            }

            string encryptionMethod = Header.Enc;

            byte[] plaintext;
            if (A256GCM.Equals(encryptionMethod))
            {
                plaintext = AesGcm.Decrypt(unwrappedKey, this);
            }
            else if (A128CBC_HS256.Equals(encryptionMethod))
            {
                plaintext = AesCbc.Decrypt(unwrappedKey, this);
            }
            else
            {
                throw new EncryptionException(String.Format("Encryption method {0} is not supported", encryptionMethod));
            }
            return(Encoding.UTF8.GetString(plaintext));
        }
Exemplo n.º 14
0
        internal static string EncryptKey(string key)
        {
            var keyChars = ObscuredString.Encrypt(key.ToCharArray(), GetCryptoKey());

            key = Base64Utils.ToBase64(keyChars);
            return(key);
        }
Exemplo n.º 15
0
        public async Task <ActionResult> StepOne(string referringGroup, string source, string email, CancellationToken cancellationToken)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(Redirect("/account"));
            }

            int referringGroupId = -1;

            if (!string.IsNullOrEmpty(referringGroup))
            {
                try
                {
                    referringGroupId = Base64Utils.Base64DecodeToInt(referringGroup);
                }
                catch { }
            }

            RegistrationFormVariant registrationFormVariant = await _groupService.GetRegistrationFormVariant(referringGroupId, source, cancellationToken);

            var group = await _groupService.GetGroupById(referringGroupId, CancellationToken.None);

            return(View(new RegistrationViewModel
            {
                ActiveStep = 1,
                FirebaseConfiguration = _configuration["Firebase:Configuration"],
                RegistrationFormVariant = registrationFormVariant,
                ReferringGroupID = referringGroupId,
                Source = source,
                GroupName = group.GroupName,
                Email = email
            }));
        }
Exemplo n.º 16
0
        public DataRecordCollection GetFileContents(bool b64encode)
        {
            DataRecordCollection result = null;
            var           csvLines      = File.ReadLines(path);
            List <String> schema        = new List <String>();

            //---Loop through each line in target file and send POST request to server---
            foreach (String line in csvLines)
            {
                if (schema.Count() == 0)//if we dont yet have the schema, assume that the first line of the SV file contains the schema header.  If it doesnt, well... that sucks
                {
                    schema = line.Split(delim).ToList();
                    continue;
                }
                string[] values = (b64encode == true) ? Base64Utils.MakeB64(line.Split(delim)):line.Split(delim);
                if (values.Length > 0)    //Ensure that we are returning data, and not the empty final line from the file
                {
                    if (result == null)
                    {
                        result = new DataRecordCollection(schema.ToArray());
                    }
                    else
                    {
                        result.AddRecord(values.ToArray());
                    }
                }
            }
            return(result);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Returns a base64-encoded HMAC-SHA1 signature of a given string.
        /// </summary>
        /// <param name="key">The key used for the signature, base64 encoded.</param>
        /// <param name="payload">The payload to sign.</param>
        /// <returns>Result signature</returns>
        public string SignHMAC(string key, string payload)
        {
            var decodedKey = Base64Utils.UrlSafeBase64Decode(key);
            var hmac       = new HMACSHA1(Encoding.ASCII.GetBytes(decodedKey));
            var hash       = hmac.ComputeHash(Encoding.ASCII.GetBytes(payload));

            return(Base64Utils.UrlSafeBase64Encode(hash));
        }
Exemplo n.º 18
0
 public void FromBase64Test()
 {
     foreach (var item in _testFrom64)
     {
         var result = Base64Utils.FromBase64(item.Key);
         Assert.Equal(item.Value, result);
     }
 }
Exemplo n.º 19
0
 public void TestToBase64()
 {
     Assert.AreEqual("TWFu", Base64Utils.ToBase64("Man"));
     Assert.AreEqual("dGhpcyBpcyBhIHN0cmluZyEh", Base64Utils.ToBase64("this is a string!!"));
     Assert.AreEqual("ZWU=", Base64Utils.ToBase64("ee"));
     Assert.AreEqual("ZQ==", Base64Utils.ToBase64("e"));
     Assert.AreEqual("", Base64Utils.ToBase64(""));
 }
Exemplo n.º 20
0
        public IActionResult GetAssignCredentialPopup(string u, string g, string c)
        {
            int targetUserId = Base64Utils.Base64DecodeToInt(u);
            int groupId      = Base64Utils.Base64DecodeToInt(g);
            int credentialId = Base64Utils.Base64DecodeToInt(c);

            return(ViewComponent("AssignCredentialsPopup", new { targetUserId, groupId, credentialId }));
        }
Exemplo n.º 21
0
        public void Base64Encode_TryBase64DecodeToInt_NotANumber()
        {
            string encodedString = Base64Utils.Base64Encode("Not a number");

            int?result = Base64Utils.TryBase64DecodeToInt(encodedString);

            Assert.AreEqual(null, result);
        }
        private string GetBlobPathWithAuthorization(SearchResult <IndexedContent> expected)
        {
            var expectedFileName = Base64Utils.Decode(expected.Document.Id);
            var sas      = blobClient.GetSAS(expectedFileName);
            var blobPath = expected.Document.BlobPath + sas;

            return(blobPath);
        }
Exemplo n.º 23
0
 public void TestFromBase64()
 {
     Assert.AreEqual("A", Base64Utils.FromBase64("QQ=="));
     Assert.AreEqual("Man", Base64Utils.FromBase64("TWFu"));
     Assert.AreEqual("this is a string!!", Base64Utils.FromBase64("dGhpcyBpcyBhIHN0cmluZyEh"));
     Assert.AreEqual("ee", Base64Utils.FromBase64("ZWU="));
     Assert.AreEqual("e", Base64Utils.FromBase64("ZQ=="));
     Assert.AreEqual("", Base64Utils.FromBase64(""));
 }
Exemplo n.º 24
0
        private async void GetUserId()
        {
            var oauthSerivce = GDriveManager.OAuthService;

            _userInfo = await oauthSerivce.Userinfo.Get().ExecuteAsync();

            userNameLabel.Text = "Logged in with email: " + _userInfo.Email;
            _userId            = Base64Utils.EncodeBase64(_userInfo.Email);
        }
Exemplo n.º 25
0
        public async Task <IActionResult> GetLeaveGroupPopup(string g, CancellationToken cancellationToken)
        {
            int groupId = Base64Utils.Base64DecodeToInt(g);
            var group   = await _groupService.GetGroupById(groupId, cancellationToken);

            var community = _communityRepository.GetCommunityDetailByKey(group.GroupKey);

            return(PartialView("_LeaveGroupPopup", community));
        }
Exemplo n.º 26
0
        public IActionResult GetWhatIsThisCredentialPopup(string g, string c, string i)
        {
            int groupId      = Base64Utils.Base64DecodeToInt(g);
            int?credentialId = c != null?Base64Utils.Base64DecodeToInt(c) : (int?)null;

            string item = i;

            return(ViewComponent("WhatIsThisCredentialPopup", new { groupId, credentialId, item }));
        }
Exemplo n.º 27
0
        public void ToBase64Test()
        {
            var q = Base64Utils.ToBase64("e");

            foreach (var item in _testFrom64)
            {
                var result = Base64Utils.ToBase64(item.Value);
                Assert.Equal(item.Key, result);
            }
        }
        private string GetJobUrl(int jobId, int requestId, int jobCount)
        {
            string baseUrl   = _sendGridConfig.Value.BaseUrl;
            string encodedId = jobCount == 1 ? Base64Utils.Base64Encode(jobId.ToString()) : Base64Utils.Base64Encode(requestId.ToString());

            string tailUrl = jobCount == 1 ? $"/link/j/{encodedId}" : $"/link/r/{encodedId}";
            var    token   = _linkRepository.CreateLink(tailUrl, _linkConfig.Value.ExpiryDays).Result;

            return($"{baseUrl}/link/{token}");
        }
Exemplo n.º 29
0
 private void AddHighlightIdsToViewModel(AccountViewModel viewModel, string encodedJobId, string encodedRequestId)
 {
     if (!string.IsNullOrEmpty(encodedJobId))
     {
         viewModel.HighlightJobId = Base64Utils.Base64DecodeToInt(encodedJobId);
     }
     if (!string.IsNullOrEmpty(encodedRequestId))
     {
         viewModel.HighlightRequestId = Base64Utils.Base64DecodeToInt(encodedRequestId);
     }
 }
Exemplo n.º 30
0
 private int DecodeGroupIdOrGetDefault(string encodedGroupId)
 {
     try
     {
         return(Base64Utils.Base64DecodeToInt(encodedGroupId));
     }
     catch
     {
         return(-1);
     }
 }