Version 8 #43
|
@ -6,81 +6,85 @@ open PrayerTracker.Entities
|
|||
/// EF Core data context for PrayerTracker
|
||||
[<AllowNullLiteral>]
|
||||
type AppDbContext (options : DbContextOptions<AppDbContext>) =
|
||||
inherit DbContext (options)
|
||||
inherit DbContext (options)
|
||||
|
||||
[<DefaultValue>]
|
||||
val mutable private churches : DbSet<Church>
|
||||
[<DefaultValue>]
|
||||
val mutable private members : DbSet<Member>
|
||||
[<DefaultValue>]
|
||||
val mutable private prayerRequests : DbSet<PrayerRequest>
|
||||
[<DefaultValue>]
|
||||
val mutable private preferences : DbSet<ListPreferences>
|
||||
[<DefaultValue>]
|
||||
val mutable private smallGroups : DbSet<SmallGroup>
|
||||
[<DefaultValue>]
|
||||
val mutable private timeZones : DbSet<TimeZone>
|
||||
[<DefaultValue>]
|
||||
val mutable private users : DbSet<User>
|
||||
[<DefaultValue>]
|
||||
val mutable private userGroupXref : DbSet<UserSmallGroup>
|
||||
[<DefaultValue>]
|
||||
val mutable private churches : DbSet<Church>
|
||||
[<DefaultValue>]
|
||||
val mutable private members : DbSet<Member>
|
||||
[<DefaultValue>]
|
||||
val mutable private prayerRequests : DbSet<PrayerRequest>
|
||||
[<DefaultValue>]
|
||||
val mutable private preferences : DbSet<ListPreferences>
|
||||
[<DefaultValue>]
|
||||
val mutable private smallGroups : DbSet<SmallGroup>
|
||||
[<DefaultValue>]
|
||||
val mutable private timeZones : DbSet<TimeZone>
|
||||
[<DefaultValue>]
|
||||
val mutable private users : DbSet<User>
|
||||
[<DefaultValue>]
|
||||
val mutable private userGroupXref : DbSet<UserSmallGroup>
|
||||
|
||||
/// Churches
|
||||
member this.Churches
|
||||
with get() = this.churches
|
||||
and set v = this.churches <- v
|
||||
/// Churches
|
||||
member this.Churches
|
||||
with get() = this.churches
|
||||
and set v = this.churches <- v
|
||||
|
||||
/// Small group members
|
||||
member this.Members
|
||||
with get() = this.members
|
||||
and set v = this.members <- v
|
||||
/// Small group members
|
||||
member this.Members
|
||||
with get() = this.members
|
||||
and set v = this.members <- v
|
||||
|
||||
/// Prayer requests
|
||||
member this.PrayerRequests
|
||||
with get() = this.prayerRequests
|
||||
and set v = this.prayerRequests <- v
|
||||
/// Prayer requests
|
||||
member this.PrayerRequests
|
||||
with get() = this.prayerRequests
|
||||
and set v = this.prayerRequests <- v
|
||||
|
||||
/// Request list preferences (by class)
|
||||
member this.Preferences
|
||||
with get() = this.preferences
|
||||
and set v = this.preferences <- v
|
||||
/// Request list preferences (by class)
|
||||
member this.Preferences
|
||||
with get() = this.preferences
|
||||
and set v = this.preferences <- v
|
||||
|
||||
/// Small groups
|
||||
member this.SmallGroups
|
||||
with get() = this.smallGroups
|
||||
and set v = this.smallGroups <- v
|
||||
/// Small groups
|
||||
member this.SmallGroups
|
||||
with get() = this.smallGroups
|
||||
and set v = this.smallGroups <- v
|
||||
|
||||
/// Time zones
|
||||
member this.TimeZones
|
||||
with get() = this.timeZones
|
||||
and set v = this.timeZones <- v
|
||||
/// Time zones
|
||||
member this.TimeZones
|
||||
with get() = this.timeZones
|
||||
and set v = this.timeZones <- v
|
||||
|
||||
/// Users
|
||||
member this.Users
|
||||
with get() = this.users
|
||||
and set v = this.users <- v
|
||||
/// Users
|
||||
member this.Users
|
||||
with get() = this.users
|
||||
and set v = this.users <- v
|
||||
|
||||
/// User / small group cross-reference
|
||||
member this.UserGroupXref
|
||||
with get() = this.userGroupXref
|
||||
and set v = this.userGroupXref <- v
|
||||
/// User / small group cross-reference
|
||||
member this.UserGroupXref
|
||||
with get() = this.userGroupXref
|
||||
and set v = this.userGroupXref <- v
|
||||
|
||||
/// F#-style async for saving changes
|
||||
member this.AsyncSaveChanges () =
|
||||
this.SaveChangesAsync () |> Async.AwaitTask
|
||||
/// F#-style async for saving changes
|
||||
member this.AsyncSaveChanges () =
|
||||
this.SaveChangesAsync () |> Async.AwaitTask
|
||||
|
||||
override __.OnModelCreating (modelBuilder : ModelBuilder) =
|
||||
base.OnModelCreating modelBuilder
|
||||
override _.OnConfiguring (optionsBuilder : DbContextOptionsBuilder) =
|
||||
base.OnConfiguring optionsBuilder
|
||||
optionsBuilder.UseQueryTrackingBehavior QueryTrackingBehavior.NoTracking |> ignore
|
||||
|
||||
modelBuilder.HasDefaultSchema "pt" |> ignore
|
||||
override _.OnModelCreating (modelBuilder : ModelBuilder) =
|
||||
base.OnModelCreating modelBuilder
|
||||
|
||||
[ Church.configureEF
|
||||
ListPreferences.configureEF
|
||||
Member.configureEF
|
||||
PrayerRequest.configureEF
|
||||
SmallGroup.configureEF
|
||||
TimeZone.configureEF
|
||||
User.configureEF
|
||||
UserSmallGroup.configureEF
|
||||
]
|
||||
|> List.iter (fun x -> x modelBuilder)
|
||||
modelBuilder.HasDefaultSchema "pt" |> ignore
|
||||
|
||||
[ Church.configureEF
|
||||
ListPreferences.configureEF
|
||||
Member.configureEF
|
||||
PrayerRequest.configureEF
|
||||
SmallGroup.configureEF
|
||||
TimeZone.configureEF
|
||||
User.configureEF
|
||||
UserSmallGroup.configureEF
|
||||
]
|
||||
|> List.iter (fun x -> x modelBuilder)
|
||||
|
|
|
@ -1,380 +1,287 @@
|
|||
[<AutoOpen>]
|
||||
module PrayerTracker.DataAccess
|
||||
|
||||
open Microsoft.EntityFrameworkCore
|
||||
open PrayerTracker.Entities
|
||||
open System.Collections.Generic
|
||||
open System.Linq
|
||||
open PrayerTracker.Entities
|
||||
|
||||
[<AutoOpen>]
|
||||
module private Helpers =
|
||||
|
||||
open Microsoft.FSharpLu
|
||||
open System.Threading.Tasks
|
||||
/// Central place to append sort criteria for prayer request queries
|
||||
let reqSort sort (q : IQueryable<PrayerRequest>) =
|
||||
match sort with
|
||||
| SortByDate ->
|
||||
q.OrderByDescending(fun req -> req.updatedDate)
|
||||
.ThenByDescending(fun req -> req.enteredDate)
|
||||
.ThenBy (fun req -> req.requestor)
|
||||
| SortByRequestor ->
|
||||
q.OrderBy(fun req -> req.requestor)
|
||||
.ThenByDescending(fun req -> req.updatedDate)
|
||||
.ThenByDescending (fun req -> req.enteredDate)
|
||||
|
||||
/// Central place to append sort criteria for prayer request queries
|
||||
let reqSort sort (q : IQueryable<PrayerRequest>) =
|
||||
match sort with
|
||||
| SortByDate ->
|
||||
query {
|
||||
for req in q do
|
||||
sortByDescending req.updatedDate
|
||||
thenByDescending req.enteredDate
|
||||
thenBy req.requestor
|
||||
}
|
||||
| SortByRequestor ->
|
||||
query {
|
||||
for req in q do
|
||||
sortBy req.requestor
|
||||
thenByDescending req.updatedDate
|
||||
thenByDescending req.enteredDate
|
||||
}
|
||||
/// Paginate a prayer request query
|
||||
let paginate pageNbr pageSize (q : IQueryable<PrayerRequest>) =
|
||||
q.Skip((pageNbr - 1) * pageSize).Take pageSize
|
||||
|
||||
/// Convert a possibly-null object to an option, wrapped as a task
|
||||
let toOptionTask<'T> (item : 'T) = (Option.fromObject >> Task.FromResult) item
|
||||
|
||||
open System.Collections.Generic
|
||||
open Microsoft.EntityFrameworkCore
|
||||
open Microsoft.FSharpLu
|
||||
|
||||
type AppDbContext with
|
||||
|
||||
(*-- DISCONNECTED DATA EXTENSIONS --*)
|
||||
(*-- DISCONNECTED DATA EXTENSIONS --*)
|
||||
|
||||
/// Add an entity entry to the tracked data context with the status of Added
|
||||
member this.AddEntry<'TEntity when 'TEntity : not struct> (e : 'TEntity) =
|
||||
this.Entry<'TEntity>(e).State <- EntityState.Added
|
||||
/// Add an entity entry to the tracked data context with the status of Added
|
||||
member this.AddEntry<'TEntity when 'TEntity : not struct> (e : 'TEntity) =
|
||||
this.Entry<'TEntity>(e).State <- EntityState.Added
|
||||
|
||||
/// Add an entity entry to the tracked data context with the status of Updated
|
||||
member this.UpdateEntry<'TEntity when 'TEntity : not struct> (e : 'TEntity) =
|
||||
this.Entry<'TEntity>(e).State <- EntityState.Modified
|
||||
/// Add an entity entry to the tracked data context with the status of Updated
|
||||
member this.UpdateEntry<'TEntity when 'TEntity : not struct> (e : 'TEntity) =
|
||||
this.Entry<'TEntity>(e).State <- EntityState.Modified
|
||||
|
||||
/// Add an entity entry to the tracked data context with the status of Deleted
|
||||
member this.RemoveEntry<'TEntity when 'TEntity : not struct> (e : 'TEntity) =
|
||||
this.Entry<'TEntity>(e).State <- EntityState.Deleted
|
||||
/// Add an entity entry to the tracked data context with the status of Deleted
|
||||
member this.RemoveEntry<'TEntity when 'TEntity : not struct> (e : 'TEntity) =
|
||||
this.Entry<'TEntity>(e).State <- EntityState.Deleted
|
||||
|
||||
(*-- CHURCH EXTENSIONS --*)
|
||||
(*-- CHURCH EXTENSIONS --*)
|
||||
|
||||
/// Find a church by its Id
|
||||
member this.TryChurchById cId =
|
||||
query {
|
||||
for ch in this.Churches.AsNoTracking () do
|
||||
where (ch.churchId = cId)
|
||||
exactlyOneOrDefault
|
||||
}
|
||||
|> toOptionTask
|
||||
/// Find a church by its Id
|
||||
member this.TryChurchById cId = backgroundTask {
|
||||
let! church = this.Churches.SingleOrDefaultAsync (fun ch -> ch.churchId = cId)
|
||||
return Option.fromObject church
|
||||
}
|
||||
|
||||
/// Find all churches
|
||||
member this.AllChurches () =
|
||||
task {
|
||||
let q =
|
||||
query {
|
||||
for ch in this.Churches.AsNoTracking () do
|
||||
sortBy ch.name
|
||||
}
|
||||
let! churches = q.ToListAsync ()
|
||||
return List.ofSeq churches
|
||||
}
|
||||
/// Find all churches
|
||||
member this.AllChurches () = backgroundTask {
|
||||
let! churches = this.Churches.OrderBy(fun ch -> ch.name).ToListAsync ()
|
||||
return List.ofSeq churches
|
||||
}
|
||||
|
||||
(*-- MEMBER EXTENSIONS --*)
|
||||
(*-- MEMBER EXTENSIONS --*)
|
||||
|
||||
/// Get a small group member by its Id
|
||||
member this.TryMemberById mId =
|
||||
query {
|
||||
for mbr in this.Members.AsNoTracking () do
|
||||
where (mbr.memberId = mId)
|
||||
select mbr
|
||||
exactlyOneOrDefault
|
||||
}
|
||||
|> toOptionTask
|
||||
/// Get a small group member by its Id
|
||||
member this.TryMemberById mbrId = backgroundTask {
|
||||
let! mbr = this.Members.SingleOrDefaultAsync (fun m -> m.memberId = mbrId)
|
||||
return Option.fromObject mbr
|
||||
}
|
||||
|
||||
/// Find all members for a small group
|
||||
member this.AllMembersForSmallGroup gId =
|
||||
task {
|
||||
let q =
|
||||
query {
|
||||
for mbr in this.Members.AsNoTracking () do
|
||||
where (mbr.smallGroupId = gId)
|
||||
sortBy mbr.memberName
|
||||
}
|
||||
let! mbrs = q.ToListAsync ()
|
||||
return List.ofSeq mbrs
|
||||
}
|
||||
/// Find all members for a small group
|
||||
member this.AllMembersForSmallGroup gId = backgroundTask {
|
||||
let! members =
|
||||
this.Members.Where(fun mbr -> mbr.smallGroupId = gId)
|
||||
.OrderBy(fun mbr -> mbr.memberName)
|
||||
.ToListAsync ()
|
||||
return List.ofSeq members
|
||||
}
|
||||
|
||||
/// Count members for a small group
|
||||
member this.CountMembersForSmallGroup gId =
|
||||
this.Members.CountAsync (fun m -> m.smallGroupId = gId)
|
||||
/// Count members for a small group
|
||||
member this.CountMembersForSmallGroup gId = backgroundTask {
|
||||
return! this.Members.CountAsync (fun m -> m.smallGroupId = gId)
|
||||
}
|
||||
|
||||
(*-- PRAYER REQUEST EXTENSIONS --*)
|
||||
(*-- PRAYER REQUEST EXTENSIONS --*)
|
||||
|
||||
/// Get a prayer request by its Id
|
||||
member this.TryRequestById reqId =
|
||||
query {
|
||||
for req in this.PrayerRequests.AsNoTracking () do
|
||||
where (req.prayerRequestId = reqId)
|
||||
exactlyOneOrDefault
|
||||
}
|
||||
|> toOptionTask
|
||||
/// Get a prayer request by its Id
|
||||
member this.TryRequestById reqId = backgroundTask {
|
||||
let! req = this.PrayerRequests.SingleOrDefaultAsync (fun r -> r.prayerRequestId = reqId)
|
||||
return Option.fromObject req
|
||||
}
|
||||
|
||||
/// Get all (or active) requests for a small group as of now or the specified date
|
||||
// TODO: why not make this an async list like the rest of these methods?
|
||||
member this.AllRequestsForSmallGroup (grp : SmallGroup) clock listDate activeOnly pageNbr : PrayerRequest seq =
|
||||
let theDate = match listDate with Some dt -> dt | _ -> grp.localDateNow clock
|
||||
query {
|
||||
for req in this.PrayerRequests.AsNoTracking () do
|
||||
where (req.smallGroupId = grp.smallGroupId)
|
||||
}
|
||||
|> function
|
||||
| q when activeOnly ->
|
||||
let asOf = theDate.AddDays(-(float grp.preferences.daysToExpire)).Date
|
||||
query {
|
||||
for req in q do
|
||||
where ( ( req.updatedDate > asOf
|
||||
|| req.expiration = Manual
|
||||
|| req.requestType = LongTermRequest
|
||||
|| req.requestType = Expecting)
|
||||
&& req.expiration <> Forced)
|
||||
}
|
||||
| q -> q
|
||||
|> reqSort grp.preferences.requestSort
|
||||
|> function
|
||||
| q ->
|
||||
match activeOnly with
|
||||
| true -> upcast q
|
||||
| false ->
|
||||
upcast query {
|
||||
for req in q do
|
||||
skip ((pageNbr - 1) * grp.preferences.pageSize)
|
||||
take grp.preferences.pageSize
|
||||
}
|
||||
/// Get all (or active) requests for a small group as of now or the specified date
|
||||
member this.AllRequestsForSmallGroup (grp : SmallGroup) clock listDate activeOnly pageNbr = backgroundTask {
|
||||
let theDate = match listDate with Some dt -> dt | _ -> grp.localDateNow clock
|
||||
let query =
|
||||
this.PrayerRequests.Where(fun req -> req.smallGroupId = grp.smallGroupId)
|
||||
|> function
|
||||
| q when activeOnly ->
|
||||
let asOf = theDate.AddDays(-(float grp.preferences.daysToExpire)).Date
|
||||
q.Where(fun req ->
|
||||
( req.updatedDate > asOf
|
||||
|| req.expiration = Manual
|
||||
|| req.requestType = LongTermRequest
|
||||
|| req.requestType = Expecting)
|
||||
&& req.expiration <> Forced)
|
||||
|> reqSort grp.preferences.requestSort
|
||||
|> paginate pageNbr grp.preferences.pageSize
|
||||
| q -> reqSort grp.preferences.requestSort q
|
||||
let! reqs = query.ToListAsync ()
|
||||
return List.ofSeq reqs
|
||||
}
|
||||
|
||||
/// Count prayer requests for the given small group Id
|
||||
member this.CountRequestsBySmallGroup gId =
|
||||
this.PrayerRequests.CountAsync (fun pr -> pr.smallGroupId = gId)
|
||||
/// Count prayer requests for the given small group Id
|
||||
member this.CountRequestsBySmallGroup gId = backgroundTask {
|
||||
return! this.PrayerRequests.CountAsync (fun pr -> pr.smallGroupId = gId)
|
||||
}
|
||||
|
||||
/// Count prayer requests for the given church Id
|
||||
member this.CountRequestsByChurch cId =
|
||||
this.PrayerRequests.CountAsync (fun pr -> pr.smallGroup.churchId = cId)
|
||||
/// Count prayer requests for the given church Id
|
||||
member this.CountRequestsByChurch cId = backgroundTask {
|
||||
return! this.PrayerRequests.CountAsync (fun pr -> pr.smallGroup.churchId = cId)
|
||||
}
|
||||
|
||||
/// Get all (or active) requests for a small group as of now or the specified date
|
||||
// TODO: same as above...
|
||||
member this.SearchRequestsForSmallGroup (grp : SmallGroup) (searchTerm : string) pageNbr : PrayerRequest seq =
|
||||
let pgSz = grp.preferences.pageSize
|
||||
let toSkip = (pageNbr - 1) * pgSz
|
||||
let sql =
|
||||
""" SELECT * FROM pt."PrayerRequest" WHERE "SmallGroupId" = {0} AND "Text" ILIKE {1}
|
||||
/// Get all (or active) requests for a small group as of now or the specified date
|
||||
member this.SearchRequestsForSmallGroup (grp : SmallGroup) (searchTerm : string) pageNbr = backgroundTask {
|
||||
let sql = """
|
||||
SELECT * FROM pt."PrayerRequest" WHERE "SmallGroupId" = {0} AND "Text" ILIKE {1}
|
||||
UNION
|
||||
SELECT * FROM pt."PrayerRequest" WHERE "SmallGroupId" = {0} AND COALESCE("Requestor", '') ILIKE {1}"""
|
||||
let like = sprintf "%%%s%%"
|
||||
this.PrayerRequests.FromSqlRaw(sql, grp.smallGroupId, like searchTerm).AsNoTracking ()
|
||||
|> reqSort grp.preferences.requestSort
|
||||
|> function
|
||||
| q ->
|
||||
upcast query {
|
||||
for req in q do
|
||||
skip toSkip
|
||||
take pgSz
|
||||
}
|
||||
SELECT * FROM pt."PrayerRequest" WHERE "SmallGroupId" = {0} AND COALESCE("Requestor", '') ILIKE {1}"""
|
||||
let like = sprintf "%%%s%%"
|
||||
let query =
|
||||
this.PrayerRequests.FromSqlRaw(sql, grp.smallGroupId, like searchTerm)
|
||||
|> reqSort grp.preferences.requestSort
|
||||
|> paginate pageNbr grp.preferences.pageSize
|
||||
let! reqs = query.ToListAsync ()
|
||||
return List.ofSeq reqs
|
||||
}
|
||||
|
||||
(*-- SMALL GROUP EXTENSIONS --*)
|
||||
(*-- SMALL GROUP EXTENSIONS --*)
|
||||
|
||||
/// Find a small group by its Id
|
||||
member this.TryGroupById gId =
|
||||
query {
|
||||
for grp in this.SmallGroups.AsNoTracking().Include (fun sg -> sg.preferences) do
|
||||
where (grp.smallGroupId = gId)
|
||||
exactlyOneOrDefault
|
||||
}
|
||||
|> toOptionTask
|
||||
/// Find a small group by its Id
|
||||
member this.TryGroupById gId = backgroundTask {
|
||||
let! grp =
|
||||
this.SmallGroups.Include(fun sg -> sg.preferences)
|
||||
.SingleOrDefaultAsync (fun sg -> sg.smallGroupId = gId)
|
||||
return Option.fromObject grp
|
||||
}
|
||||
|
||||
/// Get small groups that are public or password protected
|
||||
member this.PublicAndProtectedGroups () =
|
||||
task {
|
||||
let smallGroups = this.SmallGroups.AsNoTracking().Include(fun sg -> sg.preferences).Include (fun sg -> sg.church)
|
||||
let q =
|
||||
query {
|
||||
for grp in smallGroups do
|
||||
where ( grp.preferences.isPublic
|
||||
|| (grp.preferences.groupPassword <> null && grp.preferences.groupPassword <> ""))
|
||||
sortBy grp.church.name
|
||||
thenBy grp.name
|
||||
}
|
||||
let! grps = q.ToListAsync ()
|
||||
return List.ofSeq grps
|
||||
}
|
||||
/// Get small groups that are public or password protected
|
||||
member this.PublicAndProtectedGroups () = backgroundTask {
|
||||
let! groups =
|
||||
this.SmallGroups.Include(fun sg -> sg.preferences).Include(fun sg -> sg.church)
|
||||
.Where(fun sg ->
|
||||
sg.preferences.isPublic
|
||||
|| (sg.preferences.groupPassword <> null && sg.preferences.groupPassword <> ""))
|
||||
.OrderBy(fun sg -> sg.church.name).ThenBy(fun sg -> sg.name)
|
||||
.ToListAsync ()
|
||||
return List.ofSeq groups
|
||||
}
|
||||
|
||||
/// Get small groups that are password protected
|
||||
member this.ProtectedGroups () =
|
||||
task {
|
||||
let q =
|
||||
query {
|
||||
for grp in this.SmallGroups.AsNoTracking().Include (fun sg -> sg.church) do
|
||||
where (grp.preferences.groupPassword <> null && grp.preferences.groupPassword <> "")
|
||||
sortBy grp.church.name
|
||||
thenBy grp.name
|
||||
}
|
||||
let! grps = q.ToListAsync ()
|
||||
return List.ofSeq grps
|
||||
}
|
||||
/// Get small groups that are password protected
|
||||
member this.ProtectedGroups () = backgroundTask {
|
||||
let! groups =
|
||||
this.SmallGroups.Include(fun sg -> sg.church)
|
||||
.Where(fun sg -> sg.preferences.groupPassword <> null && sg.preferences.groupPassword <> "")
|
||||
.OrderBy(fun sg -> sg.church.name).ThenBy(fun sg -> sg.name)
|
||||
.ToListAsync ()
|
||||
return List.ofSeq groups
|
||||
}
|
||||
|
||||
/// Get all small groups
|
||||
member this.AllGroups () =
|
||||
task {
|
||||
let! grps =
|
||||
this.SmallGroups.AsNoTracking()
|
||||
.Include(fun sg -> sg.church)
|
||||
.Include(fun sg -> sg.preferences)
|
||||
.Include(fun sg -> sg.preferences.timeZone)
|
||||
.OrderBy(fun sg -> sg.name)
|
||||
.ToListAsync ()
|
||||
return List.ofSeq grps
|
||||
}
|
||||
/// Get all small groups
|
||||
member this.AllGroups () = backgroundTask {
|
||||
let! groups =
|
||||
this.SmallGroups
|
||||
.Include(fun sg -> sg.church)
|
||||
.Include(fun sg -> sg.preferences)
|
||||
.Include(fun sg -> sg.preferences.timeZone)
|
||||
.OrderBy(fun sg -> sg.name)
|
||||
.ToListAsync ()
|
||||
return List.ofSeq groups
|
||||
}
|
||||
|
||||
/// Get a small group list by their Id, with their church prepended to their name
|
||||
member this.GroupList () =
|
||||
task {
|
||||
let q =
|
||||
query {
|
||||
for grp in this.SmallGroups.AsNoTracking().Include (fun sg -> sg.church) do
|
||||
sortBy grp.church.name
|
||||
thenBy grp.name
|
||||
}
|
||||
let! grps = q.ToListAsync ()
|
||||
return grps
|
||||
|> Seq.map (fun grp -> grp.smallGroupId.ToString "N", $"{grp.church.name} | {grp.name}")
|
||||
|> List.ofSeq
|
||||
}
|
||||
/// Get a small group list by their Id, with their church prepended to their name
|
||||
member this.GroupList () = backgroundTask {
|
||||
let! groups =
|
||||
this.SmallGroups.Include(fun sg -> sg.church)
|
||||
.OrderBy(fun sg -> sg.church.name).ThenBy(fun sg -> sg.name)
|
||||
.ToListAsync ()
|
||||
return groups
|
||||
|> Seq.map (fun sg -> sg.smallGroupId.ToString "N", $"{sg.church.name} | {sg.name}")
|
||||
|> List.ofSeq
|
||||
}
|
||||
|
||||
/// Log on a small group
|
||||
member this.TryGroupLogOnByPassword gId pw =
|
||||
task {
|
||||
match! this.TryGroupById gId with
|
||||
| None -> return None
|
||||
| Some grp ->
|
||||
match pw = grp.preferences.groupPassword with
|
||||
| true -> return Some grp
|
||||
| _ -> return None
|
||||
}
|
||||
/// Log on a small group
|
||||
member this.TryGroupLogOnByPassword gId pw = backgroundTask {
|
||||
match! this.TryGroupById gId with
|
||||
| None -> return None
|
||||
| Some grp -> return if pw = grp.preferences.groupPassword then Some grp else None
|
||||
}
|
||||
|
||||
/// Check a cookie log on for a small group
|
||||
member this.TryGroupLogOnByCookie gId pwHash (hasher : string -> string) =
|
||||
task {
|
||||
match! this.TryGroupById gId with
|
||||
| None -> return None
|
||||
| Some grp ->
|
||||
match pwHash = hasher grp.preferences.groupPassword with
|
||||
| true -> return Some grp
|
||||
| _ -> return None
|
||||
}
|
||||
/// Check a cookie log on for a small group
|
||||
member this.TryGroupLogOnByCookie gId pwHash (hasher : string -> string) = backgroundTask {
|
||||
match! this.TryGroupById gId with
|
||||
| None -> return None
|
||||
| Some grp -> return if pwHash = hasher grp.preferences.groupPassword then Some grp else None
|
||||
}
|
||||
|
||||
/// Count small groups for the given church Id
|
||||
member this.CountGroupsByChurch cId =
|
||||
this.SmallGroups.CountAsync (fun sg -> sg.churchId = cId)
|
||||
/// Count small groups for the given church Id
|
||||
member this.CountGroupsByChurch cId = backgroundTask {
|
||||
return! this.SmallGroups.CountAsync (fun sg -> sg.churchId = cId)
|
||||
}
|
||||
|
||||
(*-- TIME ZONE EXTENSIONS --*)
|
||||
(*-- TIME ZONE EXTENSIONS --*)
|
||||
|
||||
/// Get a time zone by its Id
|
||||
member this.TryTimeZoneById tzId =
|
||||
query {
|
||||
for tz in this.TimeZones do
|
||||
where (tz.timeZoneId = tzId)
|
||||
exactlyOneOrDefault
|
||||
}
|
||||
|> toOptionTask
|
||||
/// Get a time zone by its Id
|
||||
member this.TryTimeZoneById tzId = backgroundTask {
|
||||
let! zone = this.TimeZones.SingleOrDefaultAsync (fun tz -> tz.timeZoneId = tzId)
|
||||
return Option.fromObject zone
|
||||
}
|
||||
|
||||
/// Get all time zones
|
||||
member this.AllTimeZones () =
|
||||
task {
|
||||
let q =
|
||||
query {
|
||||
for tz in this.TimeZones do
|
||||
sortBy tz.sortOrder
|
||||
}
|
||||
let! tzs = q.ToListAsync ()
|
||||
return List.ofSeq tzs
|
||||
}
|
||||
/// Get all time zones
|
||||
member this.AllTimeZones () = backgroundTask {
|
||||
let! zones = this.TimeZones.OrderBy(fun tz -> tz.sortOrder).ToListAsync ()
|
||||
return List.ofSeq zones
|
||||
}
|
||||
|
||||
(*-- USER EXTENSIONS --*)
|
||||
(*-- USER EXTENSIONS --*)
|
||||
|
||||
/// Find a user by its Id
|
||||
member this.TryUserById uId =
|
||||
query {
|
||||
for usr in this.Users.AsNoTracking () do
|
||||
where (usr.userId = uId)
|
||||
exactlyOneOrDefault
|
||||
}
|
||||
|> toOptionTask
|
||||
/// Find a user by its Id
|
||||
member this.TryUserById uId = backgroundTask {
|
||||
let! usr = this.Users.SingleOrDefaultAsync (fun u -> u.userId = uId)
|
||||
return Option.fromObject usr
|
||||
}
|
||||
|
||||
/// Find a user by its e-mail address and authorized small group
|
||||
member this.TryUserByEmailAndGroup email gId =
|
||||
query {
|
||||
for usr in this.Users.AsNoTracking () do
|
||||
where (usr.emailAddress = email && usr.smallGroups.Any (fun xref -> xref.smallGroupId = gId))
|
||||
exactlyOneOrDefault
|
||||
}
|
||||
|> toOptionTask
|
||||
/// Find a user by its e-mail address and authorized small group
|
||||
member this.TryUserByEmailAndGroup email gId = backgroundTask {
|
||||
let! usr =
|
||||
this.Users.SingleOrDefaultAsync (fun u ->
|
||||
u.emailAddress = email && u.smallGroups.Any (fun xref -> xref.smallGroupId = gId))
|
||||
return Option.fromObject usr
|
||||
}
|
||||
|
||||
/// Find a user by its Id (tracked entity), eagerly loading the user's groups
|
||||
member this.TryUserByIdWithGroups uId =
|
||||
query {
|
||||
for usr in this.Users.AsNoTracking().Include (fun u -> u.smallGroups) do
|
||||
where (usr.userId = uId)
|
||||
exactlyOneOrDefault
|
||||
}
|
||||
|> toOptionTask
|
||||
/// Find a user by its Id, eagerly loading the user's groups
|
||||
member this.TryUserByIdWithGroups uId = backgroundTask {
|
||||
let! usr = this.Users.Include(fun u -> u.smallGroups).SingleOrDefaultAsync (fun u -> u.userId = uId)
|
||||
return Option.fromObject usr
|
||||
}
|
||||
|
||||
/// Get a list of all users
|
||||
member this.AllUsers () =
|
||||
task {
|
||||
let q =
|
||||
query {
|
||||
for usr in this.Users.AsNoTracking () do
|
||||
sortBy usr.lastName
|
||||
thenBy usr.firstName
|
||||
}
|
||||
let! usrs = q.ToListAsync ()
|
||||
return List.ofSeq usrs
|
||||
}
|
||||
/// Get a list of all users
|
||||
member this.AllUsers () = backgroundTask {
|
||||
let! users = this.Users.OrderBy(fun u -> u.lastName).ThenBy(fun u -> u.firstName).ToListAsync ()
|
||||
return List.ofSeq users
|
||||
}
|
||||
|
||||
/// Get all PrayerTracker users as members (used to send e-mails)
|
||||
member this.AllUsersAsMembers () =
|
||||
task {
|
||||
let q =
|
||||
query {
|
||||
for usr in this.Users.AsNoTracking () do
|
||||
sortBy usr.lastName
|
||||
thenBy usr.firstName
|
||||
select { Member.empty with email = usr.emailAddress; memberName = usr.fullName }
|
||||
}
|
||||
let! usrs = q.ToListAsync ()
|
||||
return List.ofSeq usrs
|
||||
}
|
||||
/// Get all PrayerTracker users as members (used to send e-mails)
|
||||
member this.AllUsersAsMembers () = backgroundTask {
|
||||
let! users = this.AllUsers ()
|
||||
return users |> List.map (fun u -> { Member.empty with email = u.emailAddress; memberName = u.fullName })
|
||||
}
|
||||
|
||||
/// Find a user based on their credentials
|
||||
member this.TryUserLogOnByPassword email pwHash gId =
|
||||
query {
|
||||
for usr in this.Users.AsNoTracking () do
|
||||
where ( usr.emailAddress = email
|
||||
&& usr.passwordHash = pwHash
|
||||
&& usr.smallGroups.Any (fun xref -> xref.smallGroupId = gId))
|
||||
exactlyOneOrDefault
|
||||
}
|
||||
|> toOptionTask
|
||||
/// Find a user based on their credentials
|
||||
member this.TryUserLogOnByPassword email pwHash gId = backgroundTask {
|
||||
let! usr =
|
||||
this.Users.SingleOrDefaultAsync (fun u ->
|
||||
u.emailAddress = email
|
||||
&& u.passwordHash = pwHash
|
||||
&& u.smallGroups.Any (fun xref -> xref.smallGroupId = gId))
|
||||
return Option.fromObject usr
|
||||
}
|
||||
|
||||
/// Find a user based on credentials stored in a cookie
|
||||
member this.TryUserLogOnByCookie uId gId pwHash =
|
||||
task {
|
||||
match! this.TryUserByIdWithGroups uId with
|
||||
| None -> return None
|
||||
| Some usr ->
|
||||
match pwHash = usr.passwordHash && usr.smallGroups |> Seq.exists (fun xref -> xref.smallGroupId = gId) with
|
||||
| true ->
|
||||
this.Entry<User>(usr).State <- EntityState.Detached
|
||||
return Some { usr with passwordHash = ""; salt = None; smallGroups = List<UserSmallGroup>() }
|
||||
| _ -> return None
|
||||
}
|
||||
/// Find a user based on credentials stored in a cookie
|
||||
member this.TryUserLogOnByCookie uId gId pwHash = backgroundTask {
|
||||
match! this.TryUserByIdWithGroups uId with
|
||||
| None -> return None
|
||||
| Some usr ->
|
||||
if pwHash = usr.passwordHash && usr.smallGroups |> Seq.exists (fun xref -> xref.smallGroupId = gId) then
|
||||
return Some { usr with passwordHash = ""; salt = None; smallGroups = List<UserSmallGroup>() }
|
||||
else return None
|
||||
}
|
||||
|
||||
/// Count the number of users for a small group
|
||||
member this.CountUsersBySmallGroup gId =
|
||||
this.Users.CountAsync (fun u -> u.smallGroups.Any (fun xref -> xref.smallGroupId = gId))
|
||||
/// Count the number of users for a small group
|
||||
member this.CountUsersBySmallGroup gId = backgroundTask {
|
||||
return! this.Users.CountAsync (fun u -> u.smallGroups.Any (fun xref -> xref.smallGroupId = gId))
|
||||
}
|
||||
|
||||
/// Count the number of users for a church
|
||||
member this.CountUsersByChurch cId =
|
||||
this.Users.CountAsync (fun u -> u.smallGroups.Any (fun xref -> xref.smallGroup.churchId = cId))
|
||||
/// Count the number of users for a church
|
||||
member this.CountUsersByChurch cId = backgroundTask {
|
||||
return! this.Users.CountAsync (fun u -> u.smallGroups.Any (fun xref -> xref.smallGroup.churchId = cId))
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -2,4 +2,4 @@
|
|||
|
||||
[<EntryPoint>]
|
||||
let main argv =
|
||||
runTestsInAssembly defaultConfig argv
|
||||
runTestsInAssembly defaultConfig argv
|
||||
|
|
|
@ -5,189 +5,192 @@ open PrayerTracker
|
|||
|
||||
[<Tests>]
|
||||
let ckEditorToTextTests =
|
||||
testList "ckEditorToText" [
|
||||
test "replaces newline/tab sequence with nothing" {
|
||||
Expect.equal (ckEditorToText "Here is some \n\ttext") "Here is some text"
|
||||
"Newline/tab sequence should have been removed"
|
||||
}
|
||||
test "replaces with a space" {
|
||||
Expect.equal (ckEditorToText "Test text") "Test text" " should have been replaced with a space"
|
||||
}
|
||||
test "replaces double space with one non-breaking space and one regular space" {
|
||||
Expect.equal (ckEditorToText "Test text") "Test  text"
|
||||
"double space should have been replaced with one non-breaking space and one regular space"
|
||||
}
|
||||
test "replaces paragraph break with two line breaks" {
|
||||
Expect.equal (ckEditorToText "some</p><p>text") "some<br><br>text"
|
||||
"paragraph break should have been replaced with two line breaks"
|
||||
}
|
||||
test "removes start and end paragraph tags" {
|
||||
Expect.equal (ckEditorToText "<p>something something</p>") "something something"
|
||||
"start/end paragraph tags should have been removed"
|
||||
}
|
||||
test "trims the result" {
|
||||
Expect.equal (ckEditorToText " abc ") "abc" "Should have trimmed the resulting text"
|
||||
}
|
||||
test "does all the replacements and removals at one time" {
|
||||
Expect.equal (ckEditorToText " <p>Paragraph 1\n\t line two</p><p>Paragraph 2 x</p>")
|
||||
"Paragraph 1 line two<br><br>Paragraph 2  x"
|
||||
"all replacements and removals were not made correctly"
|
||||
}
|
||||
testList "ckEditorToText" [
|
||||
test "replaces newline/tab sequence with nothing" {
|
||||
Expect.equal (ckEditorToText "Here is some \n\ttext") "Here is some text"
|
||||
"Newline/tab sequence should have been removed"
|
||||
}
|
||||
test "replaces with a space" {
|
||||
Expect.equal (ckEditorToText "Test text") "Test text" " should have been replaced with a space"
|
||||
}
|
||||
test "replaces double space with one non-breaking space and one regular space" {
|
||||
Expect.equal (ckEditorToText "Test text") "Test  text"
|
||||
"double space should have been replaced with one non-breaking space and one regular space"
|
||||
}
|
||||
test "replaces paragraph break with two line breaks" {
|
||||
Expect.equal (ckEditorToText "some</p><p>text") "some<br><br>text"
|
||||
"paragraph break should have been replaced with two line breaks"
|
||||
}
|
||||
test "removes start and end paragraph tags" {
|
||||
Expect.equal (ckEditorToText "<p>something something</p>") "something something"
|
||||
"start/end paragraph tags should have been removed"
|
||||
}
|
||||
test "trims the result" {
|
||||
Expect.equal (ckEditorToText " abc ") "abc" "Should have trimmed the resulting text"
|
||||
}
|
||||
test "does all the replacements and removals at one time" {
|
||||
Expect.equal (ckEditorToText " <p>Paragraph 1\n\t line two</p><p>Paragraph 2 x</p>")
|
||||
"Paragraph 1 line two<br><br>Paragraph 2  x"
|
||||
"all replacements and removals were not made correctly"
|
||||
}
|
||||
]
|
||||
|
||||
[<Tests>]
|
||||
let htmlToPlainTextTests =
|
||||
testList "htmlToPlainText" [
|
||||
test "decodes HTML-encoded entities" {
|
||||
Expect.equal (htmlToPlainText "1 > 0") "1 > 0" "HTML-encoded entities should have been decoded"
|
||||
}
|
||||
test "trims the input HTML" {
|
||||
Expect.equal (htmlToPlainText " howdy ") "howdy" "HTML input string should have been trimmed"
|
||||
}
|
||||
test "replaces line breaks with new lines" {
|
||||
Expect.equal (htmlToPlainText "Lots<br>of<br />new<br>lines") "Lots\nof\nnew\nlines"
|
||||
"Break tags should have been converted to newline characters"
|
||||
}
|
||||
test "replaces non-breaking spaces with spaces" {
|
||||
Expect.equal (htmlToPlainText "Here is some more text") "Here is some more text"
|
||||
"Non-breaking spaces should have been replaced with spaces"
|
||||
}
|
||||
test "does all replacements at one time" {
|
||||
Expect.equal (htmlToPlainText " < <<br>test") "< <\ntest" "All replacements were not made correctly"
|
||||
}
|
||||
test "does not fail when passed null" {
|
||||
Expect.equal (htmlToPlainText null) "" "Should return an empty string for null input"
|
||||
}
|
||||
test "does not fail when passed an empty string" {
|
||||
Expect.equal (htmlToPlainText "") "" "Should return an empty string when given an empty string"
|
||||
}
|
||||
test "preserves blank lines for two consecutive line breaks" {
|
||||
let expected = "Paragraph 1\n\nParagraph 2\n\n...and paragraph 3"
|
||||
Expect.equal (htmlToPlainText "Paragraph 1<br><br>Paragraph 2<br><br>...and <strong>paragraph</strong> <i>3</i>")
|
||||
expected "Blank lines not preserved for consecutive line breaks"
|
||||
}
|
||||
testList "htmlToPlainText" [
|
||||
test "decodes HTML-encoded entities" {
|
||||
Expect.equal (htmlToPlainText "1 > 0") "1 > 0" "HTML-encoded entities should have been decoded"
|
||||
}
|
||||
test "trims the input HTML" {
|
||||
Expect.equal (htmlToPlainText " howdy ") "howdy" "HTML input string should have been trimmed"
|
||||
}
|
||||
test "replaces line breaks with new lines" {
|
||||
Expect.equal (htmlToPlainText "Lots<br>of<br />new<br>lines") "Lots\nof\nnew\nlines"
|
||||
"Break tags should have been converted to newline characters"
|
||||
}
|
||||
test "replaces non-breaking spaces with spaces" {
|
||||
Expect.equal (htmlToPlainText "Here is some more text") "Here is some more text"
|
||||
"Non-breaking spaces should have been replaced with spaces"
|
||||
}
|
||||
test "does all replacements at one time" {
|
||||
Expect.equal (htmlToPlainText " < <<br>test") "< <\ntest"
|
||||
"All replacements were not made correctly"
|
||||
}
|
||||
test "does not fail when passed null" {
|
||||
Expect.equal (htmlToPlainText null) "" "Should return an empty string for null input"
|
||||
}
|
||||
test "does not fail when passed an empty string" {
|
||||
Expect.equal (htmlToPlainText "") "" "Should return an empty string when given an empty string"
|
||||
}
|
||||
test "preserves blank lines for two consecutive line breaks" {
|
||||
let expected = "Paragraph 1\n\nParagraph 2\n\n...and paragraph 3"
|
||||
Expect.equal
|
||||
(htmlToPlainText "Paragraph 1<br><br>Paragraph 2<br><br>...and <strong>paragraph</strong> <i>3</i>")
|
||||
expected "Blank lines not preserved for consecutive line breaks"
|
||||
}
|
||||
]
|
||||
|
||||
[<Tests>]
|
||||
let makeUrlTests =
|
||||
testList "makeUrl" [
|
||||
test "returns the URL when there are no parameters" {
|
||||
Expect.equal (makeUrl "/test" []) "/test" "The URL should not have had any query string parameters added"
|
||||
}
|
||||
test "returns the URL with one query string parameter" {
|
||||
Expect.equal (makeUrl "/test" [ "unit", "true" ]) "/test?unit=true" "The URL was not constructed properly"
|
||||
}
|
||||
test "returns the URL with multiple encoded query string parameters" {
|
||||
let url = makeUrl "/test" [ "space", "a space"; "turkey", "=" ]
|
||||
Expect.equal url "/test?space=a+space&turkey=%3D" "The URL was not constructed properly"
|
||||
}
|
||||
testList "makeUrl" [
|
||||
test "returns the URL when there are no parameters" {
|
||||
Expect.equal (makeUrl "/test" []) "/test" "The URL should not have had any query string parameters added"
|
||||
}
|
||||
test "returns the URL with one query string parameter" {
|
||||
Expect.equal (makeUrl "/test" [ "unit", "true" ]) "/test?unit=true" "The URL was not constructed properly"
|
||||
}
|
||||
test "returns the URL with multiple encoded query string parameters" {
|
||||
let url = makeUrl "/test" [ "space", "a space"; "turkey", "=" ]
|
||||
Expect.equal url "/test?space=a+space&turkey=%3D" "The URL was not constructed properly"
|
||||
}
|
||||
]
|
||||
|
||||
[<Tests>]
|
||||
let sndAsStringTests =
|
||||
testList "sndAsString" [
|
||||
test "converts the second item to a string" {
|
||||
Expect.equal (sndAsString ("a", 5)) "5" "The second part of the tuple should have been converted to a string"
|
||||
}
|
||||
testList "sndAsString" [
|
||||
test "converts the second item to a string" {
|
||||
Expect.equal (sndAsString ("a", 5)) "5"
|
||||
"The second part of the tuple should have been converted to a string"
|
||||
}
|
||||
]
|
||||
|
||||
module StringTests =
|
||||
|
||||
open PrayerTracker.Utils.String
|
||||
open PrayerTracker.Utils.String
|
||||
|
||||
[<Tests>]
|
||||
let replaceFirstTests =
|
||||
testList "String.replaceFirst" [
|
||||
test "replaces the first occurrence when it is found at the beginning of the string" {
|
||||
let testString = "unit unit unit"
|
||||
Expect.equal (replaceFirst "unit" "test" testString) "test unit unit"
|
||||
"First occurrence of a substring was not replaced properly at the beginning of the string"
|
||||
}
|
||||
test "replaces the first occurrence when it is found in the center of the string" {
|
||||
let testString = "test unit test"
|
||||
Expect.equal (replaceFirst "unit" "test" testString) "test test test"
|
||||
"First occurrence of a substring was not replaced properly when it is in the center of the string"
|
||||
}
|
||||
test "returns the original string if the replacement isn't found" {
|
||||
let testString = "unit tests"
|
||||
Expect.equal (replaceFirst "tested" "testing" testString) "unit tests"
|
||||
"String which did not have the target substring was not returned properly"
|
||||
}
|
||||
]
|
||||
[<Tests>]
|
||||
let replaceFirstTests =
|
||||
testList "String.replaceFirst" [
|
||||
test "replaces the first occurrence when it is found at the beginning of the string" {
|
||||
let testString = "unit unit unit"
|
||||
Expect.equal (replaceFirst "unit" "test" testString) "test unit unit"
|
||||
"First occurrence of a substring was not replaced properly at the beginning of the string"
|
||||
}
|
||||
test "replaces the first occurrence when it is found in the center of the string" {
|
||||
let testString = "test unit test"
|
||||
Expect.equal (replaceFirst "unit" "test" testString) "test test test"
|
||||
"First occurrence of a substring was not replaced properly when it is in the center of the string"
|
||||
}
|
||||
test "returns the original string if the replacement isn't found" {
|
||||
let testString = "unit tests"
|
||||
Expect.equal (replaceFirst "tested" "testing" testString) "unit tests"
|
||||
"String which did not have the target substring was not returned properly"
|
||||
}
|
||||
]
|
||||
|
||||
[<Tests>]
|
||||
let replaceTests =
|
||||
testList "String.replace" [
|
||||
test "succeeds" {
|
||||
Expect.equal (replace "a" "b" "abacab") "bbbcbb" "String did not replace properly"
|
||||
}
|
||||
]
|
||||
[<Tests>]
|
||||
let replaceTests =
|
||||
testList "String.replace" [
|
||||
test "succeeds" {
|
||||
Expect.equal (replace "a" "b" "abacab") "bbbcbb" "String did not replace properly"
|
||||
}
|
||||
]
|
||||
|
||||
[<Tests>]
|
||||
let trimTests =
|
||||
testList "String.trim" [
|
||||
test "succeeds" {
|
||||
Expect.equal (trim " abc ") "abc" "Space not trimmed from string properly"
|
||||
}
|
||||
]
|
||||
[<Tests>]
|
||||
let trimTests =
|
||||
testList "String.trim" [
|
||||
test "succeeds" {
|
||||
Expect.equal (trim " abc ") "abc" "Space not trimmed from string properly"
|
||||
}
|
||||
]
|
||||
|
||||
[<Tests>]
|
||||
let stripTagsTests =
|
||||
let testString = "<p class=\"testing\">Here is some text<br> <br />and some more</p>"
|
||||
testList "stripTags" [
|
||||
test "does nothing if all tags are allowed" {
|
||||
Expect.equal (stripTags [ "p"; "br" ] testString) testString
|
||||
"There should have been no replacements in the target string"
|
||||
}
|
||||
test "strips the start/end tag for non allowed tag" {
|
||||
Expect.equal (stripTags [ "br" ] testString) "Here is some text<br> <br />and some more"
|
||||
"There should have been no \"p\" tag, but all \"br\" tags, in the returned string"
|
||||
}
|
||||
test "strips void/self-closing tags" {
|
||||
Expect.equal (stripTags [] testString) "Here is some text and some more"
|
||||
"There should have been no tags; all void and self-closing tags should have been stripped"
|
||||
}
|
||||
let testString = "<p class=\"testing\">Here is some text<br> <br />and some more</p>"
|
||||
testList "stripTags" [
|
||||
test "does nothing if all tags are allowed" {
|
||||
Expect.equal (stripTags [ "p"; "br" ] testString) testString
|
||||
"There should have been no replacements in the target string"
|
||||
}
|
||||
test "strips the start/end tag for non allowed tag" {
|
||||
Expect.equal (stripTags [ "br" ] testString) "Here is some text<br> <br />and some more"
|
||||
"There should have been no \"p\" tag, but all \"br\" tags, in the returned string"
|
||||
}
|
||||
test "strips void/self-closing tags" {
|
||||
Expect.equal (stripTags [] testString) "Here is some text and some more"
|
||||
"There should have been no tags; all void and self-closing tags should have been stripped"
|
||||
}
|
||||
]
|
||||
|
||||
[<Tests>]
|
||||
let wordWrapTests =
|
||||
testList "wordWrap" [
|
||||
test "breaks where it is supposed to" {
|
||||
let testString = "The quick brown fox jumps over the lazy dog\nIt does!"
|
||||
Expect.equal (wordWrap 20 testString) "The quick brown fox\njumps over the lazy\ndog\nIt does!\n"
|
||||
"Line not broken correctly"
|
||||
}
|
||||
test "wraps long line without a space" {
|
||||
let testString = "Asamatteroffact, the dog does too"
|
||||
Expect.equal (wordWrap 10 testString) "Asamattero\nffact, the\ndog does\ntoo\n"
|
||||
"Longer line not broken correctly"
|
||||
}
|
||||
test "preserves blank lines" {
|
||||
let testString = "Here is\n\na string with blank lines"
|
||||
Expect.equal (wordWrap 80 testString) testString "Blank lines were not preserved"
|
||||
}
|
||||
testList "wordWrap" [
|
||||
test "breaks where it is supposed to" {
|
||||
let testString = "The quick brown fox jumps over the lazy dog\nIt does!"
|
||||
Expect.equal (wordWrap 20 testString) "The quick brown fox\njumps over the lazy\ndog\nIt does!\n"
|
||||
"Line not broken correctly"
|
||||
}
|
||||
test "wraps long line without a space" {
|
||||
let testString = "Asamatteroffact, the dog does too"
|
||||
Expect.equal (wordWrap 10 testString) "Asamattero\nffact, the\ndog does\ntoo\n"
|
||||
"Longer line not broken correctly"
|
||||
}
|
||||
test "preserves blank lines" {
|
||||
let testString = "Here is\n\na string with blank lines"
|
||||
Expect.equal (wordWrap 80 testString) testString "Blank lines were not preserved"
|
||||
}
|
||||
]
|
||||
|
||||
[<Tests>]
|
||||
let wordWrapBTests =
|
||||
testList "wordWrapB" [
|
||||
test "breaks where it is supposed to" {
|
||||
let testString = "The quick brown fox jumps over the lazy dog\nIt does!"
|
||||
Expect.equal (wordWrap 20 testString) "The quick brown fox\njumps over the lazy\ndog\nIt does!\n"
|
||||
"Line not broken correctly"
|
||||
}
|
||||
test "wraps long line without a space and a line with exact length" {
|
||||
let testString = "Asamatteroffact, the dog does too"
|
||||
Expect.equal (wordWrap 10 testString) "Asamattero\nffact, the\ndog does\ntoo\n"
|
||||
"Longer line not broken correctly"
|
||||
}
|
||||
test "wraps long line without a space and a line with non-exact length" {
|
||||
let testString = "Asamatteroffact, that dog does too"
|
||||
Expect.equal (wordWrap 10 testString) "Asamattero\nffact,\nthat dog\ndoes too\n"
|
||||
"Longer line not broken correctly"
|
||||
}
|
||||
test "preserves blank lines" {
|
||||
let testString = "Here is\n\na string with blank lines"
|
||||
Expect.equal (wordWrap 80 testString) testString "Blank lines were not preserved"
|
||||
}
|
||||
testList "wordWrapB" [
|
||||
test "breaks where it is supposed to" {
|
||||
let testString = "The quick brown fox jumps over the lazy dog\nIt does!"
|
||||
Expect.equal (wordWrap 20 testString) "The quick brown fox\njumps over the lazy\ndog\nIt does!\n"
|
||||
"Line not broken correctly"
|
||||
}
|
||||
test "wraps long line without a space and a line with exact length" {
|
||||
let testString = "Asamatteroffact, the dog does too"
|
||||
Expect.equal (wordWrap 10 testString) "Asamattero\nffact, the\ndog does\ntoo\n"
|
||||
"Longer line not broken correctly"
|
||||
}
|
||||
test "wraps long line without a space and a line with non-exact length" {
|
||||
let testString = "Asamatteroffact, that dog does too"
|
||||
Expect.equal (wordWrap 10 testString) "Asamattero\nffact,\nthat dog\ndoes too\n"
|
||||
"Longer line not broken correctly"
|
||||
}
|
||||
test "preserves blank lines" {
|
||||
let testString = "Here is\n\na string with blank lines"
|
||||
Expect.equal (wordWrap 80 testString) testString "Blank lines were not preserved"
|
||||
}
|
||||
]
|
||||
|
|
|
@ -6,104 +6,107 @@ open PrayerTracker.ViewModels
|
|||
|
||||
/// View for the church edit page
|
||||
let edit (m : EditChurch) ctx vi =
|
||||
let pageTitle = match m.isNew () with true -> "Add a New Church" | false -> "Edit Church"
|
||||
let s = I18N.localizer.Force ()
|
||||
[ form [ _action "/web/church/save"; _method "post"; _class "pt-center-columns" ] [
|
||||
style [ _scoped ]
|
||||
[ rawText "#name { width: 20rem; } #city { width: 10rem; } #st { width: 3rem; } #interfaceAddress { width: 30rem; }" ]
|
||||
csrfToken ctx
|
||||
input [ _type "hidden"; _name "churchId"; _value (flatGuid m.churchId) ]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "name" ] [ locStr s.["Church Name"] ]
|
||||
input [ _type "text"; _name "name"; _id "name"; _required; _autofocus; _value m.name ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "City"] [ locStr s.["City"] ]
|
||||
input [ _type "text"; _name "city"; _id "city"; _required; _value m.city ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "ST" ] [ locStr s.["State"] ]
|
||||
input [ _type "text"; _name "st"; _id "st"; _required; _minlength "2"; _maxlength "2"; _value m.st ]
|
||||
]
|
||||
let pageTitle = match m.isNew () with true -> "Add a New Church" | false -> "Edit Church"
|
||||
let s = I18N.localizer.Force ()
|
||||
[ form [ _action "/web/church/save"; _method "post"; _class "pt-center-columns" ] [
|
||||
style [ _scoped ] [
|
||||
rawText "#name { width: 20rem; } #city { width: 10rem; } #st { width: 3rem; } #interfaceAddress { width: 30rem; }"
|
||||
]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-checkbox-field" ] [
|
||||
input [ _type "checkbox"
|
||||
_name "hasInterface"
|
||||
_id "hasInterface"
|
||||
_value "True"
|
||||
match m.hasInterface with Some x when x -> _checked | _ -> () ]
|
||||
label [ _for "hasInterface" ] [ locStr s.["Has an interface with Virtual Prayer Room"] ]
|
||||
]
|
||||
csrfToken ctx
|
||||
input [ _type "hidden"; _name "churchId"; _value (flatGuid m.churchId) ]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "name" ] [ locStr s["Church Name"] ]
|
||||
input [ _type "text"; _name "name"; _id "name"; _required; _autofocus; _value m.name ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "City"] [ locStr s["City"] ]
|
||||
input [ _type "text"; _name "city"; _id "city"; _required; _value m.city ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "ST" ] [ locStr s["State"] ]
|
||||
input [ _type "text"; _name "st"; _id "st"; _required; _minlength "2"; _maxlength "2"; _value m.st ]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field-row pt-fadeable"; _id "divInterfaceAddress" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "interfaceAddress" ] [ locStr s.["VPR Interface URL"] ]
|
||||
input [ _type "url"; _name "interfaceAddress"; _id "interfaceAddress";
|
||||
_value (match m.interfaceAddress with Some ia -> ia | None -> "") ]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-checkbox-field" ] [
|
||||
input [ _type "checkbox"
|
||||
_name "hasInterface"
|
||||
_id "hasInterface"
|
||||
_value "True"
|
||||
match m.hasInterface with Some x when x -> _checked | _ -> () ]
|
||||
label [ _for "hasInterface" ] [ locStr s["Has an interface with Virtual Prayer Room"] ]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [ submit [] "save" s.["Save Church"] ]
|
||||
]
|
||||
script [] [ rawText "PT.onLoad(PT.church.edit.onPageLoad)" ]
|
||||
div [ _class "pt-field-row pt-fadeable"; _id "divInterfaceAddress" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "interfaceAddress" ] [ locStr s["VPR Interface URL"] ]
|
||||
input
|
||||
[ _type "url"; _name "interfaceAddress"; _id "interfaceAddress";
|
||||
_value (match m.interfaceAddress with Some ia -> ia | None -> "")
|
||||
]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [ submit [] "save" s["Save Church"] ]
|
||||
]
|
||||
script [] [ rawText "PT.onLoad(PT.church.edit.onPageLoad)" ]
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|
||||
|
||||
/// View for church maintenance page
|
||||
let maintain (churches : Church list) (stats : Map<string, ChurchStats>) ctx vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let chTbl =
|
||||
match churches with
|
||||
| [] -> space
|
||||
| _ ->
|
||||
table [ _class "pt-table pt-action-table" ] [
|
||||
thead [] [
|
||||
tr [] [
|
||||
th [] [ locStr s.["Actions"] ]
|
||||
th [] [ locStr s.["Name"] ]
|
||||
th [] [ locStr s.["Location"] ]
|
||||
th [] [ locStr s.["Groups"] ]
|
||||
th [] [ locStr s.["Requests"] ]
|
||||
th [] [ locStr s.["Users"] ]
|
||||
th [] [ locStr s.["Interface?"] ]
|
||||
]
|
||||
let s = I18N.localizer.Force ()
|
||||
let chTbl =
|
||||
match churches with
|
||||
| [] -> space
|
||||
| _ ->
|
||||
table [ _class "pt-table pt-action-table" ] [
|
||||
thead [] [
|
||||
tr [] [
|
||||
th [] [ locStr s["Actions"] ]
|
||||
th [] [ locStr s["Name"] ]
|
||||
th [] [ locStr s["Location"] ]
|
||||
th [] [ locStr s["Groups"] ]
|
||||
th [] [ locStr s["Requests"] ]
|
||||
th [] [ locStr s["Users"] ]
|
||||
th [] [ locStr s["Interface?"] ]
|
||||
]
|
||||
]
|
||||
churches
|
||||
|> List.map (fun ch ->
|
||||
let chId = flatGuid ch.churchId
|
||||
let delAction = $"/web/church/{chId}/delete"
|
||||
let delPrompt = s["Are you sure you want to delete this {0}? This action cannot be undone.",
|
||||
$"""{s["Church"].Value.ToLower ()} ({ch.name})"""]
|
||||
tr [] [
|
||||
td [] [
|
||||
a [ _href $"/web/church/{chId}/edit"; _title s["Edit This Church"].Value ] [ icon "edit" ]
|
||||
a [ _href delAction
|
||||
_title s["Delete This Church"].Value
|
||||
_onclick $"return PT.confirmDelete('{delAction}','{delPrompt}')" ]
|
||||
[ icon "delete_forever" ]
|
||||
]
|
||||
td [] [ str ch.name ]
|
||||
td [] [ str ch.city; rawText ", "; str ch.st ]
|
||||
td [ _class "pt-right-text" ] [ rawText (stats[chId].smallGroups.ToString "N0") ]
|
||||
td [ _class "pt-right-text" ] [ rawText (stats[chId].prayerRequests.ToString "N0") ]
|
||||
td [ _class "pt-right-text" ] [ rawText (stats[chId].users.ToString "N0") ]
|
||||
td [ _class "pt-center-text" ] [ locStr s[if ch.hasInterface then "Yes" else "No"] ]
|
||||
])
|
||||
|> tbody []
|
||||
]
|
||||
churches
|
||||
|> List.map (fun ch ->
|
||||
let chId = flatGuid ch.churchId
|
||||
let delAction = $"/web/church/{chId}/delete"
|
||||
let delPrompt = s.["Are you sure you want to delete this {0}? This action cannot be undone.",
|
||||
$"""{s.["Church"].Value.ToLower ()} ({ch.name})"""]
|
||||
tr [] [
|
||||
td [] [
|
||||
a [ _href $"/web/church/{chId}/edit"; _title s.["Edit This Church"].Value ] [ icon "edit" ]
|
||||
a [ _href delAction
|
||||
_title s.["Delete This Church"].Value
|
||||
_onclick $"return PT.confirmDelete('{delAction}','{delPrompt}')" ]
|
||||
[ icon "delete_forever" ]
|
||||
]
|
||||
td [] [ str ch.name ]
|
||||
td [] [ str ch.city; rawText ", "; str ch.st ]
|
||||
td [ _class "pt-right-text" ] [ rawText (stats.[chId].smallGroups.ToString "N0") ]
|
||||
td [ _class "pt-right-text" ] [ rawText (stats.[chId].prayerRequests.ToString "N0") ]
|
||||
td [ _class "pt-right-text" ] [ rawText (stats.[chId].users.ToString "N0") ]
|
||||
td [ _class "pt-center-text" ] [ locStr s.[match ch.hasInterface with true -> "Yes" | false -> "No"] ]
|
||||
])
|
||||
|> tbody []
|
||||
]
|
||||
[ div [ _class "pt-center-text" ] [
|
||||
br []
|
||||
a [ _href $"/web/church/{emptyGuid}/edit"; _title s.["Add a New Church"].Value ]
|
||||
[ icon "add_circle"; rawText " "; locStr s.["Add a New Church"] ]
|
||||
br []
|
||||
br []
|
||||
[ div [ _class "pt-center-text" ] [
|
||||
br []
|
||||
a [ _href $"/web/church/{emptyGuid}/edit"; _title s["Add a New Church"].Value ]
|
||||
[ icon "add_circle"; rawText " "; locStr s["Add a New Church"] ]
|
||||
br []
|
||||
br []
|
||||
]
|
||||
tableSummary churches.Length s
|
||||
chTbl
|
||||
form [ _id "DeleteForm"; _action ""; _method "post" ] [ csrfToken ctx ]
|
||||
tableSummary churches.Length s
|
||||
chTbl
|
||||
form [ _id "DeleteForm"; _action ""; _method "post" ] [ csrfToken ctx ]
|
||||
]
|
||||
|> Layout.Content.wide
|
||||
|> Layout.standard vi "Maintain Churches"
|
||||
|> Layout.Content.wide
|
||||
|> Layout.standard vi "Maintain Churches"
|
||||
|
|
|
@ -1,26 +1,24 @@
|
|||
[<AutoOpen>]
|
||||
module PrayerTracker.Views.CommonFunctions
|
||||
|
||||
open System.IO
|
||||
open System.Text.Encodings.Web
|
||||
open Giraffe
|
||||
open Giraffe.ViewEngine
|
||||
open Microsoft.AspNetCore.Antiforgery
|
||||
open Microsoft.AspNetCore.Html
|
||||
open Microsoft.AspNetCore.Http
|
||||
open Microsoft.AspNetCore.Mvc.Localization
|
||||
open Microsoft.Extensions.Localization
|
||||
open System
|
||||
open System.IO
|
||||
open System.Text.Encodings.Web
|
||||
|
||||
/// Encoded text for a localized string
|
||||
let locStr (text : LocalizedString) = str text.Value
|
||||
|
||||
/// Raw text for a localized HTML string
|
||||
let rawLocText (writer : StringWriter) (text : LocalizedHtmlString) =
|
||||
text.WriteTo (writer, HtmlEncoder.Default)
|
||||
let txt = string writer
|
||||
writer.GetStringBuilder().Clear () |> ignore
|
||||
rawText txt
|
||||
text.WriteTo (writer, HtmlEncoder.Default)
|
||||
let txt = string writer
|
||||
writer.GetStringBuilder().Clear () |> ignore
|
||||
rawText txt
|
||||
|
||||
/// A space (used for back-to-back localization string breaks)
|
||||
let space = rawText " "
|
||||
|
@ -33,69 +31,73 @@ let iconSized size name = i [ _class $"material-icons md-{size}" ] [ rawText nam
|
|||
|
||||
/// Generate a CSRF prevention token
|
||||
let csrfToken (ctx : HttpContext) =
|
||||
let antiForgery = ctx.GetService<IAntiforgery> ()
|
||||
let tokenSet = antiForgery.GetAndStoreTokens ctx
|
||||
input [ _type "hidden"; _name tokenSet.FormFieldName; _value tokenSet.RequestToken ]
|
||||
let antiForgery = ctx.GetService<IAntiforgery> ()
|
||||
let tokenSet = antiForgery.GetAndStoreTokens ctx
|
||||
input [ _type "hidden"; _name tokenSet.FormFieldName; _value tokenSet.RequestToken ]
|
||||
|
||||
/// Create a summary for a table of items
|
||||
let tableSummary itemCount (s : IStringLocalizer) =
|
||||
div [ _class "pt-center-text" ] [
|
||||
small [] [
|
||||
match itemCount with
|
||||
| 0 -> s.["No Entries to Display"]
|
||||
| 1 -> s.["Displaying {0} Entry", itemCount]
|
||||
| _ -> s.["Displaying {0} Entries", itemCount]
|
||||
|> locStr
|
||||
]
|
||||
div [ _class "pt-center-text" ] [
|
||||
small [] [
|
||||
match itemCount with
|
||||
| 0 -> s["No Entries to Display"]
|
||||
| 1 -> s["Displaying {0} Entry", itemCount]
|
||||
| _ -> s["Displaying {0} Entries", itemCount]
|
||||
|> locStr
|
||||
]
|
||||
]
|
||||
|
||||
/// Generate a list of named HTML colors
|
||||
let namedColorList name selected attrs (s : IStringLocalizer) =
|
||||
/// The list of HTML named colors (name, display, text color)
|
||||
seq {
|
||||
("aqua", s.["Aqua"], "black")
|
||||
("black", s.["Black"], "white")
|
||||
("blue", s.["Blue"], "white")
|
||||
("fuchsia", s.["Fuchsia"], "black")
|
||||
("gray", s.["Gray"], "white")
|
||||
("green", s.["Green"], "white")
|
||||
("lime", s.["Lime"], "black")
|
||||
("maroon", s.["Maroon"], "white")
|
||||
("navy", s.["Navy"], "white")
|
||||
("olive", s.["Olive"], "white")
|
||||
("purple", s.["Purple"], "white")
|
||||
("red", s.["Red"], "black")
|
||||
("silver", s.["Silver"], "black")
|
||||
("teal", s.["Teal"], "white")
|
||||
("white", s.["White"], "black")
|
||||
("yellow", s.["Yellow"], "black")
|
||||
// The list of HTML named colors (name, display, text color)
|
||||
seq {
|
||||
("aqua", s["Aqua"], "black")
|
||||
("black", s["Black"], "white")
|
||||
("blue", s["Blue"], "white")
|
||||
("fuchsia", s["Fuchsia"], "black")
|
||||
("gray", s["Gray"], "white")
|
||||
("green", s["Green"], "white")
|
||||
("lime", s["Lime"], "black")
|
||||
("maroon", s["Maroon"], "white")
|
||||
("navy", s["Navy"], "white")
|
||||
("olive", s["Olive"], "white")
|
||||
("purple", s["Purple"], "white")
|
||||
("red", s["Red"], "black")
|
||||
("silver", s["Silver"], "black")
|
||||
("teal", s["Teal"], "white")
|
||||
("white", s["White"], "black")
|
||||
("yellow", s["Yellow"], "black")
|
||||
}
|
||||
|> Seq.map (fun color ->
|
||||
let (colorName, dispText, txtColor) = color
|
||||
option [ yield _value colorName
|
||||
yield _style $"background-color:{colorName};color:{txtColor};"
|
||||
match colorName = selected with true -> yield _selected | false -> () ] [
|
||||
encodedText (dispText.Value.ToLower ())
|
||||
])
|
||||
|> List.ofSeq
|
||||
|> select (_name name :: attrs)
|
||||
|> Seq.map (fun color ->
|
||||
let colorName, text, txtColor = color
|
||||
option
|
||||
[ _value colorName
|
||||
_style $"background-color:{colorName};color:{txtColor};"
|
||||
if colorName = selected then _selected
|
||||
] [ encodedText (text.Value.ToLower ()) ])
|
||||
|> List.ofSeq
|
||||
|> select (_name name :: attrs)
|
||||
|
||||
/// Generate an input[type=radio] that is selected if its value is the current value
|
||||
let radio name domId value current =
|
||||
input [ _type "radio"
|
||||
input
|
||||
[ _type "radio"
|
||||
_name name
|
||||
_id domId
|
||||
_value value
|
||||
match value = current with true -> _checked | false -> () ]
|
||||
if value = current then _checked
|
||||
]
|
||||
|
||||
/// Generate a select list with the current value selected
|
||||
let selectList name selected attrs items =
|
||||
items
|
||||
|> Seq.map (fun (value, text) ->
|
||||
option [ _value value
|
||||
match value = selected with true -> _selected | false -> () ] [ encodedText text ])
|
||||
|> List.ofSeq
|
||||
|> select (List.concat [ [ _name name; _id name ]; attrs ])
|
||||
items
|
||||
|> Seq.map (fun (value, text) ->
|
||||
option
|
||||
[ _value value
|
||||
if value = selected then _selected
|
||||
] [ encodedText text ])
|
||||
|> List.ofSeq
|
||||
|> select (List.concat [ [ _name name; _id name ]; attrs ])
|
||||
|
||||
/// Generate the text for a default entry at the top of a select list
|
||||
let selectDefault text = $"— {text} —"
|
||||
|
@ -103,6 +105,9 @@ let selectDefault text = $"— {text} —"
|
|||
/// Generate a standard submit button with icon and text
|
||||
let submit attrs ico text = button (_type "submit" :: attrs) [ icon ico; rawText " "; locStr text ]
|
||||
|
||||
|
||||
open System
|
||||
|
||||
/// Format a GUID with no dashes (used for URLs and forms)
|
||||
let flatGuid (x : Guid) = x.ToString "N"
|
||||
|
||||
|
@ -129,6 +134,9 @@ let _scoped = flag "scoped"
|
|||
/// The name this function used to have when the view engine was part of Giraffe
|
||||
let renderHtmlNode = RenderView.AsString.htmlNode
|
||||
|
||||
|
||||
open Microsoft.AspNetCore.Html
|
||||
|
||||
/// Render an HTML node, then return the value as an HTML string
|
||||
let renderHtmlString = renderHtmlNode >> HtmlString
|
||||
|
||||
|
@ -136,20 +144,20 @@ let renderHtmlString = renderHtmlNode >> HtmlString
|
|||
/// Utility methods to help with time zones (and localization of their names)
|
||||
module TimeZones =
|
||||
|
||||
open System.Collections.Generic
|
||||
open System.Collections.Generic
|
||||
|
||||
/// Cross-reference between time zone Ids and their English names
|
||||
let private xref =
|
||||
[ "America/Chicago", "Central"
|
||||
"America/Denver", "Mountain"
|
||||
"America/Los_Angeles", "Pacific"
|
||||
"America/New_York", "Eastern"
|
||||
"America/Phoenix", "Mountain (Arizona)"
|
||||
"Europe/Berlin", "Central European"
|
||||
]
|
||||
|> Map.ofList
|
||||
/// Cross-reference between time zone Ids and their English names
|
||||
let private xref =
|
||||
[ "America/Chicago", "Central"
|
||||
"America/Denver", "Mountain"
|
||||
"America/Los_Angeles", "Pacific"
|
||||
"America/New_York", "Eastern"
|
||||
"America/Phoenix", "Mountain (Arizona)"
|
||||
"Europe/Berlin", "Central European"
|
||||
]
|
||||
|> Map.ofList
|
||||
|
||||
/// Get the name of a time zone, given its Id
|
||||
let name tzId (s : IStringLocalizer) =
|
||||
try s.[xref.[tzId]]
|
||||
with :? KeyNotFoundException -> LocalizedString (tzId, tzId)
|
||||
/// Get the name of a time zone, given its Id
|
||||
let name tzId (s : IStringLocalizer) =
|
||||
try s[xref[tzId]]
|
||||
with :? KeyNotFoundException -> LocalizedString (tzId, tzId)
|
||||
|
|
|
@ -1,262 +1,261 @@
|
|||
/// Views associated with the home page, or those that don't fit anywhere else
|
||||
module PrayerTracker.Views.Home
|
||||
|
||||
open Giraffe.ViewEngine
|
||||
open Microsoft.AspNetCore.Html
|
||||
open PrayerTracker.ViewModels
|
||||
open System.IO
|
||||
open Giraffe.ViewEngine
|
||||
open PrayerTracker.ViewModels
|
||||
|
||||
/// The error page
|
||||
let error code vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Home/Error"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
let is404 = "404" = code
|
||||
let pageTitle = match is404 with true -> "Page Not Found" | false -> "Server Error"
|
||||
[ yield!
|
||||
match is404 with
|
||||
| true ->
|
||||
[ p [] [
|
||||
raw l.["The page you requested cannot be found."]
|
||||
raw l.["Please use your “Back” button to return to {0}.", s.["PrayerTracker"]]
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Home/Error"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
let is404 = "404" = code
|
||||
let pageTitle = if is404 then "Page Not Found" else "Server Error"
|
||||
[ yield!
|
||||
if is404 then
|
||||
[ p [] [
|
||||
raw l["The page you requested cannot be found."]
|
||||
raw l["Please use your “Back” button to return to {0}.", s["PrayerTracker"]]
|
||||
]
|
||||
p [] [
|
||||
raw l.["If you reached this page from a link within {0}, please copy the link from the browser's address bar, and send it to support, along with the group for which you were currently authenticated (if any).",
|
||||
s.["PrayerTracker"]]
|
||||
p [] [
|
||||
raw l["If you reached this page from a link within {0}, please copy the link from the browser's address bar, and send it to support, along with the group for which you were currently authenticated (if any).",
|
||||
s["PrayerTracker"]]
|
||||
]
|
||||
]
|
||||
| false ->
|
||||
[ p [] [
|
||||
raw l.["An error ({0}) has occurred.", code]
|
||||
raw l.["Please use your “Back” button to return to {0}.", s.["PrayerTracker"]]
|
||||
else
|
||||
[ p [] [
|
||||
raw l["An error ({0}) has occurred.", code]
|
||||
raw l["Please use your “Back” button to return to {0}.", s["PrayerTracker"]]
|
||||
]
|
||||
]
|
||||
br []
|
||||
hr []
|
||||
div [ _style "font-size:70%;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen-Sans,Ubuntu,Cantarell,'Helvetica Neue',sans-serif" ] [
|
||||
img [ _src $"""/img/%A{s.["footer_en"]}.png"""
|
||||
_alt $"""%A{s.["PrayerTracker"]} %A{s.["from Bit Badger Solutions"]}"""
|
||||
_title $"""%A{s.["PrayerTracker"]} %A{s.["from Bit Badger Solutions"]}"""
|
||||
_style "vertical-align:text-bottom;" ]
|
||||
str vi.version
|
||||
br []
|
||||
hr []
|
||||
div [ _style "font-size:70%;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen-Sans,Ubuntu,Cantarell,'Helvetica Neue',sans-serif" ] [
|
||||
img [ _src $"""/img/%A{s["footer_en"]}.png"""
|
||||
_alt $"""%A{s["PrayerTracker"]} %A{s["from Bit Badger Solutions"]}"""
|
||||
_title $"""%A{s["PrayerTracker"]} %A{s["from Bit Badger Solutions"]}"""
|
||||
_style "vertical-align:text-bottom;" ]
|
||||
str vi.version
|
||||
]
|
||||
]
|
||||
|> div []
|
||||
|> Layout.bare pageTitle
|
||||
|> div []
|
||||
|> Layout.bare pageTitle
|
||||
|
||||
|
||||
/// The home page
|
||||
let index vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Home/Index"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Home/Index"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
|
||||
[ p [] [
|
||||
raw l.["Welcome to <strong>{0}</strong>!", s.["PrayerTracker"]]
|
||||
space
|
||||
raw l.["{0} is an interactive website that provides churches, Sunday School classes, and other organizations an easy way to keep up with their prayer requests.",
|
||||
s.["PrayerTracker"]]
|
||||
space
|
||||
raw l.["It is provided at no charge, as a ministry and a community service."]
|
||||
[ p [] [
|
||||
raw l["Welcome to <strong>{0}</strong>!", s["PrayerTracker"]]
|
||||
space
|
||||
raw l["{0} is an interactive website that provides churches, Sunday School classes, and other organizations an easy way to keep up with their prayer requests.",
|
||||
s["PrayerTracker"]]
|
||||
space
|
||||
raw l["It is provided at no charge, as a ministry and a community service."]
|
||||
]
|
||||
h4 [] [ raw l.["What Does It Do?"] ]
|
||||
p [] [
|
||||
raw l.["{0} has what you need to make maintaining a prayer request list a breeze.", s.["PrayerTracker"]]
|
||||
space
|
||||
raw l.["Some of the things it can do..."]
|
||||
h4 [] [ raw l["What Does It Do?"] ]
|
||||
p [] [
|
||||
raw l["{0} has what you need to make maintaining a prayer request list a breeze.", s["PrayerTracker"]]
|
||||
space
|
||||
raw l["Some of the things it can do..."]
|
||||
]
|
||||
ul [] [
|
||||
li [] [
|
||||
raw l.["It drops old requests off the list automatically."]
|
||||
space
|
||||
raw l.["Requests other than “{0}” requests will expire at 14 days, though this can be changed by the organization.",
|
||||
s.["Long-Term Requests"]]
|
||||
space
|
||||
raw l.["This expiration is based on the last update, not the initial request."]
|
||||
space
|
||||
raw l.["(And, once requests do “drop off”, they are not gone - they may be recovered if needed.)"]
|
||||
]
|
||||
li [] [
|
||||
raw l.["Requests can be viewed any time."]
|
||||
space
|
||||
raw l.["Lists can be made public, or they can be secured with a password, if desired."]
|
||||
]
|
||||
li [] [
|
||||
raw l.["Lists can be e-mailed to a pre-defined list of members."]
|
||||
space
|
||||
raw l.["This can be useful for folks who may not be able to write down all the requests during class, but want a list so that they can pray for them the rest of week."]
|
||||
space
|
||||
raw l.["E-mails are sent individually to each person, which keeps the e-mail list private and keeps the messages from being flagged as spam."]
|
||||
]
|
||||
li [] [
|
||||
raw l.["The look and feel of the list can be configured for each group."]
|
||||
space
|
||||
raw l.["All fonts, colors, and sizes can be customized."]
|
||||
space
|
||||
raw l.["This allows for configuration of large-print lists, among other things."]
|
||||
]
|
||||
ul [] [
|
||||
li [] [
|
||||
raw l["It drops old requests off the list automatically."]
|
||||
space
|
||||
raw l["Requests other than “{0}” requests will expire at 14 days, though this can be changed by the organization.",
|
||||
s["Long-Term Requests"]]
|
||||
space
|
||||
raw l["This expiration is based on the last update, not the initial request."]
|
||||
space
|
||||
raw l["(And, once requests do “drop off”, they are not gone - they may be recovered if needed.)"]
|
||||
]
|
||||
li [] [
|
||||
raw l["Requests can be viewed any time."]
|
||||
space
|
||||
raw l["Lists can be made public, or they can be secured with a password, if desired."]
|
||||
]
|
||||
li [] [
|
||||
raw l["Lists can be e-mailed to a pre-defined list of members."]
|
||||
space
|
||||
raw l["This can be useful for folks who may not be able to write down all the requests during class, but want a list so that they can pray for them the rest of week."]
|
||||
space
|
||||
raw l["E-mails are sent individually to each person, which keeps the e-mail list private and keeps the messages from being flagged as spam."]
|
||||
]
|
||||
li [] [
|
||||
raw l["The look and feel of the list can be configured for each group."]
|
||||
space
|
||||
raw l["All fonts, colors, and sizes can be customized."]
|
||||
space
|
||||
raw l["This allows for configuration of large-print lists, among other things."]
|
||||
]
|
||||
]
|
||||
h4 [] [ raw l.["How Can Your Organization Use {0}?", s.["PrayerTracker"]] ]
|
||||
p [] [
|
||||
raw l.["Like God’s gift of salvation, {0} is free for the asking for any church, Sunday School class, or other organization who wishes to use it.",
|
||||
s.["PrayerTracker"]]
|
||||
space
|
||||
raw l.["If your organization would like to get set up, just <a href=\"mailto:daniel@djs-consulting.com?subject=New%20{0}%20Class\">e-mail</a> Daniel and let him know.",
|
||||
s.["PrayerTracker"]]
|
||||
h4 [] [ raw l["How Can Your Organization Use {0}?", s["PrayerTracker"]] ]
|
||||
p [] [
|
||||
raw l["Like God’s gift of salvation, {0} is free for the asking for any church, Sunday School class, or other organization who wishes to use it.",
|
||||
s["PrayerTracker"]]
|
||||
space
|
||||
raw l["If your organization would like to get set up, just <a href=\"mailto:daniel@djs-consulting.com?subject=New%20{0}%20Class\">e-mail</a> Daniel and let him know.",
|
||||
s["PrayerTracker"]]
|
||||
]
|
||||
h4 [] [ raw l.["Do I Have to Register to See the Requests?"] ]
|
||||
p [] [
|
||||
raw l.["This depends on the group."]
|
||||
space
|
||||
raw l.["Lists can be configured to be password-protected, but they do not have to be."]
|
||||
space
|
||||
raw l.["If you click on the “{0}” link above, you will see a list of groups - those that do not indicate that they require logging in are publicly viewable.",
|
||||
s.["View Request List"]]
|
||||
h4 [] [ raw l["Do I Have to Register to See the Requests?"] ]
|
||||
p [] [
|
||||
raw l["This depends on the group."]
|
||||
space
|
||||
raw l["Lists can be configured to be password-protected, but they do not have to be."]
|
||||
space
|
||||
raw l["If you click on the “{0}” link above, you will see a list of groups - those that do not indicate that they require logging in are publicly viewable.",
|
||||
s["View Request List"]]
|
||||
]
|
||||
h4 [] [ raw l.["How Does It Work?"] ]
|
||||
p [] [
|
||||
raw l.["Check out the “{0}” link above - it details each of the processes and how they work.", s.["Help"]]
|
||||
h4 [] [ raw l["How Does It Work?"] ]
|
||||
p [] [
|
||||
raw l["Check out the “{0}” link above - it details each of the processes and how they work.", s["Help"]]
|
||||
]
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Welcome!"
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Welcome!"
|
||||
|
||||
|
||||
/// Privacy Policy page
|
||||
let privacyPolicy vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Home/PrivacyPolicy"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Home/PrivacyPolicy"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
|
||||
[ p [ _class "pt-right-text" ] [ small[] [ em [] [ raw l.["(as of July 31, 2018)"] ] ] ]
|
||||
p [] [
|
||||
raw l.["The nature of the service is one where privacy is a must."]
|
||||
space
|
||||
raw l.["The items below will help you understand the data we collect, access, and store on your behalf as you use this service."]
|
||||
]
|
||||
h3 [] [ raw l.["What We Collect"] ]
|
||||
ul [] [
|
||||
li [] [
|
||||
strong [] [ raw l.["Identifying Data"] ]
|
||||
rawText " – "
|
||||
raw l.["{0} stores the first and last names, e-mail addresses, and hashed passwords of all authorized users.", s.["PrayerTracker"]]
|
||||
space
|
||||
raw l.["Users are also associated with one or more small groups."]
|
||||
[ p [ _class "pt-right-text" ] [ small [] [ em [] [ raw l["(as of July 31, 2018)"] ] ] ]
|
||||
p [] [
|
||||
raw l["The nature of the service is one where privacy is a must."]
|
||||
space
|
||||
raw l["The items below will help you understand the data we collect, access, and store on your behalf as you use this service."]
|
||||
]
|
||||
li [] [
|
||||
strong [] [ raw l.["User Provided Data"] ]
|
||||
rawText " – "
|
||||
raw l.["{0} stores the text of prayer requests.", s.["PrayerTracker"]]
|
||||
space
|
||||
raw l.["It also stores names and e-mail addreses of small group members, and plain-text passwords for small groups with password-protected lists."]
|
||||
h3 [] [ raw l["What We Collect"] ]
|
||||
ul [] [
|
||||
li [] [
|
||||
strong [] [ raw l["Identifying Data"] ]
|
||||
rawText " – "
|
||||
raw l["{0} stores the first and last names, e-mail addresses, and hashed passwords of all authorized users.",
|
||||
s["PrayerTracker"]]
|
||||
space
|
||||
raw l["Users are also associated with one or more small groups."]
|
||||
]
|
||||
li [] [
|
||||
strong [] [ raw l["User Provided Data"] ]
|
||||
rawText " – "
|
||||
raw l["{0} stores the text of prayer requests.", s["PrayerTracker"]]
|
||||
space
|
||||
raw l["It also stores names and e-mail addreses of small group members, and plain-text passwords for small groups with password-protected lists."]
|
||||
]
|
||||
]
|
||||
h3 [] [ raw l["How Your Data Is Accessed / Secured"] ]
|
||||
ul [] [
|
||||
li [] [
|
||||
raw l["While you are signed in, {0} utilizes a session cookie, and transmits that cookie to the server to establish your identity.",
|
||||
s["PrayerTracker"]]
|
||||
space
|
||||
raw l["If you utilize the “{0}” box on sign in, a second cookie is stored, and transmitted to establish a session; this cookie is removed by clicking the “{1}” link.",
|
||||
s["Remember Me"], s["Log Off"]]
|
||||
space
|
||||
raw l["Both of these cookies are encrypted, both in your browser and in transit."]
|
||||
space
|
||||
raw l["Finally, a third cookie is used to maintain your currently selected language, so that this selection is maintained across browser sessions."]
|
||||
]
|
||||
li [] [
|
||||
raw l["Data for your small group is returned to you, as required, to display and edit."]
|
||||
space
|
||||
raw l["{0} also sends e-mails on behalf of the configured owner of a small group; these e-mails are sent from prayer@djs-consulting.com, with the “Reply To” header set to the configured owner of the small group.",
|
||||
s["PrayerTracker"]]
|
||||
space
|
||||
raw l["Distinct e-mails are sent to each user, as to not disclose the other recipients."]
|
||||
space
|
||||
raw l["On the server, all data is stored in a controlled-access database."]
|
||||
]
|
||||
li [] [
|
||||
raw l["Your data is backed up, along with other Bit Badger Solutions hosted systems, in a rolling manner; backups are preserved for the prior 7 days, and backups from the 1st and 15th are preserved for 3 months."]
|
||||
space
|
||||
raw l["These backups are stored in a private cloud data repository."]
|
||||
]
|
||||
li [] [
|
||||
raw l["Access to servers and backups is strictly controlled and monitored for unauthorized access attempts."]
|
||||
]
|
||||
]
|
||||
h3 [] [ raw l["Removing Your Data"] ]
|
||||
p [] [
|
||||
raw l["At any time, you may choose to discontinue using {0}; just e-mail Daniel, as you did to register, and request deletion of your small group.",
|
||||
s["PrayerTracker"]]
|
||||
]
|
||||
]
|
||||
h3 [] [ raw l.["How Your Data Is Accessed / Secured"] ]
|
||||
ul [] [
|
||||
li [] [
|
||||
raw l.["While you are signed in, {0} utilizes a session cookie, and transmits that cookie to the server to establish your identity.",
|
||||
s.["PrayerTracker"]]
|
||||
space
|
||||
raw l.["If you utilize the “{0}” box on sign in, a second cookie is stored, and transmitted to establish a session; this cookie is removed by clicking the “{1}” link.",
|
||||
s.["Remember Me"], s.["Log Off"]]
|
||||
space
|
||||
raw l.["Both of these cookies are encrypted, both in your browser and in transit."]
|
||||
space
|
||||
raw l.["Finally, a third cookie is used to maintain your currently selected language, so that this selection is maintained across browser sessions."]
|
||||
]
|
||||
li [] [
|
||||
raw l.["Data for your small group is returned to you, as required, to display and edit."]
|
||||
space
|
||||
raw l.["{0} also sends e-mails on behalf of the configured owner of a small group; these e-mails are sent from prayer@djs-consulting.com, with the “Reply To” header set to the configured owner of the small group.",
|
||||
s.["PrayerTracker"]]
|
||||
space
|
||||
raw l.["Distinct e-mails are sent to each user, as to not disclose the other recipients."]
|
||||
space
|
||||
raw l.["On the server, all data is stored in a controlled-access database."]
|
||||
]
|
||||
li [] [
|
||||
raw l.["Your data is backed up, along with other Bit Badger Solutions hosted systems, in a rolling manner; backups are preserved for the prior 7 days, and backups from the 1st and 15th are preserved for 3 months."]
|
||||
space
|
||||
raw l.["These backups are stored in a private cloud data repository."]
|
||||
]
|
||||
li [] [
|
||||
raw l.["Access to servers and backups is strictly controlled and monitored for unauthorized access attempts."]
|
||||
]
|
||||
]
|
||||
h3 [] [ raw l.["Removing Your Data"] ]
|
||||
p [] [
|
||||
raw l.["At any time, you may choose to discontinue using {0}; just e-mail Daniel, as you did to register, and request deletion of your small group.",
|
||||
s.["PrayerTracker"]]
|
||||
]
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Privacy Policy"
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Privacy Policy"
|
||||
|
||||
|
||||
/// Terms of Service page
|
||||
let termsOfService vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Home/TermsOfService"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
let ppLink =
|
||||
a [ _href "/web/legal/privacy-policy" ] [ str (s.["Privacy Policy"].Value.ToLower ()) ]
|
||||
|> renderHtmlString
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Home/TermsOfService"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
let ppLink =
|
||||
a [ _href "/web/legal/privacy-policy" ] [ str (s["Privacy Policy"].Value.ToLower ()) ]
|
||||
|> renderHtmlString
|
||||
|
||||
[ p [ _class "pt-right-text" ] [ small [] [ em [] [ raw l.["(as of May 24, 2018)"] ] ] ]
|
||||
h3 [] [ str "1. "; raw l.["Acceptance of Terms"] ]
|
||||
p [] [
|
||||
raw l.["By accessing this web site, you are agreeing to be bound by these Terms and Conditions, and that you are responsible to ensure that your use of this site complies with all applicable laws."]
|
||||
space
|
||||
raw l.["Your continued use of this site implies your acceptance of these terms."]
|
||||
[ p [ _class "pt-right-text" ] [ small [] [ em [] [ raw l["(as of May 24, 2018)"] ] ] ]
|
||||
h3 [] [ str "1. "; raw l["Acceptance of Terms"] ]
|
||||
p [] [
|
||||
raw l["By accessing this web site, you are agreeing to be bound by these Terms and Conditions, and that you are responsible to ensure that your use of this site complies with all applicable laws."]
|
||||
space
|
||||
raw l["Your continued use of this site implies your acceptance of these terms."]
|
||||
]
|
||||
h3 [] [ str "2. "; raw l.["Description of Service and Registration"] ]
|
||||
p [] [
|
||||
raw l.["{0} is a service that allows individuals to enter and amend prayer requests on behalf of organizations.",
|
||||
s.["PrayerTracker"]]
|
||||
space
|
||||
raw l.["Registration is accomplished via e-mail to Daniel Summers (daniel at bitbadger dot solutions, substituting punctuation)."]
|
||||
space
|
||||
raw l.["See our {0} for details on the personal (user) information we maintain.", ppLink]
|
||||
h3 [] [ str "2. "; raw l["Description of Service and Registration"] ]
|
||||
p [] [
|
||||
raw l["{0} is a service that allows individuals to enter and amend prayer requests on behalf of organizations.",
|
||||
s["PrayerTracker"]]
|
||||
space
|
||||
raw l["Registration is accomplished via e-mail to Daniel Summers (daniel at bitbadger dot solutions, substituting punctuation)."]
|
||||
space
|
||||
raw l["See our {0} for details on the personal (user) information we maintain.", ppLink]
|
||||
]
|
||||
h3 [] [ str "3. "; raw l.["Liability"] ]
|
||||
p [] [
|
||||
raw l.["This service is provided “as is”, and no warranty (express or implied) exists."]
|
||||
space
|
||||
raw l.["The service and its developers may not be held liable for any damages that may arise through the use of this service."]
|
||||
h3 [] [ str "3. "; raw l["Liability"] ]
|
||||
p [] [
|
||||
raw l["This service is provided “as is”, and no warranty (express or implied) exists."]
|
||||
space
|
||||
raw l["The service and its developers may not be held liable for any damages that may arise through the use of this service."]
|
||||
]
|
||||
h3 [] [ str "4. "; raw l.["Updates to Terms"] ]
|
||||
p [] [
|
||||
raw l.["These terms and conditions may be updated at any time."]
|
||||
space
|
||||
raw l.["When these terms are updated, users will be notified by a system-generated announcement."]
|
||||
space
|
||||
raw l.["Additionally, the date at the top of this page will be updated."]
|
||||
h3 [] [ str "4. "; raw l["Updates to Terms"] ]
|
||||
p [] [
|
||||
raw l["These terms and conditions may be updated at any time."]
|
||||
space
|
||||
raw l["When these terms are updated, users will be notified by a system-generated announcement."]
|
||||
space
|
||||
raw l["Additionally, the date at the top of this page will be updated."]
|
||||
]
|
||||
hr []
|
||||
p [] [ raw l.["You may also wish to review our {0} to learn how we handle your data.", ppLink] ]
|
||||
hr []
|
||||
p [] [ raw l["You may also wish to review our {0} to learn how we handle your data.", ppLink] ]
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Terms of Service"
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Terms of Service"
|
||||
|
||||
|
||||
/// View for unauthorized page
|
||||
let unauthorized vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Home/Unauthorized"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
[ p [] [
|
||||
raw l.["If you feel you have reached this page in error, please <a href=\"mailto:daniel@djs-consulting.com?Subject={0}%20Unauthorized%20Access\">contact Daniel</a> and provide the details as to what you were doing (i.e., what link did you click, where had you been, etc.).",
|
||||
s.["PrayerTracker"]]
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Home/Unauthorized"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
[ p [] [
|
||||
raw l["If you feel you have reached this page in error, please <a href=\"mailto:daniel@djs-consulting.com?Subject={0}%20Unauthorized%20Access\">contact Daniel</a> and provide the details as to what you were doing (i.e., what link did you click, where had you been, etc.).",
|
||||
s["PrayerTracker"]]
|
||||
]
|
||||
p [] [
|
||||
raw l.["Otherwise, you may select one of the links above to get back into an authorized portion of {0}.",
|
||||
s.["PrayerTracker"]]
|
||||
p [] [
|
||||
raw l["Otherwise, you may select one of the links above to get back into an authorized portion of {0}.",
|
||||
s["PrayerTracker"]]
|
||||
]
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Unauthorized Access"
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Unauthorized Access"
|
||||
|
|
|
@ -11,12 +11,12 @@ let private resAsmName = typeof<Common>.Assembly.GetName().Name
|
|||
|
||||
/// Set up the string and HTML localizer factories
|
||||
let setUpFactories fac =
|
||||
stringLocFactory <- fac
|
||||
htmlLocFactory <- HtmlLocalizerFactory stringLocFactory
|
||||
stringLocFactory <- fac
|
||||
htmlLocFactory <- HtmlLocalizerFactory stringLocFactory
|
||||
|
||||
/// An instance of the common string localizer
|
||||
let localizer = lazy (stringLocFactory.Create ("Common", resAsmName))
|
||||
|
||||
/// Get a view localizer
|
||||
let forView (view : string) =
|
||||
htmlLocFactory.Create ($"""Views.{view.Replace ('/', '.')}""", resAsmName)
|
||||
htmlLocFactory.Create ($"""Views.{view.Replace ('/', '.')}""", resAsmName)
|
||||
|
|
|
@ -9,282 +9,285 @@ open System.Globalization
|
|||
|
||||
|
||||
/// Get the two-character language code for the current request
|
||||
let langCode () = match CultureInfo.CurrentCulture.Name.StartsWith "es" with true -> "es" | _ -> "en"
|
||||
let langCode () = if CultureInfo.CurrentCulture.Name.StartsWith "es" then "es" else "en"
|
||||
|
||||
|
||||
/// Navigation items
|
||||
module Navigation =
|
||||
|
||||
/// Top navigation bar
|
||||
let top m =
|
||||
let s = PrayerTracker.Views.I18N.localizer.Force ()
|
||||
let menuSpacer = rawText " "
|
||||
let leftLinks = [
|
||||
match m.user with
|
||||
| Some u ->
|
||||
li [ _class "dropdown" ] [
|
||||
a [ _class "dropbtn"; _role "button"; _aria "label" s.["Requests"].Value; _title s.["Requests"].Value ]
|
||||
[ icon "question_answer"; space; locStr s.["Requests"]; space; icon "keyboard_arrow_down" ]
|
||||
div [ _class "dropdown-content"; _role "menu" ] [
|
||||
a [ _href "/web/prayer-requests" ] [ icon "compare_arrows"; menuSpacer; locStr s.["Maintain"] ]
|
||||
a [ _href "/web/prayer-requests/view" ] [ icon "list"; menuSpacer; locStr s.["View List"] ]
|
||||
]
|
||||
]
|
||||
li [ _class "dropdown" ] [
|
||||
a [ _class "dropbtn"; _role "button"; _aria "label" s.["Group"].Value; _title s.["Group"].Value ]
|
||||
[ icon "group"; space; locStr s.["Group"]; space; icon "keyboard_arrow_down" ]
|
||||
div [ _class "dropdown-content"; _role "menu" ] [
|
||||
a [ _href "/web/small-group/members" ] [ icon "email"; menuSpacer; locStr s.["Maintain Group Members"] ]
|
||||
a [ _href "/web/small-group/announcement" ] [ icon "send"; menuSpacer; locStr s.["Send Announcement"] ]
|
||||
a [ _href "/web/small-group/preferences" ] [ icon "build"; menuSpacer; locStr s.["Change Preferences"] ]
|
||||
]
|
||||
]
|
||||
match u.isAdmin with
|
||||
| true ->
|
||||
li [ _class "dropdown" ] [
|
||||
a [ _class "dropbtn"; _role "button"; _aria "label" s.["Administration"].Value; _title s.["Administration"].Value ]
|
||||
[ icon "settings"; space; locStr s.["Administration"]; space; icon "keyboard_arrow_down" ]
|
||||
div [ _class "dropdown-content"; _role "menu" ] [
|
||||
a [ _href "/web/churches" ] [ icon "home"; menuSpacer; locStr s.["Churches"] ]
|
||||
a [ _href "/web/small-groups" ] [ icon "send"; menuSpacer; locStr s.["Groups"] ]
|
||||
a [ _href "/web/users" ] [ icon "build"; menuSpacer; locStr s.["Users"] ]
|
||||
]
|
||||
]
|
||||
| false -> ()
|
||||
| None ->
|
||||
match m.group with
|
||||
| Some _ ->
|
||||
li [] [
|
||||
a [ _href "/web/prayer-requests/view"
|
||||
_aria "label" s.["View Request List"].Value
|
||||
_title s.["View Request List"].Value ]
|
||||
[ icon "list"; space; locStr s.["View Request List"] ]
|
||||
]
|
||||
| None ->
|
||||
li [ _class "dropdown" ] [
|
||||
a [ _class "dropbtn"; _role "button"; _aria "label" s.["Log On"].Value; _title s.["Log On"].Value ]
|
||||
[ icon "security"; space; locStr s.["Log On"]; space; icon "keyboard_arrow_down" ]
|
||||
div [ _class "dropdown-content"; _role "menu" ] [
|
||||
a [ _href "/web/user/log-on" ] [ icon "person"; menuSpacer; locStr s.["User"] ]
|
||||
a [ _href "/web/small-group/log-on" ] [ icon "group"; menuSpacer; locStr s.["Group"] ]
|
||||
]
|
||||
]
|
||||
li [] [
|
||||
a [ _href "/web/prayer-requests/lists"
|
||||
_aria "label" s.["View Request List"].Value
|
||||
_title s.["View Request List"].Value ]
|
||||
[ icon "list"; space; locStr s.["View Request List"] ]
|
||||
]
|
||||
li [] [
|
||||
a [ _href $"https://docs.prayer.bitbadger.solutions/{langCode ()}"
|
||||
_aria "label" s.["Help"].Value;
|
||||
_title s.["View Help"].Value
|
||||
_target "_blank"
|
||||
]
|
||||
[ icon "help"; space; locStr s.["Help"] ]
|
||||
]
|
||||
]
|
||||
let rightLinks =
|
||||
match m.group with
|
||||
| Some _ ->
|
||||
[ match m.user with
|
||||
| Some _ ->
|
||||
li [] [
|
||||
a [ _href "/web/user/password"
|
||||
_aria "label" s.["Change Your Password"].Value
|
||||
_title s.["Change Your Password"].Value ]
|
||||
[ icon "lock"; space; locStr s.["Change Your Password"] ]
|
||||
]
|
||||
| None -> ()
|
||||
li [] [
|
||||
a [ _href "/web/log-off"; _aria "label" s.["Log Off"].Value; _title s.["Log Off"].Value ]
|
||||
[ icon "power_settings_new"; space; locStr s.["Log Off"] ]
|
||||
]
|
||||
]
|
||||
| None -> List.empty
|
||||
header [ _class "pt-title-bar" ] [
|
||||
section [ _class "pt-title-bar-left" ] [
|
||||
span [ _class "pt-title-bar-home" ] [
|
||||
a [ _href "/web/"; _title s.["Home"].Value ] [ locStr s.["PrayerTracker"] ]
|
||||
]
|
||||
ul [] leftLinks
|
||||
]
|
||||
section [ _class "pt-title-bar-center" ] []
|
||||
section [ _class "pt-title-bar-right"; _role "toolbar" ] [
|
||||
ul [] rightLinks
|
||||
]
|
||||
]
|
||||
|
||||
/// Identity bar (below top nav)
|
||||
let identity m =
|
||||
let s = I18N.localizer.Force ()
|
||||
header [ _id "pt-language" ] [
|
||||
div [] [
|
||||
span [ _class "u" ] [ locStr s.["Language"]; rawText ": " ]
|
||||
match langCode () with
|
||||
| "es" ->
|
||||
locStr s.["Spanish"]
|
||||
rawText " • "
|
||||
a [ _href "/web/language/en" ] [ locStr s.["Change to English"] ]
|
||||
| _ ->
|
||||
locStr s.["English"]
|
||||
rawText " • "
|
||||
a [ _href "/web/language/es" ] [ locStr s.["Cambie a Español"] ]
|
||||
]
|
||||
match m.group with
|
||||
| Some g ->
|
||||
[ match m.user with
|
||||
| Some u ->
|
||||
span [ _class "u" ] [ locStr s.["Currently Logged On"] ]
|
||||
rawText " "
|
||||
icon "person"
|
||||
strong [] [ str u.fullName ]
|
||||
rawText " "
|
||||
| None ->
|
||||
locStr s.["Logged On as a Member of"]
|
||||
rawText " "
|
||||
icon "group"
|
||||
space
|
||||
/// Top navigation bar
|
||||
let top m =
|
||||
let s = I18N.localizer.Force ()
|
||||
let menuSpacer = rawText " "
|
||||
let leftLinks = [
|
||||
match m.user with
|
||||
| Some _ -> a [ _href "/web/small-group" ] [ strong [] [ str g.name ] ]
|
||||
| None -> strong [] [ str g.name ]
|
||||
rawText " "
|
||||
| Some u ->
|
||||
li [ _class "dropdown" ] [
|
||||
a [ _class "dropbtn"; _role "button"; _aria "label" s["Requests"].Value; _title s["Requests"].Value ]
|
||||
[ icon "question_answer"; space; locStr s["Requests"]; space; icon "keyboard_arrow_down" ]
|
||||
div [ _class "dropdown-content"; _role "menu" ] [
|
||||
a [ _href "/web/prayer-requests" ] [ icon "compare_arrows"; menuSpacer; locStr s["Maintain"] ]
|
||||
a [ _href "/web/prayer-requests/view" ] [ icon "list"; menuSpacer; locStr s["View List"] ]
|
||||
]
|
||||
]
|
||||
li [ _class "dropdown" ] [
|
||||
a [ _class "dropbtn"; _role "button"; _aria "label" s["Group"].Value; _title s["Group"].Value ]
|
||||
[ icon "group"; space; locStr s["Group"]; space; icon "keyboard_arrow_down" ]
|
||||
div [ _class "dropdown-content"; _role "menu" ] [
|
||||
a [ _href "/web/small-group/members" ]
|
||||
[ icon "email"; menuSpacer; locStr s["Maintain Group Members"] ]
|
||||
a [ _href "/web/small-group/announcement" ]
|
||||
[ icon "send"; menuSpacer; locStr s["Send Announcement"] ]
|
||||
a [ _href "/web/small-group/preferences" ]
|
||||
[ icon "build"; menuSpacer; locStr s["Change Preferences"] ]
|
||||
]
|
||||
]
|
||||
if u.isAdmin then
|
||||
li [ _class "dropdown" ] [
|
||||
a [ _class "dropbtn"
|
||||
_role "button"
|
||||
_aria "label" s["Administration"].Value
|
||||
_title s["Administration"].Value
|
||||
] [ icon "settings"; space; locStr s["Administration"]; space; icon "keyboard_arrow_down" ]
|
||||
div [ _class "dropdown-content"; _role "menu" ] [
|
||||
a [ _href "/web/churches" ] [ icon "home"; menuSpacer; locStr s["Churches"] ]
|
||||
a [ _href "/web/small-groups" ] [ icon "send"; menuSpacer; locStr s["Groups"] ]
|
||||
a [ _href "/web/users" ] [ icon "build"; menuSpacer; locStr s["Users"] ]
|
||||
]
|
||||
]
|
||||
| None ->
|
||||
match m.group with
|
||||
| Some _ ->
|
||||
li [] [
|
||||
a [ _href "/web/prayer-requests/view"
|
||||
_aria "label" s["View Request List"].Value
|
||||
_title s["View Request List"].Value
|
||||
] [ icon "list"; space; locStr s["View Request List"] ]
|
||||
]
|
||||
| None ->
|
||||
li [ _class "dropdown" ] [
|
||||
a [ _class "dropbtn"
|
||||
_role "button"
|
||||
_aria "label" s["Log On"].Value
|
||||
_title s["Log On"].Value
|
||||
] [ icon "security"; space; locStr s["Log On"]; space; icon "keyboard_arrow_down" ]
|
||||
div [ _class "dropdown-content"; _role "menu" ] [
|
||||
a [ _href "/web/user/log-on" ] [ icon "person"; menuSpacer; locStr s["User"] ]
|
||||
a [ _href "/web/small-group/log-on" ] [ icon "group"; menuSpacer; locStr s["Group"] ]
|
||||
]
|
||||
]
|
||||
li [] [
|
||||
a [ _href "/web/prayer-requests/lists"
|
||||
_aria "label" s["View Request List"].Value
|
||||
_title s["View Request List"].Value
|
||||
] [ icon "list"; space; locStr s["View Request List"] ]
|
||||
]
|
||||
li [] [
|
||||
a [ _href $"https://docs.prayer.bitbadger.solutions/{langCode ()}"
|
||||
_aria "label" s["Help"].Value;
|
||||
_title s["View Help"].Value
|
||||
_target "_blank"
|
||||
] [ icon "help"; space; locStr s["Help"] ]
|
||||
]
|
||||
| None -> []
|
||||
|> div []
|
||||
]
|
||||
]
|
||||
let rightLinks =
|
||||
match m.group with
|
||||
| Some _ -> [
|
||||
match m.user with
|
||||
| Some _ ->
|
||||
li [] [
|
||||
a [ _href "/web/user/password"
|
||||
_aria "label" s["Change Your Password"].Value
|
||||
_title s["Change Your Password"].Value
|
||||
] [ icon "lock"; space; locStr s["Change Your Password"] ]
|
||||
]
|
||||
| None -> ()
|
||||
li [] [
|
||||
a [ _href "/web/log-off"; _aria "label" s["Log Off"].Value; _title s["Log Off"].Value ]
|
||||
[ icon "power_settings_new"; space; locStr s["Log Off"] ]
|
||||
]
|
||||
]
|
||||
| None -> []
|
||||
header [ _class "pt-title-bar" ] [
|
||||
section [ _class "pt-title-bar-left" ] [
|
||||
span [ _class "pt-title-bar-home" ] [
|
||||
a [ _href "/web/"; _title s["Home"].Value ] [ locStr s["PrayerTracker"] ]
|
||||
]
|
||||
ul [] leftLinks
|
||||
]
|
||||
section [ _class "pt-title-bar-center" ] []
|
||||
section [ _class "pt-title-bar-right"; _role "toolbar" ] [
|
||||
ul [] rightLinks
|
||||
]
|
||||
]
|
||||
|
||||
/// Identity bar (below top nav)
|
||||
let identity m =
|
||||
let s = I18N.localizer.Force ()
|
||||
header [ _id "pt-language" ] [
|
||||
div [] [
|
||||
span [ _class "u" ] [ locStr s["Language"]; rawText ": " ]
|
||||
match langCode () with
|
||||
| "es" ->
|
||||
locStr s["Spanish"]
|
||||
rawText " • "
|
||||
a [ _href "/web/language/en" ] [ locStr s["Change to English"] ]
|
||||
| _ ->
|
||||
locStr s["English"]
|
||||
rawText " • "
|
||||
a [ _href "/web/language/es" ] [ locStr s["Cambie a Español"] ]
|
||||
]
|
||||
match m.group with
|
||||
| Some g ->[
|
||||
match m.user with
|
||||
| Some u ->
|
||||
span [ _class "u" ] [ locStr s["Currently Logged On"] ]
|
||||
rawText " "
|
||||
icon "person"
|
||||
strong [] [ str u.fullName ]
|
||||
rawText " "
|
||||
| None ->
|
||||
locStr s["Logged On as a Member of"]
|
||||
rawText " "
|
||||
icon "group"
|
||||
space
|
||||
match m.user with
|
||||
| Some _ -> a [ _href "/web/small-group" ] [ strong [] [ str g.name ] ]
|
||||
| None -> strong [] [ str g.name ]
|
||||
rawText " "
|
||||
]
|
||||
| None -> []
|
||||
|> div []
|
||||
]
|
||||
|
||||
|
||||
/// Content layouts
|
||||
module Content =
|
||||
/// Content layout that tops at 60rem
|
||||
let standard = div [ _class "pt-content" ]
|
||||
|
||||
/// Content layout that uses the full width of the browser window
|
||||
let wide = div [ _class "pt-content pt-full-width" ]
|
||||
/// Content layout that tops at 60rem
|
||||
let standard = div [ _class "pt-content" ]
|
||||
|
||||
/// Content layout that uses the full width of the browser window
|
||||
let wide = div [ _class "pt-content pt-full-width" ]
|
||||
|
||||
|
||||
/// Separator for parts of the title
|
||||
let private titleSep = rawText " « "
|
||||
|
||||
/// Common HTML head tag items
|
||||
let private commonHead =
|
||||
[ meta [ _name "viewport"; _content "width=device-width, initial-scale=1" ]
|
||||
meta [ _name "generator"; _content "Giraffe" ]
|
||||
link [ _rel "stylesheet"; _href "https://fonts.googleapis.com/icon?family=Material+Icons" ]
|
||||
link [ _rel "stylesheet"; _href "/css/app.css" ]
|
||||
script [ _src "/js/app.js" ] []
|
||||
[ meta [ _name "viewport"; _content "width=device-width, initial-scale=1" ]
|
||||
meta [ _name "generator"; _content "Giraffe" ]
|
||||
link [ _rel "stylesheet"; _href "https://fonts.googleapis.com/icon?family=Material+Icons" ]
|
||||
link [ _rel "stylesheet"; _href "/css/app.css" ]
|
||||
script [ _src "/js/app.js" ] []
|
||||
]
|
||||
|
||||
/// Render the <head> portion of the page
|
||||
let private htmlHead m pageTitle =
|
||||
let s = I18N.localizer.Force ()
|
||||
head [] [
|
||||
meta [ _charset "UTF-8" ]
|
||||
title [] [ locStr pageTitle; titleSep; locStr s.["PrayerTracker"] ]
|
||||
yield! commonHead
|
||||
for cssFile in m.style do
|
||||
link [ _rel "stylesheet"; _href $"/css/{cssFile}.css"; _type "text/css" ]
|
||||
for jsFile in m.script do
|
||||
script [ _src $"/js/{jsFile}.js" ] []
|
||||
let s = I18N.localizer.Force ()
|
||||
head [] [
|
||||
meta [ _charset "UTF-8" ]
|
||||
title [] [ locStr pageTitle; titleSep; locStr s["PrayerTracker"] ]
|
||||
yield! commonHead
|
||||
for cssFile in m.style do
|
||||
link [ _rel "stylesheet"; _href $"/css/{cssFile}.css"; _type "text/css" ]
|
||||
for jsFile in m.script do
|
||||
script [ _src $"/js/{jsFile}.js" ] []
|
||||
]
|
||||
|
||||
/// Render a link to the help page for the current page
|
||||
let private helpLink link =
|
||||
let s = I18N.localizer.Force ()
|
||||
sup [] [
|
||||
a [ _href link
|
||||
_title s.["Click for Help on This Page"].Value
|
||||
_onclick $"return PT.showHelp('{link}')" ] [
|
||||
icon "help_outline"
|
||||
]
|
||||
let s = I18N.localizer.Force ()
|
||||
sup [] [
|
||||
a [ _href link; _title s["Click for Help on This Page"].Value; _onclick $"return PT.showHelp('{link}')" ]
|
||||
[ icon "help_outline" ]
|
||||
]
|
||||
|
||||
/// Render the page title, and optionally a help link
|
||||
let private renderPageTitle m pageTitle =
|
||||
h2 [ _id "pt-page-title" ] [
|
||||
match m.helpLink with Some link -> Help.fullLink (langCode ()) link |> helpLink | None -> ()
|
||||
locStr pageTitle
|
||||
h2 [ _id "pt-page-title" ] [
|
||||
match m.helpLink with Some link -> Help.fullLink (langCode ()) link |> helpLink | None -> ()
|
||||
locStr pageTitle
|
||||
]
|
||||
|
||||
/// Render the messages that may need to be displayed to the user
|
||||
let private messages m =
|
||||
let s = I18N.localizer.Force ()
|
||||
m.messages
|
||||
|> List.map (fun msg ->
|
||||
table [ _class $"pt-msg {msg.level.ToLower ()}" ] [
|
||||
tr [] [
|
||||
td [] [
|
||||
match msg.level with
|
||||
| "Info" -> ()
|
||||
| lvl ->
|
||||
strong [] [ locStr s.[lvl] ]
|
||||
rawText " » "
|
||||
rawText msg.text.Value
|
||||
match msg.description with
|
||||
| Some desc ->
|
||||
br []
|
||||
div [ _class "description" ] [ rawText desc.Value ]
|
||||
| None -> ()
|
||||
let s = I18N.localizer.Force ()
|
||||
m.messages
|
||||
|> List.map (fun msg ->
|
||||
table [ _class $"pt-msg {msg.level.ToLower ()}" ] [
|
||||
tr [] [
|
||||
td [] [
|
||||
match msg.level with
|
||||
| "Info" -> ()
|
||||
| lvl ->
|
||||
strong [] [ locStr s[lvl] ]
|
||||
rawText " » "
|
||||
rawText msg.text.Value
|
||||
match msg.description with
|
||||
| Some desc ->
|
||||
br []
|
||||
div [ _class "description" ] [ rawText desc.Value ]
|
||||
| None -> ()
|
||||
]
|
||||
]
|
||||
]
|
||||
])
|
||||
|
||||
/// Render the <footer> at the bottom of the page
|
||||
let private htmlFooter m =
|
||||
let s = I18N.localizer.Force ()
|
||||
let imgText = sprintf "%O %O" s.["PrayerTracker"] s.["from Bit Badger Solutions"]
|
||||
let resultTime = TimeSpan(DateTime.Now.Ticks - m.requestStart).TotalSeconds
|
||||
footer [] [
|
||||
div [ _id "pt-legal" ] [
|
||||
a [ _href "/web/legal/privacy-policy" ] [ locStr s.["Privacy Policy"] ]
|
||||
rawText " • "
|
||||
a [ _href "/web/legal/terms-of-service" ] [ locStr s.["Terms of Service"] ]
|
||||
rawText " • "
|
||||
a [ _href "https://github.com/bit-badger/PrayerTracker"
|
||||
_title s.["View source code and get technical support"].Value
|
||||
_target "_blank"
|
||||
_rel "noopener" ] [
|
||||
locStr s.["Source & Support"]
|
||||
let s = I18N.localizer.Force ()
|
||||
let imgText = sprintf "%O %O" s["PrayerTracker"] s["from Bit Badger Solutions"]
|
||||
let resultTime = TimeSpan(DateTime.Now.Ticks - m.requestStart).TotalSeconds
|
||||
footer [] [
|
||||
div [ _id "pt-legal" ] [
|
||||
a [ _href "/web/legal/privacy-policy" ] [ locStr s["Privacy Policy"] ]
|
||||
rawText " • "
|
||||
a [ _href "/web/legal/terms-of-service" ] [ locStr s["Terms of Service"] ]
|
||||
rawText " • "
|
||||
a [ _href "https://github.com/bit-badger/PrayerTracker"
|
||||
_title s["View source code and get technical support"].Value
|
||||
_target "_blank"
|
||||
_rel "noopener"
|
||||
] [ locStr s["Source & Support"]
|
||||
]
|
||||
]
|
||||
]
|
||||
div [ _id "pt-footer" ] [
|
||||
a [ _href "/web/"; _style "line-height:28px;" ] [
|
||||
img [ _src $"""/img/%O{s.["footer_en"]}.png"""; _alt imgText; _title imgText ]
|
||||
div [ _id "pt-footer" ] [
|
||||
a [ _href "/web/"; _style "line-height:28px;" ]
|
||||
[ img [ _src $"""/img/%O{s["footer_en"]}.png"""; _alt imgText; _title imgText ] ]
|
||||
str m.version
|
||||
space
|
||||
i [ _title s["This page loaded in {0:N3} seconds", resultTime].Value; _class "material-icons md-18" ]
|
||||
[ str "schedule" ]
|
||||
]
|
||||
str m.version
|
||||
space
|
||||
i [ _title s.["This page loaded in {0:N3} seconds", resultTime].Value; _class "material-icons md-18" ] [
|
||||
str "schedule"
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
/// The standard layout for PrayerTracker
|
||||
let standard m pageTitle (content : XmlNode) =
|
||||
let s = I18N.localizer.Force ()
|
||||
let ttl = s.[pageTitle]
|
||||
html [ _lang "" ] [
|
||||
htmlHead m ttl
|
||||
body [] [
|
||||
Navigation.top m
|
||||
div [ _id "pt-body" ] [
|
||||
Navigation.identity m
|
||||
renderPageTitle m ttl
|
||||
yield! messages m
|
||||
content
|
||||
htmlFooter m
|
||||
let s = I18N.localizer.Force ()
|
||||
let ttl = s[pageTitle]
|
||||
html [ _lang "" ] [
|
||||
htmlHead m ttl
|
||||
body [] [
|
||||
Navigation.top m
|
||||
div [ _id "pt-body" ] [
|
||||
Navigation.identity m
|
||||
renderPageTitle m ttl
|
||||
yield! messages m
|
||||
content
|
||||
htmlFooter m
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
/// A layout with nothing but a title and content
|
||||
let bare pageTitle content =
|
||||
let s = I18N.localizer.Force ()
|
||||
let ttl = s.[pageTitle]
|
||||
html [ _lang "" ] [
|
||||
head [] [
|
||||
meta [ _charset "UTF-8" ]
|
||||
title [] [ locStr ttl; titleSep; locStr s.["PrayerTracker"] ]
|
||||
]
|
||||
body [] [ content ]
|
||||
let s = I18N.localizer.Force ()
|
||||
let ttl = s[pageTitle]
|
||||
html [ _lang "" ] [
|
||||
head [] [
|
||||
meta [ _charset "UTF-8" ]
|
||||
title [] [ locStr ttl; titleSep; locStr s["PrayerTracker"] ]
|
||||
]
|
||||
body [] [ content ]
|
||||
]
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
module PrayerTracker.Views.PrayerRequest
|
||||
|
||||
open System
|
||||
open System.IO
|
||||
open Giraffe
|
||||
open Giraffe.ViewEngine
|
||||
open Microsoft.AspNetCore.Http
|
||||
|
@ -7,364 +9,347 @@ open NodaTime
|
|||
open PrayerTracker
|
||||
open PrayerTracker.Entities
|
||||
open PrayerTracker.ViewModels
|
||||
open System
|
||||
open System.IO
|
||||
open System.Text
|
||||
|
||||
/// View for the prayer request edit page
|
||||
let edit (m : EditRequest) today ctx vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = match m.isNew () with true -> "Add a New Request" | false -> "Edit Request"
|
||||
[ form [ _action "/web/prayer-request/save"; _method "post"; _class "pt-center-columns" ] [
|
||||
csrfToken ctx
|
||||
input [ _type "hidden"; _name "requestId"; _value (flatGuid m.requestId) ]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "requestType" ] [ locStr s.["Request Type"] ]
|
||||
ReferenceList.requestTypeList s
|
||||
|> Seq.ofList
|
||||
|> Seq.map (fun (typ, desc) -> typ.code, desc.Value)
|
||||
|> selectList "requestType" m.requestType [ _required; _autofocus ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "requestor" ] [ locStr s.["Requestor / Subject"] ]
|
||||
input [ _type "text"
|
||||
_name "requestor"
|
||||
_id "requestor"
|
||||
_value (match m.requestor with Some x -> x | None -> "") ]
|
||||
]
|
||||
match m.isNew () with
|
||||
| true ->
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = if m.isNew () then "Add a New Request" else "Edit Request"
|
||||
[ form [ _action "/web/prayer-request/save"; _method "post"; _class "pt-center-columns" ] [
|
||||
csrfToken ctx
|
||||
input [ _type "hidden"; _name "requestId"; _value (flatGuid m.requestId) ]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "enteredDate" ] [ locStr s.["Date"] ]
|
||||
input [ _type "date"; _name "enteredDate"; _id "enteredDate"; _placeholder today ]
|
||||
]
|
||||
| false ->
|
||||
label [ _for "requestType" ] [ locStr s["Request Type"] ]
|
||||
ReferenceList.requestTypeList s
|
||||
|> Seq.ofList
|
||||
|> Seq.map (fun (typ, desc) -> typ.code, desc.Value)
|
||||
|> selectList "requestType" m.requestType [ _required; _autofocus ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
div [ _class "pt-checkbox-field" ] [
|
||||
br []
|
||||
input [ _type "checkbox"; _name "skipDateUpdate"; _id "skipDateUpdate"; _value "True" ]
|
||||
label [ _for "skipDateUpdate" ] [ locStr s.["Check to not update the date"] ]
|
||||
br []
|
||||
small [] [ em [] [ str (s.["Typo Corrections"].Value.ToLower ()); rawText ", etc." ] ]
|
||||
label [ _for "requestor" ] [ locStr s["Requestor / Subject"] ]
|
||||
input [ _type "text"
|
||||
_name "requestor"
|
||||
_id "requestor"
|
||||
_value (match m.requestor with Some x -> x | None -> "") ]
|
||||
]
|
||||
if m.isNew () then
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "enteredDate" ] [ locStr s["Date"] ]
|
||||
input [ _type "date"; _name "enteredDate"; _id "enteredDate"; _placeholder today ]
|
||||
]
|
||||
else
|
||||
div [ _class "pt-field" ] [
|
||||
div [ _class "pt-checkbox-field" ] [
|
||||
br []
|
||||
input [ _type "checkbox"; _name "skipDateUpdate"; _id "skipDateUpdate"; _value "True" ]
|
||||
label [ _for "skipDateUpdate" ] [ locStr s["Check to not update the date"] ]
|
||||
br []
|
||||
small [] [ em [] [ str (s["Typo Corrections"].Value.ToLower ()); rawText ", etc." ] ]
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [] [ locStr s.["Expiration"] ]
|
||||
ReferenceList.expirationList s ((m.isNew >> not) ())
|
||||
|> List.map (fun exp ->
|
||||
let radioId = $"expiration_{fst exp}"
|
||||
span [ _class "text-nowrap" ] [
|
||||
radio "expiration" radioId (fst exp) m.expiration
|
||||
label [ _for radioId ] [ locStr (snd exp) ]
|
||||
rawText " "
|
||||
])
|
||||
|> div [ _class "pt-center-text" ]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [] [ locStr s["Expiration"] ]
|
||||
ReferenceList.expirationList s ((m.isNew >> not) ())
|
||||
|> List.map (fun exp ->
|
||||
let radioId = $"expiration_{fst exp}"
|
||||
span [ _class "text-nowrap" ] [
|
||||
radio "expiration" radioId (fst exp) m.expiration
|
||||
label [ _for radioId ] [ locStr (snd exp) ]
|
||||
rawText " "
|
||||
])
|
||||
|> div [ _class "pt-center-text" ]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field pt-editor" ] [
|
||||
label [ _for "text" ] [ locStr s.["Request"] ]
|
||||
textarea [ _name "text"; _id "text" ] [ str m.text ]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field pt-editor" ] [
|
||||
label [ _for "text" ] [ locStr s["Request"] ]
|
||||
textarea [ _name "text"; _id "text" ] [ str m.text ]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [ submit [] "save" s.["Save Request"] ]
|
||||
]
|
||||
script [] [ rawText "PT.onLoad(PT.initCKEditor)" ]
|
||||
div [ _class "pt-field-row" ] [ submit [] "save" s["Save Request"] ]
|
||||
]
|
||||
script [] [ rawText "PT.onLoad(PT.initCKEditor)" ]
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|
||||
/// View for the request e-mail results page
|
||||
let email m vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = $"""{s.["Prayer Requests"].Value} • {m.listGroup.name}"""
|
||||
let prefs = m.listGroup.preferences
|
||||
let addresses =
|
||||
m.recipients
|
||||
|> List.fold (fun (acc : StringBuilder) mbr -> acc.AppendFormat(", {0} <{1}>", mbr.memberName, mbr.email))
|
||||
(StringBuilder ())
|
||||
[ p [ _style $"font-family:{prefs.listFonts};font-size:%i{prefs.textFontSize}pt;" ] [
|
||||
locStr s.["The request list was sent to the following people, via individual e-mails"]
|
||||
rawText ":"
|
||||
br []
|
||||
small [] [ str (addresses.Remove(0, 2).ToString ()) ]
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = $"""{s["Prayer Requests"].Value} • {m.listGroup.name}"""
|
||||
let prefs = m.listGroup.preferences
|
||||
let addresses = String.Join (", ", m.recipients |> List.map (fun mbr -> $"{mbr.memberName} <{mbr.email}>"))
|
||||
[ p [ _style $"font-family:{prefs.listFonts};font-size:%i{prefs.textFontSize}pt;" ] [
|
||||
locStr s["The request list was sent to the following people, via individual e-mails"]
|
||||
rawText ":"
|
||||
br []
|
||||
small [] [ str addresses ]
|
||||
]
|
||||
span [ _class "pt-email-heading" ] [ locStr s.["HTML Format"]; rawText ":" ]
|
||||
div [ _class "pt-email-canvas" ] [ rawText (m.asHtml s) ]
|
||||
br []
|
||||
br []
|
||||
span [ _class "pt-email-heading" ] [ locStr s.["Plain-Text Format"]; rawText ":" ]
|
||||
div[ _class "pt-email-canvas" ] [ pre [] [ str (m.asText s) ] ]
|
||||
span [ _class "pt-email-heading" ] [ locStr s["HTML Format"]; rawText ":" ]
|
||||
div [ _class "pt-email-canvas" ] [ rawText (m.asHtml s) ]
|
||||
br []
|
||||
br []
|
||||
span [ _class "pt-email-heading" ] [ locStr s["Plain-Text Format"]; rawText ":" ]
|
||||
div [ _class "pt-email-canvas" ] [ pre [] [ str (m.asText s) ] ]
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|
||||
|
||||
/// View for a small group's public prayer request list
|
||||
let list (m : RequestList) vi =
|
||||
[ br []
|
||||
I18N.localizer.Force () |> (m.asHtml >> rawText)
|
||||
[ br []
|
||||
I18N.localizer.Force () |> (m.asHtml >> rawText)
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "View Request List"
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "View Request List"
|
||||
|
||||
|
||||
/// View for the prayer request lists page
|
||||
let lists (grps : SmallGroup list) vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Requests/Lists"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
[ p [] [
|
||||
raw l.["The groups listed below have either public or password-protected request lists."]
|
||||
space
|
||||
raw l.["Those with list icons are public, and those with log on icons are password-protected."]
|
||||
space
|
||||
raw l.["Click the appropriate icon to log on or view the request list."]
|
||||
let lists (groups : SmallGroup list) vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Requests/Lists"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
[ p [] [
|
||||
raw l["The groups listed below have either public or password-protected request lists."]
|
||||
space
|
||||
raw l["Those with list icons are public, and those with log on icons are password-protected."]
|
||||
space
|
||||
raw l["Click the appropriate icon to log on or view the request list."]
|
||||
]
|
||||
match grps.Length with
|
||||
| 0 -> p [] [ raw l.["There are no groups with public or password-protected request lists."] ]
|
||||
| count ->
|
||||
tableSummary count s
|
||||
table [ _class "pt-table pt-action-table" ] [
|
||||
thead [] [
|
||||
tr [] [
|
||||
th [] [ locStr s.["Actions"] ]
|
||||
th [] [ locStr s.["Church"] ]
|
||||
th [] [ locStr s.["Group"] ]
|
||||
match groups.Length with
|
||||
| 0 -> p [] [ raw l["There are no groups with public or password-protected request lists."] ]
|
||||
| count ->
|
||||
tableSummary count s
|
||||
table [ _class "pt-table pt-action-table" ] [
|
||||
thead [] [
|
||||
tr [] [
|
||||
th [] [ locStr s["Actions"] ]
|
||||
th [] [ locStr s["Church"] ]
|
||||
th [] [ locStr s["Group"] ]
|
||||
]
|
||||
]
|
||||
]
|
||||
grps
|
||||
|> List.map (fun grp ->
|
||||
let grpId = flatGuid grp.smallGroupId
|
||||
tr [] [
|
||||
match grp.preferences.isPublic with
|
||||
| true ->
|
||||
a [ _href $"/web/prayer-requests/{grpId}/list"; _title s.["View"].Value ] [ icon "list" ]
|
||||
| false ->
|
||||
a [ _href $"/web/small-group/log-on/{grpId}"; _title s.["Log On"].Value ]
|
||||
[ icon "verified_user" ]
|
||||
|> List.singleton
|
||||
|> td []
|
||||
td [] [ str grp.church.name ]
|
||||
td [] [ str grp.name ]
|
||||
])
|
||||
|> tbody []
|
||||
groups
|
||||
|> List.map (fun grp ->
|
||||
let grpId = flatGuid grp.smallGroupId
|
||||
tr [] [
|
||||
if grp.preferences.isPublic then
|
||||
a [ _href $"/web/prayer-requests/{grpId}/list"; _title s["View"].Value ] [ icon "list" ]
|
||||
else
|
||||
a [ _href $"/web/small-group/log-on/{grpId}"; _title s["Log On"].Value ]
|
||||
[ icon "verified_user" ]
|
||||
|> List.singleton
|
||||
|> td []
|
||||
td [] [ str grp.church.name ]
|
||||
td [] [ str grp.name ]
|
||||
])
|
||||
|> tbody []
|
||||
]
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Request Lists"
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Request Lists"
|
||||
|
||||
|
||||
/// View for the prayer request maintenance page
|
||||
let maintain m (ctx : HttpContext) vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Requests/Maintain"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
let now = m.smallGroup.localDateNow (ctx.GetService<IClock> ())
|
||||
let typs = ReferenceList.requestTypeList s |> Map.ofList
|
||||
let updReq (req : PrayerRequest) =
|
||||
match req.updateRequired now m.smallGroup.preferences.daysToExpire m.smallGroup.preferences.longTermUpdateWeeks with
|
||||
| true -> "pt-request-update"
|
||||
| false -> ""
|
||||
|> _class
|
||||
let reqExp (req : PrayerRequest) =
|
||||
_class (match req.isExpired now m.smallGroup.preferences.daysToExpire with true -> "pt-request-expired" | false -> "")
|
||||
/// Iterate the sequence once, before we render, so we can get the count of it at the top of the table
|
||||
let requests =
|
||||
m.requests
|
||||
|> Seq.map (fun req ->
|
||||
let reqId = flatGuid req.prayerRequestId
|
||||
let reqText = htmlToPlainText req.text
|
||||
let delAction = $"/web/prayer-request/{reqId}/delete"
|
||||
let delPrompt =
|
||||
[ s.["Are you sure you want to delete this {0}? This action cannot be undone.",
|
||||
s.["Prayer Request"].Value.ToLower() ]
|
||||
.Value
|
||||
"\\n"
|
||||
l.["(If the prayer request has been answered, or an event has passed, consider inactivating it instead.)"]
|
||||
.Value
|
||||
]
|
||||
|> String.concat ""
|
||||
tr [] [
|
||||
td [] [
|
||||
a [ _href $"/web/prayer-request/{reqId}/edit"; _title l.["Edit This Prayer Request"].Value ]
|
||||
[ icon "edit" ]
|
||||
match req.isExpired now m.smallGroup.preferences.daysToExpire with
|
||||
| true ->
|
||||
a [ _href $"/web/prayer-request/{reqId}/restore"
|
||||
_title l.["Restore This Inactive Request"].Value ]
|
||||
[ icon "visibility" ]
|
||||
| false ->
|
||||
a [ _href $"/web/prayer-request/{reqId}/expire"
|
||||
_title l.["Expire This Request Immediately"].Value ]
|
||||
[ icon "visibility_off" ]
|
||||
a [ _href delAction; _title l.["Delete This Request"].Value;
|
||||
_onclick $"return PT.confirmDelete('{delAction}','{delPrompt}')" ]
|
||||
[ icon "delete_forever" ]
|
||||
]
|
||||
td [ updReq req ] [
|
||||
str (req.updatedDate.ToString(s.["MMMM d, yyyy"].Value, Globalization.CultureInfo.CurrentUICulture))
|
||||
]
|
||||
td [] [ locStr typs.[req.requestType] ]
|
||||
td [ reqExp req ] [ str (match req.requestor with Some r -> r | None -> " ") ]
|
||||
td [] [
|
||||
match reqText.Length with
|
||||
| len when len < 60 -> rawText reqText
|
||||
| _ -> rawText $"{reqText.[0..59]}…"
|
||||
]
|
||||
])
|
||||
|> List.ofSeq
|
||||
[ div [ _class "pt-center-text" ] [
|
||||
br []
|
||||
a [ _href $"/web/prayer-request/{emptyGuid}/edit"; _title s.["Add a New Request"].Value ]
|
||||
[ icon "add_circle"; rawText " "; locStr s.["Add a New Request"] ]
|
||||
rawText " "
|
||||
a [ _href "/web/prayer-requests/view"; _title s.["View Prayer Request List"].Value ]
|
||||
[ icon "list"; rawText " "; locStr s.["View Prayer Request List"] ]
|
||||
match m.searchTerm with
|
||||
| Some _ ->
|
||||
rawText " "
|
||||
a [ _href "/web/prayer-requests"; _title l.["Clear Search Criteria"].Value ]
|
||||
[ icon "highlight_off"; rawText " "; raw l.["Clear Search Criteria"] ]
|
||||
| None -> ()
|
||||
]
|
||||
form [ _action "/web/prayer-requests"; _method "get"; _class "pt-center-text pt-search-form" ] [
|
||||
input [ _type "text"
|
||||
_name "search"
|
||||
_placeholder l.["Search requests..."].Value
|
||||
_value (defaultArg m.searchTerm "")
|
||||
]
|
||||
space
|
||||
submit [] "search" s.["Search"]
|
||||
]
|
||||
br []
|
||||
tableSummary requests.Length s
|
||||
match requests.Length with
|
||||
| 0 -> ()
|
||||
| _ ->
|
||||
table [ _class "pt-table pt-action-table" ] [
|
||||
thead [] [
|
||||
let s = I18N.localizer.Force ()
|
||||
let l = I18N.forView "Requests/Maintain"
|
||||
use sw = new StringWriter ()
|
||||
let raw = rawLocText sw
|
||||
let now = m.smallGroup.localDateNow (ctx.GetService<IClock> ())
|
||||
let typs = ReferenceList.requestTypeList s |> Map.ofList
|
||||
let updReq (req : PrayerRequest) =
|
||||
if req.updateRequired now m.smallGroup.preferences.daysToExpire m.smallGroup.preferences.longTermUpdateWeeks then
|
||||
"pt-request-update"
|
||||
else ""
|
||||
|> _class
|
||||
let reqExp (req : PrayerRequest) =
|
||||
_class (if req.isExpired now m.smallGroup.preferences.daysToExpire then "pt-request-expired" else "")
|
||||
/// Iterate the sequence once, before we render, so we can get the count of it at the top of the table
|
||||
let requests =
|
||||
m.requests
|
||||
|> Seq.map (fun req ->
|
||||
let reqId = flatGuid req.prayerRequestId
|
||||
let reqText = htmlToPlainText req.text
|
||||
let delAction = $"/web/prayer-request/{reqId}/delete"
|
||||
let delPrompt =
|
||||
[ s["Are you sure you want to delete this {0}? This action cannot be undone.",
|
||||
s["Prayer Request"].Value.ToLower() ].Value
|
||||
"\\n"
|
||||
l["(If the prayer request has been answered, or an event has passed, consider inactivating it instead.)"]
|
||||
.Value
|
||||
]
|
||||
|> String.concat ""
|
||||
tr [] [
|
||||
th [] [ locStr s.["Actions"] ]
|
||||
th [] [ locStr s.["Updated Date"] ]
|
||||
th [] [ locStr s.["Type"] ]
|
||||
th [] [ locStr s.["Requestor"] ]
|
||||
th [] [ locStr s.["Request"] ]
|
||||
]
|
||||
]
|
||||
tbody [] requests
|
||||
]
|
||||
div [ _class "pt-center-text" ] [
|
||||
br []
|
||||
match m.onlyActive with
|
||||
| Some true ->
|
||||
raw l.["Inactive requests are currently not shown"]
|
||||
br []
|
||||
a [ _href "/web/prayer-requests/inactive" ] [ raw l.["Show Inactive Requests"] ]
|
||||
| _ ->
|
||||
match Option.isSome m.onlyActive with
|
||||
| true ->
|
||||
raw l.["Inactive requests are currently shown"]
|
||||
br []
|
||||
a [ _href "/web/prayer-requests" ] [ raw l.["Do Not Show Inactive Requests"] ]
|
||||
br []
|
||||
br []
|
||||
| false -> ()
|
||||
let srch = [ match m.searchTerm with Some s -> "search", s | None -> () ]
|
||||
let pg = defaultArg m.pageNbr 1
|
||||
let url =
|
||||
match m.onlyActive with Some true | None -> "" | _ -> "/inactive" |> sprintf "/web/prayer-requests%s"
|
||||
match pg with
|
||||
| 1 -> ()
|
||||
| _ ->
|
||||
// button (_type "submit" :: attrs) [ icon ico; rawText " "; locStr text ]
|
||||
let withPage = match pg with 2 -> srch | _ -> ("page", string (pg - 1)) :: srch
|
||||
a [ _href (makeUrl url withPage) ]
|
||||
[ icon "keyboard_arrow_left"; space; raw l.["Previous Page"] ]
|
||||
rawText " "
|
||||
match requests.Length = m.smallGroup.preferences.pageSize with
|
||||
| true ->
|
||||
a [ _href (makeUrl url (("page", string (pg + 1)) :: srch)) ]
|
||||
[ raw l.["Next Page"]; space; icon "keyboard_arrow_right" ]
|
||||
| false -> ()
|
||||
td [] [
|
||||
a [ _href $"/web/prayer-request/{reqId}/edit"; _title l["Edit This Prayer Request"].Value ]
|
||||
[ icon "edit" ]
|
||||
if req.isExpired now m.smallGroup.preferences.daysToExpire then
|
||||
a [ _href $"/web/prayer-request/{reqId}/restore"
|
||||
_title l["Restore This Inactive Request"].Value ]
|
||||
[ icon "visibility" ]
|
||||
else
|
||||
a [ _href $"/web/prayer-request/{reqId}/expire"
|
||||
_title l["Expire This Request Immediately"].Value ]
|
||||
[ icon "visibility_off" ]
|
||||
a [ _href delAction; _title l["Delete This Request"].Value;
|
||||
_onclick $"return PT.confirmDelete('{delAction}','{delPrompt}')" ]
|
||||
[ icon "delete_forever" ]
|
||||
]
|
||||
td [ updReq req ] [
|
||||
str (req.updatedDate.ToString(s["MMMM d, yyyy"].Value, Globalization.CultureInfo.CurrentUICulture))
|
||||
]
|
||||
td [] [ locStr typs[req.requestType] ]
|
||||
td [ reqExp req ] [ str (match req.requestor with Some r -> r | None -> " ") ]
|
||||
td [] [
|
||||
match reqText.Length with
|
||||
| len when len < 60 -> rawText reqText
|
||||
| _ -> rawText $"{reqText[0..59]}…"
|
||||
]
|
||||
])
|
||||
|> List.ofSeq
|
||||
[ div [ _class "pt-center-text" ] [
|
||||
br []
|
||||
a [ _href $"/web/prayer-request/{emptyGuid}/edit"; _title s["Add a New Request"].Value ]
|
||||
[ icon "add_circle"; rawText " "; locStr s["Add a New Request"] ]
|
||||
rawText " "
|
||||
a [ _href "/web/prayer-requests/view"; _title s["View Prayer Request List"].Value ]
|
||||
[ icon "list"; rawText " "; locStr s["View Prayer Request List"] ]
|
||||
match m.searchTerm with
|
||||
| Some _ ->
|
||||
rawText " "
|
||||
a [ _href "/web/prayer-requests"; _title l["Clear Search Criteria"].Value ]
|
||||
[ icon "highlight_off"; rawText " "; raw l["Clear Search Criteria"] ]
|
||||
| None -> ()
|
||||
]
|
||||
form [ _id "DeleteForm"; _action ""; _method "post" ] [ csrfToken ctx ]
|
||||
form [ _action "/web/prayer-requests"; _method "get"; _class "pt-center-text pt-search-form" ] [
|
||||
input [ _type "text"
|
||||
_name "search"
|
||||
_placeholder l["Search requests..."].Value
|
||||
_value (defaultArg m.searchTerm "")
|
||||
]
|
||||
space
|
||||
submit [] "search" s["Search"]
|
||||
]
|
||||
br []
|
||||
tableSummary requests.Length s
|
||||
match requests.Length with
|
||||
| 0 -> ()
|
||||
| _ ->
|
||||
table [ _class "pt-table pt-action-table" ] [
|
||||
thead [] [
|
||||
tr [] [
|
||||
th [] [ locStr s["Actions"] ]
|
||||
th [] [ locStr s["Updated Date"] ]
|
||||
th [] [ locStr s["Type"] ]
|
||||
th [] [ locStr s["Requestor"] ]
|
||||
th [] [ locStr s["Request"] ]
|
||||
]
|
||||
]
|
||||
tbody [] requests
|
||||
]
|
||||
div [ _class "pt-center-text" ] [
|
||||
br []
|
||||
match m.onlyActive with
|
||||
| Some true ->
|
||||
raw l["Inactive requests are currently not shown"]
|
||||
br []
|
||||
a [ _href "/web/prayer-requests/inactive" ] [ raw l["Show Inactive Requests"] ]
|
||||
| _ ->
|
||||
match Option.isSome m.onlyActive with
|
||||
| true ->
|
||||
raw l["Inactive requests are currently shown"]
|
||||
br []
|
||||
a [ _href "/web/prayer-requests" ] [ raw l["Do Not Show Inactive Requests"] ]
|
||||
br []
|
||||
br []
|
||||
| false -> ()
|
||||
let srch = [ match m.searchTerm with Some s -> "search", s | None -> () ]
|
||||
let pg = defaultArg m.pageNbr 1
|
||||
let url =
|
||||
match m.onlyActive with Some true | None -> "" | _ -> "/inactive" |> sprintf "/web/prayer-requests%s"
|
||||
match pg with
|
||||
| 1 -> ()
|
||||
| _ ->
|
||||
// button (_type "submit" :: attrs) [ icon ico; rawText " "; locStr text ]
|
||||
let withPage = match pg with 2 -> srch | _ -> ("page", string (pg - 1)) :: srch
|
||||
a [ _href (makeUrl url withPage) ]
|
||||
[ icon "keyboard_arrow_left"; space; raw l["Previous Page"] ]
|
||||
rawText " "
|
||||
match requests.Length = m.smallGroup.preferences.pageSize with
|
||||
| true ->
|
||||
a [ _href (makeUrl url (("page", string (pg + 1)) :: srch)) ]
|
||||
[ raw l["Next Page"]; space; icon "keyboard_arrow_right" ]
|
||||
| false -> ()
|
||||
]
|
||||
form [ _id "DeleteForm"; _action ""; _method "post" ] [ csrfToken ctx ]
|
||||
]
|
||||
|> Layout.Content.wide
|
||||
|> Layout.standard vi (match m.searchTerm with Some _ -> "Search Results" | None -> "Maintain Requests")
|
||||
|> Layout.Content.wide
|
||||
|> Layout.standard vi (match m.searchTerm with Some _ -> "Search Results" | None -> "Maintain Requests")
|
||||
|
||||
|
||||
/// View for the printable prayer request list
|
||||
let print m version =
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = $"""{s.["Prayer Requests"].Value} • {m.listGroup.name}"""
|
||||
let imgAlt = $"""{s.["PrayerTracker"].Value} {s.["from Bit Badger Solutions"].Value}"""
|
||||
article [] [
|
||||
rawText (m.asHtml s)
|
||||
br []
|
||||
hr []
|
||||
div [ _style $"font-size:70%%;font-family:{m.listGroup.preferences.listFonts};" ] [
|
||||
img [ _src $"""/img/{s.["footer_en"].Value}.png"""
|
||||
_style "vertical-align:text-bottom;"
|
||||
_alt imgAlt
|
||||
_title imgAlt ]
|
||||
space
|
||||
str version
|
||||
]
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = $"""{s["Prayer Requests"].Value} • {m.listGroup.name}"""
|
||||
let imgAlt = $"""{s["PrayerTracker"].Value} {s["from Bit Badger Solutions"].Value}"""
|
||||
article [] [
|
||||
rawText (m.asHtml s)
|
||||
br []
|
||||
hr []
|
||||
div [ _style $"font-size:70%%;font-family:{m.listGroup.preferences.listFonts};" ] [
|
||||
img [ _src $"""/img/{s["footer_en"].Value}.png"""
|
||||
_style "vertical-align:text-bottom;"
|
||||
_alt imgAlt
|
||||
_title imgAlt ]
|
||||
space
|
||||
str version
|
||||
]
|
||||
]
|
||||
|> Layout.bare pageTitle
|
||||
|> Layout.bare pageTitle
|
||||
|
||||
|
||||
/// View for the prayer request list
|
||||
let view m vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = $"""{s.["Prayer Requests"].Value} • {m.listGroup.name}"""
|
||||
let spacer = rawText " "
|
||||
let dtString = m.date.ToString "yyyy-MM-dd"
|
||||
[ div [ _class "pt-center-text" ] [
|
||||
br []
|
||||
a [ _class "pt-icon-link"
|
||||
_href $"/web/prayer-requests/print/{dtString}"
|
||||
_title s.["View Printable"].Value ] [
|
||||
icon "print"; rawText " "; locStr s.["View Printable"]
|
||||
]
|
||||
match m.canEmail with
|
||||
| true ->
|
||||
spacer
|
||||
match m.date.DayOfWeek = DayOfWeek.Sunday with
|
||||
| true -> ()
|
||||
| false ->
|
||||
let rec findSunday (date : DateTime) =
|
||||
match date.DayOfWeek = DayOfWeek.Sunday with
|
||||
| true -> date
|
||||
| false -> findSunday (date.AddDays 1.)
|
||||
let sunday = findSunday m.date
|
||||
a [ _class "pt-icon-link"
|
||||
_href $"""/web/prayer-requests/view/{sunday.ToString "yyyy-MM-dd"}"""
|
||||
_title s.["List for Next Sunday"].Value ] [
|
||||
icon "update"; rawText " "; locStr s.["List for Next Sunday"]
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = $"""{s["Prayer Requests"].Value} • {m.listGroup.name}"""
|
||||
let spacer = rawText " "
|
||||
let dtString = m.date.ToString "yyyy-MM-dd"
|
||||
[ div [ _class "pt-center-text" ] [
|
||||
br []
|
||||
a [ _class "pt-icon-link"
|
||||
_href $"/web/prayer-requests/print/{dtString}"
|
||||
_title s["View Printable"].Value
|
||||
] [ icon "print"; rawText " "; locStr s["View Printable"] ]
|
||||
if m.canEmail then
|
||||
spacer
|
||||
if m.date.DayOfWeek <> DayOfWeek.Sunday then
|
||||
let rec findSunday (date : DateTime) =
|
||||
if date.DayOfWeek = DayOfWeek.Sunday then date else findSunday (date.AddDays 1.)
|
||||
let sunday = findSunday m.date
|
||||
a [ _class "pt-icon-link"
|
||||
_href $"""/web/prayer-requests/view/{sunday.ToString "yyyy-MM-dd"}"""
|
||||
_title s["List for Next Sunday"].Value ] [
|
||||
icon "update"; rawText " "; locStr s["List for Next Sunday"]
|
||||
]
|
||||
spacer
|
||||
let emailPrompt = s.["This will e-mail the current list to every member of your group, without further prompting. Are you sure this is what you are ready to do?"].Value
|
||||
a [ _class "pt-icon-link"
|
||||
_href $"/web/prayer-requests/email/{dtString}"
|
||||
_title s.["Send via E-mail"].Value
|
||||
_onclick $"return PT.requests.view.promptBeforeEmail('{emailPrompt}')" ] [
|
||||
icon "mail_outline"; rawText " "; locStr s.["Send via E-mail"]
|
||||
spacer
|
||||
let emailPrompt = s["This will e-mail the current list to every member of your group, without further prompting. Are you sure this is what you are ready to do?"].Value
|
||||
a [ _class "pt-icon-link"
|
||||
_href $"/web/prayer-requests/email/{dtString}"
|
||||
_title s["Send via E-mail"].Value
|
||||
_onclick $"return PT.requests.view.promptBeforeEmail('{emailPrompt}')" ] [
|
||||
icon "mail_outline"; rawText " "; locStr s["Send via E-mail"]
|
||||
]
|
||||
spacer
|
||||
a [ _class "pt-icon-link"; _href "/web/prayer-requests"; _title s.["Maintain Prayer Requests"].Value ] [
|
||||
icon "compare_arrows"; rawText " "; locStr s.["Maintain Prayer Requests"]
|
||||
]
|
||||
| false -> ()
|
||||
spacer
|
||||
a [ _class "pt-icon-link"; _href "/web/prayer-requests"; _title s["Maintain Prayer Requests"].Value ] [
|
||||
icon "compare_arrows"; rawText " "; locStr s["Maintain Prayer Requests"]
|
||||
]
|
||||
]
|
||||
br []
|
||||
rawText (m.asHtml s)
|
||||
br []
|
||||
rawText (m.asHtml s)
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -6,221 +6,219 @@ open PrayerTracker.ViewModels
|
|||
|
||||
/// View for the group assignment page
|
||||
let assignGroups m groups curGroups ctx vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = sprintf "%s • %A" m.userName s.["Assign Groups"]
|
||||
form [ _action "/web/user/small-groups/save"; _method "post"; _class "pt-center-columns" ] [
|
||||
csrfToken ctx
|
||||
input [ _type "hidden"; _name "userId"; _value (flatGuid m.userId) ]
|
||||
input [ _type "hidden"; _name "userName"; _value m.userName ]
|
||||
table [ _class "pt-table" ] [
|
||||
thead [] [
|
||||
tr [] [
|
||||
th [] [ rawText " " ]
|
||||
th [] [ locStr s.["Group"] ]
|
||||
]
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = sprintf "%s • %A" m.userName s["Assign Groups"]
|
||||
form [ _action "/web/user/small-groups/save"; _method "post"; _class "pt-center-columns" ] [
|
||||
csrfToken ctx
|
||||
input [ _type "hidden"; _name "userId"; _value (flatGuid m.userId) ]
|
||||
input [ _type "hidden"; _name "userName"; _value m.userName ]
|
||||
table [ _class "pt-table" ] [
|
||||
thead [] [
|
||||
tr [] [
|
||||
th [] [ rawText " " ]
|
||||
th [] [ locStr s["Group"] ]
|
||||
]
|
||||
]
|
||||
groups
|
||||
|> List.map (fun (grpId, grpName) ->
|
||||
let inputId = $"id-{grpId}"
|
||||
tr [] [
|
||||
td [] [
|
||||
input [ _type "checkbox"
|
||||
_name "smallGroups"
|
||||
_id inputId
|
||||
_value grpId
|
||||
match curGroups |> List.contains grpId with true -> _checked | false -> () ]
|
||||
]
|
||||
td [] [ label [ _for inputId ] [ str grpName ] ]
|
||||
])
|
||||
|> tbody []
|
||||
]
|
||||
groups
|
||||
|> List.map (fun (grpId, grpName) ->
|
||||
let inputId = $"id-{grpId}"
|
||||
tr [] [
|
||||
td [] [
|
||||
input [ _type "checkbox"
|
||||
_name "smallGroups"
|
||||
_id inputId
|
||||
_value grpId
|
||||
match curGroups |> List.contains grpId with true -> _checked | false -> () ]
|
||||
]
|
||||
td [] [ label [ _for inputId ] [ str grpName ] ]
|
||||
])
|
||||
|> tbody []
|
||||
]
|
||||
div [ _class "pt-field-row" ] [ submit [] "save" s.["Save Group Assignments"] ]
|
||||
div [ _class "pt-field-row" ] [ submit [] "save" s["Save Group Assignments"] ]
|
||||
]
|
||||
|> List.singleton
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|> List.singleton
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|
||||
|
||||
/// View for the password change page
|
||||
let changePassword ctx vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
[ p [ _class "pt-center-text" ] [
|
||||
locStr s.["To change your password, enter your current password in the specified box below, then enter your new password twice."]
|
||||
let s = I18N.localizer.Force ()
|
||||
[ p [ _class "pt-center-text" ] [
|
||||
locStr s["To change your password, enter your current password in the specified box below, then enter your new password twice."]
|
||||
]
|
||||
form [ _action "/web/user/password/change"
|
||||
_method "post"
|
||||
_onsubmit $"""return PT.compareValidation('newPassword','newPasswordConfirm','%A{s.["The passwords do not match"]}')""" ] [
|
||||
style [ _scoped ] [ rawText "#oldPassword, #newPassword, #newPasswordConfirm { width: 10rem; } "]
|
||||
csrfToken ctx
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "oldPassword" ] [ locStr s.["Current Password"] ]
|
||||
input [ _type "password"; _name "oldPassword"; _id "oldPassword"; _required; _autofocus ]
|
||||
form [ _action "/web/user/password/change"
|
||||
_method "post"
|
||||
_onsubmit $"""return PT.compareValidation('newPassword','newPasswordConfirm','%A{s["The passwords do not match"]}')""" ] [
|
||||
style [ _scoped ] [ rawText "#oldPassword, #newPassword, #newPasswordConfirm { width: 10rem; } "]
|
||||
csrfToken ctx
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "oldPassword" ] [ locStr s["Current Password"] ]
|
||||
input [ _type "password"; _name "oldPassword"; _id "oldPassword"; _required; _autofocus ]
|
||||
]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "newPassword" ] [ locStr s.["New Password Twice"] ]
|
||||
input [ _type "password"; _name "newPassword"; _id "newPassword"; _required ]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "newPassword" ] [ locStr s["New Password Twice"] ]
|
||||
input [ _type "password"; _name "newPassword"; _id "newPassword"; _required ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [] [ rawText " " ]
|
||||
input [ _type "password"; _name "newPasswordConfirm"; _id "newPasswordConfirm"; _required ]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [] [ rawText " " ]
|
||||
input [ _type "password"; _name "newPasswordConfirm"; _id "newPasswordConfirm"; _required ]
|
||||
div [ _class "pt-field-row" ] [
|
||||
submit [ _onclick "document.getElementById('newPasswordConfirm').setCustomValidity('')" ] "done"
|
||||
s["Change Your Password"]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [
|
||||
submit [ _onclick "document.getElementById('newPasswordConfirm').setCustomValidity('')" ] "done"
|
||||
s.["Change Your Password"]
|
||||
]
|
||||
]
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Change Your Password"
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Change Your Password"
|
||||
|
||||
|
||||
/// View for the edit user page
|
||||
let edit (m : EditUser) ctx vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = match m.isNew () with true -> "Add a New User" | false -> "Edit User"
|
||||
let pwPlaceholder = s.[match m.isNew () with true -> "" | false -> "No change"].Value
|
||||
[ form [ _action "/web/user/edit/save"; _method "post"; _class "pt-center-columns"
|
||||
_onsubmit $"""return PT.compareValidation('password','passwordConfirm','%A{s.["The passwords do not match"]}')""" ] [
|
||||
style [ _scoped ]
|
||||
[ rawText "#firstName, #lastName, #password, #passwordConfirm { width: 10rem; } #emailAddress { width: 20rem; } " ]
|
||||
csrfToken ctx
|
||||
input [ _type "hidden"; _name "userId"; _value (flatGuid m.userId) ]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "firstName" ] [ locStr s.["First Name"] ]
|
||||
input [ _type "text"; _name "firstName"; _id "firstName"; _value m.firstName; _required; _autofocus ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "lastName" ] [ locStr s.["Last Name"] ]
|
||||
input [ _type "text"; _name "lastName"; _id "lastName"; _value m.lastName; _required ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "emailAddress" ] [ locStr s.["E-mail Address"] ]
|
||||
input [ _type "email"; _name "emailAddress"; _id "emailAddress"; _value m.emailAddress; _required ]
|
||||
]
|
||||
let s = I18N.localizer.Force ()
|
||||
let pageTitle = if m.isNew () then "Add a New User" else "Edit User"
|
||||
let pwPlaceholder = s[if m.isNew () then "" else "No change"].Value
|
||||
[ form [ _action "/web/user/edit/save"; _method "post"; _class "pt-center-columns"
|
||||
_onsubmit $"""return PT.compareValidation('password','passwordConfirm','%A{s["The passwords do not match"]}')""" ] [
|
||||
style [ _scoped ]
|
||||
[ rawText "#firstName, #lastName, #password, #passwordConfirm { width: 10rem; } #emailAddress { width: 20rem; } " ]
|
||||
csrfToken ctx
|
||||
input [ _type "hidden"; _name "userId"; _value (flatGuid m.userId) ]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "firstName" ] [ locStr s["First Name"] ]
|
||||
input [ _type "text"; _name "firstName"; _id "firstName"; _value m.firstName; _required; _autofocus ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "lastName" ] [ locStr s["Last Name"] ]
|
||||
input [ _type "text"; _name "lastName"; _id "lastName"; _value m.lastName; _required ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "emailAddress" ] [ locStr s["E-mail Address"] ]
|
||||
input [ _type "email"; _name "emailAddress"; _id "emailAddress"; _value m.emailAddress; _required ]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "password" ] [ locStr s.["Password"] ]
|
||||
input [ _type "password"; _name "password"; _id "password"; _placeholder pwPlaceholder ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "passwordConfirm" ] [ locStr s.["Password Again"] ]
|
||||
input [ _type "password"; _name "passwordConfirm"; _id "passwordConfirm"; _placeholder pwPlaceholder ]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "password" ] [ locStr s["Password"] ]
|
||||
input [ _type "password"; _name "password"; _id "password"; _placeholder pwPlaceholder ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "passwordConfirm" ] [ locStr s["Password Again"] ]
|
||||
input [ _type "password"; _name "passwordConfirm"; _id "passwordConfirm"; _placeholder pwPlaceholder ]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-checkbox-field" ] [
|
||||
input [ _type "checkbox"
|
||||
_name "isAdmin"
|
||||
_id "isAdmin"
|
||||
_value "True"
|
||||
match m.isAdmin with Some x when x -> _checked | _ -> () ]
|
||||
label [ _for "isAdmin" ] [ locStr s.["This user is a PrayerTracker administrator"] ]
|
||||
div [ _class "pt-checkbox-field" ] [
|
||||
input [ _type "checkbox"
|
||||
_name "isAdmin"
|
||||
_id "isAdmin"
|
||||
_value "True"
|
||||
match m.isAdmin with Some x when x -> _checked | _ -> () ]
|
||||
label [ _for "isAdmin" ] [ locStr s["This user is a PrayerTracker administrator"] ]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [ submit [] "save" s.["Save User"] ]
|
||||
div [ _class "pt-field-row" ] [ submit [] "save" s["Save User"] ]
|
||||
]
|
||||
script [] [ rawText $"PT.onLoad(PT.user.edit.onPageLoad({(string (m.isNew ())).ToLower ()}))" ]
|
||||
script [] [ rawText $"PT.onLoad(PT.user.edit.onPageLoad({(string (m.isNew ())).ToLower ()}))" ]
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi pageTitle
|
||||
|
||||
|
||||
/// View for the user log on page
|
||||
let logOn (m : UserLogOn) groups ctx vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
form [ _action "/web/user/log-on"; _method "post"; _class "pt-center-columns" ] [
|
||||
style [ _scoped ] [ rawText "#emailAddress { width: 20rem; }" ]
|
||||
csrfToken ctx
|
||||
input [ _type "hidden"; _name "redirectUrl"; _value (defaultArg m.redirectUrl "") ]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "emailAddress"] [ locStr s.["E-mail Address"] ]
|
||||
input [ _type "email"; _name "emailAddress"; _id "emailAddress"; _value m.emailAddress; _required; _autofocus ]
|
||||
let s = I18N.localizer.Force ()
|
||||
form [ _action "/web/user/log-on"; _method "post"; _class "pt-center-columns" ] [
|
||||
style [ _scoped ] [ rawText "#emailAddress { width: 20rem; }" ]
|
||||
csrfToken ctx
|
||||
input [ _type "hidden"; _name "redirectUrl"; _value (defaultArg m.redirectUrl "") ]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "emailAddress"] [ locStr s["E-mail Address"] ]
|
||||
input [ _type "email"; _name "emailAddress"; _id "emailAddress"; _value m.emailAddress; _required
|
||||
_autofocus ]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "password" ] [ locStr s["Password"] ]
|
||||
input [ _type "password"; _name "password"; _id "password"; _required;
|
||||
_placeholder (sprintf "(%s)" (s["Case-Sensitive"].Value.ToLower ())) ]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "password" ] [ locStr s.["Password"] ]
|
||||
input [ _type "password"; _name "password"; _id "password"; _required;
|
||||
_placeholder (sprintf "(%s)" (s.["Case-Sensitive"].Value.ToLower ())) ]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "smallGroupId" ] [ locStr s["Group"] ]
|
||||
seq {
|
||||
"", selectDefault s["Select Group"].Value
|
||||
yield! groups
|
||||
}
|
||||
|> selectList "smallGroupId" "" [ _required ]
|
||||
]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [
|
||||
div [ _class "pt-field" ] [
|
||||
label [ _for "smallGroupId" ] [ locStr s.["Group"] ]
|
||||
seq {
|
||||
"", selectDefault s.["Select Group"].Value
|
||||
yield! groups
|
||||
}
|
||||
|> selectList "smallGroupId" "" [ _required ]
|
||||
|
||||
div [ _class "pt-checkbox-field" ] [
|
||||
input [ _type "checkbox"; _name "rememberMe"; _id "rememberMe"; _value "True" ]
|
||||
label [ _for "rememberMe" ] [ locStr s["Remember Me"] ]
|
||||
br []
|
||||
small [] [ em [] [ rawText "("; str (s["Requires Cookies"].Value.ToLower ()); rawText ")" ] ]
|
||||
]
|
||||
]
|
||||
div [ _class "pt-checkbox-field" ] [
|
||||
input [ _type "checkbox"; _name "rememberMe"; _id "rememberMe"; _value "True" ]
|
||||
label [ _for "rememberMe" ] [ locStr s.["Remember Me"] ]
|
||||
br []
|
||||
small [] [ em [] [ rawText "("; str (s.["Requires Cookies"].Value.ToLower ()); rawText ")" ] ]
|
||||
]
|
||||
div [ _class "pt-field-row" ] [ submit [] "account_circle" s.["Log On"] ]
|
||||
div [ _class "pt-field-row" ] [ submit [] "account_circle" s["Log On"] ]
|
||||
]
|
||||
|> List.singleton
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "User Log On"
|
||||
|> List.singleton
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "User Log On"
|
||||
|
||||
|
||||
/// View for the user maintenance page
|
||||
let maintain (users : User list) ctx vi =
|
||||
let s = I18N.localizer.Force ()
|
||||
let usrTbl =
|
||||
match users with
|
||||
| [] -> space
|
||||
| _ ->
|
||||
table [ _class "pt-table pt-action-table" ] [
|
||||
thead [] [
|
||||
tr [] [
|
||||
th [] [ locStr s.["Actions"] ]
|
||||
th [] [ locStr s.["Name"] ]
|
||||
th [] [ locStr s.["Admin?"] ]
|
||||
let s = I18N.localizer.Force ()
|
||||
let usrTbl =
|
||||
match users with
|
||||
| [] -> space
|
||||
| _ ->
|
||||
table [ _class "pt-table pt-action-table" ] [
|
||||
thead [] [
|
||||
tr [] [
|
||||
th [] [ locStr s["Actions"] ]
|
||||
th [] [ locStr s["Name"] ]
|
||||
th [] [ locStr s["Admin?"] ]
|
||||
]
|
||||
]
|
||||
users
|
||||
|> List.map (fun user ->
|
||||
let userId = flatGuid user.userId
|
||||
let delAction = $"/web/user/{userId}/delete"
|
||||
let delPrompt = s["Are you sure you want to delete this {0}? This action cannot be undone.",
|
||||
$"""{s["User"].Value.ToLower ()} ({user.fullName})"""].Value
|
||||
tr [] [
|
||||
td [] [
|
||||
a [ _href $"/web/user/{userId}/edit"; _title s["Edit This User"].Value ] [ icon "edit" ]
|
||||
a [ _href $"/web/user/{userId}/small-groups"; _title s["Assign Groups to This User"].Value ]
|
||||
[ icon "group" ]
|
||||
a [ _href delAction
|
||||
_title s["Delete This User"].Value
|
||||
_onclick $"return PT.confirmDelete('{delAction}','{delPrompt}')" ]
|
||||
[ icon "delete_forever" ]
|
||||
]
|
||||
td [] [ str user.fullName ]
|
||||
td [ _class "pt-center-text" ] [
|
||||
if user.isAdmin then strong [] [ locStr s["Yes"] ] else locStr s["No"]
|
||||
]
|
||||
])
|
||||
|> tbody []
|
||||
]
|
||||
]
|
||||
users
|
||||
|> List.map (fun user ->
|
||||
let userId = flatGuid user.userId
|
||||
let delAction = $"/web/user/{userId}/delete"
|
||||
let delPrompt = s.["Are you sure you want to delete this {0}? This action cannot be undone.",
|
||||
$"""{s.["User"].Value.ToLower ()} ({user.fullName})"""].Value
|
||||
tr [] [
|
||||
td [] [
|
||||
a [ _href $"/web/user/{userId}/edit"; _title s.["Edit This User"].Value ] [ icon "edit" ]
|
||||
a [ _href $"/web/user/{userId}/small-groups"; _title s.["Assign Groups to This User"].Value ]
|
||||
[ icon "group" ]
|
||||
a [ _href delAction
|
||||
_title s.["Delete This User"].Value
|
||||
_onclick $"return PT.confirmDelete('{delAction}','{delPrompt}')" ]
|
||||
[ icon "delete_forever" ]
|
||||
]
|
||||
td [] [ str user.fullName ]
|
||||
td [ _class "pt-center-text" ] [
|
||||
match user.isAdmin with
|
||||
| true -> strong [] [ locStr s.["Yes"] ]
|
||||
| false -> locStr s.["No"]
|
||||
]
|
||||
])
|
||||
|> tbody []
|
||||
]
|
||||
[ div [ _class "pt-center-text" ] [
|
||||
br []
|
||||
a [ _href $"/web/user/{emptyGuid}/edit"; _title s.["Add a New User"].Value ]
|
||||
[ icon "add_circle"; rawText " "; locStr s.["Add a New User"] ]
|
||||
br []
|
||||
br []
|
||||
[ div [ _class "pt-center-text" ] [
|
||||
br []
|
||||
a [ _href $"/web/user/{emptyGuid}/edit"; _title s["Add a New User"].Value ]
|
||||
[ icon "add_circle"; rawText " "; locStr s["Add a New User"] ]
|
||||
br []
|
||||
br []
|
||||
]
|
||||
tableSummary users.Length s
|
||||
usrTbl
|
||||
form [ _id "DeleteForm"; _action ""; _method "post" ] [ csrfToken ctx ]
|
||||
tableSummary users.Length s
|
||||
usrTbl
|
||||
form [ _id "DeleteForm"; _action ""; _method "post" ] [ csrfToken ctx ]
|
||||
]
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Maintain Users"
|
||||
|> Layout.Content.standard
|
||||
|> Layout.standard vi "Maintain Users"
|
||||
|
|
|
@ -1,207 +1,219 @@
|
|||
[<AutoOpen>]
|
||||
module PrayerTracker.Utils
|
||||
|
||||
open System.Net
|
||||
open System
|
||||
open System.Security.Cryptography
|
||||
open System.Text
|
||||
open System.Text.RegularExpressions
|
||||
open System
|
||||
|
||||
/// Hash a string with a SHA1 hash
|
||||
let sha1Hash (x : string) =
|
||||
use alg = SHA1.Create ()
|
||||
alg.ComputeHash (Encoding.ASCII.GetBytes x)
|
||||
|> Seq.map (fun chr -> chr.ToString "x2")
|
||||
|> String.concat ""
|
||||
use alg = SHA1.Create ()
|
||||
alg.ComputeHash (Encoding.ASCII.GetBytes x)
|
||||
|> Seq.map (fun chr -> chr.ToString "x2")
|
||||
|> String.concat ""
|
||||
|
||||
|
||||
/// Hash a string using 1,024 rounds of PBKDF2 and a salt
|
||||
let pbkdf2Hash (salt : Guid) (x : string) =
|
||||
use alg = new Rfc2898DeriveBytes (x, Encoding.UTF8.GetBytes (salt.ToString "N"), 1024)
|
||||
(alg.GetBytes >> Convert.ToBase64String) 64
|
||||
use alg = new Rfc2898DeriveBytes (x, Encoding.UTF8.GetBytes (salt.ToString "N"), 1024)
|
||||
(alg.GetBytes >> Convert.ToBase64String) 64
|
||||
|
||||
|
||||
/// String helper functions
|
||||
module String =
|
||||
|
||||
/// string.Trim()
|
||||
let trim (str: string) = str.Trim ()
|
||||
/// string.Trim()
|
||||
let trim (str: string) = str.Trim ()
|
||||
|
||||
/// string.Replace()
|
||||
let replace (find : string) repl (str : string) = str.Replace (find, repl)
|
||||
/// string.Replace()
|
||||
let replace (find : string) repl (str : string) = str.Replace (find, repl)
|
||||
|
||||
/// Replace the first occurrence of a string with a second string within a given string
|
||||
let replaceFirst (needle : string) replacement (haystack : string) =
|
||||
match haystack.IndexOf needle with
|
||||
| -1 -> haystack
|
||||
| idx ->
|
||||
[ haystack.[0..idx - 1]
|
||||
replacement
|
||||
haystack.[idx + needle.Length..]
|
||||
]
|
||||
|> String.concat ""
|
||||
/// Replace the first occurrence of a string with a second string within a given string
|
||||
let replaceFirst (needle : string) replacement (haystack : string) =
|
||||
match haystack.IndexOf needle with
|
||||
| -1 -> haystack
|
||||
| idx ->
|
||||
[ haystack[0..idx - 1]
|
||||
replacement
|
||||
haystack[idx + needle.Length..]
|
||||
]
|
||||
|> String.concat ""
|
||||
|
||||
|
||||
open System.Text.RegularExpressions
|
||||
|
||||
/// Strip HTML tags from the given string
|
||||
// Adapted from http://www.dijksterhuis.org/safely-cleaning-html-with-strip_tags-in-csharp/
|
||||
let stripTags allowedTags input =
|
||||
let stripHtmlExp = Regex @"(<\/?[^>]+>)"
|
||||
let mutable output = input
|
||||
for tag in stripHtmlExp.Matches input do
|
||||
let htmlTag = tag.Value.ToLower ()
|
||||
let isAllowed =
|
||||
allowedTags
|
||||
|> List.fold
|
||||
(fun acc t ->
|
||||
acc
|
||||
let stripHtmlExp = Regex @"(<\/?[^>]+>)"
|
||||
let mutable output = input
|
||||
for tag in stripHtmlExp.Matches input do
|
||||
let htmlTag = tag.Value.ToLower ()
|
||||
let isAllowed =
|
||||
allowedTags
|
||||
|> List.fold (fun acc t ->
|
||||
acc
|
||||
|| htmlTag.IndexOf $"<{t}>" = 0
|
||||
|| htmlTag.IndexOf $"<{t} " = 0
|
||||
|| htmlTag.IndexOf $"</{t}" = 0) false
|
||||
match isAllowed with
|
||||
| true -> ()
|
||||
| false -> output <- String.replaceFirst tag.Value "" output
|
||||
output
|
||||
if isAllowed then output <- String.replaceFirst tag.Value "" output
|
||||
output
|
||||
|
||||
|
||||
/// Wrap a string at the specified number of characters
|
||||
let wordWrap charPerLine (input : string) =
|
||||
match input.Length with
|
||||
| len when len <= charPerLine -> input
|
||||
| _ ->
|
||||
seq {
|
||||
for line in input.Replace("\r", "").Split '\n' do
|
||||
let mutable remaining = line
|
||||
match remaining.Length with
|
||||
| 0 -> ()
|
||||
| _ ->
|
||||
while charPerLine < remaining.Length do
|
||||
match charPerLine + 1 < remaining.Length && remaining.[charPerLine] = ' ' with
|
||||
| true ->
|
||||
// Line length is followed by a space; return [charPerLine] as a line
|
||||
yield remaining.[0..charPerLine - 1]
|
||||
remaining <- remaining.[charPerLine + 1..]
|
||||
| false ->
|
||||
match remaining.[0..charPerLine - 1].LastIndexOf ' ' with
|
||||
| -1 ->
|
||||
// No whitespace; just break it at [characters]
|
||||
yield remaining.[0..charPerLine - 1]
|
||||
remaining <- remaining.[charPerLine..]
|
||||
| spaceIdx ->
|
||||
// Break on the last space in the line
|
||||
yield remaining.[0..spaceIdx - 1]
|
||||
remaining <- remaining.[spaceIdx + 1..]
|
||||
// Leftovers - yum!
|
||||
match remaining.Length with 0 -> () | _ -> yield remaining
|
||||
match input.Length with
|
||||
| len when len <= charPerLine -> input
|
||||
| _ ->
|
||||
seq {
|
||||
for line in input.Replace("\r", "").Split '\n' do
|
||||
let mutable remaining = line
|
||||
match remaining.Length with
|
||||
| 0 -> ()
|
||||
| _ ->
|
||||
while charPerLine < remaining.Length do
|
||||
if charPerLine + 1 < remaining.Length && remaining[charPerLine] = ' ' then
|
||||
// Line length is followed by a space; return [charPerLine] as a line
|
||||
yield remaining[0..charPerLine - 1]
|
||||
remaining <- remaining[charPerLine + 1..]
|
||||
else
|
||||
match remaining[0..charPerLine - 1].LastIndexOf ' ' with
|
||||
| -1 ->
|
||||
// No whitespace; just break it at [characters]
|
||||
yield remaining[0..charPerLine - 1]
|
||||
remaining <- remaining[charPerLine..]
|
||||
| spaceIdx ->
|
||||
// Break on the last space in the line
|
||||
yield remaining[0..spaceIdx - 1]
|
||||
remaining <- remaining[spaceIdx + 1..]
|
||||
// Leftovers - yum!
|
||||
match remaining.Length with 0 -> () | _ -> yield remaining
|
||||
}
|
||||
|> Seq.fold (fun (acc : StringBuilder) line -> acc.AppendFormat ("{0}\n", line)) (StringBuilder ())
|
||||
|> string
|
||||
|> Seq.fold (fun (acc : StringBuilder) -> acc.AppendLine) (StringBuilder ())
|
||||
|> string
|
||||
|
||||
/// Modify the text returned by CKEditor into the format we need for request and announcement text
|
||||
let ckEditorToText (text : string) =
|
||||
let trim (str : string) = str.Trim ()
|
||||
[ "\n\t", ""
|
||||
" ", " "
|
||||
" ", "  "
|
||||
"</p><p>", "<br><br>"
|
||||
"</p>", ""
|
||||
"<p>", ""
|
||||
[ "\n\t", ""
|
||||
" ", " "
|
||||
" ", "  "
|
||||
"</p><p>", "<br><br>"
|
||||
"</p>", ""
|
||||
"<p>", ""
|
||||
]
|
||||
|> List.fold (fun (txt : string) (x, y) -> String.replace x y txt) text
|
||||
|> trim
|
||||
|> List.fold (fun (txt : string) (x, y) -> String.replace x y txt) text
|
||||
|> String.trim
|
||||
|
||||
|
||||
open System.Net
|
||||
|
||||
/// Convert an HTML piece of text to plain text
|
||||
let htmlToPlainText html =
|
||||
match html with
|
||||
| null | "" -> ""
|
||||
| _ ->
|
||||
html.Trim ()
|
||||
|> stripTags [ "br" ]
|
||||
|> String.replace "<br />" "\n"
|
||||
|> String.replace "<br>" "\n"
|
||||
|> WebUtility.HtmlDecode
|
||||
|> String.replace "\u00a0" " "
|
||||
match html with
|
||||
| null | "" -> ""
|
||||
| _ ->
|
||||
html.Trim ()
|
||||
|> stripTags [ "br" ]
|
||||
|> String.replace "<br />" "\n"
|
||||
|> String.replace "<br>" "\n"
|
||||
|> WebUtility.HtmlDecode
|
||||
|> String.replace "\u00a0" " "
|
||||
|
||||
/// Get the second portion of a tuple as a string
|
||||
let sndAsString x = (snd >> string) x
|
||||
|
||||
|
||||
/// Make a URL with query string parameters
|
||||
let makeUrl (url : string) (qs : (string * string) list) =
|
||||
let queryString =
|
||||
qs
|
||||
|> List.fold
|
||||
(fun (acc : StringBuilder) (key, value) ->
|
||||
acc.Append(key).Append("=").Append(WebUtility.UrlEncode value).Append "&")
|
||||
(StringBuilder ())
|
||||
match queryString.Length with
|
||||
| 0 -> url
|
||||
| _ -> queryString.Insert(0, "?").Insert(0, url).Remove(queryString.Length - 1, 1).ToString ()
|
||||
let makeUrl url qs =
|
||||
if List.isEmpty qs then url
|
||||
else $"""{url}?{String.Join('&', List.map (fun (k, v) -> $"%s{k}={WebUtility.UrlEncode v}") qs)}"""
|
||||
|
||||
|
||||
/// "Magic string" repository
|
||||
[<RequireQualifiedAccess>]
|
||||
module Key =
|
||||
|
||||
/// This contains constants for session-stored objects within PrayerTracker
|
||||
module Session =
|
||||
/// The currently logged-on small group
|
||||
let currentGroup = "CurrentGroup"
|
||||
/// The currently logged-on user
|
||||
let currentUser = "CurrentUser"
|
||||
/// User messages to be displayed the next time a page is sent
|
||||
let userMessages = "UserMessages"
|
||||
/// The URL to which the user should be redirected once they have logged in
|
||||
let redirectUrl = "RedirectUrl"
|
||||
/// This contains constants for session-stored objects within PrayerTracker
|
||||
module Session =
|
||||
|
||||
/// Names and value names for use with cookies
|
||||
module Cookie =
|
||||
/// The name of the user cookie
|
||||
let user = "LoggedInUser"
|
||||
/// The name of the class cookie
|
||||
let group = "LoggedInClass"
|
||||
/// The name of the culture cookie
|
||||
let culture = "CurrentCulture"
|
||||
/// The name of the idle timeout cookie
|
||||
let timeout = "TimeoutCookie"
|
||||
/// The cookies that should be cleared when a user or group logs off
|
||||
let logOffCookies = [ user; group; timeout ]
|
||||
/// The currently logged-on small group
|
||||
let currentGroup = "CurrentGroup"
|
||||
|
||||
/// The currently logged-on user
|
||||
let currentUser = "CurrentUser"
|
||||
|
||||
/// User messages to be displayed the next time a page is sent
|
||||
let userMessages = "UserMessages"
|
||||
|
||||
/// The URL to which the user should be redirected once they have logged in
|
||||
let redirectUrl = "RedirectUrl"
|
||||
|
||||
/// Names and value names for use with cookies
|
||||
module Cookie =
|
||||
|
||||
/// The name of the user cookie
|
||||
let user = "LoggedInUser"
|
||||
|
||||
/// The name of the class cookie
|
||||
let group = "LoggedInClass"
|
||||
|
||||
/// The name of the culture cookie
|
||||
let culture = "CurrentCulture"
|
||||
|
||||
/// The name of the idle timeout cookie
|
||||
let timeout = "TimeoutCookie"
|
||||
|
||||
/// The cookies that should be cleared when a user or group logs off
|
||||
let logOffCookies = [ user; group; timeout ]
|
||||
|
||||
|
||||
/// Enumerated values for small group request list visibility (derived from preferences, used in UI)
|
||||
module RequestVisibility =
|
||||
/// Requests are publicly accessible
|
||||
[<Literal>]
|
||||
let ``public`` = 1
|
||||
/// The small group members can enter a password to view the request list
|
||||
[<Literal>]
|
||||
let passwordProtected = 2
|
||||
/// No one can see the requests for a small group except its administrators ("User" access level)
|
||||
[<Literal>]
|
||||
let ``private`` = 3
|
||||
|
||||
/// Requests are publicly accessible
|
||||
[<Literal>]
|
||||
let ``public`` = 1
|
||||
|
||||
/// The small group members can enter a password to view the request list
|
||||
[<Literal>]
|
||||
let passwordProtected = 2
|
||||
|
||||
/// No one can see the requests for a small group except its administrators ("User" access level)
|
||||
[<Literal>]
|
||||
let ``private`` = 3
|
||||
|
||||
|
||||
/// Links for help locations
|
||||
module Help =
|
||||
/// Help link for small group preference edit page
|
||||
let groupPreferences = "small-group/preferences"
|
||||
/// Help link for send announcement page
|
||||
let sendAnnouncement = "small-group/announcement"
|
||||
/// Help link for maintain group members page
|
||||
let maintainGroupMembers = "small-group/members"
|
||||
/// Help link for request edit page
|
||||
let editRequest = "requests/edit"
|
||||
/// Help link for maintain requests page
|
||||
let maintainRequests = "requests/maintain"
|
||||
/// Help link for view request list page
|
||||
let viewRequestList = "requests/view"
|
||||
/// Help link for user and class login pages
|
||||
let logOn = "user/log-on"
|
||||
/// Help link for user password change page
|
||||
let changePassword = "user/password"
|
||||
/// Create a full link for a help page
|
||||
let fullLink lang url = $"https://docs.prayer.bitbadger.solutions/%s{lang}/%s{url}.html"
|
||||
|
||||
/// Help link for small group preference edit page
|
||||
let groupPreferences = "small-group/preferences"
|
||||
|
||||
/// Help link for send announcement page
|
||||
let sendAnnouncement = "small-group/announcement"
|
||||
|
||||
/// Help link for maintain group members page
|
||||
let maintainGroupMembers = "small-group/members"
|
||||
|
||||
/// Help link for request edit page
|
||||
let editRequest = "requests/edit"
|
||||
|
||||
/// Help link for maintain requests page
|
||||
let maintainRequests = "requests/maintain"
|
||||
|
||||
/// Help link for view request list page
|
||||
let viewRequestList = "requests/view"
|
||||
|
||||
/// Help link for user and class login pages
|
||||
let logOn = "user/log-on"
|
||||
|
||||
/// Help link for user password change page
|
||||
let changePassword = "user/password"
|
||||
|
||||
/// Create a full link for a help page
|
||||
let fullLink lang url = $"https://docs.prayer.bitbadger.solutions/%s{lang}/%s{url}.html"
|
||||
|
||||
|
||||
/// This class serves as a common anchor for resources
|
||||
type Common () =
|
||||
do ()
|
||||
do ()
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -7,195 +7,196 @@ open Microsoft.AspNetCore.Hosting
|
|||
[<RequireQualifiedAccess>]
|
||||
module Configure =
|
||||
|
||||
open Cookies
|
||||
open Giraffe
|
||||
open Giraffe.EndpointRouting
|
||||
open Microsoft.AspNetCore.Localization
|
||||
open Microsoft.AspNetCore.Server.Kestrel.Core
|
||||
open Microsoft.EntityFrameworkCore
|
||||
open Microsoft.Extensions.Configuration
|
||||
open Microsoft.Extensions.DependencyInjection
|
||||
open Microsoft.Extensions.Hosting
|
||||
open Microsoft.Extensions.Localization
|
||||
open Microsoft.Extensions.Logging
|
||||
open Microsoft.Extensions.Options
|
||||
open NodaTime
|
||||
open System.Globalization
|
||||
open Cookies
|
||||
open Giraffe
|
||||
open Giraffe.EndpointRouting
|
||||
open Microsoft.AspNetCore.Localization
|
||||
open Microsoft.AspNetCore.Server.Kestrel.Core
|
||||
open Microsoft.EntityFrameworkCore
|
||||
open Microsoft.Extensions.Configuration
|
||||
open Microsoft.Extensions.DependencyInjection
|
||||
open Microsoft.Extensions.Hosting
|
||||
open Microsoft.Extensions.Localization
|
||||
open Microsoft.Extensions.Logging
|
||||
open Microsoft.Extensions.Options
|
||||
open NodaTime
|
||||
open System.Globalization
|
||||
|
||||
/// Set up the configuration for the app
|
||||
let configuration (ctx : WebHostBuilderContext) (cfg : IConfigurationBuilder) =
|
||||
cfg.SetBasePath(ctx.HostingEnvironment.ContentRootPath)
|
||||
.AddJsonFile("appsettings.json", optional = true, reloadOnChange = true)
|
||||
.AddJsonFile($"appsettings.{ctx.HostingEnvironment.EnvironmentName}.json", optional = true)
|
||||
.AddEnvironmentVariables()
|
||||
|> ignore
|
||||
/// Set up the configuration for the app
|
||||
let configuration (ctx : WebHostBuilderContext) (cfg : IConfigurationBuilder) =
|
||||
cfg.SetBasePath(ctx.HostingEnvironment.ContentRootPath)
|
||||
.AddJsonFile("appsettings.json", optional = true, reloadOnChange = true)
|
||||
.AddJsonFile($"appsettings.{ctx.HostingEnvironment.EnvironmentName}.json", optional = true)
|
||||
.AddEnvironmentVariables()
|
||||
|> ignore
|
||||
|
||||
/// Configure Kestrel from appsettings.json
|
||||
let kestrel (ctx : WebHostBuilderContext) (opts : KestrelServerOptions) =
|
||||
(ctx.Configuration.GetSection >> opts.Configure >> ignore) "Kestrel"
|
||||
/// Configure Kestrel from appsettings.json
|
||||
let kestrel (ctx : WebHostBuilderContext) (opts : KestrelServerOptions) =
|
||||
(ctx.Configuration.GetSection >> opts.Configure >> ignore) "Kestrel"
|
||||
|
||||
let services (svc : IServiceCollection) =
|
||||
svc.AddOptions()
|
||||
.AddLocalization(fun options -> options.ResourcesPath <- "Resources")
|
||||
.Configure<RequestLocalizationOptions>(
|
||||
fun (opts : RequestLocalizationOptions) ->
|
||||
let supportedCultures =
|
||||
[| CultureInfo "en-US"; CultureInfo "en-GB"; CultureInfo "en-AU"; CultureInfo "en"
|
||||
CultureInfo "es-MX"; CultureInfo "es-ES"; CultureInfo "es"
|
||||
|]
|
||||
opts.DefaultRequestCulture <- RequestCulture ("en-US", "en-US")
|
||||
opts.SupportedCultures <- supportedCultures
|
||||
opts.SupportedUICultures <- supportedCultures)
|
||||
.AddDistributedMemoryCache()
|
||||
.AddSession()
|
||||
.AddAntiforgery()
|
||||
.AddRouting()
|
||||
.AddSingleton<IClock>(SystemClock.Instance)
|
||||
|> ignore
|
||||
let config = svc.BuildServiceProvider().GetRequiredService<IConfiguration>()
|
||||
let crypto = config.GetSection "CookieCrypto"
|
||||
CookieCrypto (crypto.["Key"], crypto.["IV"]) |> setCrypto
|
||||
svc.AddDbContext<AppDbContext>(
|
||||
(fun options ->
|
||||
options.UseNpgsql (config.GetConnectionString "PrayerTracker") |> ignore),
|
||||
ServiceLifetime.Scoped, ServiceLifetime.Singleton)
|
||||
|> ignore
|
||||
let services (svc : IServiceCollection) =
|
||||
let _ = svc.AddOptions()
|
||||
let _ = svc.AddLocalization(fun options -> options.ResourcesPath <- "Resources")
|
||||
let _ =
|
||||
svc.Configure<RequestLocalizationOptions>(fun (opts : RequestLocalizationOptions) ->
|
||||
let supportedCultures =[|
|
||||
CultureInfo "en-US"; CultureInfo "en-GB"; CultureInfo "en-AU"; CultureInfo "en"
|
||||
CultureInfo "es-MX"; CultureInfo "es-ES"; CultureInfo "es"
|
||||
|]
|
||||
opts.DefaultRequestCulture <- RequestCulture ("en-US", "en-US")
|
||||
opts.SupportedCultures <- supportedCultures
|
||||
opts.SupportedUICultures <- supportedCultures)
|
||||
let _ = svc.AddDistributedMemoryCache()
|
||||
let _ = svc.AddSession()
|
||||
let _ = svc.AddAntiforgery()
|
||||
let _ = svc.AddRouting()
|
||||
let _ = svc.AddSingleton<IClock>(SystemClock.Instance)
|
||||
|
||||
/// Routes for PrayerTracker
|
||||
let routes =
|
||||
[ subRoute "/web" [
|
||||
GET_HEAD [
|
||||
subRoute "/church" [
|
||||
route "es" Handlers.Church.maintain
|
||||
routef "/%O/edit" Handlers.Church.edit
|
||||
let config = svc.BuildServiceProvider().GetRequiredService<IConfiguration>()
|
||||
let crypto = config.GetSection "CookieCrypto"
|
||||
CookieCrypto (crypto["Key"], crypto["IV"]) |> setCrypto
|
||||
|
||||
let _ = svc.AddDbContext<AppDbContext>(
|
||||
(fun options ->
|
||||
options.UseNpgsql (config.GetConnectionString "PrayerTracker") |> ignore),
|
||||
ServiceLifetime.Scoped, ServiceLifetime.Singleton)
|
||||
()
|
||||
|
||||
/// Routes for PrayerTracker
|
||||
let routes = [
|
||||
subRoute "/web" [
|
||||
GET_HEAD [
|
||||
subRoute "/church" [
|
||||
route "es" Handlers.Church.maintain
|
||||
routef "/%O/edit" Handlers.Church.edit
|
||||
]
|
||||
route "/class/logon" (redirectTo true "/web/small-group/log-on")
|
||||
routef "/error/%s" Handlers.Home.error
|
||||
routef "/language/%s" Handlers.Home.language
|
||||
subRoute "/legal" [
|
||||
route "/privacy-policy" Handlers.Home.privacyPolicy
|
||||
route "/terms-of-service" Handlers.Home.tos
|
||||
]
|
||||
route "/log-off" Handlers.Home.logOff
|
||||
subRoute "/prayer-request" [
|
||||
route "s" (Handlers.PrayerRequest.maintain true)
|
||||
routef "s/email/%s" Handlers.PrayerRequest.email
|
||||
route "s/inactive" (Handlers.PrayerRequest.maintain false)
|
||||
route "s/lists" Handlers.PrayerRequest.lists
|
||||
routef "s/%O/list" Handlers.PrayerRequest.list
|
||||
route "s/maintain" (redirectTo true "/web/prayer-requests")
|
||||
routef "s/print/%s" Handlers.PrayerRequest.print
|
||||
route "s/view" (Handlers.PrayerRequest.view None)
|
||||
routef "s/view/%s" (Some >> Handlers.PrayerRequest.view)
|
||||
routef "/%O/edit" Handlers.PrayerRequest.edit
|
||||
routef "/%O/expire" Handlers.PrayerRequest.expire
|
||||
routef "/%O/restore" Handlers.PrayerRequest.restore
|
||||
]
|
||||
subRoute "/small-group" [
|
||||
route "" Handlers.SmallGroup.overview
|
||||
route "s" Handlers.SmallGroup.maintain
|
||||
route "/announcement" Handlers.SmallGroup.announcement
|
||||
routef "/%O/edit" Handlers.SmallGroup.edit
|
||||
route "/log-on" (Handlers.SmallGroup.logOn None)
|
||||
routef "/log-on/%O" (Some >> Handlers.SmallGroup.logOn)
|
||||
route "/logon" (redirectTo true "/web/small-group/log-on")
|
||||
routef "/member/%O/edit" Handlers.SmallGroup.editMember
|
||||
route "/members" Handlers.SmallGroup.members
|
||||
route "/preferences" Handlers.SmallGroup.preferences
|
||||
]
|
||||
route "/unauthorized" Handlers.Home.unauthorized
|
||||
subRoute "/user" [
|
||||
route "s" Handlers.User.maintain
|
||||
routef "/%O/edit" Handlers.User.edit
|
||||
routef "/%O/small-groups" Handlers.User.smallGroups
|
||||
route "/log-on" Handlers.User.logOn
|
||||
route "/logon" (redirectTo true "/web/user/log-on")
|
||||
route "/password" Handlers.User.password
|
||||
]
|
||||
route "/" Handlers.Home.homePage
|
||||
]
|
||||
route "/class/logon" (redirectTo true "/web/small-group/log-on")
|
||||
routef "/error/%s" Handlers.Home.error
|
||||
routef "/language/%s" Handlers.Home.language
|
||||
subRoute "/legal" [
|
||||
route "/privacy-policy" Handlers.Home.privacyPolicy
|
||||
route "/terms-of-service" Handlers.Home.tos
|
||||
POST [
|
||||
subRoute "/church" [
|
||||
routef "/%O/delete" Handlers.Church.delete
|
||||
route "/save" Handlers.Church.save
|
||||
]
|
||||
subRoute "/prayer-request" [
|
||||
routef "/%O/delete" Handlers.PrayerRequest.delete
|
||||
route "/save" Handlers.PrayerRequest.save
|
||||
]
|
||||
subRoute "/small-group" [
|
||||
route "/announcement/send" Handlers.SmallGroup.sendAnnouncement
|
||||
routef "/%O/delete" Handlers.SmallGroup.delete
|
||||
route "/log-on/submit" Handlers.SmallGroup.logOnSubmit
|
||||
routef "/member/%O/delete" Handlers.SmallGroup.deleteMember
|
||||
route "/member/save" Handlers.SmallGroup.saveMember
|
||||
route "/preferences/save" Handlers.SmallGroup.savePreferences
|
||||
route "/save" Handlers.SmallGroup.save
|
||||
]
|
||||
subRoute "/user" [
|
||||
routef "/%O/delete" Handlers.User.delete
|
||||
route "/edit/save" Handlers.User.save
|
||||
route "/log-on" Handlers.User.doLogOn
|
||||
route "/password/change" Handlers.User.changePassword
|
||||
route "/small-groups/save" Handlers.User.saveGroups
|
||||
]
|
||||
]
|
||||
route "/log-off" Handlers.Home.logOff
|
||||
subRoute "/prayer-request" [
|
||||
route "s" (Handlers.PrayerRequest.maintain true)
|
||||
routef "s/email/%s" Handlers.PrayerRequest.email
|
||||
route "s/inactive" (Handlers.PrayerRequest.maintain false)
|
||||
route "s/lists" Handlers.PrayerRequest.lists
|
||||
routef "s/%O/list" Handlers.PrayerRequest.list
|
||||
route "s/maintain" (redirectTo true "/web/prayer-requests")
|
||||
routef "s/print/%s" Handlers.PrayerRequest.print
|
||||
route "s/view" (Handlers.PrayerRequest.view None)
|
||||
routef "s/view/%s" (Some >> Handlers.PrayerRequest.view)
|
||||
routef "/%O/edit" Handlers.PrayerRequest.edit
|
||||
routef "/%O/expire" Handlers.PrayerRequest.expire
|
||||
routef "/%O/restore" Handlers.PrayerRequest.restore
|
||||
]
|
||||
subRoute "/small-group" [
|
||||
route "" Handlers.SmallGroup.overview
|
||||
route "s" Handlers.SmallGroup.maintain
|
||||
route "/announcement" Handlers.SmallGroup.announcement
|
||||
routef "/%O/edit" Handlers.SmallGroup.edit
|
||||
route "/log-on" (Handlers.SmallGroup.logOn None)
|
||||
routef "/log-on/%O" (Some >> Handlers.SmallGroup.logOn)
|
||||
route "/logon" (redirectTo true "/web/small-group/log-on")
|
||||
routef "/member/%O/edit" Handlers.SmallGroup.editMember
|
||||
route "/members" Handlers.SmallGroup.members
|
||||
route "/preferences" Handlers.SmallGroup.preferences
|
||||
]
|
||||
route "/unauthorized" Handlers.Home.unauthorized
|
||||
subRoute "/user" [
|
||||
route "s" Handlers.User.maintain
|
||||
routef "/%O/edit" Handlers.User.edit
|
||||
routef "/%O/small-groups" Handlers.User.smallGroups
|
||||
route "/log-on" Handlers.User.logOn
|
||||
route "/logon" (redirectTo true "/web/user/log-on")
|
||||
route "/password" Handlers.User.password
|
||||
]
|
||||
route "/" Handlers.Home.homePage
|
||||
]
|
||||
POST [
|
||||
subRoute "/church" [
|
||||
routef "/%O/delete" Handlers.Church.delete
|
||||
route "/save" Handlers.Church.save
|
||||
]
|
||||
subRoute "/prayer-request" [
|
||||
routef "/%O/delete" Handlers.PrayerRequest.delete
|
||||
route "/save" Handlers.PrayerRequest.save
|
||||
]
|
||||
subRoute "/small-group" [
|
||||
route "/announcement/send" Handlers.SmallGroup.sendAnnouncement
|
||||
routef "/%O/delete" Handlers.SmallGroup.delete
|
||||
route "/log-on/submit" Handlers.SmallGroup.logOnSubmit
|
||||
routef "/member/%O/delete" Handlers.SmallGroup.deleteMember
|
||||
route "/member/save" Handlers.SmallGroup.saveMember
|
||||
route "/preferences/save" Handlers.SmallGroup.savePreferences
|
||||
route "/save" Handlers.SmallGroup.save
|
||||
]
|
||||
subRoute "/user" [
|
||||
routef "/%O/delete" Handlers.User.delete
|
||||
route "/edit/save" Handlers.User.save
|
||||
route "/log-on" Handlers.User.doLogOn
|
||||
route "/password/change" Handlers.User.changePassword
|
||||
route "/small-groups/save" Handlers.User.saveGroups
|
||||
]
|
||||
]
|
||||
]
|
||||
// Temp redirect to new URLs
|
||||
route "/" (redirectTo false "/web/")
|
||||
]
|
||||
// Temp redirect to new URLs
|
||||
route "/" (redirectTo false "/web/")
|
||||
]
|
||||
|
||||
/// Giraffe error handler
|
||||
let errorHandler (ex : exn) (logger : ILogger) =
|
||||
logger.LogError(EventId(), ex, "An unhandled exception has occurred while executing the request.")
|
||||
clearResponse >=> setStatusCode 500 >=> text ex.Message
|
||||
/// Giraffe error handler
|
||||
let errorHandler (ex : exn) (logger : ILogger) =
|
||||
logger.LogError (EventId(), ex, "An unhandled exception has occurred while executing the request.")
|
||||
clearResponse >=> setStatusCode 500 >=> text ex.Message
|
||||
|
||||
/// Configure logging
|
||||
let logging (log : ILoggingBuilder) =
|
||||
let env = log.Services.BuildServiceProvider().GetService<IWebHostEnvironment> ()
|
||||
match env.IsDevelopment () with
|
||||
| true -> log
|
||||
| false -> log.AddFilter (fun l -> l > LogLevel.Information)
|
||||
|> function l -> l.AddConsole().AddDebug()
|
||||
|> ignore
|
||||
/// Configure logging
|
||||
let logging (log : ILoggingBuilder) =
|
||||
let env = log.Services.BuildServiceProvider().GetService<IWebHostEnvironment> ()
|
||||
if env.IsDevelopment () then log else log.AddFilter (fun l -> l > LogLevel.Information)
|
||||
|> function l -> l.AddConsole().AddDebug()
|
||||
|> ignore
|
||||
|
||||
let app (app : IApplicationBuilder) =
|
||||
let env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>()
|
||||
(match env.IsDevelopment () with
|
||||
| true ->
|
||||
app.UseDeveloperExceptionPage ()
|
||||
| false ->
|
||||
try
|
||||
use scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope ()
|
||||
scope.ServiceProvider.GetService<AppDbContext>().Database.Migrate ()
|
||||
with _ -> () // om nom nom
|
||||
app.UseGiraffeErrorHandler errorHandler)
|
||||
.UseStatusCodePagesWithReExecute("/error/{0}")
|
||||
.UseStaticFiles()
|
||||
.UseRouting()
|
||||
.UseSession()
|
||||
.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value)
|
||||
.UseEndpoints (fun e -> e.MapGiraffeEndpoints routes)
|
||||
|> ignore
|
||||
Views.I18N.setUpFactories <| app.ApplicationServices.GetRequiredService<IStringLocalizerFactory> ()
|
||||
let app (app : IApplicationBuilder) =
|
||||
let env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>()
|
||||
if env.IsDevelopment () then
|
||||
let _ = app.UseDeveloperExceptionPage ()
|
||||
()
|
||||
else
|
||||
try
|
||||
use scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope ()
|
||||
scope.ServiceProvider.GetService<AppDbContext>().Database.Migrate ()
|
||||
with _ -> () // om nom nom
|
||||
let _ = app.UseGiraffeErrorHandler errorHandler
|
||||
()
|
||||
|
||||
let _ = app.UseStatusCodePagesWithReExecute "/error/{0}"
|
||||
let _ = app.UseStaticFiles ()
|
||||
let _ = app.UseRouting ()
|
||||
let _ = app.UseSession ()
|
||||
let _ = app.UseRequestLocalization
|
||||
(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value)
|
||||
let _ = app.UseEndpoints (fun e -> e.MapGiraffeEndpoints routes)
|
||||
Views.I18N.setUpFactories <| app.ApplicationServices.GetRequiredService<IStringLocalizerFactory> ()
|
||||
|
||||
|
||||
/// The web application
|
||||
module App =
|
||||
|
||||
open System.IO
|
||||
open System.IO
|
||||
|
||||
[<EntryPoint>]
|
||||
let main _ =
|
||||
let contentRoot = Directory.GetCurrentDirectory ()
|
||||
WebHostBuilder()
|
||||
.UseContentRoot(contentRoot)
|
||||
.ConfigureAppConfiguration(Configure.configuration)
|
||||
.UseKestrel(Configure.kestrel)
|
||||
.UseWebRoot(Path.Combine (contentRoot, "wwwroot"))
|
||||
.ConfigureServices(Configure.services)
|
||||
.ConfigureLogging(Configure.logging)
|
||||
.Configure(System.Action<IApplicationBuilder> Configure.app)
|
||||
.Build()
|
||||
.Run ()
|
||||
0
|
||||
[<EntryPoint>]
|
||||
let main _ =
|
||||
let contentRoot = Directory.GetCurrentDirectory ()
|
||||
WebHostBuilder()
|
||||
.UseContentRoot(contentRoot)
|
||||
.ConfigureAppConfiguration(Configure.configuration)
|
||||
.UseKestrel(Configure.kestrel)
|
||||
.UseWebRoot(Path.Combine (contentRoot, "wwwroot"))
|
||||
.ConfigureServices(Configure.services)
|
||||
.ConfigureLogging(Configure.logging)
|
||||
.Configure(System.Action<IApplicationBuilder> Configure.app)
|
||||
.Build()
|
||||
.Run ()
|
||||
0
|
||||
|
|
|
@ -1,27 +1,24 @@
|
|||
module PrayerTracker.Handlers.Church
|
||||
|
||||
open System
|
||||
open System.Threading.Tasks
|
||||
open Giraffe
|
||||
open PrayerTracker
|
||||
open PrayerTracker.Entities
|
||||
open PrayerTracker.ViewModels
|
||||
open PrayerTracker.Views.CommonFunctions
|
||||
open System
|
||||
open System.Threading.Tasks
|
||||
|
||||
/// Find statistics for the given church
|
||||
let private findStats (db : AppDbContext) churchId = task {
|
||||
let! grps = db.CountGroupsByChurch churchId
|
||||
let! reqs = db.CountRequestsByChurch churchId
|
||||
let! usrs = db.CountUsersByChurch churchId
|
||||
return flatGuid churchId, { smallGroups = grps; prayerRequests = reqs; users = usrs }
|
||||
}
|
||||
let! grps = db.CountGroupsByChurch churchId
|
||||
let! reqs = db.CountRequestsByChurch churchId
|
||||
let! usrs = db.CountUsersByChurch churchId
|
||||
return flatGuid churchId, { smallGroups = grps; prayerRequests = reqs; users = usrs }
|
||||
}
|
||||
|
||||
|
||||
/// POST /church/[church-id]/delete
|
||||
let delete churchId : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx -> task {
|
||||
let delete churchId : HttpHandler = requireAccess [ Admin ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.db.TryChurchById churchId with
|
||||
| Some church ->
|
||||
let! _, stats = findStats ctx.db churchId
|
||||
|
@ -29,70 +26,61 @@ let delete churchId : HttpHandler =
|
|||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
addInfo ctx
|
||||
s.["The church {0} and its {1} small groups (with {2} prayer request(s)) were deleted successfully; revoked access from {3} user(s)",
|
||||
s["The church {0} and its {1} small groups (with {2} prayer request(s)) were deleted successfully; revoked access from {3} user(s)",
|
||||
church.name, stats.smallGroups, stats.prayerRequests, stats.users]
|
||||
return! redirectTo false "/web/churches" next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /church/[church-id]/edit
|
||||
let edit churchId : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> fun next ctx -> task {
|
||||
let edit churchId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
match churchId with
|
||||
| x when x = Guid.Empty ->
|
||||
if churchId = Guid.Empty then
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.Church.edit EditChurch.empty ctx
|
||||
|> renderHtml next ctx
|
||||
| _ ->
|
||||
viewInfo ctx startTicks
|
||||
|> Views.Church.edit EditChurch.empty ctx
|
||||
|> renderHtml next ctx
|
||||
else
|
||||
match! ctx.db.TryChurchById churchId with
|
||||
| Some church ->
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.Church.edit (EditChurch.fromChurch church) ctx
|
||||
|> renderHtml next ctx
|
||||
viewInfo ctx startTicks
|
||||
|> Views.Church.edit (EditChurch.fromChurch church) ctx
|
||||
|> renderHtml next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /churches
|
||||
let maintain : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> fun next ctx -> task {
|
||||
let maintain : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let await = Async.AwaitTask >> Async.RunSynchronously
|
||||
let! churches = ctx.db.AllChurches ()
|
||||
let stats = churches |> List.map (fun c -> await (findStats ctx.db c.churchId))
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.Church.maintain churches (stats |> Map.ofList) ctx
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
viewInfo ctx startTicks
|
||||
|> Views.Church.maintain churches (stats |> Map.ofList) ctx
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
|
||||
|
||||
/// POST /church/save
|
||||
let save : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx -> task {
|
||||
let save : HttpHandler = requireAccess [ Admin ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.TryBindFormAsync<EditChurch> () with
|
||||
| Ok m ->
|
||||
let! church =
|
||||
match m.isNew () with
|
||||
| true -> Task.FromResult<Church option>(Some { Church.empty with churchId = Guid.NewGuid () })
|
||||
| false -> ctx.db.TryChurchById m.churchId
|
||||
if m.isNew () then Task.FromResult (Some { Church.empty with churchId = Guid.NewGuid () })
|
||||
else ctx.db.TryChurchById m.churchId
|
||||
match church with
|
||||
| Some ch ->
|
||||
m.populateChurch ch
|
||||
|> (match m.isNew () with true -> ctx.db.AddEntry | false -> ctx.db.UpdateEntry)
|
||||
|> (if m.isNew () then ctx.db.AddEntry else ctx.db.UpdateEntry)
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
let act = s.[match m.isNew () with true -> "Added" | _ -> "Updated"].Value.ToLower ()
|
||||
addInfo ctx s.["Successfully {0} church “{1}”", act, m.name]
|
||||
let act = s[if m.isNew () then "Added" else "Updated"].Value.ToLower ()
|
||||
addInfo ctx s["Successfully {0} church “{1}”", act, m.name]
|
||||
return! redirectTo false "/web/churches" next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,6 +2,10 @@
|
|||
[<AutoOpen>]
|
||||
module PrayerTracker.Handlers.CommonFunctions
|
||||
|
||||
open System
|
||||
open System.Net
|
||||
open System.Reflection
|
||||
open System.Threading.Tasks
|
||||
open Giraffe
|
||||
open Microsoft.AspNetCore.Antiforgery
|
||||
open Microsoft.AspNetCore.Html
|
||||
|
@ -12,244 +16,235 @@ open Microsoft.Extensions.Localization
|
|||
open PrayerTracker
|
||||
open PrayerTracker.Cookies
|
||||
open PrayerTracker.ViewModels
|
||||
open System
|
||||
open System.Net
|
||||
open System.Reflection
|
||||
open System.Threading.Tasks
|
||||
|
||||
/// Create a select list from an enumeration
|
||||
let toSelectList<'T> valFunc textFunc withDefault emptyText (items : 'T seq) =
|
||||
match items with null -> nullArg "items" | _ -> ()
|
||||
[ match withDefault with
|
||||
| true ->
|
||||
let s = PrayerTracker.Views.I18N.localizer.Force ()
|
||||
yield SelectListItem ($"""— %A{s.[emptyText]} —""", "")
|
||||
| _ -> ()
|
||||
yield! items |> Seq.map (fun x -> SelectListItem (textFunc x, valFunc x))
|
||||
match items with null -> nullArg "items" | _ -> ()
|
||||
[ match withDefault with
|
||||
| true ->
|
||||
let s = PrayerTracker.Views.I18N.localizer.Force ()
|
||||
yield SelectListItem ($"""— %A{s[emptyText]} —""", "")
|
||||
| _ -> ()
|
||||
yield! items |> Seq.map (fun x -> SelectListItem (textFunc x, valFunc x))
|
||||
]
|
||||
|
||||
/// Create a select list from an enumeration
|
||||
let toSelectListWithEmpty<'T> valFunc textFunc emptyText (items : 'T seq) =
|
||||
toSelectList valFunc textFunc true emptyText items
|
||||
toSelectList valFunc textFunc true emptyText items
|
||||
|
||||
/// Create a select list from an enumeration
|
||||
let toSelectListWithDefault<'T> valFunc textFunc (items : 'T seq) =
|
||||
toSelectList valFunc textFunc true "Select" items
|
||||
toSelectList valFunc textFunc true "Select" items
|
||||
|
||||
/// The version of PrayerTracker
|
||||
let appVersion =
|
||||
let v = Assembly.GetExecutingAssembly().GetName().Version
|
||||
let v = Assembly.GetExecutingAssembly().GetName().Version
|
||||
#if (DEBUG)
|
||||
$"v{v}"
|
||||
$"v{v}"
|
||||
#else
|
||||
seq {
|
||||
$"v%d{v.Major}"
|
||||
match v.Minor with
|
||||
| 0 -> match v.Build with 0 -> () | _ -> $".0.%d{v.Build}"
|
||||
| _ ->
|
||||
$".%d{v.Minor}"
|
||||
match v.Build with 0 -> () | _ -> $".%d{v.Build}"
|
||||
seq {
|
||||
$"v%d{v.Major}"
|
||||
match v.Minor with
|
||||
| 0 -> match v.Build with 0 -> () | _ -> $".0.%d{v.Build}"
|
||||
| _ ->
|
||||
$".%d{v.Minor}"
|
||||
match v.Build with 0 -> () | _ -> $".%d{v.Build}"
|
||||
}
|
||||
|> String.concat ""
|
||||
|> String.concat ""
|
||||
#endif
|
||||
|
||||
/// The currently signed-in user (will raise if none exists)
|
||||
let currentUser (ctx : HttpContext) =
|
||||
match ctx.Session.user with Some u -> u | None -> nullArg "User"
|
||||
match ctx.Session.user with Some u -> u | None -> nullArg "User"
|
||||
|
||||
/// The currently signed-in small group (will raise if none exists)
|
||||
let currentGroup (ctx : HttpContext) =
|
||||
match ctx.Session.smallGroup with Some g -> g | None -> nullArg "SmallGroup"
|
||||
match ctx.Session.smallGroup with Some g -> g | None -> nullArg "SmallGroup"
|
||||
|
||||
/// Create the common view information heading
|
||||
let viewInfo (ctx : HttpContext) startTicks =
|
||||
let msg =
|
||||
match ctx.Session.messages with
|
||||
| [] -> []
|
||||
| x ->
|
||||
ctx.Session.messages <- []
|
||||
x
|
||||
match ctx.Session.user with
|
||||
| Some u ->
|
||||
// The idle timeout is 2 hours; if the app pool is recycled or the actual session goes away, we will log the
|
||||
// user back in transparently using this cookie. Every request resets the timer.
|
||||
let timeout =
|
||||
{ Id = u.userId
|
||||
GroupId = (currentGroup ctx).smallGroupId
|
||||
Until = DateTime.UtcNow.AddHours(2.).Ticks
|
||||
Password = ""
|
||||
}
|
||||
ctx.Response.Cookies.Append
|
||||
(Key.Cookie.timeout, { timeout with Password = saltedTimeoutHash timeout }.toPayload (),
|
||||
CookieOptions (Expires = Nullable<DateTimeOffset> (DateTimeOffset (DateTime timeout.Until)), HttpOnly = true))
|
||||
| None -> ()
|
||||
{ AppViewInfo.fresh with
|
||||
version = appVersion
|
||||
messages = msg
|
||||
requestStart = startTicks
|
||||
user = ctx.Session.user
|
||||
group = ctx.Session.smallGroup
|
||||
}
|
||||
let msg =
|
||||
match ctx.Session.messages with
|
||||
| [] -> []
|
||||
| x ->
|
||||
ctx.Session.messages <- []
|
||||
x
|
||||
match ctx.Session.user with
|
||||
| Some u ->
|
||||
// The idle timeout is 2 hours; if the app pool is recycled or the actual session goes away, we will log the
|
||||
// user back in transparently using this cookie. Every request resets the timer.
|
||||
let timeout =
|
||||
{ Id = u.userId
|
||||
GroupId = (currentGroup ctx).smallGroupId
|
||||
Until = DateTime.UtcNow.AddHours(2.).Ticks
|
||||
Password = ""
|
||||
}
|
||||
ctx.Response.Cookies.Append
|
||||
(Key.Cookie.timeout, { timeout with Password = saltedTimeoutHash timeout }.toPayload (),
|
||||
CookieOptions (Expires = Nullable<DateTimeOffset> (DateTimeOffset (DateTime timeout.Until)),
|
||||
HttpOnly = true))
|
||||
| None -> ()
|
||||
{ AppViewInfo.fresh with
|
||||
version = appVersion
|
||||
messages = msg
|
||||
requestStart = startTicks
|
||||
user = ctx.Session.user
|
||||
group = ctx.Session.smallGroup
|
||||
}
|
||||
|
||||
/// The view is the last parameter, so it can be composed
|
||||
let renderHtml next ctx view =
|
||||
htmlView view next ctx
|
||||
htmlView view next ctx
|
||||
|
||||
/// Display an error regarding form submission
|
||||
let bindError (msg : string) next (ctx : HttpContext) =
|
||||
System.Console.WriteLine msg
|
||||
ctx.SetStatusCode 400
|
||||
text msg next ctx
|
||||
Console.WriteLine msg
|
||||
ctx.SetStatusCode 400
|
||||
text msg next ctx
|
||||
|
||||
/// Handler that will return a status code 404 and the text "Not Found"
|
||||
let fourOhFour next (ctx : HttpContext) =
|
||||
ctx.SetStatusCode 404
|
||||
text "Not Found" next ctx
|
||||
ctx.SetStatusCode 404
|
||||
text "Not Found" next ctx
|
||||
|
||||
|
||||
/// Handler to validate CSRF prevention token
|
||||
let validateCSRF : HttpHandler =
|
||||
fun next ctx -> task {
|
||||
let validateCSRF : HttpHandler = fun next ctx -> task {
|
||||
match! (ctx.GetService<IAntiforgery> ()).IsRequestValidAsync ctx with
|
||||
| true -> return! next ctx
|
||||
| false ->
|
||||
return! (clearResponse >=> setStatusCode 400 >=> text "Quit hacking...") (fun _ -> Task.FromResult None) ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Add a message to the session
|
||||
let addUserMessage (ctx : HttpContext) msg =
|
||||
ctx.Session.messages <- msg :: ctx.Session.messages
|
||||
ctx.Session.messages <- msg :: ctx.Session.messages
|
||||
|
||||
/// Convert a localized string to an HTML string
|
||||
let htmlLocString (x : LocalizedString) =
|
||||
(WebUtility.HtmlEncode >> HtmlString) x.Value
|
||||
(WebUtility.HtmlEncode >> HtmlString) x.Value
|
||||
|
||||
let htmlString (x : LocalizedString) =
|
||||
HtmlString x.Value
|
||||
HtmlString x.Value
|
||||
|
||||
/// Add an error message to the session
|
||||
let addError ctx msg =
|
||||
addUserMessage ctx { UserMessage.error with text = htmlLocString msg }
|
||||
addUserMessage ctx { UserMessage.error with text = htmlLocString msg }
|
||||
|
||||
/// Add an informational message to the session
|
||||
let addInfo ctx msg =
|
||||
addUserMessage ctx { UserMessage.info with text = htmlLocString msg }
|
||||
addUserMessage ctx { UserMessage.info with text = htmlLocString msg }
|
||||
|
||||
/// Add an informational HTML message to the session
|
||||
let addHtmlInfo ctx msg =
|
||||
addUserMessage ctx { UserMessage.info with text = htmlString msg }
|
||||
addUserMessage ctx { UserMessage.info with text = htmlString msg }
|
||||
|
||||
/// Add a warning message to the session
|
||||
let addWarning ctx msg =
|
||||
addUserMessage ctx { UserMessage.warning with text = htmlLocString msg }
|
||||
addUserMessage ctx { UserMessage.warning with text = htmlLocString msg }
|
||||
|
||||
|
||||
/// A level of required access
|
||||
type AccessLevel =
|
||||
/// Administrative access
|
||||
| Admin
|
||||
/// Small group administrative access
|
||||
| User
|
||||
/// Small group member access
|
||||
| Group
|
||||
/// Errbody
|
||||
| Public
|
||||
/// Administrative access
|
||||
| Admin
|
||||
/// Small group administrative access
|
||||
| User
|
||||
/// Small group member access
|
||||
| Group
|
||||
/// Errbody
|
||||
| Public
|
||||
|
||||
|
||||
/// Require the given access role (also refreshes "Remember Me" user and group logons)
|
||||
let requireAccess level : HttpHandler =
|
||||
|
||||
/// Is there currently a user logged on?
|
||||
let isUserLoggedOn (ctx : HttpContext) =
|
||||
ctx.Session.user |> Option.isSome
|
||||
/// Is there currently a user logged on?
|
||||
let isUserLoggedOn (ctx : HttpContext) =
|
||||
ctx.Session.user |> Option.isSome
|
||||
|
||||
/// Log a user on from the timeout cookie
|
||||
let logOnUserFromTimeoutCookie (ctx : HttpContext) = task {
|
||||
// Make sure the cookie hasn't been tampered with
|
||||
try
|
||||
match TimeoutCookie.fromPayload ctx.Request.Cookies.[Key.Cookie.timeout] with
|
||||
| Some c when c.Password = saltedTimeoutHash c ->
|
||||
let! user = ctx.db.TryUserById c.Id
|
||||
match user with
|
||||
| Some _ ->
|
||||
ctx.Session.user <- user
|
||||
let! grp = ctx.db.TryGroupById c.GroupId
|
||||
ctx.Session.smallGroup <- grp
|
||||
| _ -> ()
|
||||
| _ -> ()
|
||||
// If something above doesn't work, the user doesn't get logged in
|
||||
with _ -> ()
|
||||
/// Log a user on from the timeout cookie
|
||||
let logOnUserFromTimeoutCookie (ctx : HttpContext) = task {
|
||||
// Make sure the cookie hasn't been tampered with
|
||||
try
|
||||
match TimeoutCookie.fromPayload ctx.Request.Cookies[Key.Cookie.timeout] with
|
||||
| Some c when c.Password = saltedTimeoutHash c ->
|
||||
let! user = ctx.db.TryUserById c.Id
|
||||
match user with
|
||||
| Some _ ->
|
||||
ctx.Session.user <- user
|
||||
let! grp = ctx.db.TryGroupById c.GroupId
|
||||
ctx.Session.smallGroup <- grp
|
||||
| _ -> ()
|
||||
| _ -> ()
|
||||
// If something above doesn't work, the user doesn't get logged in
|
||||
with _ -> ()
|
||||
}
|
||||
|
||||
/// Attempt to log the user on from their stored cookie
|
||||
let logOnUserFromCookie (ctx : HttpContext) = task {
|
||||
match UserCookie.fromPayload ctx.Request.Cookies.[Key.Cookie.user] with
|
||||
| Some c ->
|
||||
let! user = ctx.db.TryUserLogOnByCookie c.Id c.GroupId c.PasswordHash
|
||||
match user with
|
||||
| Some _ ->
|
||||
ctx.Session.user <- user
|
||||
let! grp = ctx.db.TryGroupById c.GroupId
|
||||
ctx.Session.smallGroup <- grp
|
||||
// Rewrite the cookie to extend the expiration
|
||||
ctx.Response.Cookies.Append (Key.Cookie.user, c.toPayload (), autoRefresh)
|
||||
/// Attempt to log the user on from their stored cookie
|
||||
let logOnUserFromCookie (ctx : HttpContext) = task {
|
||||
match UserCookie.fromPayload ctx.Request.Cookies[Key.Cookie.user] with
|
||||
| Some c ->
|
||||
let! user = ctx.db.TryUserLogOnByCookie c.Id c.GroupId c.PasswordHash
|
||||
match user with
|
||||
| Some _ ->
|
||||
ctx.Session.user <- user
|
||||
let! grp = ctx.db.TryGroupById c.GroupId
|
||||
ctx.Session.smallGroup <- grp
|
||||
// Rewrite the cookie to extend the expiration
|
||||
ctx.Response.Cookies.Append (Key.Cookie.user, c.toPayload (), autoRefresh)
|
||||
| _ -> ()
|
||||
| _ -> ()
|
||||
| _ -> ()
|
||||
}
|
||||
|
||||
/// Is there currently a small group (or member thereof) logged on?
|
||||
let isGroupLoggedOn (ctx : HttpContext) =
|
||||
ctx.Session.smallGroup |> Option.isSome
|
||||
/// Is there currently a small group (or member thereof) logged on?
|
||||
let isGroupLoggedOn (ctx : HttpContext) =
|
||||
ctx.Session.smallGroup |> Option.isSome
|
||||
|
||||
/// Attempt to log the small group on from their stored cookie
|
||||
let logOnGroupFromCookie (ctx : HttpContext) =
|
||||
task {
|
||||
match GroupCookie.fromPayload ctx.Request.Cookies.[Key.Cookie.group] with
|
||||
| Some c ->
|
||||
let! grp = ctx.db.TryGroupLogOnByCookie c.GroupId c.PasswordHash sha1Hash
|
||||
match grp with
|
||||
| Some _ ->
|
||||
ctx.Session.smallGroup <- grp
|
||||
// Rewrite the cookie to extend the expiration
|
||||
ctx.Response.Cookies.Append (Key.Cookie.group, c.toPayload (), autoRefresh)
|
||||
| None -> ()
|
||||
| None -> ()
|
||||
/// Attempt to log the small group on from their stored cookie
|
||||
let logOnGroupFromCookie (ctx : HttpContext) = task {
|
||||
match GroupCookie.fromPayload ctx.Request.Cookies[Key.Cookie.group] with
|
||||
| Some c ->
|
||||
let! grp = ctx.db.TryGroupLogOnByCookie c.GroupId c.PasswordHash sha1Hash
|
||||
match grp with
|
||||
| Some _ ->
|
||||
ctx.Session.smallGroup <- grp
|
||||
// Rewrite the cookie to extend the expiration
|
||||
ctx.Response.Cookies.Append (Key.Cookie.group, c.toPayload (), autoRefresh)
|
||||
| None -> ()
|
||||
| None -> ()
|
||||
}
|
||||
|
||||
fun next ctx -> FSharp.Control.Tasks.Affine.task {
|
||||
// Auto-logon user or class, if required
|
||||
match isUserLoggedOn ctx with
|
||||
| true -> ()
|
||||
| false ->
|
||||
do! logOnUserFromTimeoutCookie ctx
|
||||
match isUserLoggedOn ctx with
|
||||
| true -> ()
|
||||
| false ->
|
||||
do! logOnUserFromCookie ctx
|
||||
match isGroupLoggedOn ctx with true -> () | false -> do! logOnGroupFromCookie ctx
|
||||
fun next ctx -> task {
|
||||
// Auto-logon user or class, if required
|
||||
if not (isUserLoggedOn ctx) then
|
||||
do! logOnUserFromTimeoutCookie ctx
|
||||
if not (isUserLoggedOn ctx) then
|
||||
do! logOnUserFromCookie ctx
|
||||
if not (isGroupLoggedOn ctx) then do! logOnGroupFromCookie ctx
|
||||
|
||||
match true with
|
||||
| _ when level |> List.contains Public -> return! next ctx
|
||||
| _ when level |> List.contains User && isUserLoggedOn ctx -> return! next ctx
|
||||
| _ when level |> List.contains Group && isGroupLoggedOn ctx -> return! next ctx
|
||||
| _ when level |> List.contains Admin && isUserLoggedOn ctx ->
|
||||
match (currentUser ctx).isAdmin with
|
||||
| true -> return! next ctx
|
||||
| false ->
|
||||
match true with
|
||||
| _ when level |> List.contains Public -> return! next ctx
|
||||
| _ when level |> List.contains User && isUserLoggedOn ctx -> return! next ctx
|
||||
| _ when level |> List.contains Group && isGroupLoggedOn ctx -> return! next ctx
|
||||
| _ when level |> List.contains Admin && isUserLoggedOn ctx ->
|
||||
match (currentUser ctx).isAdmin with
|
||||
| true -> return! next ctx
|
||||
| false ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
addError ctx s["You are not authorized to view the requested page."]
|
||||
return! redirectTo false "/web/unauthorized" next ctx
|
||||
| _ when level |> List.contains User ->
|
||||
// Redirect to the user log on page
|
||||
ctx.Session.SetString (Key.Session.redirectUrl, ctx.Request.GetEncodedUrl ())
|
||||
return! redirectTo false "/web/user/log-on" next ctx
|
||||
| _ when level |> List.contains Group ->
|
||||
// Redirect to the small group log on page
|
||||
ctx.Session.SetString (Key.Session.redirectUrl, ctx.Request.GetEncodedUrl ())
|
||||
return! redirectTo false "/web/small-group/log-on" next ctx
|
||||
| _ ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
addError ctx s.["You are not authorized to view the requested page."]
|
||||
addError ctx s["You are not authorized to view the requested page."]
|
||||
return! redirectTo false "/web/unauthorized" next ctx
|
||||
| _ when level |> List.contains User ->
|
||||
// Redirect to the user log on page
|
||||
ctx.Session.SetString (Key.Session.redirectUrl, ctx.Request.GetEncodedUrl ())
|
||||
return! redirectTo false "/web/user/log-on" next ctx
|
||||
| _ when level |> List.contains Group ->
|
||||
// Redirect to the small group log on page
|
||||
ctx.Session.SetString (Key.Session.redirectUrl, ctx.Request.GetEncodedUrl ())
|
||||
return! redirectTo false "/web/small-group/log-on" next ctx
|
||||
| _ ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
addError ctx s.["You are not authorized to view the requested page."]
|
||||
return! redirectTo false "/web/unauthorized" next ctx
|
||||
}
|
||||
|
|
|
@ -10,47 +10,49 @@ open System.IO
|
|||
|
||||
/// Cryptography settings to use for encrypting cookies
|
||||
type CookieCrypto (key : string, iv : string) =
|
||||
/// The key for the AES encryptor/decryptor
|
||||
member __.Key = Convert.FromBase64String key
|
||||
/// The initialization vector for the AES encryptor/decryptor
|
||||
member __.IV = Convert.FromBase64String iv
|
||||
|
||||
/// The key for the AES encryptor/decryptor
|
||||
member _.Key = Convert.FromBase64String key
|
||||
|
||||
/// The initialization vector for the AES encryptor/decryptor
|
||||
member _.IV = Convert.FromBase64String iv
|
||||
|
||||
|
||||
/// Helpers for encrypting/decrypting cookies
|
||||
[<AutoOpen>]
|
||||
module private Crypto =
|
||||
|
||||
/// An instance of the cookie cryptography settings
|
||||
let mutable crypto = CookieCrypto ("", "")
|
||||
/// An instance of the cookie cryptography settings
|
||||
let mutable crypto = CookieCrypto ("", "")
|
||||
|
||||
/// Encrypt a cookie payload
|
||||
let encrypt (payload : string) =
|
||||
use aes = Aes.Create ()
|
||||
use enc = aes.CreateEncryptor (crypto.Key, crypto.IV)
|
||||
use ms = new MemoryStream ()
|
||||
use cs = new CryptoStream (ms, enc, CryptoStreamMode.Write)
|
||||
use sw = new StreamWriter (cs)
|
||||
sw.Write payload
|
||||
sw.Close ()
|
||||
(ms.ToArray >> Convert.ToBase64String) ()
|
||||
/// Encrypt a cookie payload
|
||||
let encrypt (payload : string) =
|
||||
use aes = Aes.Create ()
|
||||
use enc = aes.CreateEncryptor (crypto.Key, crypto.IV)
|
||||
use ms = new MemoryStream ()
|
||||
use cs = new CryptoStream (ms, enc, CryptoStreamMode.Write)
|
||||
use sw = new StreamWriter (cs)
|
||||
sw.Write payload
|
||||
sw.Close ()
|
||||
(ms.ToArray >> Convert.ToBase64String) ()
|
||||
|
||||
/// Decrypt a cookie payload
|
||||
let decrypt payload =
|
||||
use aes = Aes.Create ()
|
||||
use dec = aes.CreateDecryptor (crypto.Key, crypto.IV)
|
||||
use ms = new MemoryStream (Convert.FromBase64String payload)
|
||||
use cs = new CryptoStream (ms, dec, CryptoStreamMode.Read)
|
||||
use sr = new StreamReader (cs)
|
||||
sr.ReadToEnd ()
|
||||
/// Decrypt a cookie payload
|
||||
let decrypt payload =
|
||||
use aes = Aes.Create ()
|
||||
use dec = aes.CreateDecryptor (crypto.Key, crypto.IV)
|
||||
use ms = new MemoryStream (Convert.FromBase64String payload)
|
||||
use cs = new CryptoStream (ms, dec, CryptoStreamMode.Read)
|
||||
use sr = new StreamReader (cs)
|
||||
sr.ReadToEnd ()
|
||||
|
||||
/// Encrypt a cookie
|
||||
let encryptCookie cookie =
|
||||
(JsonConvert.SerializeObject >> encrypt) cookie
|
||||
/// Encrypt a cookie
|
||||
let encryptCookie cookie =
|
||||
(JsonConvert.SerializeObject >> encrypt) cookie
|
||||
|
||||
/// Decrypt a cookie
|
||||
let decryptCookie<'T> payload =
|
||||
(decrypt >> JsonConvert.DeserializeObject<'T> >> box) payload
|
||||
|> function null -> None | x -> Some (unbox<'T> x)
|
||||
/// Decrypt a cookie
|
||||
let decryptCookie<'T> payload =
|
||||
(decrypt >> JsonConvert.DeserializeObject<'T> >> box) payload
|
||||
|> function null -> None | x -> Some (unbox<'T> x)
|
||||
|
||||
|
||||
/// Accessor so that the crypto settings instance can be set during startup
|
||||
|
@ -59,71 +61,83 @@ let setCrypto c = Crypto.crypto <- c
|
|||
|
||||
/// Properties stored in the Small Group cookie
|
||||
type GroupCookie =
|
||||
{ /// The Id of the small group
|
||||
[<JsonProperty "g">]
|
||||
GroupId : Guid
|
||||
/// The password hash of the small group
|
||||
[<JsonProperty "p">]
|
||||
PasswordHash : string
|
||||
{ /// The Id of the small group
|
||||
[<JsonProperty "g">]
|
||||
GroupId : Guid
|
||||
|
||||
/// The password hash of the small group
|
||||
[<JsonProperty "p">]
|
||||
PasswordHash : string
|
||||
}
|
||||
with
|
||||
with
|
||||
|
||||
/// Convert these properties to a cookie payload
|
||||
member this.toPayload () =
|
||||
encryptCookie this
|
||||
encryptCookie this
|
||||
|
||||
/// Create a set of strongly-typed properties from the cookie payload
|
||||
static member fromPayload x =
|
||||
try decryptCookie<GroupCookie> x with _ -> None
|
||||
try decryptCookie<GroupCookie> x with _ -> None
|
||||
|
||||
|
||||
/// The payload for the timeout cookie
|
||||
type TimeoutCookie =
|
||||
{ /// The Id of the small group to which the user is currently logged in
|
||||
[<JsonProperty "g">]
|
||||
GroupId : Guid
|
||||
/// The Id of the user who is currently logged in
|
||||
[<JsonProperty "i">]
|
||||
Id : Guid
|
||||
/// The salted timeout hash to ensure that there has been no tampering with the cookie
|
||||
[<JsonProperty "p">]
|
||||
Password : string
|
||||
/// How long this cookie is valid
|
||||
[<JsonProperty "u">]
|
||||
Until : int64
|
||||
{ /// The Id of the small group to which the user is currently logged in
|
||||
[<JsonProperty "g">]
|
||||
GroupId : Guid
|
||||
|
||||
/// The Id of the user who is currently logged in
|
||||
[<JsonProperty "i">]
|
||||
Id : Guid
|
||||
|
||||
/// The salted timeout hash to ensure that there has been no tampering with the cookie
|
||||
[<JsonProperty "p">]
|
||||
Password : string
|
||||
|
||||
/// How long this cookie is valid
|
||||
[<JsonProperty "u">]
|
||||
Until : int64
|
||||
}
|
||||
with
|
||||
with
|
||||
|
||||
/// Convert this set of properties to the cookie payload
|
||||
member this.toPayload () =
|
||||
encryptCookie this
|
||||
encryptCookie this
|
||||
|
||||
/// Create a strongly-typed timeout cookie from the cookie payload
|
||||
static member fromPayload x =
|
||||
try decryptCookie<TimeoutCookie> x with _ -> None
|
||||
try decryptCookie<TimeoutCookie> x with _ -> None
|
||||
|
||||
|
||||
/// The payload for the user's "Remember Me" cookie
|
||||
type UserCookie =
|
||||
{ /// The Id of the group into to which the user is logged
|
||||
[< JsonProperty "g">]
|
||||
GroupId : Guid
|
||||
/// The Id of the user
|
||||
[<JsonProperty "i">]
|
||||
Id : Guid
|
||||
/// The user's password hash
|
||||
[<JsonProperty "p">]
|
||||
PasswordHash : string
|
||||
{ /// The Id of the group into to which the user is logged
|
||||
[< JsonProperty "g">]
|
||||
GroupId : Guid
|
||||
|
||||
/// The Id of the user
|
||||
[<JsonProperty "i">]
|
||||
Id : Guid
|
||||
|
||||
/// The user's password hash
|
||||
[<JsonProperty "p">]
|
||||
PasswordHash : string
|
||||
}
|
||||
with
|
||||
with
|
||||
|
||||
/// Convert this set of properties to a cookie payload
|
||||
member this.toPayload () =
|
||||
encryptCookie this
|
||||
encryptCookie this
|
||||
|
||||
/// Create the strongly-typed cookie properties from a cookie payload
|
||||
static member fromPayload x =
|
||||
try decryptCookie<UserCookie> x with _ -> None
|
||||
try decryptCookie<UserCookie> x with _ -> None
|
||||
|
||||
|
||||
/// Create a salted hash to use to validate the idle timeout key
|
||||
let saltedTimeoutHash (c : TimeoutCookie) =
|
||||
sha1Hash $"Prayer%A{c.Id}Tracker%A{c.GroupId}Idle%d{c.Until}Timeout"
|
||||
sha1Hash $"Prayer%A{c.Id}Tracker%A{c.GroupId}Idle%d{c.Until}Timeout"
|
||||
|
||||
/// Cookie options to push an expiration out by 100 days
|
||||
let autoRefresh =
|
||||
CookieOptions (Expires = Nullable<DateTimeOffset> (DateTimeOffset (DateTime.UtcNow.AddDays 100.)), HttpOnly = true)
|
||||
CookieOptions (Expires = Nullable<DateTimeOffset> (DateTimeOffset (DateTime.UtcNow.AddDays 100.)), HttpOnly = true)
|
||||
|
|
|
@ -14,64 +14,67 @@ let private fromAddress = "prayer@bitbadger.solutions"
|
|||
/// Get an SMTP client connection
|
||||
// FIXME: make host configurable
|
||||
let getConnection () = task {
|
||||
let client = new SmtpClient ()
|
||||
do! client.ConnectAsync ("127.0.0.1", 25, SecureSocketOptions.None)
|
||||
return client
|
||||
}
|
||||
let client = new SmtpClient ()
|
||||
do! client.ConnectAsync ("127.0.0.1", 25, SecureSocketOptions.None)
|
||||
return client
|
||||
}
|
||||
|
||||
/// Create a mail message object, filled with everything but the body content
|
||||
let createMessage (grp : SmallGroup) subj =
|
||||
let msg = MimeMessage ()
|
||||
msg.From.Add (MailboxAddress (grp.preferences.emailFromName, fromAddress))
|
||||
msg.Subject <- subj
|
||||
msg.ReplyTo.Add (MailboxAddress (grp.preferences.emailFromName, grp.preferences.emailFromAddress))
|
||||
msg
|
||||
let msg = MimeMessage ()
|
||||
msg.From.Add (MailboxAddress (grp.preferences.emailFromName, fromAddress))
|
||||
msg.Subject <- subj
|
||||
msg.ReplyTo.Add (MailboxAddress (grp.preferences.emailFromName, grp.preferences.emailFromAddress))
|
||||
msg
|
||||
|
||||
/// Create an HTML-format e-mail message
|
||||
let createHtmlMessage grp subj body (s : IStringLocalizer) =
|
||||
let bodyText =
|
||||
[ """<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><title></title></head><body>"""
|
||||
body
|
||||
"""<hr><div style="text-align:right;font-family:Arial,Helvetica,sans-serif;font-size:8pt;padding-right:10px;">"""
|
||||
s.["Generated by P R A Y E R T R A C K E R"].Value
|
||||
"<br><small>"
|
||||
s.["from Bit Badger Solutions"].Value
|
||||
"</small></div></body></html>"
|
||||
]
|
||||
|> String.concat ""
|
||||
let msg = createMessage grp subj
|
||||
msg.Body <- TextPart (TextFormat.Html, Text = bodyText)
|
||||
msg
|
||||
let bodyText =
|
||||
[ """<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><title></title></head><body>"""
|
||||
body
|
||||
"""<hr><div style="text-align:right;font-family:Arial,Helvetica,sans-serif;font-size:8pt;padding-right:10px;">"""
|
||||
s["Generated by P R A Y E R T R A C K E R"].Value
|
||||
"<br><small>"
|
||||
s["from Bit Badger Solutions"].Value
|
||||
"</small></div></body></html>"
|
||||
]
|
||||
|> String.concat ""
|
||||
let msg = createMessage grp subj
|
||||
msg.Body <- TextPart (TextFormat.Html, Text = bodyText)
|
||||
msg
|
||||
|
||||
/// Create a plain-text-format e-mail message
|
||||
let createTextMessage grp subj body (s : IStringLocalizer) =
|
||||
let bodyText =
|
||||
[ body
|
||||
"\n\n--\n"
|
||||
s.["Generated by P R A Y E R T R A C K E R"].Value
|
||||
"\n"
|
||||
s.["from Bit Badger Solutions"].Value
|
||||
]
|
||||
|> String.concat ""
|
||||
let msg = createMessage grp subj
|
||||
msg.Body <- TextPart (TextFormat.Plain, Text = bodyText)
|
||||
msg
|
||||
let bodyText =
|
||||
[ body
|
||||
"\n\n--\n"
|
||||
s["Generated by P R A Y E R T R A C K E R"].Value
|
||||
"\n"
|
||||
s["from Bit Badger Solutions"].Value
|
||||
]
|
||||
|> String.concat ""
|
||||
let msg = createMessage grp subj
|
||||
msg.Body <- TextPart (TextFormat.Plain, Text = bodyText)
|
||||
msg
|
||||
|
||||
/// Send e-mails to a class
|
||||
let sendEmails (client : SmtpClient) (recipients : Member list) grp subj html text s = task {
|
||||
let htmlMsg = createHtmlMessage grp subj html s
|
||||
let plainTextMsg = createTextMessage grp subj text s
|
||||
let htmlMsg = createHtmlMessage grp subj html s
|
||||
let plainTextMsg = createTextMessage grp subj text s
|
||||
|
||||
for mbr in recipients do
|
||||
let emailType = match mbr.format with Some f -> EmailFormat.fromCode f | None -> grp.preferences.defaultEmailType
|
||||
let emailTo = MailboxAddress (mbr.memberName, mbr.email)
|
||||
match emailType with
|
||||
| HtmlFormat ->
|
||||
htmlMsg.To.Add emailTo
|
||||
do! client.SendAsync htmlMsg
|
||||
htmlMsg.To.Clear ()
|
||||
| PlainTextFormat ->
|
||||
plainTextMsg.To.Add emailTo
|
||||
do! client.SendAsync plainTextMsg
|
||||
plainTextMsg.To.Clear ()
|
||||
}
|
||||
for mbr in recipients do
|
||||
let emailType =
|
||||
match mbr.format with
|
||||
| Some f -> EmailFormat.fromCode f
|
||||
| None -> grp.preferences.defaultEmailType
|
||||
let emailTo = MailboxAddress (mbr.memberName, mbr.email)
|
||||
match emailType with
|
||||
| HtmlFormat ->
|
||||
htmlMsg.To.Add emailTo
|
||||
do! client.SendAsync htmlMsg
|
||||
htmlMsg.To.Clear ()
|
||||
| PlainTextFormat ->
|
||||
plainTextMsg.To.Add emailTo
|
||||
do! client.SendAsync plainTextMsg
|
||||
plainTextMsg.To.Clear ()
|
||||
}
|
||||
|
|
|
@ -11,42 +11,42 @@ open PrayerTracker.ViewModels
|
|||
// fsharplint:disable MemberNames
|
||||
|
||||
type ISession with
|
||||
/// Set an object in the session
|
||||
member this.SetObject key value =
|
||||
this.SetString (key, JsonConvert.SerializeObject value)
|
||||
/// Set an object in the session
|
||||
member this.SetObject key value =
|
||||
this.SetString (key, JsonConvert.SerializeObject value)
|
||||
|
||||
/// Get an object from the session
|
||||
member this.GetObject<'T> key =
|
||||
match this.GetString key with
|
||||
| null -> Unchecked.defaultof<'T>
|
||||
| v -> JsonConvert.DeserializeObject<'T> v
|
||||
/// Get an object from the session
|
||||
member this.GetObject<'T> key =
|
||||
match this.GetString key with
|
||||
| null -> Unchecked.defaultof<'T>
|
||||
| v -> JsonConvert.DeserializeObject<'T> v
|
||||
|
||||
/// The current small group for the session
|
||||
member this.smallGroup
|
||||
with get () = this.GetObject<SmallGroup> Key.Session.currentGroup |> Option.fromObject
|
||||
and set (v : SmallGroup option) =
|
||||
match v with
|
||||
| Some group -> this.SetObject Key.Session.currentGroup group
|
||||
| None -> this.Remove Key.Session.currentGroup
|
||||
/// The current small group for the session
|
||||
member this.smallGroup
|
||||
with get () = this.GetObject<SmallGroup> Key.Session.currentGroup |> Option.fromObject
|
||||
and set (v : SmallGroup option) =
|
||||
match v with
|
||||
| Some group -> this.SetObject Key.Session.currentGroup group
|
||||
| None -> this.Remove Key.Session.currentGroup
|
||||
|
||||
/// The current user for the session
|
||||
member this.user
|
||||
with get () = this.GetObject<User> Key.Session.currentUser |> Option.fromObject
|
||||
and set (v : User option) =
|
||||
match v with
|
||||
| Some user -> this.SetObject Key.Session.currentUser user
|
||||
| None -> this.Remove Key.Session.currentUser
|
||||
/// The current user for the session
|
||||
member this.user
|
||||
with get () = this.GetObject<User> Key.Session.currentUser |> Option.fromObject
|
||||
and set (v : User option) =
|
||||
match v with
|
||||
| Some user -> this.SetObject Key.Session.currentUser user
|
||||
| None -> this.Remove Key.Session.currentUser
|
||||
|
||||
/// Current messages for the session
|
||||
member this.messages
|
||||
with get () =
|
||||
match box (this.GetObject<UserMessage list> Key.Session.userMessages) with
|
||||
| null -> List.empty<UserMessage>
|
||||
| msgs -> unbox msgs
|
||||
and set (v : UserMessage list) = this.SetObject Key.Session.userMessages v
|
||||
/// Current messages for the session
|
||||
member this.messages
|
||||
with get () =
|
||||
match box (this.GetObject<UserMessage list> Key.Session.userMessages) with
|
||||
| null -> List.empty<UserMessage>
|
||||
| msgs -> unbox msgs
|
||||
and set (v : UserMessage list) = this.SetObject Key.Session.userMessages v
|
||||
|
||||
|
||||
type HttpContext with
|
||||
/// The EF Core database context (via DI)
|
||||
member this.db
|
||||
with get () = this.RequestServices.GetRequiredService<AppDbContext> ()
|
||||
/// The EF Core database context (via DI)
|
||||
member this.db
|
||||
with get () = this.RequestServices.GetRequiredService<AppDbContext> ()
|
||||
|
|
|
@ -1,90 +1,76 @@
|
|||
module PrayerTracker.Handlers.Home
|
||||
|
||||
open System
|
||||
open System.Globalization
|
||||
open Giraffe
|
||||
open Microsoft.AspNetCore.Http
|
||||
open Microsoft.AspNetCore.Localization
|
||||
open PrayerTracker
|
||||
open System
|
||||
open System.Globalization
|
||||
|
||||
/// GET /error/[error-code]
|
||||
let error code : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> fun next ctx ->
|
||||
let error code : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
|
||||
viewInfo ctx DateTime.Now.Ticks
|
||||
|> Views.Home.error code
|
||||
|> renderHtml next ctx
|
||||
|
||||
|
||||
/// GET /
|
||||
let homePage : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> fun next ctx ->
|
||||
let homePage : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
|
||||
viewInfo ctx DateTime.Now.Ticks
|
||||
|> Views.Home.index
|
||||
|> renderHtml next ctx
|
||||
|
||||
|
||||
/// GET /language/[culture]
|
||||
let language culture : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> fun next ctx ->
|
||||
let language culture : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
|
||||
try
|
||||
match culture with
|
||||
| null
|
||||
| ""
|
||||
| "en" -> "en-US"
|
||||
| "es" -> "es-MX"
|
||||
| _ -> $"{culture}-{culture.ToUpper ()}"
|
||||
|> (CultureInfo >> Option.ofObj)
|
||||
match culture with
|
||||
| null
|
||||
| ""
|
||||
| "en" -> "en-US"
|
||||
| "es" -> "es-MX"
|
||||
| _ -> $"{culture}-{culture.ToUpper ()}"
|
||||
|> (CultureInfo >> Option.ofObj)
|
||||
with
|
||||
| :? CultureNotFoundException
|
||||
| :? ArgumentException -> None
|
||||
|> function
|
||||
| Some c ->
|
||||
ctx.Response.Cookies.Append (
|
||||
CookieRequestCultureProvider.DefaultCookieName,
|
||||
CookieRequestCultureProvider.MakeCookieValue (RequestCulture c),
|
||||
CookieOptions (Expires = Nullable<DateTimeOffset> (DateTimeOffset (DateTime.Now.AddYears 1))))
|
||||
CookieRequestCultureProvider.DefaultCookieName,
|
||||
CookieRequestCultureProvider.MakeCookieValue (RequestCulture c),
|
||||
CookieOptions (Expires = Nullable<DateTimeOffset> (DateTimeOffset (DateTime.Now.AddYears 1))))
|
||||
| _ -> ()
|
||||
let url = match string ctx.Request.Headers.["Referer"] with null | "" -> "/web/" | r -> r
|
||||
let url = match string ctx.Request.Headers["Referer"] with null | "" -> "/web/" | r -> r
|
||||
redirectTo false url next ctx
|
||||
|
||||
|
||||
/// GET /legal/privacy-policy
|
||||
let privacyPolicy : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> fun next ctx ->
|
||||
let privacyPolicy : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
|
||||
viewInfo ctx DateTime.Now.Ticks
|
||||
|> Views.Home.privacyPolicy
|
||||
|> renderHtml next ctx
|
||||
|
||||
|
||||
/// GET /legal/terms-of-service
|
||||
let tos : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> fun next ctx ->
|
||||
let tos : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
|
||||
viewInfo ctx DateTime.Now.Ticks
|
||||
|> Views.Home.termsOfService
|
||||
|> renderHtml next ctx
|
||||
|
||||
|
||||
/// GET /log-off
|
||||
let logOff : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> fun next ctx ->
|
||||
let logOff : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
|
||||
ctx.Session.Clear ()
|
||||
// Remove cookies if they exist
|
||||
Key.Cookie.logOffCookies |> List.iter ctx.Response.Cookies.Delete
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
addHtmlInfo ctx s.["Log Off Successful • Have a nice day!"]
|
||||
addHtmlInfo ctx s["Log Off Successful • Have a nice day!"]
|
||||
redirectTo false "/web/" next ctx
|
||||
|
||||
|
||||
/// GET /unauthorized
|
||||
let unauthorized : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> fun next ctx ->
|
||||
let unauthorized : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
|
||||
viewInfo ctx DateTime.Now.Ticks
|
||||
|> Views.Home.unauthorized
|
||||
|> renderHtml next ctx
|
||||
|
|
|
@ -1,253 +1,234 @@
|
|||
module PrayerTracker.Handlers.PrayerRequest
|
||||
|
||||
open System
|
||||
open System.Threading.Tasks
|
||||
open Giraffe
|
||||
open Microsoft.AspNetCore.Http
|
||||
open NodaTime
|
||||
open PrayerTracker
|
||||
open PrayerTracker.Entities
|
||||
open PrayerTracker.ViewModels
|
||||
open System
|
||||
open System.Threading.Tasks
|
||||
|
||||
/// Retrieve a prayer request, and ensure that it belongs to the current class
|
||||
let private findRequest (ctx : HttpContext) reqId = task {
|
||||
match! ctx.db.TryRequestById reqId with
|
||||
| Some req when req.smallGroupId = (currentGroup ctx).smallGroupId -> return Ok req
|
||||
| Some _ ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
addError ctx s.["The prayer request you tried to access is not assigned to your group"]
|
||||
return Error (redirectTo false "/web/unauthorized")
|
||||
| None -> return Error fourOhFour
|
||||
}
|
||||
match! ctx.db.TryRequestById reqId with
|
||||
| Some req when req.smallGroupId = (currentGroup ctx).smallGroupId -> return Ok req
|
||||
| Some _ ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
addError ctx s["The prayer request you tried to access is not assigned to your group"]
|
||||
return Error (redirectTo false "/web/unauthorized")
|
||||
| None -> return Error fourOhFour
|
||||
}
|
||||
|
||||
/// Generate a list of requests for the given date
|
||||
let private generateRequestList ctx date =
|
||||
let grp = currentGroup ctx
|
||||
let clock = ctx.GetService<IClock> ()
|
||||
let listDate =
|
||||
match date with
|
||||
| Some d -> d
|
||||
| None -> grp.localDateNow clock
|
||||
let reqs = ctx.db.AllRequestsForSmallGroup grp clock (Some listDate) true 0
|
||||
{ requests = reqs |> List.ofSeq
|
||||
date = listDate
|
||||
listGroup = grp
|
||||
showHeader = true
|
||||
canEmail = ctx.Session.user |> Option.isSome
|
||||
recipients = []
|
||||
}
|
||||
let private generateRequestList ctx date = task {
|
||||
let grp = currentGroup ctx
|
||||
let clock = ctx.GetService<IClock> ()
|
||||
let listDate = match date with Some d -> d | None -> grp.localDateNow clock
|
||||
let! reqs = ctx.db.AllRequestsForSmallGroup grp clock (Some listDate) true 0
|
||||
return
|
||||
{ requests = reqs |> List.ofSeq
|
||||
date = listDate
|
||||
listGroup = grp
|
||||
showHeader = true
|
||||
canEmail = ctx.Session.user |> Option.isSome
|
||||
recipients = []
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a string into a date (optionally, of course)
|
||||
let private parseListDate (date : string option) =
|
||||
match date with
|
||||
| Some dt -> match DateTime.TryParse dt with true, d -> Some d | false, _ -> None
|
||||
| None -> None
|
||||
match date with
|
||||
| Some dt -> match DateTime.TryParse dt with true, d -> Some d | false, _ -> None
|
||||
| None -> None
|
||||
|
||||
|
||||
/// GET /prayer-request/[request-id]/edit
|
||||
let edit (reqId : PrayerRequestId) : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> fun next ctx -> task {
|
||||
let edit (reqId : PrayerRequestId) : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let grp = currentGroup ctx
|
||||
let now = grp.localDateNow (ctx.GetService<IClock> ())
|
||||
match reqId = Guid.Empty with
|
||||
| true ->
|
||||
if reqId = Guid.Empty then
|
||||
return!
|
||||
{ viewInfo ctx startTicks with script = [ "ckeditor/ckeditor" ]; helpLink = Some Help.editRequest }
|
||||
|> Views.PrayerRequest.edit EditRequest.empty (now.ToString "yyyy-MM-dd") ctx
|
||||
|> renderHtml next ctx
|
||||
| false ->
|
||||
{ viewInfo ctx startTicks with script = [ "ckeditor/ckeditor" ]; helpLink = Some Help.editRequest }
|
||||
|> Views.PrayerRequest.edit EditRequest.empty (now.ToString "yyyy-MM-dd") ctx
|
||||
|> renderHtml next ctx
|
||||
else
|
||||
match! findRequest ctx reqId with
|
||||
| Ok req ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
match req.isExpired now grp.preferences.daysToExpire with
|
||||
| true ->
|
||||
if req.isExpired now grp.preferences.daysToExpire then
|
||||
{ UserMessage.warning with
|
||||
text = htmlLocString s.["This request is expired."]
|
||||
text = htmlLocString s["This request is expired."]
|
||||
description =
|
||||
s.["To make it active again, update it as necessary, leave “{0}” and “{1}” unchecked, and it will return as an active request.",
|
||||
s.["Expire Immediately"], s.["Check to not update the date"]]
|
||||
|> (htmlLocString >> Some)
|
||||
s["To make it active again, update it as necessary, leave “{0}” and “{1}” unchecked, and it will return as an active request.",
|
||||
s["Expire Immediately"], s["Check to not update the date"]]
|
||||
|> (htmlLocString >> Some)
|
||||
}
|
||||
|> addUserMessage ctx
|
||||
| false -> ()
|
||||
return!
|
||||
{ viewInfo ctx startTicks with script = [ "ckeditor/ckeditor" ]; helpLink = Some Help.editRequest }
|
||||
|> Views.PrayerRequest.edit (EditRequest.fromRequest req) "" ctx
|
||||
|> renderHtml next ctx
|
||||
{ viewInfo ctx startTicks with script = [ "ckeditor/ckeditor" ]; helpLink = Some Help.editRequest }
|
||||
|> Views.PrayerRequest.edit (EditRequest.fromRequest req) "" ctx
|
||||
|> renderHtml next ctx
|
||||
| Error e -> return! e next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /prayer-requests/email/[date]
|
||||
let email date : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> fun next ctx -> task {
|
||||
let email date : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
let listDate = parseListDate (Some date)
|
||||
let grp = currentGroup ctx
|
||||
let list = generateRequestList ctx listDate
|
||||
let! list = generateRequestList ctx listDate
|
||||
let! recipients = ctx.db.AllMembersForSmallGroup grp.smallGroupId
|
||||
use! client = Email.getConnection ()
|
||||
do! Email.sendEmails client recipients
|
||||
grp s.["Prayer Requests for {0} - {1:MMMM d, yyyy}", grp.name, list.date].Value
|
||||
grp s["Prayer Requests for {0} - {1:MMMM d, yyyy}", grp.name, list.date].Value
|
||||
(list.asHtml s) (list.asText s) s
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.PrayerRequest.email { list with recipients = recipients }
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
viewInfo ctx startTicks
|
||||
|> Views.PrayerRequest.email { list with recipients = recipients }
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
|
||||
|
||||
/// POST /prayer-request/[request-id]/delete
|
||||
let delete reqId : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx -> task {
|
||||
let delete reqId : HttpHandler = requireAccess [ User ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! findRequest ctx reqId with
|
||||
| Ok req ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
ctx.db.PrayerRequests.Remove req |> ignore
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
addInfo ctx s.["The prayer request was deleted successfully"]
|
||||
addInfo ctx s["The prayer request was deleted successfully"]
|
||||
return! redirectTo false "/web/prayer-requests" next ctx
|
||||
| Error e -> return! e next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /prayer-request/[request-id]/expire
|
||||
let expire reqId : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> fun next ctx -> task {
|
||||
let expire reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
|
||||
match! findRequest ctx reqId with
|
||||
| Ok req ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
ctx.db.UpdateEntry { req with expiration = Forced }
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
addInfo ctx s.["Successfully {0} prayer request", s.["Expired"].Value.ToLower ()]
|
||||
addInfo ctx s["Successfully {0} prayer request", s["Expired"].Value.ToLower ()]
|
||||
return! redirectTo false "/web/prayer-requests" next ctx
|
||||
| Error e -> return! e next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /prayer-requests/[group-id]/list
|
||||
let list groupId : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> fun next ctx -> task {
|
||||
let list groupId : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
match! ctx.db.TryGroupById groupId with
|
||||
| Some grp when grp.preferences.isPublic ->
|
||||
let clock = ctx.GetService<IClock> ()
|
||||
let reqs = ctx.db.AllRequestsForSmallGroup grp clock None true 0
|
||||
let! reqs = ctx.db.AllRequestsForSmallGroup grp clock None true 0
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.PrayerRequest.list
|
||||
{ requests = List.ofSeq reqs
|
||||
date = grp.localDateNow clock
|
||||
listGroup = grp
|
||||
showHeader = true
|
||||
canEmail = ctx.Session.user |> Option.isSome
|
||||
recipients = []
|
||||
viewInfo ctx startTicks
|
||||
|> Views.PrayerRequest.list
|
||||
{ requests = reqs
|
||||
date = grp.localDateNow clock
|
||||
listGroup = grp
|
||||
showHeader = true
|
||||
canEmail = ctx.Session.user |> Option.isSome
|
||||
recipients = []
|
||||
}
|
||||
|> renderHtml next ctx
|
||||
|> renderHtml next ctx
|
||||
| Some _ ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
addError ctx s.["The request list for the group you tried to view is not public."]
|
||||
addError ctx s["The request list for the group you tried to view is not public."]
|
||||
return! redirectTo false "/web/unauthorized" next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /prayer-requests/lists
|
||||
let lists : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> fun next ctx -> task {
|
||||
let lists : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let! grps = ctx.db.PublicAndProtectedGroups ()
|
||||
let! groups = ctx.db.PublicAndProtectedGroups ()
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.PrayerRequest.lists grps
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
viewInfo ctx startTicks
|
||||
|> Views.PrayerRequest.lists groups
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
|
||||
|
||||
/// GET /prayer-requests[/inactive?]
|
||||
/// - OR -
|
||||
/// GET /prayer-requests?search=[search-query]
|
||||
let maintain onlyActive : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> fun next ctx ->
|
||||
let maintain onlyActive : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let grp = currentGroup ctx
|
||||
let pageNbr =
|
||||
match ctx.GetQueryStringValue "page" with
|
||||
| Ok pg -> match Int32.TryParse pg with true, p -> p | false, _ -> 1
|
||||
| Error _ -> 1
|
||||
let m =
|
||||
match ctx.GetQueryStringValue "search" with
|
||||
| Ok srch ->
|
||||
{ MaintainRequests.empty with
|
||||
requests = ctx.db.SearchRequestsForSmallGroup grp srch pageNbr
|
||||
searchTerm = Some srch
|
||||
pageNbr = Some pageNbr
|
||||
}
|
||||
| Error _ ->
|
||||
{ MaintainRequests.empty with
|
||||
requests = ctx.db.AllRequestsForSmallGroup grp (ctx.GetService<IClock> ()) None onlyActive pageNbr
|
||||
onlyActive = Some onlyActive
|
||||
pageNbr = match onlyActive with true -> None | false -> Some pageNbr
|
||||
}
|
||||
{ viewInfo ctx startTicks with helpLink = Some Help.maintainRequests }
|
||||
|> Views.PrayerRequest.maintain { m with smallGroup = grp } ctx
|
||||
|> renderHtml next ctx
|
||||
|
||||
match ctx.GetQueryStringValue "page" with
|
||||
| Ok pg -> match Int32.TryParse pg with true, p -> p | false, _ -> 1
|
||||
| Error _ -> 1
|
||||
let! m = backgroundTask {
|
||||
match ctx.GetQueryStringValue "search" with
|
||||
| Ok search ->
|
||||
let! reqs = ctx.db.SearchRequestsForSmallGroup grp search pageNbr
|
||||
return
|
||||
{ MaintainRequests.empty with
|
||||
requests = reqs
|
||||
searchTerm = Some search
|
||||
pageNbr = Some pageNbr
|
||||
}
|
||||
| Error _ ->
|
||||
let! reqs = ctx.db.AllRequestsForSmallGroup grp (ctx.GetService<IClock> ()) None onlyActive pageNbr
|
||||
return
|
||||
{ MaintainRequests.empty with
|
||||
requests = reqs
|
||||
onlyActive = Some onlyActive
|
||||
pageNbr = match onlyActive with true -> None | false -> Some pageNbr
|
||||
}
|
||||
}
|
||||
return!
|
||||
{ viewInfo ctx startTicks with helpLink = Some Help.maintainRequests }
|
||||
|> Views.PrayerRequest.maintain { m with smallGroup = grp } ctx
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
|
||||
/// GET /prayer-request/print/[date]
|
||||
let print date : HttpHandler =
|
||||
requireAccess [ User; Group ]
|
||||
>=> fun next ctx ->
|
||||
let list = parseListDate (Some date) |> generateRequestList ctx
|
||||
Views.PrayerRequest.print list appVersion
|
||||
|> renderHtml next ctx
|
||||
let print date : HttpHandler = requireAccess [ User; Group ] >=> fun next ctx -> task {
|
||||
let! list = generateRequestList ctx (parseListDate (Some date))
|
||||
return!
|
||||
Views.PrayerRequest.print list appVersion
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
|
||||
|
||||
|
||||
/// GET /prayer-request/[request-id]/restore
|
||||
let restore reqId : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> fun next ctx -> task {
|
||||
let restore reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
|
||||
match! findRequest ctx reqId with
|
||||
| Ok req ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
ctx.db.UpdateEntry { req with expiration = Automatic; updatedDate = DateTime.Now }
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
addInfo ctx s.["Successfully {0} prayer request", s.["Restored"].Value.ToLower ()]
|
||||
addInfo ctx s["Successfully {0} prayer request", s["Restored"].Value.ToLower ()]
|
||||
return! redirectTo false "/web/prayer-requests" next ctx
|
||||
| Error e -> return! e next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// POST /prayer-request/save
|
||||
let save : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx -> task {
|
||||
let save : HttpHandler = requireAccess [ User ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.TryBindFormAsync<EditRequest> () with
|
||||
| Ok m ->
|
||||
let! req =
|
||||
match m.isNew () with
|
||||
| true -> Task.FromResult (Some { PrayerRequest.empty with prayerRequestId = Guid.NewGuid () })
|
||||
| false -> ctx.db.TryRequestById m.requestId
|
||||
if m.isNew () then Task.FromResult (Some { PrayerRequest.empty with prayerRequestId = Guid.NewGuid () })
|
||||
else ctx.db.TryRequestById m.requestId
|
||||
match req with
|
||||
| Some pr ->
|
||||
let upd8 =
|
||||
{ pr with
|
||||
requestType = PrayerRequestType.fromCode m.requestType
|
||||
requestor = match m.requestor with Some x when x.Trim () = "" -> None | x -> x
|
||||
text = ckEditorToText m.text
|
||||
expiration = Expiration.fromCode m.expiration
|
||||
{ pr with
|
||||
requestType = PrayerRequestType.fromCode m.requestType
|
||||
requestor = match m.requestor with Some x when x.Trim () = "" -> None | x -> x
|
||||
text = ckEditorToText m.text
|
||||
expiration = Expiration.fromCode m.expiration
|
||||
}
|
||||
let grp = currentGroup ctx
|
||||
let now = grp.localDateNow (ctx.GetService<IClock> ())
|
||||
|
@ -262,23 +243,23 @@ let save : HttpHandler =
|
|||
}
|
||||
| false when Option.isSome m.skipDateUpdate && Option.get m.skipDateUpdate -> upd8
|
||||
| false -> { upd8 with updatedDate = now }
|
||||
|> (match m.isNew () with true -> ctx.db.AddEntry | false -> ctx.db.UpdateEntry)
|
||||
|> (if m.isNew () then ctx.db.AddEntry else ctx.db.UpdateEntry)
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
let act = match m.isNew () with true -> "Added" | false -> "Updated"
|
||||
addInfo ctx s.["Successfully {0} prayer request", s.[act].Value.ToLower ()]
|
||||
let act = if m.isNew () then "Added" else "Updated"
|
||||
addInfo ctx s["Successfully {0} prayer request", s.[act].Value.ToLower ()]
|
||||
return! redirectTo false "/web/prayer-requests" next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /prayer-request/view/[date?]
|
||||
let view date : HttpHandler =
|
||||
requireAccess [ User; Group ]
|
||||
>=> fun next ctx ->
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let list = parseListDate date |> generateRequestList ctx
|
||||
viewInfo ctx startTicks
|
||||
|> Views.PrayerRequest.view { list with showHeader = false }
|
||||
|> renderHtml next ctx
|
||||
let view date : HttpHandler = requireAccess [ User; Group ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let! list = generateRequestList ctx (parseListDate date)
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.PrayerRequest.view { list with showHeader = false }
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
|
|
|
@ -14,25 +14,20 @@ open System.Threading.Tasks
|
|||
|
||||
/// Set a small group "Remember Me" cookie
|
||||
let private setGroupCookie (ctx : HttpContext) pwHash =
|
||||
ctx.Response.Cookies.Append
|
||||
(Key.Cookie.group, { GroupId = (currentGroup ctx).smallGroupId; PasswordHash = pwHash }.toPayload (), autoRefresh)
|
||||
ctx.Response.Cookies.Append
|
||||
(Key.Cookie.group, { GroupId = (currentGroup ctx).smallGroupId; PasswordHash = pwHash }.toPayload (),
|
||||
autoRefresh)
|
||||
|
||||
|
||||
/// GET /small-group/announcement
|
||||
let announcement : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> fun next ctx ->
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
{ viewInfo ctx startTicks with helpLink = Some Help.sendAnnouncement; script = [ "ckeditor/ckeditor" ] }
|
||||
let announcement : HttpHandler = requireAccess [ User ] >=> fun next ctx ->
|
||||
{ viewInfo ctx DateTime.Now.Ticks with helpLink = Some Help.sendAnnouncement; script = [ "ckeditor/ckeditor" ] }
|
||||
|> Views.SmallGroup.announcement (currentUser ctx).isAdmin ctx
|
||||
|> renderHtml next ctx
|
||||
|
||||
|
||||
/// POST /small-group/[group-id]/delete
|
||||
let delete groupId : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx -> task {
|
||||
let delete groupId : HttpHandler = requireAccess [ Admin ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
match! ctx.db.TryGroupById groupId with
|
||||
| Some grp ->
|
||||
|
@ -41,103 +36,86 @@ let delete groupId : HttpHandler =
|
|||
ctx.db.RemoveEntry grp
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
addInfo ctx
|
||||
s.["The group {0} and its {1} prayer request(s) were deleted successfully; revoked access from {2} user(s)",
|
||||
grp.name, reqs, usrs]
|
||||
s["The group {0} and its {1} prayer request(s) were deleted successfully; revoked access from {2} user(s)",
|
||||
grp.name, reqs, usrs]
|
||||
return! redirectTo false "/web/small-groups" next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// POST /small-group/member/[member-id]/delete
|
||||
let deleteMember memberId : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx -> task {
|
||||
let deleteMember memberId : HttpHandler = requireAccess [ User ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
match! ctx.db.TryMemberById memberId with
|
||||
| Some mbr when mbr.smallGroupId = (currentGroup ctx).smallGroupId ->
|
||||
ctx.db.RemoveEntry mbr
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
addHtmlInfo ctx s.["The group member “{0}” was deleted successfully", mbr.memberName]
|
||||
addHtmlInfo ctx s["The group member “{0}” was deleted successfully", mbr.memberName]
|
||||
return! redirectTo false "/web/small-group/members" next ctx
|
||||
| Some _
|
||||
| None -> return! fourOhFour next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /small-group/[group-id]/edit
|
||||
let edit (groupId : SmallGroupId) : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> fun next ctx -> task {
|
||||
let edit (groupId : SmallGroupId) : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let! churches = ctx.db.AllChurches ()
|
||||
match groupId = Guid.Empty with
|
||||
| true ->
|
||||
if groupId = Guid.Empty then
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.SmallGroup.edit EditSmallGroup.empty churches ctx
|
||||
|> renderHtml next ctx
|
||||
| false ->
|
||||
viewInfo ctx startTicks
|
||||
|> Views.SmallGroup.edit EditSmallGroup.empty churches ctx
|
||||
|> renderHtml next ctx
|
||||
else
|
||||
match! ctx.db.TryGroupById groupId with
|
||||
| Some grp ->
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.SmallGroup.edit (EditSmallGroup.fromGroup grp) churches ctx
|
||||
|> renderHtml next ctx
|
||||
viewInfo ctx startTicks
|
||||
|> Views.SmallGroup.edit (EditSmallGroup.fromGroup grp) churches ctx
|
||||
|> renderHtml next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /small-group/member/[member-id]/edit
|
||||
let editMember (memberId : MemberId) : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> fun next ctx ->
|
||||
let editMember (memberId : MemberId) : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
let grp = currentGroup ctx
|
||||
let typs = ReferenceList.emailTypeList grp.preferences.defaultEmailType s
|
||||
task {
|
||||
match memberId = Guid.Empty with
|
||||
| true ->
|
||||
return!
|
||||
if memberId = Guid.Empty then
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.SmallGroup.editMember EditMember.empty typs ctx
|
||||
|> renderHtml next ctx
|
||||
| false ->
|
||||
match! ctx.db.TryMemberById memberId with
|
||||
| Some mbr when mbr.smallGroupId = grp.smallGroupId ->
|
||||
return!
|
||||
else
|
||||
match! ctx.db.TryMemberById memberId with
|
||||
| Some mbr when mbr.smallGroupId = grp.smallGroupId ->
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.SmallGroup.editMember (EditMember.fromMember mbr) typs ctx
|
||||
|> renderHtml next ctx
|
||||
| Some _
|
||||
| None -> return! fourOhFour next ctx
|
||||
}
|
||||
| Some _
|
||||
| None -> return! fourOhFour next ctx
|
||||
}
|
||||
|
||||
|
||||
/// GET /small-group/log-on/[group-id?]
|
||||
let logOn (groupId : SmallGroupId option) : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> fun next ctx ->
|
||||
let logOn (groupId : SmallGroupId option) : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
task {
|
||||
let! grps = ctx.db.ProtectedGroups ()
|
||||
let grpId = match groupId with Some gid -> flatGuid gid | None -> ""
|
||||
return!
|
||||
let! grps = ctx.db.ProtectedGroups ()
|
||||
let grpId = match groupId with Some gid -> flatGuid gid | None -> ""
|
||||
return!
|
||||
{ viewInfo ctx startTicks with helpLink = Some Help.logOn }
|
||||
|> Views.SmallGroup.logOn grps grpId ctx
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// POST /small-group/log-on/submit
|
||||
let logOnSubmit : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx ->
|
||||
task {
|
||||
match! ctx.TryBindFormAsync<GroupLogOn> () with
|
||||
| Ok m ->
|
||||
let logOnSubmit : HttpHandler = requireAccess [ AccessLevel.Public ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.TryBindFormAsync<GroupLogOn> () with
|
||||
| Ok m ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
match! ctx.db.TryGroupLogOnByPassword m.smallGroupId m.password with
|
||||
| Some grp ->
|
||||
|
@ -145,241 +123,206 @@ let logOnSubmit : HttpHandler =
|
|||
match m.rememberMe with
|
||||
| Some x when x -> (setGroupCookie ctx << sha1Hash) m.password
|
||||
| _ -> ()
|
||||
addInfo ctx s.["Log On Successful • Welcome to {0}", s.["PrayerTracker"]]
|
||||
addInfo ctx s["Log On Successful • Welcome to {0}", s["PrayerTracker"]]
|
||||
return! redirectTo false "/web/prayer-requests/view" next ctx
|
||||
| None ->
|
||||
addError ctx s.["Password incorrect - login unsuccessful"]
|
||||
addError ctx s["Password incorrect - login unsuccessful"]
|
||||
return! redirectTo false $"/web/small-group/log-on/{flatGuid m.smallGroupId}" next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
|
||||
|
||||
/// GET /small-groups
|
||||
let maintain : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> fun next ctx ->
|
||||
let maintain : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
task {
|
||||
let! grps = ctx.db.AllGroups ()
|
||||
return!
|
||||
let! grps = ctx.db.AllGroups ()
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.SmallGroup.maintain grps ctx
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /small-group/members
|
||||
let members : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> fun next ctx ->
|
||||
let members : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let grp = currentGroup ctx
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
task {
|
||||
let! mbrs = ctx.db.AllMembersForSmallGroup grp.smallGroupId
|
||||
let typs = ReferenceList.emailTypeList grp.preferences.defaultEmailType s |> Map.ofSeq
|
||||
return!
|
||||
let! mbrs = ctx.db.AllMembersForSmallGroup grp.smallGroupId
|
||||
let typs = ReferenceList.emailTypeList grp.preferences.defaultEmailType s |> Map.ofSeq
|
||||
return!
|
||||
{ viewInfo ctx startTicks with helpLink = Some Help.maintainGroupMembers }
|
||||
|> Views.SmallGroup.members mbrs typs ctx
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /small-group
|
||||
let overview : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> fun next ctx ->
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let clock = ctx.GetService<IClock> ()
|
||||
task {
|
||||
let reqs = ctx.db.AllRequestsForSmallGroup (currentGroup ctx) clock None true 0 |> List.ofSeq
|
||||
let! reqCount = ctx.db.CountRequestsBySmallGroup (currentGroup ctx).smallGroupId
|
||||
let! mbrCount = ctx.db.CountMembersForSmallGroup (currentGroup ctx).smallGroupId
|
||||
let m =
|
||||
let overview : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let clock = ctx.GetService<IClock> ()
|
||||
let! reqs = ctx.db.AllRequestsForSmallGroup (currentGroup ctx) clock None true 0
|
||||
let! reqCount = ctx.db.CountRequestsBySmallGroup (currentGroup ctx).smallGroupId
|
||||
let! mbrCount = ctx.db.CountMembersForSmallGroup (currentGroup ctx).smallGroupId
|
||||
let m =
|
||||
{ totalActiveReqs = List.length reqs
|
||||
allReqs = reqCount
|
||||
totalMbrs = mbrCount
|
||||
activeReqsByCat =
|
||||
(reqs
|
||||
|> Seq.ofList
|
||||
|> Seq.map (fun req -> req.requestType)
|
||||
|> Seq.distinct
|
||||
|> Seq.map (fun reqType -> reqType, reqs |> List.filter (fun r -> r.requestType = reqType) |> List.length)
|
||||
|> Map.ofSeq)
|
||||
(reqs
|
||||
|> Seq.ofList
|
||||
|> Seq.map (fun req -> req.requestType)
|
||||
|> Seq.distinct
|
||||
|> Seq.map (fun reqType -> reqType, reqs |> List.filter (fun r -> r.requestType = reqType) |> List.length)
|
||||
|> Map.ofSeq)
|
||||
}
|
||||
return!
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.SmallGroup.overview m
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /small-group/preferences
|
||||
let preferences : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> fun next ctx ->
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
task {
|
||||
let! tzs = ctx.db.AllTimeZones ()
|
||||
return!
|
||||
let preferences : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let! tzs = ctx.db.AllTimeZones ()
|
||||
return!
|
||||
{ viewInfo ctx startTicks with helpLink = Some Help.groupPreferences }
|
||||
|> Views.SmallGroup.preferences (EditPreferences.fromPreferences (currentGroup ctx).preferences) tzs ctx
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// POST /small-group/save
|
||||
let save : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
task {
|
||||
match! ctx.TryBindFormAsync<EditSmallGroup> () with
|
||||
| Ok m ->
|
||||
let! group =
|
||||
match m.isNew () with
|
||||
| true -> Task.FromResult<SmallGroup option>(Some { SmallGroup.empty with smallGroupId = Guid.NewGuid () })
|
||||
| false -> ctx.db.TryGroupById m.smallGroupId
|
||||
match group with
|
||||
| Some grp ->
|
||||
m.populateGroup grp
|
||||
|> function
|
||||
| grp when m.isNew () ->
|
||||
ctx.db.AddEntry grp
|
||||
ctx.db.AddEntry { grp.preferences with smallGroupId = grp.smallGroupId }
|
||||
| grp -> ctx.db.UpdateEntry grp
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
let act = s.[match m.isNew () with true -> "Added" | false -> "Updated"].Value.ToLower ()
|
||||
addHtmlInfo ctx s.["Successfully {0} group “{1}”", act, m.name]
|
||||
return! redirectTo false "/web/small-groups" next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
let save : HttpHandler = requireAccess [ Admin ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.TryBindFormAsync<EditSmallGroup> () with
|
||||
| Ok m ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
let! group =
|
||||
if m.isNew () then Task.FromResult (Some { SmallGroup.empty with smallGroupId = Guid.NewGuid () })
|
||||
else ctx.db.TryGroupById m.smallGroupId
|
||||
match group with
|
||||
| Some grp ->
|
||||
m.populateGroup grp
|
||||
|> function
|
||||
| grp when m.isNew () ->
|
||||
ctx.db.AddEntry grp
|
||||
ctx.db.AddEntry { grp.preferences with smallGroupId = grp.smallGroupId }
|
||||
| grp -> ctx.db.UpdateEntry grp
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
let act = s[if m.isNew () then "Added" else "Updated"].Value.ToLower ()
|
||||
addHtmlInfo ctx s["Successfully {0} group “{1}”", act, m.name]
|
||||
return! redirectTo false "/web/small-groups" next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
|
||||
|
||||
/// POST /small-group/member/save
|
||||
let saveMember : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx ->
|
||||
task {
|
||||
match! ctx.TryBindFormAsync<EditMember> () with
|
||||
| Ok m ->
|
||||
let grp = currentGroup ctx
|
||||
let! mMbr =
|
||||
match m.isNew () with
|
||||
| true ->
|
||||
Task.FromResult<Member option>
|
||||
(Some
|
||||
{ Member.empty with
|
||||
memberId = Guid.NewGuid ()
|
||||
smallGroupId = grp.smallGroupId
|
||||
})
|
||||
| false -> ctx.db.TryMemberById m.memberId
|
||||
match mMbr with
|
||||
| Some mbr when mbr.smallGroupId = grp.smallGroupId ->
|
||||
{ mbr with
|
||||
memberName = m.memberName
|
||||
email = m.emailAddress
|
||||
format = match m.emailType with "" | null -> None | _ -> Some m.emailType
|
||||
}
|
||||
|> (match m.isNew () with true -> ctx.db.AddEntry | false -> ctx.db.UpdateEntry)
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
let act = s.[match m.isNew () with true -> "Added" | false -> "Updated"].Value.ToLower ()
|
||||
addInfo ctx s.["Successfully {0} group member", act]
|
||||
return! redirectTo false "/web/small-group/members" next ctx
|
||||
| Some _
|
||||
| None -> return! fourOhFour next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
let saveMember : HttpHandler = requireAccess [ User ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.TryBindFormAsync<EditMember> () with
|
||||
| Ok m ->
|
||||
let grp = currentGroup ctx
|
||||
let! mMbr =
|
||||
if m.isNew () then
|
||||
Task.FromResult (Some { Member.empty with memberId = Guid.NewGuid (); smallGroupId = grp.smallGroupId })
|
||||
else ctx.db.TryMemberById m.memberId
|
||||
match mMbr with
|
||||
| Some mbr when mbr.smallGroupId = grp.smallGroupId ->
|
||||
{ mbr with
|
||||
memberName = m.memberName
|
||||
email = m.emailAddress
|
||||
format = match m.emailType with "" | null -> None | _ -> Some m.emailType
|
||||
}
|
||||
|> (if m.isNew () then ctx.db.AddEntry else ctx.db.UpdateEntry)
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
let act = s[if m.isNew () then "Added" else "Updated"].Value.ToLower ()
|
||||
addInfo ctx s["Successfully {0} group member", act]
|
||||
return! redirectTo false "/web/small-group/members" next ctx
|
||||
| Some _
|
||||
| None -> return! fourOhFour next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
|
||||
|
||||
/// POST /small-group/preferences/save
|
||||
let savePreferences : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx ->
|
||||
task {
|
||||
match! ctx.TryBindFormAsync<EditPreferences> () with
|
||||
| Ok m ->
|
||||
// Since the class is stored in the session, we'll use an intermediate instance to persist it; once that
|
||||
// works, we can repopulate the session instance. That way, if the update fails, the page should still show
|
||||
// the database values, not the then out-of-sync session ones.
|
||||
match! ctx.db.TryGroupById (currentGroup ctx).smallGroupId with
|
||||
| Some grp ->
|
||||
let prefs = m.populatePreferences grp.preferences
|
||||
ctx.db.UpdateEntry prefs
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
// Refresh session instance
|
||||
ctx.Session.smallGroup <- Some { grp with preferences = prefs }
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
addInfo ctx s.["Group preferences updated successfully"]
|
||||
return! redirectTo false "/web/small-group/preferences" next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
let savePreferences : HttpHandler = requireAccess [ User ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.TryBindFormAsync<EditPreferences> () with
|
||||
| Ok m ->
|
||||
// Since the class is stored in the session, we'll use an intermediate instance to persist it; once that works,
|
||||
// we can repopulate the session instance. That way, if the update fails, the page should still show the
|
||||
// database values, not the then out-of-sync session ones.
|
||||
match! ctx.db.TryGroupById (currentGroup ctx).smallGroupId with
|
||||
| Some grp ->
|
||||
let prefs = m.populatePreferences grp.preferences
|
||||
ctx.db.UpdateEntry prefs
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
// Refresh session instance
|
||||
ctx.Session.smallGroup <- Some { grp with preferences = prefs }
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
addInfo ctx s["Group preferences updated successfully"]
|
||||
return! redirectTo false "/web/small-group/preferences" next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
|
||||
|
||||
/// POST /small-group/announcement/send
|
||||
let sendAnnouncement : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx ->
|
||||
let sendAnnouncement : HttpHandler = requireAccess [ User ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
task {
|
||||
match! ctx.TryBindFormAsync<Announcement> () with
|
||||
| Ok m ->
|
||||
let grp = currentGroup ctx
|
||||
let usr = currentUser ctx
|
||||
let now = grp.localTimeNow (ctx.GetService<IClock> ())
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
// Reformat the text to use the class's font stylings
|
||||
let requestText = ckEditorToText m.text
|
||||
let htmlText =
|
||||
match! ctx.TryBindFormAsync<Announcement> () with
|
||||
| Ok m ->
|
||||
let grp = currentGroup ctx
|
||||
let usr = currentUser ctx
|
||||
let now = grp.localTimeNow (ctx.GetService<IClock> ())
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
// Reformat the text to use the class's font stylings
|
||||
let requestText = ckEditorToText m.text
|
||||
let htmlText =
|
||||
p [ _style $"font-family:{grp.preferences.listFonts};font-size:%d{grp.preferences.textFontSize}pt;" ]
|
||||
[ rawText requestText ]
|
||||
|> renderHtmlNode
|
||||
let plainText = (htmlToPlainText >> wordWrap 74) htmlText
|
||||
// Send the e-mails
|
||||
let! recipients =
|
||||
let plainText = (htmlToPlainText >> wordWrap 74) htmlText
|
||||
// Send the e-mails
|
||||
let! recipients =
|
||||
match m.sendToClass with
|
||||
| "N" when usr.isAdmin -> ctx.db.AllUsersAsMembers ()
|
||||
| _ -> ctx.db.AllMembersForSmallGroup grp.smallGroupId
|
||||
use! client = Email.getConnection ()
|
||||
do! Email.sendEmails client recipients grp
|
||||
s.["Announcement for {0} - {1:MMMM d, yyyy} {2}",
|
||||
grp.name, now.Date, (now.ToString "h:mm tt").ToLower ()].Value
|
||||
use! client = Email.getConnection ()
|
||||
do! Email.sendEmails client recipients grp
|
||||
s["Announcement for {0} - {1:MMMM d, yyyy} {2}", grp.name, now.Date,
|
||||
(now.ToString "h:mm tt").ToLower ()].Value
|
||||
htmlText plainText s
|
||||
// Add to the request list if desired
|
||||
match m.sendToClass, m.addToRequestList with
|
||||
| "N", _
|
||||
| _, None -> ()
|
||||
| _, Some x when not x -> ()
|
||||
| _, _ ->
|
||||
{ PrayerRequest.empty with
|
||||
prayerRequestId = Guid.NewGuid ()
|
||||
smallGroupId = grp.smallGroupId
|
||||
userId = usr.userId
|
||||
requestType = (Option.get >> PrayerRequestType.fromCode) m.requestType
|
||||
text = requestText
|
||||
enteredDate = now
|
||||
updatedDate = now
|
||||
}
|
||||
|> ctx.db.AddEntry
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
()
|
||||
// Tell 'em what they've won, Johnny!
|
||||
let toWhom =
|
||||
// Add to the request list if desired
|
||||
match m.sendToClass, m.addToRequestList with
|
||||
| "N", _
|
||||
| _, None -> ()
|
||||
| _, Some x when not x -> ()
|
||||
| _, _ ->
|
||||
{ PrayerRequest.empty with
|
||||
prayerRequestId = Guid.NewGuid ()
|
||||
smallGroupId = grp.smallGroupId
|
||||
userId = usr.userId
|
||||
requestType = (Option.get >> PrayerRequestType.fromCode) m.requestType
|
||||
text = requestText
|
||||
enteredDate = now
|
||||
updatedDate = now
|
||||
}
|
||||
|> ctx.db.AddEntry
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
()
|
||||
// Tell 'em what they've won, Johnny!
|
||||
let toWhom =
|
||||
match m.sendToClass with
|
||||
| "N" -> s.["{0} users", s.["PrayerTracker"]].Value
|
||||
| _ -> s.["Group Members"].Value.ToLower ()
|
||||
let andAdded = match m.addToRequestList with Some x when x -> "and added it to the request list" | _ -> ""
|
||||
addInfo ctx s.["Successfully sent announcement to all {0} {1}", toWhom, s.[andAdded]]
|
||||
return!
|
||||
| "N" -> s["{0} users", s["PrayerTracker"]].Value
|
||||
| _ -> s["Group Members"].Value.ToLower ()
|
||||
let andAdded = match m.addToRequestList with Some x when x -> "and added it to the request list" | _ -> ""
|
||||
addInfo ctx s["Successfully sent announcement to all {0} {1}", toWhom, s[andAdded]]
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.SmallGroup.announcementSent { m with text = htmlText }
|
||||
|> renderHtml next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
|
|
|
@ -1,5 +1,9 @@
|
|||
module PrayerTracker.Handlers.User
|
||||
|
||||
open System
|
||||
open System.Collections.Generic
|
||||
open System.Net
|
||||
open System.Threading.Tasks
|
||||
open Giraffe
|
||||
open Microsoft.AspNetCore.Html
|
||||
open Microsoft.AspNetCore.Http
|
||||
|
@ -8,275 +12,244 @@ open PrayerTracker.Cookies
|
|||
open PrayerTracker.Entities
|
||||
open PrayerTracker.ViewModels
|
||||
open PrayerTracker.Views.CommonFunctions
|
||||
open System
|
||||
open System.Collections.Generic
|
||||
open System.Net
|
||||
open System.Threading.Tasks
|
||||
|
||||
/// Set the user's "remember me" cookie
|
||||
let private setUserCookie (ctx : HttpContext) pwHash =
|
||||
ctx.Response.Cookies.Append (
|
||||
Key.Cookie.user,
|
||||
{ Id = (currentUser ctx).userId; GroupId = (currentGroup ctx).smallGroupId; PasswordHash = pwHash }.toPayload (),
|
||||
autoRefresh)
|
||||
ctx.Response.Cookies.Append (
|
||||
Key.Cookie.user,
|
||||
{ Id = (currentUser ctx).userId; GroupId = (currentGroup ctx).smallGroupId; PasswordHash = pwHash }.toPayload (),
|
||||
autoRefresh)
|
||||
|
||||
/// Retrieve a user from the database by password
|
||||
// If the hashes do not match, determine if it matches a previous scheme, and upgrade them if it does
|
||||
let private findUserByPassword m (db : AppDbContext) = task {
|
||||
match! db.TryUserByEmailAndGroup m.emailAddress m.smallGroupId with
|
||||
| Some u when Option.isSome u.salt ->
|
||||
// Already upgraded; match = success
|
||||
let pwHash = pbkdf2Hash (Option.get u.salt) m.password
|
||||
match u.passwordHash = pwHash with
|
||||
| true -> return Some { u with passwordHash = ""; salt = None; smallGroups = List<UserSmallGroup>() }, pwHash
|
||||
| _ -> return None, ""
|
||||
| Some u when u.passwordHash = sha1Hash m.password ->
|
||||
// Not upgraded, but password is good; upgrade 'em!
|
||||
// Upgrade 'em!
|
||||
let salt = Guid.NewGuid ()
|
||||
let pwHash = pbkdf2Hash salt m.password
|
||||
let upgraded = { u with salt = Some salt; passwordHash = pwHash }
|
||||
db.UpdateEntry upgraded
|
||||
let! _ = db.SaveChangesAsync ()
|
||||
return Some { u with passwordHash = ""; salt = None; smallGroups = List<UserSmallGroup>() }, pwHash
|
||||
| _ -> return None, ""
|
||||
}
|
||||
match! db.TryUserByEmailAndGroup m.emailAddress m.smallGroupId with
|
||||
| Some u when Option.isSome u.salt ->
|
||||
// Already upgraded; match = success
|
||||
let pwHash = pbkdf2Hash (Option.get u.salt) m.password
|
||||
if u.passwordHash = pwHash then
|
||||
return Some { u with passwordHash = ""; salt = None; smallGroups = List<UserSmallGroup>() }, pwHash
|
||||
else return None, ""
|
||||
| Some u when u.passwordHash = sha1Hash m.password ->
|
||||
// Not upgraded, but password is good; upgrade 'em!
|
||||
// Upgrade 'em!
|
||||
let salt = Guid.NewGuid ()
|
||||
let pwHash = pbkdf2Hash salt m.password
|
||||
let upgraded = { u with salt = Some salt; passwordHash = pwHash }
|
||||
db.UpdateEntry upgraded
|
||||
let! _ = db.SaveChangesAsync ()
|
||||
return Some { u with passwordHash = ""; salt = None; smallGroups = List<UserSmallGroup>() }, pwHash
|
||||
| _ -> return None, ""
|
||||
}
|
||||
|
||||
|
||||
/// POST /user/password/change
|
||||
let changePassword : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx -> task {
|
||||
let changePassword : HttpHandler = requireAccess [ User ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.TryBindFormAsync<ChangePassword> () with
|
||||
| Ok m ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
let curUsr = currentUser ctx
|
||||
let! dbUsr = ctx.db.TryUserById curUsr.userId
|
||||
let! user =
|
||||
match dbUsr with
|
||||
| Some usr ->
|
||||
// Check the old password against a possibly non-salted hash
|
||||
(match usr.salt with | Some salt -> pbkdf2Hash salt | _ -> sha1Hash) m.oldPassword
|
||||
|> ctx.db.TryUserLogOnByCookie curUsr.userId (currentGroup ctx).smallGroupId
|
||||
| _ -> Task.FromResult None
|
||||
match dbUsr with
|
||||
| Some usr ->
|
||||
// Check the old password against a possibly non-salted hash
|
||||
(match usr.salt with Some salt -> pbkdf2Hash salt | None -> sha1Hash) m.oldPassword
|
||||
|> ctx.db.TryUserLogOnByCookie curUsr.userId (currentGroup ctx).smallGroupId
|
||||
| _ -> Task.FromResult None
|
||||
match user with
|
||||
| Some _ when m.newPassword = m.newPasswordConfirm ->
|
||||
match dbUsr with
|
||||
| Some usr ->
|
||||
// Generate salt if it has not been already
|
||||
let salt = match usr.salt with Some s -> s | _ -> Guid.NewGuid ()
|
||||
// Generate new salt whenever the password is changed
|
||||
let salt = Guid.NewGuid ()
|
||||
ctx.db.UpdateEntry { usr with passwordHash = pbkdf2Hash salt m.newPassword; salt = Some salt }
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
// If the user is remembered, update the cookie with the new hash
|
||||
match ctx.Request.Cookies.Keys.Contains Key.Cookie.user with
|
||||
| true -> setUserCookie ctx usr.passwordHash
|
||||
| _ -> ()
|
||||
addInfo ctx s.["Your password was changed successfully"]
|
||||
| None -> addError ctx s.["Unable to change password"]
|
||||
if ctx.Request.Cookies.Keys.Contains Key.Cookie.user then setUserCookie ctx usr.passwordHash
|
||||
addInfo ctx s["Your password was changed successfully"]
|
||||
| None -> addError ctx s["Unable to change password"]
|
||||
return! redirectTo false "/web/" next ctx
|
||||
| Some _ ->
|
||||
addError ctx s.["The new passwords did not match - your password was NOT changed"]
|
||||
addError ctx s["The new passwords did not match - your password was NOT changed"]
|
||||
return! redirectTo false "/web/user/password" next ctx
|
||||
| None ->
|
||||
addError ctx s.["The old password was incorrect - your password was NOT changed"]
|
||||
addError ctx s["The old password was incorrect - your password was NOT changed"]
|
||||
return! redirectTo false "/web/user/password" next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// POST /user/[user-id]/delete
|
||||
let delete userId : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx -> task {
|
||||
let delete userId : HttpHandler = requireAccess [ Admin ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.db.TryUserById userId with
|
||||
| Some user ->
|
||||
ctx.db.RemoveEntry user
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
addInfo ctx s.["Successfully deleted user {0}", user.fullName]
|
||||
addInfo ctx s["Successfully deleted user {0}", user.fullName]
|
||||
return! redirectTo false "/web/users" next ctx
|
||||
| _ -> return! fourOhFour next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// POST /user/log-on
|
||||
let doLogOn : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx -> task {
|
||||
let doLogOn : HttpHandler = requireAccess [ AccessLevel.Public ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.TryBindFormAsync<UserLogOn> () with
|
||||
| Ok m ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
let! usr, pwHash = findUserByPassword m ctx.db
|
||||
let! grp = ctx.db.TryGroupById m.smallGroupId
|
||||
let nextUrl =
|
||||
match usr with
|
||||
| Some _ ->
|
||||
ctx.Session.user <- usr
|
||||
ctx.Session.smallGroup <- grp
|
||||
match m.rememberMe with Some x when x -> setUserCookie ctx pwHash | _ -> ()
|
||||
addHtmlInfo ctx s.["Log On Successful • Welcome to {0}", s.["PrayerTracker"]]
|
||||
match m.redirectUrl with
|
||||
| None -> "/web/small-group"
|
||||
| Some x when x = "" -> "/web/small-group"
|
||||
| Some x -> x
|
||||
| _ ->
|
||||
let grpName = match grp with Some g -> g.name | _ -> "N/A"
|
||||
{ UserMessage.error with
|
||||
text = htmlLocString s.["Invalid credentials - log on unsuccessful"]
|
||||
description =
|
||||
[ s.["This is likely due to one of the following reasons"].Value
|
||||
":<ul><li>"
|
||||
s.["The e-mail address “{0}” is invalid.", WebUtility.HtmlEncode m.emailAddress].Value
|
||||
"</li><li>"
|
||||
s.["The password entered does not match the password for the given e-mail address."].Value
|
||||
"</li><li>"
|
||||
s.["You are not authorized to administer the group “{0}”.", WebUtility.HtmlEncode grpName].Value
|
||||
"</li></ul>"
|
||||
]
|
||||
|> String.concat ""
|
||||
|> (HtmlString >> Some)
|
||||
match usr with
|
||||
| Some _ ->
|
||||
ctx.Session.user <- usr
|
||||
ctx.Session.smallGroup <- grp
|
||||
match m.rememberMe with Some x when x -> setUserCookie ctx pwHash | _ -> ()
|
||||
addHtmlInfo ctx s["Log On Successful • Welcome to {0}", s["PrayerTracker"]]
|
||||
match m.redirectUrl with
|
||||
| None -> "/web/small-group"
|
||||
| Some x when x = "" -> "/web/small-group"
|
||||
| Some x -> x
|
||||
| _ ->
|
||||
let grpName = match grp with Some g -> g.name | _ -> "N/A"
|
||||
{ UserMessage.error with
|
||||
text = htmlLocString s["Invalid credentials - log on unsuccessful"]
|
||||
description =
|
||||
[ s["This is likely due to one of the following reasons"].Value
|
||||
":<ul><li>"
|
||||
s["The e-mail address “{0}” is invalid.", WebUtility.HtmlEncode m.emailAddress].Value
|
||||
"</li><li>"
|
||||
s["The password entered does not match the password for the given e-mail address."].Value
|
||||
"</li><li>"
|
||||
s["You are not authorized to administer the group “{0}”.",
|
||||
WebUtility.HtmlEncode grpName].Value
|
||||
"</li></ul>"
|
||||
]
|
||||
|> String.concat ""
|
||||
|> (HtmlString >> Some)
|
||||
}
|
||||
|> addUserMessage ctx
|
||||
"/web/user/log-on"
|
||||
|> addUserMessage ctx
|
||||
"/web/user/log-on"
|
||||
return! redirectTo false nextUrl next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /user/[user-id]/edit
|
||||
let edit (userId : UserId) : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> fun next ctx -> task {
|
||||
let edit (userId : UserId) : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
match userId = Guid.Empty with
|
||||
| true ->
|
||||
if userId = Guid.Empty then
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.User.edit EditUser.empty ctx
|
||||
|> renderHtml next ctx
|
||||
| false ->
|
||||
viewInfo ctx startTicks
|
||||
|> Views.User.edit EditUser.empty ctx
|
||||
|> renderHtml next ctx
|
||||
else
|
||||
match! ctx.db.TryUserById userId with
|
||||
| Some user ->
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.User.edit (EditUser.fromUser user) ctx
|
||||
|> renderHtml next ctx
|
||||
viewInfo ctx startTicks
|
||||
|> Views.User.edit (EditUser.fromUser user) ctx
|
||||
|> renderHtml next ctx
|
||||
| _ -> return! fourOhFour next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /user/log-on
|
||||
let logOn : HttpHandler =
|
||||
requireAccess [ AccessLevel.Public ]
|
||||
>=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
let! groups = ctx.db.GroupList ()
|
||||
let url = Option.ofObj <| ctx.Session.GetString Key.Session.redirectUrl
|
||||
let logOn : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
let! groups = ctx.db.GroupList ()
|
||||
let url = Option.ofObj <| ctx.Session.GetString Key.Session.redirectUrl
|
||||
match url with
|
||||
| Some _ ->
|
||||
ctx.Session.Remove Key.Session.redirectUrl
|
||||
addWarning ctx s.["The page you requested requires authentication; please log on below."]
|
||||
addWarning ctx s["The page you requested requires authentication; please log on below."]
|
||||
| None -> ()
|
||||
return!
|
||||
{ viewInfo ctx startTicks with helpLink = Some Help.logOn }
|
||||
|> Views.User.logOn { UserLogOn.empty with redirectUrl = url } groups ctx
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
{ viewInfo ctx startTicks with helpLink = Some Help.logOn }
|
||||
|> Views.User.logOn { UserLogOn.empty with redirectUrl = url } groups ctx
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
|
||||
|
||||
/// GET /users
|
||||
let maintain : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> fun next ctx -> task {
|
||||
let maintain : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
let! users = ctx.db.AllUsers ()
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.User.maintain users ctx
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
viewInfo ctx startTicks
|
||||
|> Views.User.maintain users ctx
|
||||
|> renderHtml next ctx
|
||||
}
|
||||
|
||||
|
||||
/// GET /user/password
|
||||
let password : HttpHandler =
|
||||
requireAccess [ User ]
|
||||
>=> fun next ctx ->
|
||||
let password : HttpHandler = requireAccess [ User ] >=> fun next ctx ->
|
||||
{ viewInfo ctx DateTime.Now.Ticks with helpLink = Some Help.changePassword }
|
||||
|> Views.User.changePassword ctx
|
||||
|> renderHtml next ctx
|
||||
|
||||
|
||||
/// POST /user/save
|
||||
let save : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx -> task {
|
||||
let save : HttpHandler = requireAccess [ Admin ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.TryBindFormAsync<EditUser> () with
|
||||
| Ok m ->
|
||||
let! user =
|
||||
match m.isNew () with
|
||||
| true -> Task.FromResult (Some { User.empty with userId = Guid.NewGuid () })
|
||||
| false -> ctx.db.TryUserById m.userId
|
||||
if m.isNew () then Task.FromResult (Some { User.empty with userId = Guid.NewGuid () })
|
||||
else ctx.db.TryUserById m.userId
|
||||
let saltedUser =
|
||||
match user with
|
||||
| Some u ->
|
||||
match u.salt with
|
||||
| None when m.password <> "" ->
|
||||
// Generate salt so that a new password hash can be generated
|
||||
Some { u with salt = Some (Guid.NewGuid ()) }
|
||||
| _ ->
|
||||
// Leave the user with no salt, so prior hash can be validated/upgraded
|
||||
user
|
||||
| _ -> user
|
||||
match user with
|
||||
| Some u ->
|
||||
match u.salt with
|
||||
| None when m.password <> "" ->
|
||||
// Generate salt so that a new password hash can be generated
|
||||
Some { u with salt = Some (Guid.NewGuid ()) }
|
||||
| _ ->
|
||||
// Leave the user with no salt, so prior hash can be validated/upgraded
|
||||
user
|
||||
| _ -> user
|
||||
match saltedUser with
|
||||
| Some u ->
|
||||
let updatedUser = m.populateUser u (pbkdf2Hash (Option.get u.salt))
|
||||
updatedUser |> (match m.isNew () with true -> ctx.db.AddEntry | false -> ctx.db.UpdateEntry)
|
||||
updatedUser |> (if m.isNew () then ctx.db.AddEntry else ctx.db.UpdateEntry)
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
match m.isNew () with
|
||||
| true ->
|
||||
if m.isNew () then
|
||||
let h = CommonFunctions.htmlString
|
||||
{ UserMessage.info with
|
||||
text = h s.["Successfully {0} user", s.["Added"].Value.ToLower ()]
|
||||
text = h s["Successfully {0} user", s["Added"].Value.ToLower ()]
|
||||
description =
|
||||
h s.["Please select at least one group for which this user ({0}) is authorized",
|
||||
updatedUser.fullName]
|
||||
h s["Please select at least one group for which this user ({0}) is authorized",
|
||||
updatedUser.fullName]
|
||||
|> Some
|
||||
}
|
||||
}
|
||||
|> addUserMessage ctx
|
||||
return! redirectTo false $"/web/user/{flatGuid u.userId}/small-groups" next ctx
|
||||
| false ->
|
||||
addInfo ctx s.["Successfully {0} user", s.["Updated"].Value.ToLower ()]
|
||||
else
|
||||
addInfo ctx s["Successfully {0} user", s["Updated"].Value.ToLower ()]
|
||||
return! redirectTo false "/web/users" next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// POST /user/small-groups/save
|
||||
let saveGroups : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> validateCSRF
|
||||
>=> fun next ctx -> task {
|
||||
let saveGroups : HttpHandler = requireAccess [ Admin ] >=> validateCSRF >=> fun next ctx -> task {
|
||||
match! ctx.TryBindFormAsync<AssignGroups> () with
|
||||
| Ok m ->
|
||||
let s = Views.I18N.localizer.Force ()
|
||||
match Seq.length m.smallGroups with
|
||||
| 0 ->
|
||||
addError ctx s.["You must select at least one group to assign"]
|
||||
addError ctx s["You must select at least one group to assign"]
|
||||
return! redirectTo false $"/web/user/{flatGuid m.userId}/small-groups" next ctx
|
||||
| _ ->
|
||||
match! ctx.db.TryUserByIdWithGroups m.userId with
|
||||
| Some user ->
|
||||
let grps =
|
||||
m.smallGroups.Split ','
|
||||
|> Array.map Guid.Parse
|
||||
|> List.ofArray
|
||||
m.smallGroups.Split ','
|
||||
|> Array.map Guid.Parse
|
||||
|> List.ofArray
|
||||
user.smallGroups
|
||||
|> Seq.filter (fun x -> not (grps |> List.exists (fun y -> y = x.smallGroupId)))
|
||||
|> ctx.db.UserGroupXref.RemoveRange
|
||||
|
@ -287,25 +260,23 @@ let saveGroups : HttpHandler =
|
|||
|> List.ofSeq
|
||||
|> List.iter ctx.db.AddEntry
|
||||
let! _ = ctx.db.SaveChangesAsync ()
|
||||
addInfo ctx s.["Successfully updated group permissions for {0}", m.userName]
|
||||
addInfo ctx s["Successfully updated group permissions for {0}", m.userName]
|
||||
return! redirectTo false "/web/users" next ctx
|
||||
| _ -> return! fourOhFour next ctx
|
||||
| Error e -> return! bindError e next ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// GET /user/[user-id]/small-groups
|
||||
let smallGroups userId : HttpHandler =
|
||||
requireAccess [ Admin ]
|
||||
>=> fun next ctx -> task {
|
||||
let smallGroups userId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
|
||||
let startTicks = DateTime.Now.Ticks
|
||||
match! ctx.db.TryUserByIdWithGroups userId with
|
||||
| Some user ->
|
||||
let! grps = ctx.db.GroupList ()
|
||||
let curGroups = user.smallGroups |> Seq.map (fun g -> flatGuid g.smallGroupId) |> List.ofSeq
|
||||
return!
|
||||
viewInfo ctx startTicks
|
||||
|> Views.User.assignGroups (AssignGroups.fromUser user) grps curGroups ctx
|
||||
|> renderHtml next ctx
|
||||
viewInfo ctx startTicks
|
||||
|> Views.User.assignGroups (AssignGroups.fromUser user) grps curGroups ctx
|
||||
|> renderHtml next ctx
|
||||
| None -> return! fourOhFour next ctx
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user