-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.fs
322 lines (279 loc) · 12.2 KB
/
Program.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
module GiraffeWithIdentity.App
open System
open System.IO
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Cors.Infrastructure
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Http
open Microsoft.AspNetCore.WebUtilities
open Microsoft.Extensions.Hosting
open Microsoft.Extensions.Logging
open Microsoft.Extensions.DependencyInjection
open System.Threading.Tasks
open System.Security.Claims // for 'Claim' class
open Giraffe
open Giraffe.Antiforgery
open Microsoft.AspNetCore.Identity
open Microsoft.EntityFrameworkCore
open Microsoft.EntityFrameworkCore.Sqlite
// ---------------------------------
// Views
// ---------------------------------
open Microsoft.AspNetCore.Antiforgery
module Views =
open Giraffe.ViewEngine
let layout (content: XmlNode list) =
html [] [
head [] [
title [] [ encodedText "GiraffeWithIdentity" ]
link [ _rel "stylesheet"
_type "text/css"
_href "/main.css" ]
]
body [] content
]
let registerPage (errors : string list) (token : AntiforgeryTokenSet) =
[
h1 [] [str "Please Register"]
form [_method "post"] [
input [_type "text"; _placeholder "email"; _name "email"]
input [_type "password"; _placeholder "password"; _name "password"]
input [_type "submit"; _value "register"]
antiforgeryInput token
]
a [_href "/Account/Login"] [str "Already registered?"]
ul [] (errors |> List.map (fun err -> li [] [str err]))
] |> layout
let thanksForRegisteringPage =
[
p [] [ str "thanks for registering, we'll send you a confirmation email soon!" ]
a [_href "/Account/Login"] [str "go back to login page"]
] |> layout
let emailVerificationPage (success : bool) =
[
if success then
yield p [] [ str "Thanks for verifying your email address! You can now login." ]
else
yield p [] [ str "Oops, something is wrong with your verification link, please retry" ]
yield a [_href "/Account/Login"] [str "go back to login page"]
] |> layout
let loginPage (justFailed : bool) (token : AntiforgeryTokenSet) =
[
yield h1 [] [str "Please Login"]
yield form [_method "post"] [
input [_type "text"; _placeholder "email"; _name "email"]
input [_type "password"; _placeholder "password"; _name "password"]
input [_type "submit"; _value "login"]
antiforgeryInput token
]
if justFailed then
yield p [ _style "color: Red;" ] [ str "Login failed." ]
yield a [_href "/Account/Register"] [str "Register"]
] |> layout
let userPage (user : IdentityUser) (token : AntiforgeryTokenSet) =
[
p [] [
sprintf "User name: %s, Email: %s" user.UserName user.Email
|> str
]
form [_method "post"; _action "/Account/Logout"] [
input [_type "submit"; _value "Logout"]
antiforgeryInput token
]
] |> layout
// ---------------------------------
// Web app
// ---------------------------------
[<CLIMutable>]
type RegisterModel =
{
// it's okay this is capitalized.
Email : string
Password : string
}
[<CLIMutable>]
type LoginModel =
{
Email : string
Password : string
}
[<CLIMutable>]
type EmailVerificationModel =
{
UserId: string
Token : string
}
let registerHandler : HttpHandler =
fun next ctx ->
task {
let userManager = ctx.GetService<UserManager<IdentityUser>>()
let! form = ctx.TryBindFormAsync<RegisterModel>()
match form with
| Error _ ->
return! csrfHtmlView (Views.registerPage ["Something went wrong, please try again"]) next ctx
| Ok form ->
let user = IdentityUser(Email = form.Email, UserName = form.Email)
let! result = userManager.CreateAsync(user, form.Password)
// let! f = next ctx
if result.Succeeded then
printfn "REGISTER SUCCEEDED"
let! res1 = userManager.AddToRoleAsync(user, "USER")
// let! result1 = userManager.AddToRoleAsync(user, "user")
// result1 |> Async.Ignore
let! res2 = userManager.AddClaimsAsync(user, [
Claim("tier", "free") // switch to 'paid' when user subscribes.
])
let! token = userManager.GenerateEmailConfirmationTokenAsync(user)
let baseUrl = $"{ctx.Request.Scheme}://{ctx.Request.Host}/Account/Verify"
let url = QueryHelpers.AddQueryString(baseUrl, dict["UserId", user.Id ; "Token", token])
// !!!
// This is where you would send an email to the user, with somewthing like System.Net.Mail or similar
// However, for this sample we're just going to print it to the console.
// !!!
printfn "***********\nYour verification url is: %s\n***********" url
return! redirectTo false "/Account/RegisterThanks" next ctx
else
printfn "REGISTER FAILED"
// result.Errors contains stuff like:
// Passwords must have at least one non alphanumeric character.
// Passwords must have at least one digit ('0'-'9').
// Passwords must have at least one uppercase ('A'-'Z').
let errors = result.Errors |> Seq.map (fun e -> e.Description) |> List.ofSeq
return! csrfHtmlView (Views.registerPage errors) next ctx
}
let loginHandler : HttpHandler =
fun next ctx ->
task {
let! model = ctx.TryBindFormAsync<LoginModel>()
match model with
| Ok model ->
let signInManager = ctx.GetService<SignInManager<IdentityUser>>()
let! result = signInManager.PasswordSignInAsync(model.Email, model.Password, true, false)
match result.Succeeded with
| true -> return! redirectTo false "/User" next ctx
| false -> return! csrfHtmlView (Views.loginPage true) next ctx
| Error _ -> return! csrfHtmlView (Views.loginPage true) next ctx
}
let logoutHandler : HttpHandler =
fun next ctx ->
task {
let signInManager = ctx.GetService<SignInManager<IdentityUser>>()
do! signInManager.SignOutAsync()
return! redirectTo false "/Account/Login" next ctx
}
let userPageHandler : HttpHandler =
fun next ctx ->
task {
let userManager = ctx.GetService<UserManager<IdentityUser>>()
let! user = userManager.GetUserAsync ctx.User
return! (user |> Views.userPage |> csrfHtmlView) next ctx
}
let emailVerificationHandler : HttpHandler =
fun next ctx ->
task {
let userManager = ctx.GetService<UserManager<IdentityUser>>()
match ctx.TryBindQueryString<EmailVerificationModel>() with
| Ok qs ->
let! user = userManager.FindByIdAsync(qs.UserId)
if not (isNull user) then
let! result = userManager.ConfirmEmailAsync(user, qs.Token);
return! (Views.emailVerificationPage result.Succeeded |> htmlView) next ctx
else
return! (Views.emailVerificationPage false |> htmlView) next ctx
| Error s ->
return! (Views.emailVerificationPage false |> htmlView) next ctx
}
let mustBeLoggedIn : HttpHandler =
requiresAuthentication (redirectTo false "/Account/Login")
let webApp =
choose [
GET >=>
choose [
route "/Account/Register" >=> csrfHtmlView (Views.registerPage [])
route "/Account/Login" >=> csrfHtmlView (Views.loginPage false)
route "/Account/RegisterThanks" >=> htmlView Views.thanksForRegisteringPage
route "/Account/Verify" >=> emailVerificationHandler
mustBeLoggedIn >=> route "/User" >=> userPageHandler
]
POST >=> requiresCsrfToken (setStatusCode 403 >=> text "Forbidden") >=>
choose [
route "/Account/Register" >=> registerHandler
route "/Account/Login" >=> loginHandler
route "/Account/Logout" >=> logoutHandler
]
setStatusCode 404 >=> text "Not Found" ]
// ---------------------------------
// Error handler
// ---------------------------------
let errorHandler (ex : Exception) (logger : ILogger) =
logger.LogError(ex, "An unhandled exception has occurred while executing the request.")
clearResponse >=> setStatusCode 500 >=> text ex.Message
// ---------------------------------
// Config and Main
// ---------------------------------
let configureCors (builder : CorsPolicyBuilder) =
builder
.WithOrigins(
"http://localhost:5000",
"https://localhost:5001")
.AllowAnyMethod()
.AllowAnyHeader()
|> ignore
let configureApp (app : IApplicationBuilder) =
let env = app.ApplicationServices.GetService<IWebHostEnvironment>()
(match env.IsDevelopment() with
| true ->
app.UseDeveloperExceptionPage()
| false ->
app .UseGiraffeErrorHandler(errorHandler)
.UseHttpsRedirection())
.UseCors(configureCors)
.UseStaticFiles()
.UseAuthentication()
// .UseAuthorization()
.UseGiraffe(webApp)
let configureServices (services : IServiceCollection) =
services.AddCors() |> ignore
services.AddGiraffe() |> ignore
services.AddDbContext<MyDbContext.ApplicationDbContext>(fun options ->
options.UseSqlite("Filename=identity.db") |> ignore
) |> ignore
// IdentityUser, IdentityRole from MS.ASP.Identity
services.AddIdentity<IdentityUser, IdentityRole>(fun options ->
options.Password.RequireLowercase <- true
options.Password.RequireUppercase <- true
options.Password.RequireDigit <- true
options.Lockout.MaxFailedAccessAttempts <- 5
options.Lockout.DefaultLockoutTimeSpan <- TimeSpan.FromMinutes(15)
options.User.RequireUniqueEmail <- true
// options.SignIn.RequireConfirmedEmail <- true;
)
// tell asp.net identity to use the above store
.AddEntityFrameworkStores<MyDbContext.ApplicationDbContext>()
.AddDefaultTokenProviders() // need for email verification token generation
|> ignore
services.AddAntiforgery() |> ignore
services.ConfigureApplicationCookie(fun options ->
options.LoginPath <- "/Account/Login"
options.AccessDeniedPath <- "/Account/AccessDenied")
|> ignore
let configureLogging (builder : ILoggingBuilder) =
builder.AddConsole()
.AddDebug() |> ignore
[<EntryPoint>]
let main args =
let contentRoot = Directory.GetCurrentDirectory()
let webRoot = Path.Combine(contentRoot, "WebRoot")
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(
fun webHostBuilder ->
webHostBuilder
.UseContentRoot(contentRoot)
.UseWebRoot(webRoot)
.Configure(Action<IApplicationBuilder> configureApp)
.ConfigureServices(configureServices)
.ConfigureLogging(configureLogging)
|> ignore)
.Build()
.Run()
0