diff src/set_name.html.luan @ 54:260abd8f8565

login and register
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 27 Nov 2022 23:46:27 -0700
parents src/login.html.luan@a1db5223ced1
children 7ce54f6d93f2
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/set_name.html.luan	Sun Nov 27 23:46:27 2022 -0700
@@ -0,0 +1,87 @@
+local Luan = require "luan:Luan.luan"
+local error = Luan.error
+local String = require "luan:String.luan"
+local trim = String.trim or error()
+local regex = String.regex 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 Db = require "site:/lib/Db.luan"
+local run_in_transaction = Db.run_in_transaction or error()
+
+
+local name_regex = regex "^[a-zA-Z0-9_-]+$"
+
+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" value="Set">
+			</form>
+<%
+	end)
+end