diff 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
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/lib/User.luan	Thu Oct 24 15:37:35 2024 -0600
@@ -0,0 +1,103 @@
+local Luan = require "luan:Luan.luan"
+local error = Luan.error
+local ipairs = Luan.ipairs or error()
+local to_string = Luan.to_string or error()
+local get_local_only = Luan.get_local_only or error()
+local set_local_only = Luan.set_local_only or error()
+local Lucene = require "luan:lucene/Lucene.luan"
+local lucene_quote = Lucene.quote or error()
+local Http = require "luan:http/Http.luan"
+local Db = require "site:/lib/Db.luan"
+local Logging = require "luan:logging/Logging.luan"
+local logger = Logging.logger "User"
+
+
+local User = {}
+
+local function from_doc(doc)
+	doc.type == "user" or error "wrong type"
+	return User.new {
+		id = doc.id
+		email = doc.user_email
+		password = doc.password
+	}
+end
+
+local function to_doc(user)
+	return {
+		type = "user"
+		id = user.id
+		user_email = user.email
+		password = user.password
+	}
+end
+
+function User.new(user)
+
+	function user.save()
+		local doc = to_doc(user)
+		Db.save(doc)
+		user.id = doc.id
+	end
+
+	function user.reload()
+		return User.get_by_id(user.id) or error(user.id)
+	end
+
+	function user.login()
+		local id = to_string(user.id)
+		Http.response.set_persistent_cookie("user",id)
+		Http.response.set_persistent_cookie("password",user.password)
+		Http.request.cookies.user = id
+		Http.request.cookies.password = user.password or error()
+	end
+
+	return user
+end
+
+local function get_by_id(id)
+	local doc = Db.get_document("id:"..id)
+	return doc and doc.type=="user" and from_doc(doc) or nil
+end
+User.get_by_id = get_by_id
+
+function User.get_by_email(email)
+	local doc = Db.get_document("user_email:"..lucene_quote(email))
+	return doc and from_doc(doc)
+end
+
+function User.search(query,sort,rows)
+	rows = rows or 1000000
+	local users = {}
+	local docs = Db.search(query,1,rows,{sort=sort})
+	for _, doc in ipairs(docs) do
+		users[#users+1] = from_doc(doc)
+	end
+	return users
+end
+
+function User.current()
+	local user = get_local_only(User,"current")
+	if user == nil then
+		local id = Http.request.cookies.user
+		local password = Http.request.cookies.password
+		if id == nil or password == nil then
+			user = "nil"
+		else
+			user = get_by_id(id)
+			if user == nil or user.registered == nil or user.password ~= password then
+				user = "nil"
+			end
+		end
+		set_local_only(User,"current",user)
+	end
+	return user ~= "nil" and user or nil
+end
+
+function User.current_required()
+	local user = User.current()
+	user or Http.response.send_redirect "/login.html"
+	return user
+end
+
+return User