Mercurial Hosting > chat
diff src/lib/User.luan @ 3:2c63b10781e1
add login
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Thu, 24 Oct 2024 21:43:44 -0600 |
parents | ee1f91e67509 |
children | 2da10ece826f |
line wrap: on
line diff
--- a/src/lib/User.luan Thu Oct 24 15:37:35 2024 -0600 +++ b/src/lib/User.luan Thu Oct 24 21:43:44 2024 -0600 @@ -1,13 +1,21 @@ local Luan = require "luan:Luan.luan" local error = Luan.error local ipairs = Luan.ipairs or error() +local range = Luan.range 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 String = require "luan:String.luan" +local sub_string = String.sub or error() +local Math = require "luan:Math.luan" +local random = Math.random or error() +local Table = require "luan:Table.luan" +local concat = Table.concat 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 run_in_transaction = Db.run_in_transaction or error() local Logging = require "luan:logging/Logging.luan" local logger = Logging.logger "User" @@ -61,9 +69,38 @@ 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) +local password_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +do + local t = {} + for i in range(1,#password_chars) do + t[#t+1] = sub_string(password_chars,i,i) + end + password_chars = t +end + +local function new_password() + local n = #password_chars + local t = {} + for _ in range(1,10) do + t[#t+1] = password_chars[random(n)] + end + return concat(t) +end + +function User.get_or_create_by_email(email) + return run_in_transaction( function() + local doc = Db.get_document("user_email:"..lucene_quote(email)) + if doc ~= nil then + return from_doc(doc) + else + local user = User.new{ + email = email + password = new_password() + } + user.save() + return user + end + end ) end function User.search(query,sort,rows) @@ -76,7 +113,7 @@ return users end -function User.current() +local function current() local user = get_local_only(User,"current") if user == nil then local id = Http.request.cookies.user @@ -85,7 +122,7 @@ user = "nil" else user = get_by_id(id) - if user == nil or user.registered == nil or user.password ~= password then + if user == nil or user.password ~= password then user = "nil" end end @@ -93,9 +130,10 @@ end return user ~= "nil" and user or nil end +User.current = current function User.current_required() - local user = User.current() + local user = current() user or Http.response.send_redirect "/login.html" return user end