├── .gitattributes ├── demo-apps ├── SampleApp │ ├── SampleApp │ │ ├── Models.fs │ │ ├── SampleApp.fsproj │ │ ├── HtmlViews.fs │ │ └── Program.fs │ └── SampleApp.Tests │ │ ├── SampleApp.Tests.fsproj │ │ └── Tests.fs ├── MinimalApp │ ├── Program.fs │ └── MinimalApp.fsproj ├── JwtApp │ └── JwtApp │ │ ├── JwtApp.fsproj │ │ └── Program.fs ├── GoogleAuthApp │ └── GoogleAuthApp │ │ ├── GoogleAuthApp.fsproj │ │ ├── HttpsConfig.fs │ │ └── Program.fs └── IdentityApp │ └── IdentityApp │ ├── IdentityApp.fsproj │ └── Program.fs ├── NuGet.config ├── appveyor.yml ├── .psscripts ├── install-dotnet.ps1 ├── nuget-updates.ps1 └── build-functions.ps1 ├── README.md ├── .gitignore └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto 2 | *.sh text eol=lf -------------------------------------------------------------------------------- /demo-apps/SampleApp/SampleApp/Models.fs: -------------------------------------------------------------------------------- 1 | namespace SampleApp.Models 2 | 3 | [] 4 | type Person = 5 | { 6 | Name : string 7 | } -------------------------------------------------------------------------------- /NuGet.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 0.1.0-{build} 2 | image: 3 | - Visual Studio 2019 4 | - Ubuntu 5 | environment: 6 | DOTNET_CLI_TELEMETRY_OPTOUT: 1 7 | init: 8 | - git config --global core.autocrlf true 9 | install: 10 | - ps: .\.psscripts\install-dotnet.ps1 -SdkVersions "7.0.307" 11 | build: off 12 | build_script: 13 | - ps: .\build.ps1 14 | test: off 15 | nuget: 16 | account_feed: false 17 | project_feed: false -------------------------------------------------------------------------------- /demo-apps/MinimalApp/Program.fs: -------------------------------------------------------------------------------- 1 | open Microsoft.AspNetCore.Builder 2 | open Microsoft.Extensions.Hosting 3 | open Giraffe 4 | 5 | let builder = WebApplication.CreateBuilder() 6 | builder.Services.AddGiraffe() |> ignore 7 | let app = builder.Build() 8 | let webApp = 9 | choose [ 10 | route "/ping" >=> text "pong" 11 | route "/" >=> text "Hello World" ] 12 | 13 | app.UseGiraffe(webApp) 14 | app.Run() -------------------------------------------------------------------------------- /demo-apps/MinimalApp/MinimalApp.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net7.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /demo-apps/SampleApp/SampleApp/SampleApp.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7 5 | false 6 | $(MSBuildThisFileDirectory) 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /demo-apps/JwtApp/JwtApp/JwtApp.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7 5 | false 6 | $(MSBuildThisFileDirectory) 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /demo-apps/GoogleAuthApp/GoogleAuthApp/GoogleAuthApp.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7 5 | portable 6 | false 7 | $(MSBuildThisFileDirectory) 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /demo-apps/SampleApp/SampleApp/HtmlViews.fs: -------------------------------------------------------------------------------- 1 | module SampleApp.HtmlViews 2 | 3 | open Giraffe.GiraffeViewEngine 4 | open SampleApp.Models 5 | 6 | let layout (content: XmlNode list) = 7 | html [] [ 8 | head [] [ 9 | title [] [ str "Giraffe" ] 10 | ] 11 | body [] content 12 | ] 13 | 14 | let partial () = 15 | p [] [ str "Some partial text." ] 16 | 17 | let personView (model : Person) = 18 | [ 19 | div [ _class "container" ] [ 20 | h3 [_title "Some title attribute"] [ sprintf "Hello, %s" model.Name |> str ] 21 | a [ _href "https://github.com/giraffe-fsharp/Giraffe" ] [ str "Github" ] 22 | ] 23 | div [] [ partial() ] 24 | ] |> layout -------------------------------------------------------------------------------- /demo-apps/IdentityApp/IdentityApp/IdentityApp.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7 5 | portable 6 | false 7 | $(MSBuildThisFileDirectory) 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /.psscripts/install-dotnet.ps1: -------------------------------------------------------------------------------- 1 | # ---------------------------------------------- 2 | # Install .NET Core SDK 3 | # ---------------------------------------------- 4 | 5 | param 6 | ( 7 | [string] $SdkVersions 8 | ) 9 | 10 | $ErrorActionPreference = "Stop" 11 | 12 | Import-module "$PSScriptRoot\build-functions.ps1" -Force 13 | 14 | # Get desired SDKs from argument 15 | $desiredSDKs = $SdkVersions.Split(",") | % { $_.Trim() } 16 | 17 | foreach($desiredSDK in $desiredSDKs) 18 | { 19 | Write-Host "Attempting to download and install the .NET SDK $desiredSDK..." 20 | $sdkZipPath = Get-NetCoreSdkFromWeb $desiredSDK 21 | Install-NetCoreSdkFromArchive $sdkZipPath 22 | } 23 | 24 | Write-Host ".NET SDK installations complete." -ForegroundColor Green 25 | dotnet-info 26 | dotnet-version -------------------------------------------------------------------------------- /demo-apps/SampleApp/SampleApp.Tests/SampleApp.Tests.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7 5 | SampleApp.Tests 6 | portable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Giraffe Samples 2 | 3 | ![Giraffe](https://raw.githubusercontent.com/giraffe-fsharp/Giraffe/develop/giraffe.png) 4 | 5 | ### Windows and Linux Builds 6 | 7 | [![Build status](https://ci.appveyor.com/api/projects/status/nqlrptmw8pr9cj46/branch/master?svg=true)](https://ci.appveyor.com/project/dustinmoris/samples/branch/master) 8 | 9 | [![Windows Build history](https://buildstats.info/appveyor/chart/dustinmoris/samples?branch=master&includeBuildsFromPullRequest=false)](https://ci.appveyor.com/project/dustinmoris/samples/history?branch=master) 10 | 11 | This repository contains a few sample applications built with Giraffe: 12 | 13 | | Sample | Description | 14 | | ------ | ----------- | 15 | | [GoogleAuthApp](https://github.com/giraffe-fsharp/samples/tree/master/demo-apps/GoogleAuthApp) | Demonstrates how Google Auth can be used with Giraffe. | 16 | | [IdentityApp](https://github.com/giraffe-fsharp/samples/tree/master/demo-apps/IdentityApp) | Demonstrates how ASP.NET Core Identity can be used with Giraffe. | 17 | | [JwtApp](https://github.com/giraffe-fsharp/samples/tree/master/demo-apps/JwtApp) | Demonstrates how JWT tokens can be used with Giraffe. | 18 | | [SampleApp](https://github.com/giraffe-fsharp/samples/tree/master/demo-apps/SampleApp) | Generic sample application showcasing multiple features such as file uploads, cookie auth, model binding and validation, etc. | 19 | 20 | ## License 21 | 22 | [Apache 2.0](https://raw.githubusercontent.com/giraffe-fsharp/samples/master/LICENSE) 23 | 24 | ## Support 25 | 26 | If you've got value from any of the content which I have created, but pull requests are not your thing, then I would also very much appreciate your support by buying me a coffee. Thank you! 27 | 28 | Buy Me A Coffee -------------------------------------------------------------------------------- /.psscripts/nuget-updates.ps1: -------------------------------------------------------------------------------- 1 | # ---------------------------------------------- 2 | # Helper script to find NuGet package upgrades 3 | # ---------------------------------------------- 4 | 5 | function Get-NuGetPackageInfo ($nugetPackageId, $currentVersion) 6 | { 7 | $url = "https://api-v2v3search-0.nuget.org/query?q=$nugetPackageId&prerelease=false" 8 | $result = Invoke-RestMethod -Uri $url -Method Get 9 | $packageInfo = $result.data | Where-Object { $_.id -eq $nugetPackageId } 10 | $latestVersion = $packageInfo.version 11 | $upgradeAvailable = 12 | $currentVersion ` 13 | -and $latestVersion ` 14 | -and !$latestVersion.StartsWith($currentVersion.Replace("*", "")) 15 | 16 | [PSCustomObject]@{ 17 | PackageName = $nugetPackageId; 18 | Current = $currentVersion; 19 | Latest = $latestVersion; 20 | UpgradeAvailable = $upgradeAvailable 21 | } 22 | } 23 | 24 | filter Highlight-Upgrades 25 | { 26 | $lines = $_.Split([Environment]::NewLine) 27 | foreach ($line in $lines) { 28 | if ($line.Trim().EndsWith("True")) { 29 | Write-Host $line -ForegroundColor DarkGreen 30 | } else { 31 | Write-Host $line -ForegroundColor Gray 32 | } 33 | } 34 | } 35 | 36 | Write-Host "" 37 | Write-Host "" 38 | Write-Host "--------------------------------------------------" -ForegroundColor DarkYellow 39 | Write-Host " Scanning all projects for NuGet package upgrades " -ForegroundColor DarkYellow 40 | Write-Host "--------------------------------------------------" -ForegroundColor DarkYellow 41 | Write-Host "" 42 | 43 | $projects = Get-ChildItem "$PSScriptRoot\..\**\*.*proj" -Recurse | % { $_.FullName } 44 | 45 | foreach ($project in $projects) 46 | { 47 | $projName = Split-Path $project -Leaf 48 | Write-Host $projName -ForegroundColor Magenta 49 | 50 | [xml]$proj = Get-Content $project 51 | $references = $proj.Project.ItemGroup.PackageReference | Where-Object { $_.Include -ne $null } 52 | $packages = @() 53 | 54 | foreach ($reference in $references) 55 | { 56 | $id = $reference.Include 57 | $version = $reference.Version 58 | $packages += Get-NuGetPackageInfo $id $version 59 | } 60 | 61 | $packages ` 62 | | Format-Table -Property PackageName, Current, Latest, UpgradeAvailable -AutoSize ` 63 | | Out-String ` 64 | | Highlight-Upgrades 65 | } -------------------------------------------------------------------------------- /demo-apps/GoogleAuthApp/GoogleAuthApp/HttpsConfig.fs: -------------------------------------------------------------------------------- 1 | module GoogleAuthApp.HttpsConfig 2 | 3 | open System 4 | open System.Net 5 | open System.Security.Cryptography.X509Certificates 6 | open Microsoft.AspNetCore.Hosting 7 | open Microsoft.AspNetCore.Server.Kestrel.Core 8 | open Microsoft.Extensions.DependencyInjection 9 | open Microsoft.Extensions.Hosting 10 | 11 | // Follow the following instructions to set up 12 | // a self signed certificate for localhost: 13 | // https://blogs.msdn.microsoft.com/webdev/2017/11/29/configuring-https-in-asp-net-core-across-different-platforms/ 14 | 15 | type EndpointScheme = 16 | | Http 17 | | Https 18 | 19 | type EndpointConfiguration = 20 | { 21 | Host : string 22 | Port : int option 23 | Scheme : EndpointScheme 24 | FilePath : string option 25 | Password : string option 26 | StoreName : string option 27 | StoreLocation : string option 28 | } 29 | static member Default = 30 | { 31 | Host = "localhost" 32 | Port = Some 8080 33 | Scheme = Http 34 | FilePath = None 35 | Password = None 36 | StoreName = None 37 | StoreLocation = None 38 | } 39 | 40 | let loadCertificateFromStore (storeName : string) 41 | (location : string) 42 | (cfg : EndpointConfiguration) 43 | (env : IWebHostEnvironment) = 44 | use store = new X509Store(storeName, Enum.Parse location) 45 | store.Open OpenFlags.ReadOnly 46 | let cert = 47 | store.Certificates.Find( 48 | X509FindType.FindBySubjectName, 49 | cfg.Host, 50 | not (env.IsDevelopment())) 51 | match cert.Count with 52 | | 0 -> raise(InvalidOperationException(sprintf "Certificate not found for %s." cfg.Host)) 53 | | _ -> cert.[0] 54 | 55 | let loadCertificate (cfg : EndpointConfiguration) (env : IWebHostEnvironment) = 56 | match cfg.StoreName, cfg.StoreLocation, cfg.FilePath, cfg.Password with 57 | | Some n, Some l, _, _ -> loadCertificateFromStore n l cfg env 58 | | _, _, Some f, Some p -> new X509Certificate2(f, p) 59 | | _, _, Some f, None -> new X509Certificate2(f) 60 | | _ -> raise (InvalidOperationException("No valid certificate configuration found for the current endpoint.")) 61 | 62 | type KestrelServerOptions with 63 | member this.ConfigureEndpoints (endpoints : EndpointConfiguration list) = 64 | let env = this.ApplicationServices.GetRequiredService() 65 | endpoints 66 | |> List.iter (fun endpoint -> 67 | let port = 68 | match endpoint.Port with 69 | | Some p -> p 70 | | None -> 71 | match endpoint.Scheme.Equals "https" with 72 | | true -> 443 73 | | false -> 80 74 | 75 | let ipAddresses = 76 | match endpoint.Host.Equals "localhost" with 77 | | true -> [ IPAddress.IPv6Loopback; IPAddress.Loopback ] 78 | | false -> 79 | match IPAddress.TryParse endpoint.Host with 80 | | true, ip -> [ ip ] 81 | | false, _ -> [ IPAddress.IPv6Any ] 82 | 83 | ipAddresses 84 | |> List.iter (fun ip -> 85 | this.Listen(ip, port, fun options -> 86 | match endpoint.Scheme with 87 | | Https -> 88 | loadCertificate endpoint env 89 | |> options.UseHttps 90 | |> ignore 91 | | Http -> () 92 | ) 93 | ) 94 | ) -------------------------------------------------------------------------------- /demo-apps/JwtApp/JwtApp/Program.fs: -------------------------------------------------------------------------------- 1 | module JwtApp.App 2 | 3 | open System 4 | open System.IO 5 | open System.Security.Claims 6 | open Microsoft.AspNetCore.Authentication 7 | open Microsoft.AspNetCore.Authentication.JwtBearer 8 | open Microsoft.AspNetCore.Builder 9 | open Microsoft.AspNetCore.Hosting 10 | open Microsoft.AspNetCore.Http 11 | open Microsoft.Extensions.Logging 12 | open Microsoft.Extensions.Hosting 13 | open Microsoft.Extensions.DependencyInjection 14 | open Microsoft.IdentityModel.Tokens 15 | open Giraffe 16 | 17 | // --------------------------------- 18 | // Web app 19 | // --------------------------------- 20 | 21 | type SimpleClaim = { Type: string; Value: string } 22 | 23 | let authorize = 24 | requiresAuthentication (challenge JwtBearerDefaults.AuthenticationScheme) 25 | 26 | let greet = 27 | fun (next : HttpFunc) (ctx : HttpContext) -> 28 | let claim = ctx.User.FindFirst "name" 29 | let name = claim.Value 30 | text ("Hello " + name) next ctx 31 | 32 | let showClaims = 33 | fun (next : HttpFunc) (ctx : HttpContext) -> 34 | let claims = ctx.User.Claims 35 | let simpleClaims = Seq.map (fun (i : Claim) -> {Type = i.Type; Value = i.Value}) claims 36 | json simpleClaims next ctx 37 | 38 | let webApp = 39 | choose [ 40 | GET >=> 41 | choose [ 42 | route "/" >=> text "Public endpoint." 43 | route "/greet" >=> authorize >=> greet 44 | route "/claims" >=> authorize >=> showClaims 45 | ] 46 | setStatusCode 404 >=> text "Not Found" ] 47 | 48 | // --------------------------------- 49 | // Error handler 50 | // --------------------------------- 51 | 52 | let errorHandler (ex : Exception) (logger : ILogger) = 53 | logger.LogError(EventId(), ex, "An unhandled exception has occurred while executing the request.") 54 | clearResponse >=> setStatusCode 500 >=> text ex.Message 55 | 56 | // --------------------------------- 57 | // Config and Main 58 | // --------------------------------- 59 | 60 | let configureApp (app : IApplicationBuilder) = 61 | app.UseAuthentication() 62 | .UseGiraffeErrorHandler(errorHandler) 63 | .UseStaticFiles() 64 | .UseGiraffe webApp 65 | 66 | let authenticationOptions (o : AuthenticationOptions) = 67 | o.DefaultAuthenticateScheme <- JwtBearerDefaults.AuthenticationScheme 68 | o.DefaultChallengeScheme <- JwtBearerDefaults.AuthenticationScheme 69 | 70 | let jwtBearerOptions (cfg : JwtBearerOptions) = 71 | cfg.SaveToken <- true 72 | cfg.IncludeErrorDetails <- true 73 | cfg.Authority <- "https://accounts.google.com" 74 | cfg.Audience <- "your-oauth-2.0-client-id.apps.googleusercontent.com" 75 | cfg.TokenValidationParameters <- TokenValidationParameters ( 76 | ValidIssuer = "accounts.google.com" 77 | ) 78 | 79 | let configureServices (services : IServiceCollection) = 80 | services 81 | .AddGiraffe() 82 | .AddAuthentication(authenticationOptions) 83 | .AddJwtBearer(Action jwtBearerOptions) |> ignore 84 | 85 | let configureLogging (builder : ILoggingBuilder) = 86 | let filter (l : LogLevel) = l.Equals LogLevel.Error 87 | builder.AddFilter(filter).AddConsole().AddDebug() |> ignore 88 | 89 | [] 90 | let main _ = 91 | let contentRoot = Directory.GetCurrentDirectory() 92 | let webRoot = Path.Combine(contentRoot, "WebRoot") 93 | Host.CreateDefaultBuilder() 94 | .ConfigureWebHostDefaults( 95 | fun webHostBuilder -> 96 | webHostBuilder 97 | .UseKestrel() 98 | .UseContentRoot(contentRoot) 99 | .UseWebRoot(webRoot) 100 | .Configure(configureApp) 101 | .ConfigureServices(configureServices) 102 | .ConfigureLogging(configureLogging) 103 | |> ignore) 104 | .Build() 105 | .Run() 106 | 0 -------------------------------------------------------------------------------- /demo-apps/SampleApp/SampleApp.Tests/Tests.fs: -------------------------------------------------------------------------------- 1 | module SampleApp.Tests 2 | 3 | open System 4 | open System.Net 5 | open System.Net.Http 6 | open System.IO 7 | open Microsoft.AspNetCore.Builder 8 | open Microsoft.AspNetCore.Hosting 9 | open Microsoft.AspNetCore.TestHost 10 | open Microsoft.Extensions.DependencyInjection 11 | open FSharp.Control.Tasks.V2.ContextInsensitive 12 | open Xunit 13 | 14 | // --------------------------------- 15 | // Test server/client setup 16 | // --------------------------------- 17 | 18 | let createHost() = 19 | WebHostBuilder() 20 | .UseContentRoot(Directory.GetCurrentDirectory()) 21 | .Configure(Action SampleApp.App.configureApp) 22 | .ConfigureServices(Action SampleApp.App.configureServices) 23 | 24 | // --------------------------------- 25 | // Helper functions 26 | // --------------------------------- 27 | 28 | let get (client : HttpClient) (path : string) = 29 | path 30 | |> client.GetAsync 31 | 32 | let createRequest (method : HttpMethod) (path : string) = 33 | let url = "http://127.0.0.1" + path 34 | new HttpRequestMessage(method, url) 35 | 36 | let addCookiesFromResponse (response : HttpResponseMessage) 37 | (request : HttpRequestMessage) = 38 | request.Headers.Add("Cookie", response.Headers.GetValues("Set-Cookie")) 39 | request 40 | 41 | let makeRequest (client : HttpClient) request = 42 | request 43 | |> client.SendAsync 44 | 45 | let isStatus (code : HttpStatusCode) (response : HttpResponseMessage) = 46 | Assert.Equal(code, response.StatusCode) 47 | response 48 | 49 | let isOfType (contentType : string) (response : HttpResponseMessage) = 50 | Assert.Equal(contentType, response.Content.Headers.ContentType.MediaType) 51 | response 52 | 53 | let readText (response : HttpResponseMessage) = 54 | response.Content.ReadAsStringAsync() 55 | 56 | let shouldEqual expected actual = 57 | Assert.Equal(expected, actual) 58 | 59 | // --------------------------------- 60 | // Tests 61 | // --------------------------------- 62 | 63 | [] 64 | let ``Test / is routed to index`` () = 65 | task { 66 | use server = new TestServer(createHost()) 67 | use client = server.CreateClient() 68 | let! response = get client "/" 69 | let! content = 70 | response 71 | |> isStatus HttpStatusCode.OK 72 | |> readText 73 | content 74 | |> shouldEqual "index" 75 | } 76 | 77 | [] 78 | let ``Test /error returns status code 500`` () = 79 | task { 80 | use server = new TestServer(createHost()) 81 | use client = server.CreateClient() 82 | let! response = get client "/error" 83 | let! content = 84 | response 85 | |> isStatus HttpStatusCode.InternalServerError 86 | |> readText 87 | content 88 | |> shouldEqual "Something went wrong!" 89 | } 90 | 91 | [] 92 | let ``Test /user returns error when not logged in`` () = 93 | task { 94 | use server = new TestServer(createHost()) 95 | use client = server.CreateClient() 96 | let! response = get client "/user" 97 | let! content = 98 | response 99 | |> isStatus HttpStatusCode.Unauthorized 100 | |> readText 101 | content 102 | |> shouldEqual "Access Denied" 103 | } 104 | 105 | [] 106 | let ``Test /user/{id} returns success when logged in as user`` () = 107 | task { 108 | use server = new TestServer(createHost()) 109 | use client = server.CreateClient() 110 | let! response = get client "/login" 111 | let! content = 112 | response 113 | |> isStatus HttpStatusCode.OK 114 | |> readText 115 | content 116 | |> shouldEqual "Successfully logged in" 117 | 118 | // https://github.com/aspnet/Hosting/issues/191 119 | // The session cookie is not automatically forwarded to the next request. 120 | // To overcome this we have to manually do: 121 | let! response' = 122 | "/user/1" 123 | |> createRequest HttpMethod.Get 124 | |> addCookiesFromResponse response 125 | |> makeRequest client 126 | let! content' = 127 | response' 128 | |> isStatus HttpStatusCode.OK 129 | |> readText 130 | content' 131 | |> shouldEqual "User ID: 1" 132 | } -------------------------------------------------------------------------------- /demo-apps/GoogleAuthApp/GoogleAuthApp/Program.fs: -------------------------------------------------------------------------------- 1 | module GoogleAuthApp.App 2 | 3 | open System 4 | open Microsoft.AspNetCore.Http 5 | open Microsoft.AspNetCore.Builder 6 | open Microsoft.AspNetCore.Hosting 7 | open Microsoft.AspNetCore.Authentication 8 | open Microsoft.Extensions.Hosting 9 | open Microsoft.Extensions.Logging 10 | open Microsoft.Extensions.DependencyInjection 11 | open FSharp.Control.Tasks.V2.ContextInsensitive 12 | open Giraffe 13 | open Giraffe.GiraffeViewEngine 14 | open GoogleAuthApp.HttpsConfig 15 | 16 | // --------------------------------- 17 | // Web app 18 | // --------------------------------- 19 | 20 | module AuthSchemes = 21 | 22 | let cookie = "Cookies" 23 | let google = "Google" 24 | 25 | module Urls = 26 | 27 | let index = "/" 28 | let login = "/login" 29 | let googleAuth = "/google-auth" 30 | let user = "/user" 31 | let logout = "/logout" 32 | let missing = "/missing" 33 | 34 | module Views = 35 | 36 | let master (content: XmlNode list) = 37 | html [] [ 38 | head [] [ 39 | title [] [ str "Google Auth Sample App" ] 40 | ] 41 | body [] content 42 | ] 43 | 44 | let index = 45 | [ 46 | h1 [] [ str "Google Auth Sample App" ] 47 | p [] [ str "Welcome to the Google Auth Sample App!" ] 48 | ul [] [ 49 | li [] [ a [ _href Urls.login ] [ str "Login" ] ] 50 | li [] [ a [ _href Urls.user ] [ str "User profile" ] ] 51 | ] 52 | ] |> master 53 | 54 | let login = 55 | [ 56 | h1 [] [ str "Login" ] 57 | p [] [ str "Pick one of the options to log in:" ] 58 | ul [] [ 59 | li [] [ a [ _href Urls.googleAuth ] [ str "Google" ] ] 60 | li [] [ a [ _href Urls.missing ] [ str "Facebook" ] ] 61 | li [] [ a [ _href Urls.missing ] [ str "Twitter" ] ] 62 | ] 63 | p [] [ 64 | a [ _href Urls.index ] [ str "Return to home." ] 65 | ] 66 | ] |> master 67 | 68 | let user (claims : (string * string) seq) = 69 | [ 70 | h1 [] [ str "User details" ] 71 | h2 [] [ str "Claims:" ] 72 | ul [] [ 73 | yield! claims |> Seq.map ( 74 | fun (key, value) -> 75 | li [] [ sprintf "%s: %s" key value |> str ] ) 76 | ] 77 | p [] [ 78 | a [ _href Urls.logout ] [ str "Logout" ] 79 | ] 80 | ] |> master 81 | 82 | let notFound = 83 | [ 84 | h1 [] [ str "Not Found" ] 85 | p [] [ str "The requested resource does not exist." ] 86 | p [] [ str "Facebook and Twitter auth handlers have not been configured yet." ] 87 | ul [] [ 88 | li [] [ a [ _href Urls.index ] [ str "Return to home." ] ] 89 | ] 90 | ] |> master 91 | 92 | module Handlers = 93 | 94 | let index : HttpHandler = Views.index |> htmlView 95 | let login : HttpHandler = Views.login |> htmlView 96 | 97 | let user : HttpHandler = 98 | fun (next : HttpFunc) (ctx : HttpContext) -> 99 | (ctx.User.Claims 100 | |> Seq.map (fun c -> (c.Type, c.Value)) 101 | |> Views.user 102 | |> htmlView) next ctx 103 | 104 | let logout : HttpHandler = 105 | signOut AuthSchemes.cookie 106 | >=> redirectTo false Urls.index 107 | 108 | let challenge (scheme : string) (redirectUri : string) : HttpHandler = 109 | fun (next : HttpFunc) (ctx : HttpContext) -> 110 | task { 111 | do! ctx.ChallengeAsync( 112 | scheme, 113 | AuthenticationProperties(RedirectUri = redirectUri)) 114 | return! next ctx 115 | } 116 | 117 | let googleAuth = challenge AuthSchemes.google Urls.user 118 | 119 | let authenticate : HttpHandler = 120 | requiresAuthentication login 121 | 122 | let notFound : HttpHandler = 123 | setStatusCode 404 >=> 124 | (Views.notFound |> htmlView) 125 | 126 | let webApp : HttpHandler = 127 | choose [ 128 | GET >=> 129 | choose [ 130 | route Urls.index >=> index 131 | route Urls.login >=> login 132 | route Urls.user >=> authenticate >=> user 133 | route Urls.logout >=> logout 134 | route Urls.googleAuth >=> googleAuth 135 | ] 136 | notFound ] 137 | 138 | let error (ex : Exception) (logger : ILogger) = 139 | logger.LogError(EventId(), ex, "An unhandled exception has occurred while executing the request.") 140 | clearResponse >=> setStatusCode 500 >=> text ex.Message 141 | 142 | // --------------------------------- 143 | // Config and Main 144 | // --------------------------------- 145 | 146 | let configureApp (app : IApplicationBuilder) = 147 | app.UseGiraffeErrorHandler(Handlers.error) 148 | .UseAuthentication() 149 | .UseGiraffe Handlers.webApp 150 | 151 | let configureServices (services : IServiceCollection) = 152 | // Enable Authentication providers 153 | services.AddAuthentication(fun o -> o.DefaultScheme <- AuthSchemes.cookie) 154 | .AddCookie( 155 | AuthSchemes.cookie, fun o -> 156 | o.LoginPath <- PathString Urls.login 157 | o.LogoutPath <- PathString Urls.logout) 158 | .AddGoogle( 159 | AuthSchemes.google, fun o -> 160 | o.ClientId <- "" 161 | o.ClientSecret <- "") 162 | |> ignore 163 | 164 | // Add Giraffe dependencies 165 | services.AddGiraffe() |> ignore 166 | 167 | let configureLogging (builder : ILoggingBuilder) = 168 | let filter (l : LogLevel) = l.Equals LogLevel.Error 169 | builder.AddFilter(filter).AddConsole().AddDebug() |> ignore 170 | 171 | [] 172 | let main _ = 173 | let endpoints = 174 | [ 175 | EndpointConfiguration.Default 176 | { EndpointConfiguration.Default with 177 | Port = Some 44340 178 | Scheme = Https 179 | FilePath = Some "" 180 | Password = Some "" } ] 181 | Host.CreateDefaultBuilder() 182 | .ConfigureWebHostDefaults( 183 | fun webHostBuilder -> 184 | webHostBuilder 185 | .UseKestrel(fun o -> o.ConfigureEndpoints endpoints) 186 | .Configure(configureApp) 187 | .ConfigureServices(configureServices) 188 | .ConfigureLogging(configureLogging) 189 | |> ignore) 190 | .Build() 191 | .Run() 192 | 0 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | 332 | # macOS 333 | .DS_Store 334 | 335 | # Ionide 336 | .ionide/ 337 | 338 | # Visual Studio Code 339 | .vscode -------------------------------------------------------------------------------- /demo-apps/SampleApp/SampleApp/Program.fs: -------------------------------------------------------------------------------- 1 | module SampleApp.App 2 | 3 | open System 4 | open System.Security.Claims 5 | open System.Threading 6 | open Microsoft.AspNetCore.Builder 7 | open Microsoft.AspNetCore.Hosting 8 | open Microsoft.AspNetCore.Http 9 | open Microsoft.AspNetCore.Http.Features 10 | open Microsoft.AspNetCore.Authentication 11 | open Microsoft.Extensions.Hosting 12 | open Microsoft.AspNetCore.Authentication.Cookies 13 | open Microsoft.Extensions.Configuration 14 | open Microsoft.Extensions.Logging 15 | open Microsoft.Extensions.DependencyInjection 16 | open FSharp.Control.Tasks.V2.ContextInsensitive 17 | open Giraffe 18 | open SampleApp.Models 19 | open SampleApp.HtmlViews 20 | 21 | // --------------------------------- 22 | // Error handler 23 | // --------------------------------- 24 | 25 | let errorHandler (ex : Exception) (logger : ILogger) = 26 | logger.LogError(EventId(), ex, "An unhandled exception has occurred while executing the request.") 27 | clearResponse >=> setStatusCode 500 >=> text ex.Message 28 | 29 | // --------------------------------- 30 | // Web app 31 | // --------------------------------- 32 | 33 | let authScheme = CookieAuthenticationDefaults.AuthenticationScheme 34 | 35 | let accessDenied = setStatusCode 401 >=> text "Access Denied" 36 | 37 | let mustBeUser = requiresAuthentication accessDenied 38 | 39 | let mustBeAdmin = 40 | requiresAuthentication accessDenied 41 | >=> requiresRole "Admin" accessDenied 42 | 43 | let mustBeJohn = 44 | requiresAuthentication accessDenied 45 | >=> authorizeUser (fun u -> u.HasClaim (ClaimTypes.Name, "John")) accessDenied 46 | 47 | let loginHandler = 48 | fun (next : HttpFunc) (ctx : HttpContext) -> 49 | task { 50 | let issuer = "http://localhost:5000" 51 | let claims = 52 | [ 53 | Claim(ClaimTypes.Name, "John", ClaimValueTypes.String, issuer) 54 | Claim(ClaimTypes.Surname, "Doe", ClaimValueTypes.String, issuer) 55 | Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String, issuer) 56 | ] 57 | let identity = ClaimsIdentity(claims, authScheme) 58 | let user = ClaimsPrincipal(identity) 59 | 60 | do! ctx.SignInAsync(authScheme, user) 61 | 62 | return! text "Successfully logged in" next ctx 63 | } 64 | 65 | let userHandler = 66 | fun (next : HttpFunc) (ctx : HttpContext) -> 67 | text ctx.User.Identity.Name next ctx 68 | 69 | let showUserHandler id = 70 | mustBeAdmin >=> 71 | text (sprintf "User ID: %i" id) 72 | 73 | let configuredHandler = 74 | fun (next : HttpFunc) (ctx : HttpContext) -> 75 | let configuration = ctx.GetService() 76 | text configuration.["HelloMessage"] next ctx 77 | 78 | let fileUploadHandler = 79 | fun (next : HttpFunc) (ctx : HttpContext) -> 80 | task { 81 | return! 82 | (match ctx.Request.HasFormContentType with 83 | | false -> RequestErrors.BAD_REQUEST "Bad request" 84 | | true -> 85 | ctx.Request.Form.Files 86 | |> Seq.fold (fun acc file -> sprintf "%s\n%s" acc file.FileName) "" 87 | |> text) next ctx 88 | } 89 | 90 | let fileUploadHandler2 = 91 | fun (next : HttpFunc) (ctx : HttpContext) -> 92 | task { 93 | let formFeature = ctx.Features.Get() 94 | let! form = formFeature.ReadFormAsync CancellationToken.None 95 | return! 96 | (form.Files 97 | |> Seq.fold (fun acc file -> sprintf "%s\n%s" acc file.FileName) "" 98 | |> text) next ctx 99 | } 100 | 101 | let cacheHandler1 : HttpHandler = 102 | publicResponseCaching 30 None 103 | >=> warbler (fun _ -> 104 | text (Guid.NewGuid().ToString())) 105 | 106 | let cacheHandler2 : HttpHandler = 107 | responseCaching 108 | (Public (TimeSpan.FromSeconds (float 30))) 109 | None 110 | (Some [| "key1"; "key2" |]) 111 | >=> warbler (fun _ -> 112 | text (Guid.NewGuid().ToString())) 113 | 114 | let cacheHandler3 : HttpHandler = 115 | noResponseCaching >=> warbler (fun _ -> text (Guid.NewGuid().ToString())) 116 | 117 | let time() = System.DateTime.Now.ToString() 118 | 119 | [] 120 | type Car = 121 | { 122 | Name : string 123 | Make : string 124 | Wheels : int 125 | Built : DateTime 126 | } 127 | interface IModelValidation with 128 | member this.Validate() = 129 | if this.Wheels > 1 && this.Wheels <= 6 then Ok this 130 | else Error (RequestErrors.BAD_REQUEST "Wheels must be a value between 2 and 6.") 131 | 132 | let parsingErrorHandler err = RequestErrors.BAD_REQUEST err 133 | 134 | let webApp = 135 | choose [ 136 | GET >=> 137 | choose [ 138 | route "/" >=> text "index" 139 | route "/ping" >=> text "pong" 140 | route "/error" >=> (fun _ _ -> failwith "Something went wrong!") 141 | route "/login" >=> loginHandler 142 | route "/logout" >=> signOut authScheme >=> text "Successfully logged out." 143 | route "/user" >=> mustBeUser >=> userHandler 144 | route "/john-only" >=> mustBeJohn >=> userHandler 145 | routef "/user/%i" showUserHandler 146 | route "/person" >=> (personView { Name = "Html Node" } |> htmlView) 147 | route "/once" >=> (time() |> text) 148 | route "/everytime" >=> warbler (fun _ -> (time() |> text)) 149 | route "/configured" >=> configuredHandler 150 | route "/upload" >=> fileUploadHandler 151 | route "/upload2" >=> fileUploadHandler2 152 | route "/cache/1" >=> cacheHandler1 153 | route "/cache/2" >=> cacheHandler2 154 | route "/cache/3" >=> cacheHandler3 155 | ] 156 | route "/car" >=> bindModel None json 157 | route "/car2" >=> tryBindQuery parsingErrorHandler None (validateModel xml) 158 | RequestErrors.notFound (text "Not Found") ] 159 | 160 | // --------------------------------- 161 | // Main 162 | // --------------------------------- 163 | 164 | let cookieAuth (o : CookieAuthenticationOptions) = 165 | do 166 | o.Cookie.HttpOnly <- true 167 | o.Cookie.SecurePolicy <- CookieSecurePolicy.SameAsRequest 168 | o.SlidingExpiration <- true 169 | o.ExpireTimeSpan <- TimeSpan.FromDays 7.0 170 | 171 | let configureApp (app : IApplicationBuilder) = 172 | app.UseGiraffeErrorHandler(errorHandler) 173 | .UseStaticFiles() 174 | .UseAuthentication() 175 | .UseResponseCaching() 176 | .UseGiraffe webApp 177 | 178 | let configureServices (services : IServiceCollection) = 179 | services 180 | .AddResponseCaching() 181 | .AddGiraffe() 182 | .AddAuthentication(authScheme) 183 | .AddCookie(cookieAuth) |> ignore 184 | services.AddDataProtection() |> ignore 185 | 186 | let configureLogging (loggerBuilder : ILoggingBuilder) = 187 | loggerBuilder.AddFilter(fun lvl -> lvl.Equals LogLevel.Error) 188 | .AddConsole() 189 | .AddDebug() |> ignore 190 | 191 | [] 192 | let main _ = 193 | Host.CreateDefaultBuilder() 194 | .ConfigureWebHostDefaults( 195 | fun webHostBuilder -> 196 | webHostBuilder 197 | .Configure(configureApp) 198 | .ConfigureServices(configureServices) 199 | .ConfigureLogging(configureLogging) 200 | |> ignore) 201 | .Build() 202 | .Run() 203 | 0 -------------------------------------------------------------------------------- /demo-apps/IdentityApp/IdentityApp/Program.fs: -------------------------------------------------------------------------------- 1 | module SampleApp.App 2 | 3 | open System 4 | open System.IO 5 | open System.Text 6 | open Microsoft.AspNetCore.Builder 7 | open Microsoft.AspNetCore.Cors.Infrastructure 8 | open Microsoft.AspNetCore.Hosting 9 | open Microsoft.AspNetCore.Http 10 | open Microsoft.Extensions.Hosting 11 | open Microsoft.Extensions.Logging 12 | open Microsoft.Extensions.DependencyInjection 13 | open Microsoft.AspNetCore.Identity 14 | open Microsoft.AspNetCore.Identity.EntityFrameworkCore 15 | open Microsoft.EntityFrameworkCore 16 | open FSharp.Control.Tasks.V2.ContextInsensitive 17 | open Giraffe 18 | open Giraffe.GiraffeViewEngine 19 | 20 | // --------------------------------- 21 | // View engine 22 | // --------------------------------- 23 | 24 | let masterPage (pageTitle : string) (content : XmlNode list) = 25 | html [] [ 26 | head [] [ 27 | title [] [ str pageTitle ] 28 | style [] [ rawText "label { display: inline-block; width: 80px; }" ] 29 | ] 30 | body [] [ 31 | h1 [] [ str pageTitle ] 32 | main [] content 33 | ] 34 | ] 35 | 36 | let indexPage = 37 | [ 38 | p [] [ 39 | a [ _href "/register" ] [ str "Register" ] 40 | ] 41 | p [] [ 42 | a [ _href "/user" ] [ str "User page" ] 43 | ] 44 | ] |> masterPage "Home" 45 | 46 | let registerPage = 47 | [ 48 | form [ _action "/register"; _method "POST" ] [ 49 | div [] [ 50 | label [] [ str "Email:" ] 51 | input [ _name "Email"; _type "text" ] 52 | ] 53 | div [] [ 54 | label [] [ str "User name:" ] 55 | input [ _name "UserName"; _type "text" ] 56 | ] 57 | div [] [ 58 | label [] [ str "Password:" ] 59 | input [ _name "Password"; _type "password" ] 60 | ] 61 | input [ _type "submit" ] 62 | ] 63 | ] |> masterPage "Register" 64 | 65 | let loginPage (loginFailed : bool) = 66 | [ 67 | if loginFailed then yield p [ _style "color: Red;" ] [ str "Login failed." ] 68 | 69 | yield form [ _action "/login"; _method "POST" ] [ 70 | div [] [ 71 | label [] [ str "User name:" ] 72 | input [ _name "UserName"; _type "text" ] 73 | ] 74 | div [] [ 75 | label [] [ str "Password:" ] 76 | input [ _name "Password"; _type "password" ] 77 | ] 78 | input [ _type "submit" ] 79 | ] 80 | yield p [] [ 81 | str "Don't have an account yet?" 82 | a [ _href "/register" ] [ str "Go to registration" ] 83 | ] 84 | ] |> masterPage "Login" 85 | 86 | let userPage (user : IdentityUser) = 87 | [ 88 | p [] [ 89 | sprintf "User name: %s, Email: %s" user.UserName user.Email 90 | |> str 91 | ] 92 | ] |> masterPage "User details" 93 | 94 | // --------------------------------- 95 | // Web app 96 | // --------------------------------- 97 | 98 | [] 99 | type RegisterModel = 100 | { 101 | UserName : string 102 | Email : string 103 | Password : string 104 | } 105 | 106 | [] 107 | type LoginModel = 108 | { 109 | UserName : string 110 | Password : string 111 | } 112 | 113 | let showErrors (errors : IdentityError seq) = 114 | errors 115 | |> Seq.fold (fun acc err -> 116 | sprintf "Code: %s, Description: %s" err.Code err.Description 117 | |> acc.AppendLine : StringBuilder) (StringBuilder("")) 118 | |> (fun x -> x.ToString()) 119 | |> text 120 | 121 | let registerHandler : HttpHandler = 122 | fun (next : HttpFunc) (ctx : HttpContext) -> 123 | task { 124 | let! model = ctx.BindFormAsync() 125 | let user = IdentityUser(UserName = model.UserName, Email = model.Email) 126 | let userManager = ctx.GetService>() 127 | let! result = userManager.CreateAsync(user, model.Password) 128 | 129 | match result.Succeeded with 130 | | false -> return! showErrors result.Errors next ctx 131 | | true -> 132 | let signInManager = ctx.GetService>() 133 | do! signInManager.SignInAsync(user, true) 134 | return! redirectTo false "/user" next ctx 135 | } 136 | 137 | let loginHandler : HttpHandler = 138 | fun (next : HttpFunc) (ctx : HttpContext) -> 139 | task { 140 | let! model = ctx.BindFormAsync() 141 | let signInManager = ctx.GetService>() 142 | let! result = signInManager.PasswordSignInAsync(model.UserName, model.Password, true, false) 143 | match result.Succeeded with 144 | | true -> return! redirectTo false "/user" next ctx 145 | | false -> return! htmlView (loginPage true) next ctx 146 | } 147 | 148 | let userHandler : HttpHandler = 149 | fun (next : HttpFunc) (ctx : HttpContext) -> 150 | task { 151 | let userManager = ctx.GetService>() 152 | let! user = userManager.GetUserAsync ctx.User 153 | return! (user |> userPage |> htmlView) next ctx 154 | } 155 | 156 | let mustBeLoggedIn : HttpHandler = 157 | requiresAuthentication (redirectTo false "/login") 158 | 159 | let logoutHandler : HttpHandler = 160 | fun (next : HttpFunc) (ctx : HttpContext) -> 161 | task { 162 | let signInManager = ctx.GetService>() 163 | do! signInManager.SignOutAsync() 164 | return! (redirectTo false "/") next ctx 165 | } 166 | 167 | let webApp = 168 | choose [ 169 | GET >=> 170 | choose [ 171 | route "/" >=> htmlView indexPage 172 | route "/register" >=> htmlView registerPage 173 | route "/login" >=> htmlView (loginPage false) 174 | 175 | route "/logout" >=> mustBeLoggedIn >=> logoutHandler 176 | route "/user" >=> mustBeLoggedIn >=> userHandler 177 | ] 178 | POST >=> 179 | choose [ 180 | route "/register" >=> registerHandler 181 | route "/login" >=> loginHandler 182 | ] 183 | setStatusCode 404 >=> text "Not Found" ] 184 | 185 | // --------------------------------- 186 | // Error handler 187 | // --------------------------------- 188 | 189 | let errorHandler (ex : Exception) (logger : ILogger) = 190 | logger.LogError(EventId(), ex, "An unhandled exception has occurred while executing the request.") 191 | clearResponse >=> setStatusCode 500 >=> text ex.Message 192 | 193 | // --------------------------------- 194 | // Main 195 | // --------------------------------- 196 | 197 | let configureCors (builder : CorsPolicyBuilder) = 198 | builder.WithOrigins("http://localhost:8080").AllowAnyMethod().AllowAnyHeader() |> ignore 199 | 200 | let configureApp (app : IApplicationBuilder) = 201 | app.UseCors(configureCors) 202 | .UseGiraffeErrorHandler(errorHandler) 203 | .UseAuthentication() 204 | .UseGiraffe webApp 205 | 206 | let configureServices (services : IServiceCollection) = 207 | // Configure InMemory Db for sample application 208 | services.AddDbContext>( 209 | fun options -> 210 | options.UseInMemoryDatabase("NameOfDatabase") |> ignore 211 | ) |> ignore 212 | 213 | // Register Identity Dependencies 214 | services.AddIdentity( 215 | fun options -> 216 | // Password settings 217 | options.Password.RequireDigit <- true 218 | options.Password.RequiredLength <- 8 219 | options.Password.RequireNonAlphanumeric <- false 220 | options.Password.RequireUppercase <- true 221 | options.Password.RequireLowercase <- false 222 | 223 | // Lockout settings 224 | options.Lockout.DefaultLockoutTimeSpan <- TimeSpan.FromMinutes 30.0 225 | options.Lockout.MaxFailedAccessAttempts <- 10 226 | 227 | // User settings 228 | options.User.RequireUniqueEmail <- true 229 | ) 230 | .AddEntityFrameworkStores>() 231 | .AddDefaultTokenProviders() 232 | |> ignore 233 | 234 | // Configure app cookie 235 | services.ConfigureApplicationCookie( 236 | fun options -> 237 | options.ExpireTimeSpan <- TimeSpan.FromDays 150.0 238 | options.LoginPath <- PathString "/login" 239 | options.LogoutPath <- PathString "/logout" 240 | ) |> ignore 241 | 242 | // Enable CORS 243 | services.AddCors() |> ignore 244 | 245 | // Configure Giraffe dependencies 246 | services.AddGiraffe() |> ignore 247 | 248 | let configureLogging (builder : ILoggingBuilder) = 249 | let filter (l : LogLevel) = l.Equals LogLevel.Error 250 | builder.AddFilter(filter).AddConsole().AddDebug() |> ignore 251 | 252 | [] 253 | let main _ = 254 | Host.CreateDefaultBuilder() 255 | .ConfigureWebHostDefaults( 256 | fun webHostBuilder -> 257 | webHostBuilder 258 | .UseKestrel() 259 | .UseContentRoot(Directory.GetCurrentDirectory()) 260 | .Configure(configureApp) 261 | .ConfigureServices(configureServices) 262 | .ConfigureLogging(configureLogging) 263 | |> ignore) 264 | .Build() 265 | .Run() 266 | 0 267 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /.psscripts/build-functions.ps1: -------------------------------------------------------------------------------- 1 | # ---------------------------------------------- 2 | # Generic functions 3 | # ---------------------------------------------- 4 | 5 | function Test-IsMonoInstalled 6 | { 7 | <# 8 | .DESCRIPTION 9 | Checks to see whether the current environment has the Mono framework installed. 10 | 11 | .EXAMPLE 12 | if (Test-IsMonoInstalled) { Write-Host "Mono is available." } 13 | #> 14 | 15 | try 16 | { 17 | $result = Invoke-Cmd "mono --version" -Silent 18 | return $result.StartsWith("Mono JIT compiler version") 19 | } 20 | catch { return false } 21 | } 22 | 23 | function Get-UbuntuVersion 24 | { 25 | <# 26 | .DESCRIPTION 27 | Gets the Ubuntu version. 28 | 29 | .EXAMPLE 30 | $ubuntuVersion = Get-UbuntuVersion 31 | #> 32 | 33 | $version = Invoke-Cmd "lsb_release -r -s" -Silent 34 | return $version 35 | } 36 | 37 | function Invoke-UnsafeCmd ( 38 | [string] $Cmd, 39 | [switch] $Silent) 40 | { 41 | <# 42 | .DESCRIPTION 43 | Runs a shell or bash command, but doesn't throw an error if the command didn't exit with 0. 44 | 45 | .PARAMETER cmd 46 | The command to be executed. 47 | 48 | .EXAMPLE 49 | Invoke-Cmd -Cmd "dotnet new classlib" 50 | 51 | .NOTES 52 | Use this PowerShell command to execute any CLI commands which might not exit with 0 on a success. 53 | #> 54 | 55 | if (!($Silent.IsPresent)) { Write-Host $cmd -ForegroundColor DarkCyan } 56 | if ($IsWindows) { $cmd = "cmd.exe /C $cmd" } 57 | Invoke-Expression -Command $cmd 58 | } 59 | 60 | function Invoke-Cmd ( 61 | [string] $Cmd, 62 | [switch] $Silent) 63 | { 64 | <# 65 | .DESCRIPTION 66 | Runs a shell or bash command and throws an error if the command didn't exit with 0. 67 | 68 | .PARAMETER cmd 69 | The command to be executed. 70 | 71 | .EXAMPLE 72 | Invoke-Cmd -Cmd "dotnet new classlib" 73 | 74 | .NOTES 75 | Use this PowerShell command to execute any dotnet CLI commands in order to ensure that they behave the same way in the case of an error across different environments (Windows, OSX and Linux). 76 | #> 77 | 78 | if ($Silent.IsPresent) { Invoke-UnsafeCmd $cmd -Silent } else { Invoke-UnsafeCmd $cmd } 79 | if ($LastExitCode -ne 0) { 80 | Write-Host "An error occured when executing '$Cmd'." 81 | Write-Error "An error occured when executing '$Cmd'." 82 | return 83 | } 84 | } 85 | 86 | function Remove-OldBuildArtifacts 87 | { 88 | <# 89 | .DESCRIPTION 90 | Deletes all the bin and obj folders from the current- and all sub directories. 91 | #> 92 | 93 | Write-Host "Deleting old build artifacts..." -ForegroundColor Magenta 94 | 95 | Get-ChildItem -Include "bin", "obj" -Recurse -Directory ` 96 | | ForEach-Object { 97 | Write-Host "Removing folder $_" -ForegroundColor DarkGray 98 | Remove-Item $_ -Recurse -Force } 99 | } 100 | 101 | function Get-ProjectVersion ($projFile) 102 | { 103 | <# 104 | .DESCRIPTION 105 | Gets the value of a .NET Core *.csproj, *.fsproj or *.vbproj file. 106 | 107 | .PARAMETER cmd 108 | The relative or absolute path to the .NET Core project file. 109 | #> 110 | 111 | [xml]$xml = Get-Content $projFile 112 | [string] $version = $xml.Project.PropertyGroup.Version 113 | $version 114 | } 115 | 116 | function Get-NuspecVersion ($nuspecFile) 117 | { 118 | <# 119 | .DESCRIPTION 120 | Gets the value of a .nuspec file. 121 | 122 | .PARAMETER cmd 123 | The relative or absolute path to the .nuspec file. 124 | #> 125 | 126 | [xml] $xml = Get-Content $nuspecFile 127 | [string] $version = $xml.package.metadata.version 128 | $version 129 | } 130 | 131 | function Test-CompareVersions ($version, [string]$gitTag) 132 | { 133 | Write-Host "Matching version against git tag..." -ForegroundColor Magenta 134 | Write-Host "Project version: $version" -ForegroundColor Cyan 135 | Write-Host "Git tag version: $gitTag" -ForegroundColor Cyan 136 | 137 | if (!$gitTag.EndsWith($version)) 138 | { 139 | Write-Error "Version and Git tag do not match." 140 | } 141 | } 142 | 143 | function Add-ToPathVariable ($path) 144 | { 145 | if ($IsWindows) 146 | { 147 | $updatedPath = "$path;$env:Path" 148 | [Environment]::SetEnvironmentVariable("Path", $updatedPath, "Process") 149 | [Environment]::SetEnvironmentVariable("Path", $updatedPath, "User") 150 | [Environment]::SetEnvironmentVariable("Path", $updatedPath, "Machine") 151 | } 152 | else 153 | { 154 | $updatedPath = "$path`:$env:PATH" 155 | [Environment]::SetEnvironmentVariable("PATH", $updatedPath, "Process") 156 | [Environment]::SetEnvironmentVariable("PATH", $updatedPath, "User") 157 | [Environment]::SetEnvironmentVariable("PATH", $updatedPath, "Machine") 158 | } 159 | } 160 | 161 | function Get-ProjectName ($proj) 162 | { 163 | [System.IO.Path]::GetFileNameWithoutExtension($proj) 164 | } 165 | 166 | # ---------------------------------------------- 167 | # .NET Core functions 168 | # ---------------------------------------------- 169 | 170 | function Get-TargetFrameworks ($projFile) 171 | { 172 | <# 173 | .DESCRIPTION 174 | Returns all target frameworks set up inside a specific .NET Core project file. 175 | 176 | .PARAMETER projFile 177 | The full or relative path to a .NET Core project file (*.csproj, *.fsproj, *.vbproj). 178 | 179 | .EXAMPLE 180 | Get-TargetFrameworks "MyProject.csproj" 181 | 182 | .NOTES 183 | This function will always return an array of target frameworks, even if only a single target framework was found in the project file. 184 | #> 185 | 186 | [xml]$proj = Get-Content $projFile 187 | 188 | if ($null -ne $proj.Project.PropertyGroup.TargetFrameworks) { 189 | ($proj.Project.PropertyGroup.TargetFrameworks).Split(";") 190 | } 191 | else { @($proj.Project.PropertyGroup.TargetFramework) } 192 | } 193 | 194 | function Get-NetCoreTargetFrameworks ($projFile) 195 | { 196 | <# 197 | .DESCRIPTION 198 | Returns a single .NET Core framework which could be found among all configured target frameworks of a given .NET Core project file. 199 | 200 | .PARAMETER projFile 201 | The full or relative path to a .NET Core project file (*.csproj, *.fsproj, *.vbproj). 202 | 203 | .EXAMPLE 204 | Get-NetCoreTargetFrameworks "MyProject.csproj" 205 | 206 | .NOTES 207 | This function will always return the only netstandard*/netcoreapp* target framework which is set up as a target framework. 208 | #> 209 | 210 | Get-TargetFrameworks $projFile | Where-Object { $_ -like "netstandard*" -or $_ -like "netcoreapp*" } 211 | } 212 | 213 | function Invoke-DotNetCli ($cmd, $proj, $argv) 214 | { 215 | # Currently dotnet test does not work for net461 on Linux/Mac 216 | # See: https://github.com/Microsoft/vstest/issues/1318 217 | 218 | if((!($IsWindows) -and !(Test-IsMonoInstalled)) ` 219 | -or (!($IsWindows) -and ($cmd -eq "test"))) 220 | { 221 | $netCoreFrameworks = Get-NetCoreTargetFrameworks($proj) 222 | 223 | foreach($fw in $netCoreFrameworks) { 224 | $fwArgv = "-f $fw " + $argv 225 | Invoke-Cmd "dotnet $cmd $proj $fwArgv" 226 | } 227 | } 228 | else 229 | { 230 | Invoke-Cmd "dotnet $cmd $proj $argv" 231 | } 232 | } 233 | 234 | function dotnet-info { Invoke-Cmd "dotnet --info" -Silent } 235 | function dotnet-version { Invoke-Cmd "dotnet --version" -Silent } 236 | function dotnet-restore ($project, $argv) { Invoke-Cmd "dotnet restore $project $argv" } 237 | function dotnet-build ($project, $argv) { Invoke-DotNetCli -Cmd "build" -Proj $project -Argv $argv } 238 | function dotnet-test ($project, $argv) { Invoke-DotNetCli -Cmd "test" -Proj $project -Argv $argv } 239 | function dotnet-run ($project, $argv) { Invoke-Cmd "dotnet run --project $project $argv" } 240 | function dotnet-pack ($project, $argv) { Invoke-Cmd "dotnet pack $project $argv" } 241 | function dotnet-publish ($project, $argv) { Invoke-Cmd "dotnet publish $project $argv" } 242 | 243 | function Get-DotNetRuntimeVersion 244 | { 245 | <# 246 | .DESCRIPTION 247 | Runs the dotnet --info command and extracts the .NET Core Runtime version number. 248 | 249 | .NOTES 250 | The .NET Core Runtime version can sometimes be useful for other dotnet CLI commands (e.g. dotnet xunit -fxversion ".NET Core Runtime version"). 251 | #> 252 | 253 | $info = dotnet-info 254 | [System.Array]::Reverse($info) 255 | $version = $info | Where-Object { $_.Contains("Version") } | Select-Object -First 1 256 | $version.Split(":")[1].Trim() 257 | } 258 | 259 | function Write-DotnetCoreVersions 260 | { 261 | <# 262 | .DESCRIPTION 263 | Writes the .NET Core SDK and Runtime version to the current host. 264 | #> 265 | 266 | $sdkVersion = dotnet-version 267 | $runtimeVersion = Get-DotNetRuntimeVersion 268 | Write-Host ".NET Core SDK version: $sdkVersion" -ForegroundColor Cyan 269 | Write-Host ".NET Core Runtime version: $runtimeVersion" -ForegroundColor Cyan 270 | } 271 | 272 | function Get-DesiredSdk 273 | { 274 | <# 275 | .DESCRIPTION 276 | Gets the desired .NET Core SDK version from the global.json file. 277 | #> 278 | 279 | Get-Content "global.json" ` 280 | | ConvertFrom-Json ` 281 | | ForEach-Object { $_.sdk.version.ToString() } 282 | } 283 | 284 | function Get-NetCoreSdkFromWeb ($version) 285 | { 286 | <# 287 | .DESCRIPTION 288 | Downloads the desired .NET Core SDK version from the internet and saves it under a temporary file name which will be returned by the function. 289 | 290 | .PARAMETER version 291 | The SDK version which should be downloaded. 292 | #> 293 | 294 | Write-Host "Downloading .NET Core SDK $version..." 295 | 296 | $os = 297 | if ($IsWindows) { "windows" } 298 | elseif ($IsLinux) { "linux" } 299 | elseif ($IsMacOS) { "macos" } 300 | else { Write-Error "Unknown OS, which is not supported by .NET Core." } 301 | 302 | $ext = if ($IsWindows) { ".zip" } else { ".tar.gz" } 303 | 304 | $uri = "https://www.microsoft.com/net/download/thank-you/dotnet-sdk-$version-$os-x64-binaries" 305 | Write-Host "Finding download link..." 306 | 307 | $response = Invoke-WebRequest -Uri $uri 308 | 309 | $downloadLink = 310 | $response.Links ` 311 | | Where-Object { $_.onclick -eq "recordManualDownload()" } ` 312 | | Select-Object -Expand href 313 | 314 | Write-Host "Creating temporary file..." 315 | 316 | $tempFile = [System.IO.Path]::GetTempFileName() + $ext 317 | 318 | $webClient = New-Object System.Net.WebClient 319 | $webClient.DownloadFile($downloadLink, $tempFile) 320 | 321 | Write-Host "Download finished. SDK has been saved to '$tempFile'." 322 | 323 | return $tempFile 324 | } 325 | 326 | function Install-NetCoreSdkFromArchive ($sdkPackagePath) 327 | { 328 | <# 329 | .DESCRIPTION 330 | Extracts the zip archive which contains the .NET Core SDK and installs it in the current working directory under .dotnetsdk. 331 | 332 | .PARAMETER version 333 | The zip archive which contains the .NET Core SDK. 334 | #> 335 | 336 | if ($IsWindows) 337 | { 338 | $dotnetInstallDir = [System.IO.Path]::Combine($pwd, ".dotnetsdk") 339 | 340 | if (!(Test-Path $dotnetInstallDir)) 341 | { 342 | New-Item $dotnetInstallDir -ItemType Directory -Force | Out-Null 343 | Write-Host "Created folder '$dotnetInstallDir'." 344 | } 345 | 346 | Expand-Archive -LiteralPath $sdkPackagePath -DestinationPath $dotnetInstallDir -Force 347 | Write-Host "Extracted '$sdkPackagePath' to folder '$dotnetInstallDir'." 348 | 349 | [Environment]::SetEnvironmentVariable("DOTNET_ROOT", $dotnetInstallDir, "Process") 350 | Write-Host "DOTNET_ROOT environment variable has been set to $dotnetInstallDir." 351 | } 352 | else 353 | { 354 | $dotnetInstallDir = "$env:HOME/.dotnetsdk" 355 | 356 | if (!(Test-Path $dotnetInstallDir)) 357 | { 358 | Invoke-Cmd "mkdir -p $dotnetInstallDir" 359 | Write-Host "Created folder '$dotnetInstallDir'." 360 | } 361 | 362 | Invoke-Cmd "tar -xf $sdkPackagePath -C $dotnetInstallDir" 363 | Write-Host "Extracted '$sdkPackagePath' to folder '$dotnetInstallDir'." 364 | } 365 | 366 | Add-ToPathVariable $dotnetInstallDir 367 | Write-Host "Added '$dotnetInstallDir' to the PATH environment variable:" 368 | Write-Host $env:PATH 369 | } 370 | 371 | function Install-NetCoreSdkForUbuntu ($ubuntuVersion, $sdkVersion) 372 | { 373 | Invoke-Cmd "wget -q https://packages.microsoft.com/config/ubuntu/$ubuntuVersion/packages-microsoft-prod.deb" 374 | Invoke-Cmd "sudo dpkg -i packages-microsoft-prod.deb" 375 | Invoke-Cmd "sudo apt-get install apt-transport-https" 376 | Invoke-Cmd "sudo apt-get update" 377 | Invoke-Cmd "sudo apt-get -y install dotnet-sdk-$sdkVersion" 378 | } 379 | 380 | # ---------------------------------------------- 381 | # AppVeyor functions 382 | # ---------------------------------------------- 383 | 384 | function Test-IsAppVeyorBuild { return ($env:APPVEYOR -eq $true) } 385 | function Test-IsAppVeyorBuildTriggeredByGitTag { return ($env:APPVEYOR_REPO_TAG -eq $true) } 386 | function Get-AppVeyorGitTag { return $env:APPVEYOR_REPO_TAG_NAME } 387 | 388 | function Update-AppVeyorBuildVersion ($version) 389 | { 390 | if (Test-IsAppVeyorBuild) 391 | { 392 | Write-Host "Updating AppVeyor build version..." -ForegroundColor Magenta 393 | $buildVersion = "$version-$env:APPVEYOR_BUILD_NUMBER" 394 | Write-Host "Setting AppVeyor build version to $buildVersion." 395 | Update-AppveyorBuild -Version $buildVersion 396 | } 397 | } 398 | 399 | # ---------------------------------------------- 400 | # Host Writing functions 401 | # ---------------------------------------------- 402 | 403 | function Write-BuildHeader ($projectTitle) 404 | { 405 | $header = " $projectTitle "; 406 | $bar = "" 407 | for ($i = 0; $i -lt $header.Length; $i++) { $bar += "-" } 408 | 409 | Write-Host "" 410 | Write-Host $bar -ForegroundColor DarkYellow 411 | Write-Host $header -ForegroundColor DarkYellow 412 | Write-Host $bar -ForegroundColor DarkYellow 413 | Write-Host "" 414 | } 415 | 416 | function Write-SuccessFooter ($msg) 417 | { 418 | $footer = " $msg "; 419 | $bar = "" 420 | for ($i = 0; $i -lt $footer.Length; $i++) { $bar += "-" } 421 | 422 | Write-Host "" 423 | Write-Host $bar -ForegroundColor Green 424 | Write-Host $footer -ForegroundColor Green 425 | Write-Host $bar -ForegroundColor Green 426 | Write-Host "" 427 | } --------------------------------------------------------------------------------