-
Notifications
You must be signed in to change notification settings - Fork 3
/
Common.fs
327 lines (260 loc) · 9.81 KB
/
Common.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
323
324
325
326
327
[<AutoOpen>]
module FreyaMusicStore.Common
open System
open Freya.Core
module Async =
let map f x = async { let! v = x in return f v }
module Option =
let fromNullable = function | null -> None | x -> Some x
module Either =
let Success = Choice1Of2
let Failure = Choice2Of2
let (|Success|Failure|) m =
match m with
| Choice1Of2 x -> Success x
| Choice2Of2 x -> Failure x
let bind f m =
match m with
| Success x -> f x
| Failure err -> Failure err
let toOption =
function Success x -> Some x | _ -> None
module Tuple =
let map f (x,y) = f x, f y
[<AutoOpen>]
module Utils =
let passHash (pass: string) =
use sha = Security.Cryptography.SHA256.Create()
Text.Encoding.UTF8.GetBytes(pass)
|> sha.ComputeHash
|> Array.map (fun b -> b.ToString("x2"))
|> String.concat ""
type MaybeBuilder() =
member __.Bind(m, f) = Option.bind f m
member __.Return(x) = Some x
member __.ReturnFrom(x) = x
let maybe = MaybeBuilder()
type Auth = {
UserName : string
Role : string
}
[<AutoOpen>]
module Katana =
open System.Security.Claims
open Microsoft.AspNet.Identity
open Microsoft.Owin
open Microsoft.Owin.Security
let getEnv: Freya<FreyaEnvironment> = (fun freyaState -> async { return freyaState.Environment, freyaState })
let toAuth (authResult: AuthenticateResult) =
maybe {
let! nameClaim = authResult.Identity.Claims |> Seq.tryFind (fun claim -> claim.Type = ClaimTypes.Name)
let! roleClaim = authResult.Identity.Claims |> Seq.tryFind (fun claim -> claim.Type = ClaimTypes.Role)
return {
UserName = nameClaim.Value
Role = roleClaim.Value
}
}
let authType = DefaultAuthenticationTypes.ApplicationCookie
let auth (ctx: OwinContext) =
ctx.Authentication.AuthenticateAsync(authType)
|> Async.AwaitTask
|> Async.map (Option.fromNullable >> Option.bind toAuth)
let ctxSignIn auth (ctx: OwinContext) =
let claims =
[ Claim(ClaimTypes.Role, auth.Role)
Claim(ClaimTypes.Name, auth.UserName) ]
ctx.Authentication.SignIn(ClaimsIdentity(claims, authType))
let ctxSignOut (ctx: OwinContext) =
ctx.Authentication.SignOut(authType)
let owinContext = getEnv |> Freya.map (fun env -> OwinContext(env))
let setResponseCookie key value = owinContext |> Freya.map (fun ctx -> ctx.Response.Cookies.Append(key, value))
let getRequestCookie key = owinContext |> Freya.map (fun ctx -> ctx.Request.Cookies.[key] |> Option.fromNullable)
let deleteResponseCookie key = owinContext |> Freya.map (fun ctx -> ctx.Response.Cookies.Delete(key, CookieOptions()))
let getAuth = owinContext |> Freya.bind (Freya.fromAsync auth) |> Freya.memo
let signIn auth = owinContext |> Freya.map (ctxSignIn auth)
let signOut = owinContext |> Freya.map ctxSignOut
let isAuthenticated = getAuth |> Freya.map Option.isSome
let isAdmin = getAuth |> Freya.map (Option.exists (fun auth -> auth.Role = "admin"))
[<AutoOpen>]
module Parsing =
open System.IO
open System.Globalization
open Arachne.Http
open Chiron
open Chiron.Operators
open Freya.Lenses.Http
let mInt (s: string) =
match Int32.TryParse s with
| true, x -> Some x
| _ -> None
let mDec (s: string) =
match Decimal.TryParse(s, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture) with
| true, x -> Some x
| _ -> None
let keyValue (s: string) =
match s.Split([| '=' |]) with
| [|k;v|] -> Some(k,v)
| _ -> None
let decode = System.Net.WebUtility.UrlDecode
let toMap (s: string) =
s.Split([| '&' |])
|> Array.choose keyValue
|> Array.map (Tuple.map decode)
|> Map.ofArray
let readStream (x: Stream) =
use reader = new StreamReader (x)
reader.ReadToEndAsync()
|> Async.AwaitTask
let query =
Freya.getLens Request.Query_
|> Freya.map (fun x -> let (Arachne.Uri.Query q) = x in q |> toMap)
|> Freya.memo
let body =
Freya.getLens Request.Body_
|> Freya.bind (Freya.fromAsync readStream)
let form =
body
|> Freya.map toMap
|> Freya.memo
type AlbumForm =
{ Title : string
ArtistId : int
GenreId : int
Price : decimal
AlbumArtUrl : string }
static member FromJson (_: AlbumForm) =
fun t a g p art ->
{ Title = t
ArtistId = a
GenreId = g
Price = p
AlbumArtUrl = art }
<!> Json.read "title"
<*> Json.read "artistId"
<*> Json.read "genreId"
<*> Json.read "price"
<*> Json.read "albumArtUrl"
let readAlbum =
freya {
let! contentType = Freya.getLensPartial Request.Headers.ContentType_
match contentType with
| Some (ContentType (MediaType (Type "application", SubType "x-www-form-urlencoded",_))) ->
let! form = form
let album =
maybe {
let! title = form |> Map.tryFind "Title"
let! artistId = form |> Map.tryFind "ArtistId" |> Option.bind mInt
let! genreId = form |> Map.tryFind "GenreId" |> Option.bind mInt
let! price = form |> Map.tryFind "Price" |> Option.bind mDec
let! albumArtUrl = form |> Map.tryFind "ArtUrl"
return
{ Title = title
ArtistId = artistId
GenreId = genreId
Price = price
AlbumArtUrl = albumArtUrl }
}
return album
| Some (ContentType m) when m = MediaType.Json ->
let! body = body
return (Json.tryParse body |> Either.bind Json.tryDeserialize |> Either.toOption)
| _ ->
return None
} |> Freya.memo
[<AutoOpen>]
module Representations =
open System.Text
open Arachne.Http
open Chiron
open Freya.Machine.Extensions.Http
open RazorEngine.Templating
let inline writeHtml (view : string, model : 'a) =
freya {
let! authResult = getAuth
let! cartId = getRequestCookie "cartId"
let albumsInCart cartId = Db.getCartsDetails cartId (Db.getContext()) |> List.sumBy (fun c -> c.Count)
let viewBag = DynamicViewBag()
match authResult, cartId with
| Some authResult, _ ->
viewBag.AddValue("CartItems", albumsInCart authResult.UserName)
viewBag.AddValue("UserName", authResult.UserName)
| _, Some cartId ->
viewBag.AddValue("CartItems", albumsInCart cartId)
viewBag.AddValue("CartId", cartId)
| _ ->
()
let result = RazorEngine.Engine.Razor.RunCompile(view, typeof<'a>, model, viewBag)
return {
Data = Encoding.UTF8.GetBytes result
Description =
{ Charset = Some Charset.Utf8
Encodings = None
MediaType = Some MediaType.Html
Languages = None } } }
let inline repJson x =
Freya.init
{ Data = (Json.serialize >> Json.format >> Encoding.UTF8.GetBytes) x
Description =
{ Charset = Some Charset.Utf8
Encodings = None
MediaType = Some MediaType.Json
Languages = None } }
let inline ok fetch name spec =
freya {
let ctx = Db.getContext()
let! fetch = fetch
let res = fetch ctx
return!
match spec.MediaTypes with
| Free -> repJson res
| Negotiated (m :: _) when m = MediaType.Json -> repJson res
| Negotiated (m :: _) when m = MediaType.Html -> writeHtml (name, res)
| _ -> failwith "Representation Failure"
}
module Logon =
type Logon = {
ReturnUrl : string
ValidationMsg : string
}
let onUnauthorized returnUrl _ =
freya {
let! returnUrl = returnUrl
return! writeHtml ("logon", {Logon.Logon.ReturnUrl = returnUrl; Logon.Logon.ValidationMsg = ""})
}
let onForbidden _ =
freya {
return! writeHtml ("forbidden", ())
}
[<AutoOpen>]
module Machine =
open Arachne.Http
open Freya.Machine
open Freya.Machine.Extensions.Http
open Freya.Lenses.Http
let common =
freyaMachine {
using http
mediaTypesSupported (Freya.init [MediaType.Html]) }
let inline res fetch name =
freyaMachine {
using http
mediaTypesSupported (Freya.init [MediaType.Html; MediaType.Json])
handleOk (ok fetch name) }
let onMeths meths f def =
freya {
let! meth = Freya.getLens Request.Method_
if meths |> List.exists ((=) meth) then
return! f
else
return def
}
let protectAuthenticated meths returnUrl =
freyaMachine {
authorized (onMeths meths isAuthenticated true)
handleUnauthorized (onUnauthorized returnUrl)
}
let protectAdmin meths =
freyaMachine {
allowed (onMeths meths isAdmin true)
handleForbidden onForbidden
}