view src/set_name.html.luan @ 57:169ac5fdb320

add change email
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 28 Nov 2022 23:47:19 -0700
parents 7ce54f6d93f2
children
line wrap: on
line source

local Luan = require "luan:Luan.luan"
local error = Luan.error
local String = require "luan:String.luan"
local trim = String.trim or error()
local Io = require "luan:Io.luan"
local Http = require "luan:http/Http.luan"
local Shared = require "site:/lib/Shared.luan"
local head = Shared.head or error()
local header = Shared.header or error()
local footer = Shared.footer or error()
local Forum = require "site:/lib/Forum.luan"
local forum_title = Forum.title or error()
local User = require "site:/lib/User.luan"
local name_regex = User.name_regex
local Db = require "site:/lib/Db.luan"
local run_in_transaction = Db.run_in_transaction or error()


local function page(contents)
	Io.stdout = Http.response.text_writer()
%>
<!doctype html>
<html>
	<head>
<%		head() %>
		<title><%=forum_title%> - Set Name</title>
	</head>
	<body>
<%		header() %>
		<div content>
			<h1>Set Name</h1>
<%
			contents()
%>
		</div>
<%		footer() %>
	</body>
</html>
<%
end

return function()
	local email = Http.request.parameters.email
	local password = Http.request.parameters.password
	local name = Http.request.parameters.name
	local user = User.get_by_email(email)
	user or error "email not found"
	user.password == password or error "wrong password"
	local error_message = nil
	if Http.request.method == "POST" then
		name = trim(name)
		name_regex.matches(name) or error "invalid name"
		run_in_transaction( function()
			user = user.reload()
			if user.name ~= name and User.get_by_name(name) ~= nil then
				error_message = "Name already in use"
			else
				user.name = name
				user.save()
			end
		end )
		if error_message == nil then
			user.login()
			page(function()
%>
				<p>You are now logged in.</p>
<%
			end)
			return
		end
	end
	page(function()
		if error_message ~= nil then %>
			<p error>Error: <%= error_message %></p>
<%		end %>
			<form action="set_name.html" method=post>
				<input type="hidden" name="email" value="<%= user.email %>" >
				<input type="hidden" name="password" value="<%= user.password %>" >
				<label>User name for <%= user.email %></label>
				<input type="text" name="name" value="<%= name or "" %>" autofocus required pattern="[a-zA-Z0-9_-]+">
				<input type="submit">
			</form>
<%
	end)
end