public Task <string> GetTokenAsync(HttpContext context, bool createIfNotExists)
        {
            string current = context.Request.Cookies[_cookieName];

            if (current == null && createIfNotExists)
            {
                return(GenerateAndSetCookie());
            }
            return(Task.FromResult(current));

            async Task <string> GenerateAndSetCookie()
            {
                long next;

                using (CancellationTokenSource source = new CancellationTokenSource(TimeSpan.FromSeconds(1.5)))
                {
                    Sequence actual = await _authorizedUsersSequence.GetNextSequenceValue(source.Token).ConfigureAwait(false);

                    next = actual.Value;
                }
                string value = _converter.GenerateKey(next);

                context.Response.Cookies.Append(_cookieName, value);
                return(value);
            }
        }
Ejemplo n.º 2
0
        public Task <string> Compress(string url)
        {
            if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                Response.StatusCode = 400;                                // bad request
                return(Task.FromResult("Error: url should be absolute")); // don't allocate an async state machine if user provided invalid input
            }
            return(CompressInternal());

            async Task <string> CompressInternal()
            {
                string userKey = await _authTokenProvider.GetTokenAsync(HttpContext, createIfNotExists : true).ConfigureAwait(false);

                long     newlyGeneratedLinkId;
                Sequence seq = await _sequenceProvider.GetSequenceAsync("linksSequence_" + userKey).ConfigureAwait(false);

                using (CancellationTokenSource source = new CancellationTokenSource(_defaultTimeout))
                {
                    seq = await seq.GetNextSequenceValue(source.Token).ConfigureAwait(false);

                    newlyGeneratedLinkId = seq.Value;
                }
                string             key    = String.Concat(userKey, "~", _converter.GenerateKey(newlyGeneratedLinkId));
                long               userId = _converter.RegenerateId(userKey);
                ShortenedLinkModel model  = new ShortenedLinkModel {
                    Id = new ShortenedLinkModelId {
                        LinkId = newlyGeneratedLinkId, UserId = userId
                    }, Key = key, Value = url
                };

                using (CancellationTokenSource source = new CancellationTokenSource(_defaultTimeout))
                    await _links.InsertOneAsync(model, _insertOptions, source.Token).ConfigureAwait(false);

                return(model.Key);
            }
        }