comparison src/lib/User.luan @ 2:ee1f91e67509

add Db
author Franklin Schmidt <fschmidt@gmail.com>
date Thu, 24 Oct 2024 15:37:35 -0600
parents
children 2c63b10781e1
comparison
equal deleted inserted replaced
1:b116b6ef07bf 2:ee1f91e67509
1 local Luan = require "luan:Luan.luan"
2 local error = Luan.error
3 local ipairs = Luan.ipairs or error()
4 local to_string = Luan.to_string or error()
5 local get_local_only = Luan.get_local_only or error()
6 local set_local_only = Luan.set_local_only or error()
7 local Lucene = require "luan:lucene/Lucene.luan"
8 local lucene_quote = Lucene.quote or error()
9 local Http = require "luan:http/Http.luan"
10 local Db = require "site:/lib/Db.luan"
11 local Logging = require "luan:logging/Logging.luan"
12 local logger = Logging.logger "User"
13
14
15 local User = {}
16
17 local function from_doc(doc)
18 doc.type == "user" or error "wrong type"
19 return User.new {
20 id = doc.id
21 email = doc.user_email
22 password = doc.password
23 }
24 end
25
26 local function to_doc(user)
27 return {
28 type = "user"
29 id = user.id
30 user_email = user.email
31 password = user.password
32 }
33 end
34
35 function User.new(user)
36
37 function user.save()
38 local doc = to_doc(user)
39 Db.save(doc)
40 user.id = doc.id
41 end
42
43 function user.reload()
44 return User.get_by_id(user.id) or error(user.id)
45 end
46
47 function user.login()
48 local id = to_string(user.id)
49 Http.response.set_persistent_cookie("user",id)
50 Http.response.set_persistent_cookie("password",user.password)
51 Http.request.cookies.user = id
52 Http.request.cookies.password = user.password or error()
53 end
54
55 return user
56 end
57
58 local function get_by_id(id)
59 local doc = Db.get_document("id:"..id)
60 return doc and doc.type=="user" and from_doc(doc) or nil
61 end
62 User.get_by_id = get_by_id
63
64 function User.get_by_email(email)
65 local doc = Db.get_document("user_email:"..lucene_quote(email))
66 return doc and from_doc(doc)
67 end
68
69 function User.search(query,sort,rows)
70 rows = rows or 1000000
71 local users = {}
72 local docs = Db.search(query,1,rows,{sort=sort})
73 for _, doc in ipairs(docs) do
74 users[#users+1] = from_doc(doc)
75 end
76 return users
77 end
78
79 function User.current()
80 local user = get_local_only(User,"current")
81 if user == nil then
82 local id = Http.request.cookies.user
83 local password = Http.request.cookies.password
84 if id == nil or password == nil then
85 user = "nil"
86 else
87 user = get_by_id(id)
88 if user == nil or user.registered == nil or user.password ~= password then
89 user = "nil"
90 end
91 end
92 set_local_only(User,"current",user)
93 end
94 return user ~= "nil" and user or nil
95 end
96
97 function User.current_required()
98 local user = User.current()
99 user or Http.response.send_redirect "/login.html"
100 return user
101 end
102
103 return User