Skip to content

Instantly share code, notes, and snippets.

@qwe2
Created May 2, 2016 09:25
Show Gist options
  • Save qwe2/f9d4c3250765b8fae5b784522e1c9177 to your computer and use it in GitHub Desktop.
Save qwe2/f9d4c3250765b8fae5b784522e1c9177 to your computer and use it in GitHub Desktop.
WebSharper simple forms authentication with Sitelet.Protect
namespace SimpleLogin
open WebSharper
open WebSharper.Sitelets
open WebSharper.UI.Next
open WebSharper.UI.Next.Server
type EndPoint =
| [<EndPoint "POST /login">] DoLogin of credentials: Credentials
| [<EndPoint "/login">] Login
| [<EndPoint "/content">] ProtectedContent
and Credentials =
{
[<FormData; Name "username">] Username: string
[<FormData; Name "password">] Password: string
}
module Site =
open WebSharper.UI.Next.Html
let ToPage body =
Content.Page(Body = [body])
let LoginPage ctx =
formAttr [
// here, I abuse the fact that Login and DoLogin point to the same URL
attr.action (ctx.Link Login)
attr.``method`` "POST"
] [
inputAttr [attr.name "username"] []
br []
inputAttr [attr.name "password"; attr.``type`` "password"] []
br []
inputAttr [attr.``type`` "submit"; attr.value "Login"] []
]
let ProtectedPage ctx =
async {
let! username = ctx.UserSession.GetLoggedInUser ()
let content =
match username with
| Some username -> h1 [text (sprintf "Hello %s!" username)]
| None -> h1 [text "Should never be the case if we use Protect on this."]
return! ToPage content
}
[<Website>]
let Main =
let protectedPage =
Sitelet.Protect
{
VerifyUser = fun _ -> true
LoginRedirect = fun _ -> Login
}
<| Sitelet.Content "/content" ProtectedContent ProtectedPage
Sitelet.Sum [
protectedPage
Sitelet.Infer (fun ctx -> function
| DoLogin creds ->
async {
// handle authentication
if creds.Username = "test" && creds.Password = "test" then
do! ctx.UserSession.LoginUser(creds.Username, true)
return! Content.RedirectPermanent ProtectedContent
}
| Login ->
ToPage (LoginPage ctx)
| ProtectedContent ->
failwith "Should never match"
)
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment