view src/change_name.html.luan @ 61:389e5d8e5f8a default tip

minor
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 06 Dec 2022 13:37:25 -0700
parents 169ac5fdb320
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%> - Change Name</title>
	</head>
	<body>
<%		header() %>
		<div content>
			<h1>Change Name</h1>
<%
			contents()
%>
		</div>
<%		footer() %>
	</body>
</html>
<%
end

return function()
	local user = User.current_required()
	if user==nil then return end
	local name = user.name or error()
	local error_message = nil
	if Http.request.method == "POST" then
		name = Http.request.parameters.name or error()
		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
			page(function()
%>
				<p>Your name has been changed.</p>
<%
			end)
			return
		end
	end
	page(function()
		if error_message ~= nil then %>
			<p error>Error: <%= error_message %></p>
<%		end %>
			<form method=post>
				<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