Beispiel #1
0
        public async Task <bool> Delete(string hashId)
        {
            var ids     = new Hashids(minHashLength: 5);
            var storyId = ids.Decode(hashId).First();

            if (storyId == 0)
            {
                return(false);
            }

            var story = await StoriesDbContext.Stories.Include(s => s.Comments)
                        .Where(s => s.Id == storyId)
                        .FirstOrDefaultAsync();

            if (story == null)
            {
                return(false);
            }

            foreach (var comment in story.Comments)
            {
                StoriesDbContext.Votes.RemoveRange(comment.Votes);
            }

            StoriesDbContext.Comments.RemoveRange(story.Comments);
            StoriesDbContext.Stories.Remove(story);

            return(await StoriesDbContext.SaveChangesAsync() > 0);
        }
Beispiel #2
0
        public async Task <StorySummaryViewModel> Create(CreateViewModel model, string username, Guid userId)
        {
            UriBuilder uri = null;

            if (!string.IsNullOrEmpty(model.Url))
            {
                uri        = new UriBuilder(model.Url);
                uri.Scheme = "https";
                uri.Port   = uri.Port == 80 || uri.Port == 443 ? -1 : uri.Port;
            }

            var story = await StoriesDbContext.Stories.AddAsync(new Story()
            {
                Title = model.Title,
                DescriptionMarkdown = model.DescriptionMarkdown,
                Description         = CommonMarkConverter.Convert(model.DescriptionMarkdown),
                Url          = uri?.Uri.ToString(),
                UserId       = userId,
                UserIsAuthor = model.IsAuthor,
            });

            var rowCount = await StoriesDbContext.SaveChangesAsync();

            var hashIds = new Hashids(minHashLength: 5);

            VoteQueueService.QueueStoryVote(story.Entity.Id);

            return(MapToStorySummaryViewModel(story.Entity, hashIds.Encode(story.Entity.Id), userId, false));
        }
Beispiel #3
0
        private async Task <StoriesViewModel> GetAll(Expression <Func <Story, double> > sort, int page, int pageSize, Guid?userId)
        {
            var model = new StoriesViewModel()
            {
                CurrentPage = page, PageSize = pageSize
            };

            var stories = await StoriesDbContext.Stories.Include(s => s.User)
                          .Include(s => s.Comments)
                          .Include(s => s.Score)
                          .OrderByDescending(s => s.Score != null)
                          .ThenBy(sort)
                          .ThenByDescending(s => s.CreatedDate)
                          .Skip(page * pageSize)
                          .Take(pageSize)
                          .ToListAsync();

            List <int> upvotedStoryIds = new List <int>();

            if (userId != null)
            {
                upvotedStoryIds = await StoriesDbContext.Votes.Where(v => stories.Any(s => s.Id == v.StoryId) && v.UserId == userId).Select(v => v.StoryId.Value).ToListAsync();
            }

            foreach (var story in stories)
            {
                var userUpvoted = upvotedStoryIds.Any(id => id == story.Id);
                var hashId      = new Hashids(minHashLength: 5).Encode(story.Id);

                model.Stories.Add(MapToStorySummaryViewModel(story, hashId, userId, userUpvoted));
            }

            return(model);
        }
Beispiel #4
0
        public static int Decode(string encoded)
        {
            var hashids = new Hashids(salt);
            var link    = hashids.Decode(encoded);

            return(link[0]);
        }
Beispiel #5
0
        public string GetCode()
        {
            var hashids   = new Hashids(_salt, 6);
            int timestamp = Math.Abs((int)(Int64)(DateTime.UtcNow.Subtract(DateTime.UnixEpoch)).TotalMilliseconds);

            return(hashids.Encode(timestamp));
        }
Beispiel #6
0
        public async Task <StoryViewModel> Get(string hashId, Guid?userId)
        {
            var ids     = new Hashids(minHashLength: 5);
            var storyId = ids.Decode(hashId).First();

            var story = await StoriesDbContext.Stories.Include(s => s.User)
                        .Include(s => s.Comments)
                        .SingleOrDefaultAsync(s => s.Id == storyId);

            if (story == null)
            {
                return(null);
            }

            var userUpvoted = userId != null && await StoriesDbContext.Votes.AnyAsync(v => story.Id == v.StoryId && v.UserId == userId);

            var model = new StoryViewModel
            {
                Summary = MapToStorySummaryViewModel(story, hashId, userId, userUpvoted)
            };

            var upvotedComments = await StoriesDbContext.Votes.Where(v => v.CommentId != null && v.UserId == userId)
                                  .Select(v => (int)v.CommentId)
                                  .ToListAsync();

            foreach (var comment in story.Comments.OrderByDescending(c => c.Score?.Value).Where(c => c.ParentCommentId == null))
            {
                model.Comments.Add(MapCommentToCommentViewModel(comment, upvotedComments));
            }

            return(model);
        }
Beispiel #7
0
 void alphabet_shorter_than_minimum_should_throw_exception()
 {
     Assert.Throws <ArgumentException>(() =>
     {
         var hashids = new Hashids("janottaa", 6, new string(GenerateAlphabet(Hashids.MIN_ALPHABET_LENGTH - 1).ToArray()));
     });
 }
        private void It_does_not_decode_with_a_different_salt()
        {
            var peppers = new Hashids("this is my pepper");

            _hashids.Decode("NkK9").ShouldBe(new[] { 12345 });
            peppers.Decode("NkK9").ShouldBe(new int[0]);
        }
Beispiel #9
0
        public static string OrganizationId(this IAssetService service, int organizationId)
        {
            _hashids = _hashids ?? new Hashids(service.Salt);
            var enc = service.EncodeString($"org:{organizationId}");

            return($"organization/{enc}");
        }
        private void Issue_18_it_should_return_empty_string_if_negative_numbers()
        {
            var hashids = new Hashids("this is my salt");

            hashids.Encode(1, 4, 5, -3).ShouldBe(string.Empty);
            hashids.EncodeLong(4, 5, 2, -4).ShouldBe(string.Empty);
        }
        static HashingHelper()
        {
            var config = ConfigurationHelper.Configuration;

            HashGenerator = new Hashids(config.HashSalt, 6, config.HashAlphabet);
            AccountLegalEntityHashGenerator = new Hashids(config.AccountLegalEntityHashSalt, 6, config.AccountLegalEntityHashAlphabet);
        }
Beispiel #12
0
        public static string Create(string prefix     = null, int length        = 16,
                                    bool useLowerCase = true, bool useUpperCase = true, bool useDigits = true)
        {
            var alphabet = string.Empty;

            if (useLowerCase)
            {
                alphabet = string.Concat(alphabet, _lowerCaseCharacters);
            }
            if (useUpperCase)
            {
                alphabet = string.Concat(alphabet, _upperCaseCharacters);
            }
            if (useDigits)
            {
                alphabet = string.Concat(alphabet, _digits);
            }

            var salt = Guid.NewGuid().ToString();

            var hashids = new Hashids(salt, length, alphabet: alphabet);

            var numbers = Enumerable.Range(0, 3).Select(r => _random.Next(100)).ToList();

            var hash = hashids.Encode(numbers);

            if (string.IsNullOrWhiteSpace(prefix) == false)
            {
                hash = string.Concat(prefix, hash);
            }

            return(hash);
        }
        public static string Generate(string name, string salt)
        {
            var ids             = name.Select(cha => Convert.ToInt32(cha)).ToArray();
            var hashIdGenerator = new Hashids(salt);

            return(hashIdGenerator.Encode(ids));
        }
        public string DecodeLink(string link)
        {
            var decoder     = new Hashids(link);
            var decodedLink = _context.Links.Find(link);

            return(decodedLink.FullLink);
        }
Beispiel #15
0
        void issue_18_it_should_return_empty_string_if_negative_numbers()
        {
            var hashids = new Hashids("this is my salt");

            hashids.Encode(1, 4, 5, -3).Should().Be(string.Empty);
            hashids.Encode(4, 5, 2, (long)-4).Should().Be(string.Empty);
        }
Beispiel #16
0
        public string Hash(int number)
        {
            var    hashids = new Hashids("salt");
            string hash    = hashids.Encode(number);

            return(hash);
        }
Beispiel #17
0
 public void AlphabetAtLeastMinLength_ShouldNotThrowException()
 {
     var minLengthAlphabet    = Hashids.DEFAULT_ALPHABET.Substring(0, Hashids.MIN_ALPHABET_LENGTH);
     var largerLengthAlphabet = Hashids.DEFAULT_ALPHABET.Substring(0, Hashids.MIN_ALPHABET_LENGTH + 1);
     var results1             = new Hashids(alphabet: minLengthAlphabet);
     var results2             = new Hashids(alphabet: largerLengthAlphabet);
 }
Beispiel #18
0
        public static string Decode(string encodedText)
        {
            var hashIds = new Hashids("LotusInn");
            var intArr  = hashIds.Decode(encodedText);

            return(Encoding.UTF8.GetString(intArr.Select(i => (byte)i).ToArray()));
        }
Beispiel #19
0
        public static string Encode(string text)
        {
            var bytes   = Encoding.UTF8.GetBytes(text);
            var hashIds = new Hashids("LotusInn");

            return(hashIds.Encode(bytes.Select(b => (int)b)));
        }
        public ValidationResult Validate(DeleteCommentModel instance)
        {
            var result = new ValidationResult {
                IsValid = false
            };

            var hashIds = new Hashids(minHashLength: 5);

            var commentId = hashIds.Decode(instance.HashId).FirstOrDefault();

            if (commentId == 0)
            {
                result.Messages.Add("Invalid comment id.");
                return(result);
            }

            var comment = DbContext.Comments.FirstOrDefault(c => c.Id == commentId);

            if (comment == null)
            {
                result.Messages.Add("Invalid comment id.");
                return(result);
            }

            if (comment.UserId != instance.UserId)
            {
                result.Messages.Add("You are not the owner of this comment.");
                return(result);
            }

            result.IsValid = true;
            return(result);
        }
        public static string Decode(string salt, string code)
        {
            var hashids = new Hashids(salt, 4, Alphabet);
            var decode  = hashids.DecodeLong(code);

            return(decode.Length > 0 ? decode[0].ToString() : null);
        }
Beispiel #22
0
        private async Task <bool> UpdateUrl(URL url)
        {
            if (!ModelState.IsValid)
            {
                return(false);
            }

            try
            {
                var hashids = new Hashids($"{url.FullUrl}");
                var id      = hashids.Encode(1, 2, 3, 4, 5);
                url.ShortUrl = "https://voronintask.ru/go?id=" + id;
                dataContext.Update(url);
                await dataContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (dataContext.Urls.Any(e => e.ID == url.ID))
                {
                    return(false);
                }
            }

            return(true);
        }
        public async Task <IActionResult> Post(BookingModel model)
        {
            using (var context = new AppContext())
            {
                try
                {
                    model.Timestamp = DateTime.UtcNow;

                    var salt = model.Timestamp.ToString("o") + model.Timestamp.Millisecond + model.DateTimeOfBooking.ToString("o") + ":" + model.UserId + model.OrganizationId;

                    var hashids = new Hashids(salt, 6);
                    var id      = hashids.Encode(1, 2, 3);

                    model.Id = id;


                    var bookings = await context.Bookings.AddAsync(model);

                    await context.SaveChangesAsync();

                    return(Ok(model));
                }
                catch (Exception ex)
                {
                    return(BadRequest(JsonConvert.SerializeObject(new { error = ex.Message })));
                }
            }
        }
        public async Task <IActionResult> Find(string name, string bookingcode)
        {
            if (name != null && bookingcode != null)
            {
                var booking = await _context.Bookings
                              .SingleOrDefaultAsync(m => m.CustomerName == name && m.ReservationCode == bookingcode);

                if (booking == null)
                {
                    ViewData["msg"] = "Fant ikke reserverasjon";
                    return(View());
                }

                var hashids = new Hashids($"{name}saltAp!2131");
                var id      = hashids.Encode(name.Length, booking.BookingId);

                if (id == bookingcode)
                {
                    return(RedirectToAction("Edit", new { id = booking.BookingId }));
                }
            }

            ViewData["msg"] = "Fant ikke reserverasjon";
            return(View());
        }
        void it_does_not_decode_with_a_different_salt()
        {
            var peppers = new Hashids("this is my pepper");

            hashids.Decode("NkK9").Should().Equal(new [] { 12345 });
            peppers.Decode("NkK9").Should().Equal(new int [0]);
        }
Beispiel #26
0
        public async Task <IActionResult> Post(OrganizationModel model)
        {
            using (var context = new AppContext())
            {
                try
                {
                    var timeNow = DateTime.UtcNow;

                    var salt = model.Name + ":" + timeNow.ToString("o") + model.Latitude + model.Longitude + model.ZipCode;

                    var hashids = new Hashids(salt, 6);
                    var id      = hashids.Encode(1, 2, 3);

                    model.Id          = id;
                    model.CreatedTime = timeNow;

                    var bookings = await context.Organizations.AddAsync(model);

                    await context.SaveChangesAsync();

                    return(Ok(model));
                }
                catch (Exception ex)
                {
                    return(BadRequest(JsonConvert.SerializeObject(new { error = ex.Message })));
                }
            }
        }
        public IActionResult CreateGradeSet()
        {
            var newGradeSet = new GradeSet
            {
            };

            _ctx.GradeSets.Add(newGradeSet);
            _ctx.SaveChanges();

            var grade1 = new Grade
            {
                Subject    = "science",
                Unit       = 1m,
                Score      = 1.5m,
                GradeSetId = newGradeSet.Id
            };

            _ctx.Grades.Add(grade1);
            _ctx.SaveChanges();

            var hashid = new Hashids("gwa-calc-server");
            var id     = hashid.Encode(newGradeSet.Id, 8, 2, 1988);

            return(new ObjectResult(id));
        }
Beispiel #28
0
        private void button2_Click_1(object sender, EventArgs e)
        {
            using (MySqlConnection cn = new MySqlConnection(_myconnectionstring))
            {
                string idClear = textBox1.Text;
                int    intId;
                string sql = null;
                int    idHashKonvertert;

                if (textBox1.Text == string.Empty)
                {
                    MessageBox.Show(@"Du må taste inn noe!");
                    return;
                }


                if (int.TryParse(idClear, out intId))
                {
                    sql = "DELETE FROM booking WHERE bookingId=" + intId;
                }

                else
                {
                    var   hashids = new Hashids("Tralalalalala, dette er min SALT");
                    int[] idHash  = hashids.Decode(idClear);
                    try
                    {
                        idHashKonvertert = idHash[0];
                    }
                    catch (Exception exception)
                    {
                        idHashKonvertert = 9999999;
                    }
                    sql = "DELETE FROM booking WHERE bookingId=" + idHashKonvertert;
                }


                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection  = cn;
                cmd.CommandText = sql;
                cn.Open();
                int numRowsUpdated = cmd.ExecuteNonQuery();
                cmd.Dispose();

                if (numRowsUpdated == 1)
                {
                    MessageBox.Show("Booking med id/ref: " + idClear +
                                    " ble slettet. Applikasjonen vil nå laste på nytt");
                    Hide();
                    HotelBookForm hotelBookForm = new HotelBookForm();
                    hotelBookForm.Closed += (s, args) => Close();
                    hotelBookForm.Show();
                }
                else
                {
                    MessageBox.Show("Fant ingen booking med inntastet id eller ref nummer");
                }
            }
        }
Beispiel #29
0
        public void GuardCharacterOnly_DecodesToEmptyArray()
        {
            // no salt creates guard characters: "abde"
            var hashids      = new Hashids("");
            var decodedValue = hashids.Decode("a");

            decodedValue.Should().Equal(Array.Empty <int>());
        }
Beispiel #30
0
        public void CustomAlphabet2_Roundtrip()
        {
            var hashids = new Hashids(salt, 0, "ABCDEFGHIJKMNOPQRSTUVWXYZ23456789");
            var input   = new[] { 1, 2, 3, 4, 5 };

            hashids.Encode(input).Should().Be("44HYIRU3TO");
            hashids.Decode(hashids.Encode(input)).Should().BeEquivalentTo(input);
        }
Beispiel #31
0
        void issue_14_it_should_decode_encode_hex_correctly()
        {
            var hashids = new Hashids("this is my salt");
            var encoded = hashids.EncodeHex("DEADBEEF");
            encoded.Should().Be("kRNrpKlJ");

            var decoded = hashids.DecodeHex(encoded);
            decoded.Should().Be("DEADBEEF");

            var encoded2 = hashids.EncodeHex("1234567890ABCDEF");
            var decoded2 = hashids.DecodeHex(encoded2);
            decoded2.Should().Be("1234567890ABCDEF");
        }
Beispiel #32
0
        void issue_12_should_not_throw_out_of_range_exception()
        {
            var hash = new Hashids("zXZVFf2N38uV");
            var longs = new List<long>();
            var rand = new Random();
            var valueBuffer = new byte[8];
            var randLong = 0L;
            for (var i = 0; i < 100000; i++)
            {
                rand.NextBytes(valueBuffer);
                randLong = BitConverter.ToInt64(valueBuffer, 0);
                longs.Add(Math.Abs(randLong));
            }

            var encoded = hash.EncodeLong(longs);
            var decoded = hash.DecodeLong(encoded);
            decoded.Should().Equal(longs.ToArray());
        }
Beispiel #33
0
 void it_can_encode_with_a_custom_alphabet()
 {
     var h = new Hashids(salt, 0, "ABCDEFGhijklmn34567890-:");
     h.Encode(1, 2, 3, 4, 5).Should().Be("6nhmFDikA0");
 }
Beispiel #34
0
		public virtual void SetUp() {
			salt = "this is my salt";
			alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
			hashids = new Hashids(salt: salt, alphabet: alphabet);
		}
Beispiel #35
0
        void it_can_encodes_to_a_minimum_length()
        {
            var h = new Hashids(salt, 18);
            h.Encode(1).Should().Be("aJEDngB0NV05ev1WwP");

            h.Encode(4140, 21147, 115975, 678570, 4213597, 27644437).
                Should().Be("pLMlCWnJSXr1BSpKgqUwbJ7oimr7l6");
        }
Beispiel #36
0
 void it_can_decode_from_a_hash_with_a_minimum_length()
 {
     var h = new Hashids(salt, 8);
     h.Decode("gB0NV05e").Should().Equal(new [] {1});
     h.Decode("mxi8XH87").Should().Equal(new[] { 25, 100, 950 });
     h.Decode("KQcmkIW8hX").Should().Equal(new[] { 5, 200, 195, 1 });
 }
		void it_can_decrypt_from_a_hash_with_a_minimum_length()
		{
			var h = new Hashids(salt, 8);
			h.Decrypt("b9iLXiAa").Should().Equal(new [] {1});
		}
		void it_does_not_decrypt_with_a_different_salt()
		{
			var peppers = new Hashids("this is my pepper");
			hashids.Decrypt("ryBo").Should().Equal(new []{ 12345 });
			peppers.Decrypt("ryBo").Should().Equal(new int [0]);
		}
		void it_can_encrypt_with_a_swapped_custom()
		{
			var hashids = new Hashids("this is my salt", 0, "abcd");
			hashids.Encrypt(1, 2, 3, 4, 5).Should().Be("adcdacddcdaacdad");
		}
		public Hashids_test()
		{
			hashids = new Hashids(salt);
		}
		void it_can_encrypt_to_a_minimum_length()
		{
			var h = new Hashids(salt, 8);
			h.Encrypt(1).Should().Be("b9iLXiAa");
		}
Beispiel #42
0
 void issue_8_should_not_throw_out_of_range_exception()
 {
     var hashids = new Hashids("janottaa", 6);
     var numbers = hashids.Decode("NgAzADEANAA=");
 }
Beispiel #43
0
		public virtual void Dispose() {
			hashids = null;
		}