public async Task <bool> CreateShortUrl(UrlInformation urlInformation)
        {
            try
            {
                var cosmosContainer = GetCosmosDbContainer();
                await cosmosContainer.CreateItemAsync(urlInformation, new PartitionKey(urlInformation.Id));

                return(true);
            }
            catch (CosmosException ex) when(ex.StatusCode == HttpStatusCode.Conflict)
            {
                return(false);
            }
        }
示例#2
0
 /// <summary>
 /// This makes sure required is configured correctly by inspecting the paths.
 /// Will emit a warning if the spec file got this wrong
 /// </summary>
 private static void EnforceRequiredOnParts(string jsonFile, UrlInformation url)
 {
     if (url.IsPartless)
     {
         return;
     }
     foreach (var part in url.Parts)
     {
         var required = url.Paths.All(p => p.Path.Contains($"{{{part.Name}}}"));
         if (part.Required != required)
         {
             ApiGenerator.Warnings.Add($"{jsonFile} has part: {part.Name} listed as {part.Required} but should be {required}");
         }
         part.Required = required;
     }
 }
        public async Task <ShortUrlResponse> CreateShortUrl(UrlToShorten urlToShorten)
        {
            if (!urlToShorten.LongUrl.Contains("https://") || !urlToShorten.LongUrl.Contains("http://"))
            {
                if (urlToShorten.LongUrl.StartsWith("www."))
                {
                    urlToShorten.LongUrl = $"{Https}{urlToShorten.LongUrl}";
                }
            }

            var validUri = Uri.IsWellFormedUriString(urlToShorten.LongUrl, UriKind.Absolute);

            if (validUri == false)
            {
                throw new ArgumentException($"The submitted value isn't a valid url: {urlToShorten}");
            }

            var shortId = CreateRandomString(ShortIdLength);

            var baseUrl = AssembleBaseUrl();

            var urlInformation = new UrlInformation
            {
                CreationDate = _clock.Now(),
                Id           = shortId,
                ShortId      = shortId,
                LogUrl       = urlToShorten.LongUrl,
                ShortUrl     = $"{baseUrl}/{shortId}"
            };

            var success = await _cosmosDbRepository.CreateShortUrl(urlInformation);

            if (success)
            {
                return new ShortUrlResponse
                       {
                           ShortUrl = urlInformation.ShortUrl
                       }
            }
            ;

            return(null);
        }
示例#4
0
 /// <summary>
 /// This makes sure required is configured correctly by inspecting the paths.
 /// Will emit a warning if the spec file got this wrong
 /// </summary>
 private static void EnforceRequiredOnParts(string jsonFile, UrlInformation url)
 {
     if (url.IsPartless)
     {
         return;
     }
     foreach (var part in url.Parts)
     {
         var required = url.Paths.All(p => p.Path.Contains($"{{{part.Name}}}"));
         if (part.Required != required)
         {
             var message = required
                                         ? "is [b green] required [/] but appears in spec as [b red] optional [/]"
                                         : "is [b green] optional [/] but marked as [b red] required [/]  ";
             // TODO submit PR to fix these, too noisy for now
             //ApiGenerator.Warnings.Add($"[grey]{jsonFile}[/] part [b white] {part.Name} [/] {message}");
         }
         part.Required = required;
     }
 }
        public void MediaServiceSaved(IMediaService sender, SaveEventArgs <IMedia> eventArgs)
        {
            foreach (IMedia media in eventArgs.SavedEntities)
            {
                string url = media.GetValue <string>("umbracoFile");
                if (string.IsNullOrEmpty(url))
                {
                    // Media item doesn't have an umbracoFileProperty
                    continue;
                }

                UrlInformation result = GetUrlInformation(url);
                if (!result.IsMedia)
                {
                    // Unable to extract media information
                    continue;
                }

                // Media is protected if it is in a protected folder
                IMedia parent      = media.Parent();
                bool   isProtected = parent != null && parent.ContentType.Alias == "protectedFolder" &&
                                     parent.HasProperty("memberGroups");

                using (Transaction transaction = ApplicationContext.Current.DatabaseContext.Database.GetTransaction())
                {
                    // Clear any previous protection
                    ApplicationContext.Current.DatabaseContext.Database.Execute(@"delete from AuthorisedMedia where MediaPathId = @0", result.MediaFolderId);
                    if (isProtected)
                    {
                        // Apply database record indicating protection
                        ApplicationContext.Current.DatabaseContext.Database.Execute(
                            @"insert into AuthorisedMedia (MediaPathId, MediaParentId) values (@0, @1)", result.MediaFolderId, parent.Id);
                    }

                    transaction.Complete();
                }
            }
        }
        private void ContextBeginRequest(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;
            string      url     = context.Request.Path;

            // Determine whether URL is a media URL
            UrlInformation urlInformation = AuthorisedMediaManager.Instance.GetUrlInformation(url);

            if (!urlInformation.IsMedia)
            {
                return;
            }

            bool isProtected = AuthorisedMediaManager.Instance.IsProtected(urlInformation.MediaFolderId);

            if (!isProtected)
            {
                return;
            }

            // TODO : Maintain URL
            context.Response.Redirect("/umbraco/surface/authorisedmediasurface/index?url=" + HttpUtility.UrlEncode(url));
        }
示例#7
0
        public ActionResult Index(string url)
        {
            UrlInformation result = AuthorisedMediaManager.Instance.GetUrlInformation(url);

            if (!result.IsMedia)
            {
                // Not a valid media URL - so can't be returned via this controller
                return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
            }

            int parentId = AuthorisedMediaManager.Instance.ParentId(result.MediaFolderId);

            if (parentId < 1)
            {
                // No record of a protected parent folder, so return the file
                return(GetFileStreamResult(url));
            }

            IPublishedContent parent = Umbraco.TypedMedia(parentId);

            if (parent == null)
            {
                // No parent media item, so it can't be protected
                return(GetFileStreamResult(url));
            }

            if (parent.ContentType.Alias != "protectedFolder" || !parent.HasProperty("memberGroups") || !parent.HasValue("memberGroups"))
            {
                // Not a protected folder - with a value for membergroups
                return(GetFileStreamResult(url));
            }

            FormsAuthenticationTicket authenticationTicket = new HttpContextWrapper(System.Web.HttpContext.Current).GetUmbracoAuthTicket();
            bool memberLoggedIn    = Members.IsLoggedIn();
            bool hasUserAuthTicket = authenticationTicket != null;

            if (hasUserAuthTicket && IsUserLoggedIn(authenticationTicket))
            {
                // All users can access media
                return(GetFileStreamResult(url));
            }

            if (memberLoggedIn)
            {
                MemberPublishedContent member = (MemberPublishedContent)Members.GetCurrentMember();

                if (member == null)
                {
                    // Can't get the current member - so return a 404
                    return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
                }

                string[] allowedMemberGroups = parent.GetPropertyValue <string>("memberGroups").Split(',');
                string[] memberRoles         = Roles.GetRolesForUser(member.UserName);

                foreach (string role in memberRoles)
                {
                    if (allowedMemberGroups.Contains(role))
                    {
                        // Member is in an appropriate group. allow access
                        return(GetFileStreamResult(url));
                    }
                }
            }

            // No Member logged in - so return a 404
            return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
        }
示例#8
0
        private static IEnumerable <Constructor> GenerateConstructors(
            UrlInformation url,
            bool inheritsFromPlainRequestBase,
            bool generateGeneric,
            string typeName,
            string generic
            )
        {
            var ctors = new List <Constructor>();

            var paths = url.Paths.ToList();

            if (url.IsPartless)
            {
                return(ctors);
            }

            ctors.AddRange(from path in paths
                           let baseArgs = inheritsFromPlainRequestBase ? path.RequestBaseArguments : path.TypedSubClassBaseArguments
                                          let constParams = path.ConstructorArguments
                                                            let generated = $"public {typeName}({constParams}) : base({baseArgs})"
                                                                            select new Constructor
            {
                Parameterless = string.IsNullOrEmpty(constParams),
                Generated     = generated,
                Description   = path.GetXmlDocs(Indent),
                //Body = isDocumentApi ? $" => Q(\"routing\", new Routing(() => AutoRouteDocument()));" : string.Empty
                Body = string.Empty
            });

            if (generateGeneric && !string.IsNullOrWhiteSpace(generic))
            {
                ctors.AddRange(from path in paths.Where(path => path.HasResolvableArguments)
                               let baseArgs = path.AutoResolveBaseArguments(generic)
                                              let constructorArgs = path.AutoResolveConstructorArguments
                                                                    let baseOrThis = inheritsFromPlainRequestBase
                                                ? "this"
                                                : "base"
                                                                                     let generated = $"public {typeName}({constructorArgs}) : {baseOrThis}({baseArgs})"
                                                                                                     select new Constructor
                {
                    Parameterless = string.IsNullOrEmpty(constructorArgs),
                    Generated     = generated,
                    Description   = path.GetXmlDocs(Indent, skipResolvable: true),
                    Body          = string.Empty
                });

                if (url.TryGetDocumentApiPath(out var docPath))
                {
                    var docPathBaseArgs  = docPath.DocumentPathBaseArgument(generic);
                    var docPathConstArgs = docPath.DocumentPathConstructorArgument(generic);
                    ctors.Add(new Constructor
                    {
                        Parameterless = string.IsNullOrEmpty(docPathConstArgs),
                        Generated     = $"public {typeName}({docPathConstArgs}) : this({docPathBaseArgs})",

                        AdditionalCode = $"partial void DocumentFromPath({generic} document);",
                        Description    = docPath.GetXmlDocs(Indent, skipResolvable: true, documentConstructor: true),
                        Body           = "=> DocumentFromPath(documentWithId);"
                    });
                }
            }
            var constructors = ctors.GroupBy(c => c.Generated.Split(new[] { ':' }, 2)[0]).Select(g => g.Last()).ToList();

            if (!constructors.Any(c => c.Parameterless))
            {
                constructors.Add(new Constructor
                {
                    Parameterless = true,
                    Generated     = $"protected {typeName}() : base()",
                    Description   =
                        $"///<summary>Used for serialization purposes, making sure we have a parameterless constructor</summary>{Indent}[SerializationConstructor]",
                });
            }
            return(constructors);
        }
示例#9
0
        public static IEnumerable <Constructor> RequestConstructors(CsharpNames names, UrlInformation url, bool inheritsFromPlainRequestBase)
        {
            var generic         = FirstGeneric(names.GenericsDeclaredOnRequest);
            var generateGeneric = CodeConfiguration.GenericOnlyInterfaces.Contains(names.RequestInterfaceName) || !inheritsFromPlainRequestBase;

            return(GenerateConstructors(url, inheritsFromPlainRequestBase, generateGeneric, names.RequestName, generic));
        }
示例#10
0
        public static IEnumerable <Constructor> DescriptorConstructors(CsharpNames names, UrlInformation url)
        {
            var m               = names.DescriptorName;
            var generic         = FirstGeneric(names.GenericsDeclaredOnDescriptor);
            var generateGeneric = !string.IsNullOrEmpty(generic);

            return(GenerateConstructors(url, true, generateGeneric, m, generic));
        }