1
0
mirror of https://github.com/Jermolene/TiddlyWiki5 synced 2025-01-08 08:20:27 +00:00

#8757 add exception handling to creating new users & roles functions (#8763)

This commit is contained in:
webplusai 2024-11-20 09:10:16 +01:00 committed by GitHub
parent 4dc2486d4b
commit 9f48e75945
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 198 additions and 50 deletions

View File

@ -18,6 +18,10 @@ exports.path = /^\/admin\/users$/;
exports.handler = function(request,response,state) {
var userList = state.server.sqlTiddlerDatabase.listUsers();
if (request.url.includes("*")) {
$tw.mws.store.adminWiki.deleteTiddler("$:/temp/mws/post-user/error");
$tw.mws.store.adminWiki.deleteTiddler("$:/temp/mws/post-user/success");
}
// Ensure userList is an array
if (!Array.isArray(userList)) {

View File

@ -17,6 +17,10 @@ exports.method = "GET";
exports.path = /^\/admin\/roles\/?$/;
exports.handler = function(request, response, state) {
if (request.url.includes("*")) {
$tw.mws.store.adminWiki.deleteTiddler("$:/temp/mws/post-role/error");
$tw.mws.store.adminWiki.deleteTiddler("$:/temp/mws/post-role/success");
}
var roles = state.server.sqlTiddlerDatabase.listRoles();
var editRoleId = request.url.includes("?") ? request.url.split("?")[1]?.split("=")[1] : null;
var editRole = editRoleId ? roles.find(role => role.role_id === $tw.utils.parseInt(editRoleId, 10)) : null;

View File

@ -25,12 +25,58 @@ exports.handler = function (request, response, state) {
var role_name = state.data.role_name;
var role_description = state.data.role_description;
// Add your authentication check here if needed
if(!state.authenticatedUser || !state.authenticatedUser.isAdmin) {
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-role/error",
text: "Unauthorized access. Admin privileges required."
}));
response.writeHead(302, { "Location": "/login" });
response.end();
return;
}
sqlTiddlerDatabase.createRole(role_name, role_description);
if(!role_name || !role_description) {
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-role/error",
text: "Role name and description are required"
}));
response.writeHead(302, { "Location": "/admin/roles" });
response.end();
return;
}
response.writeHead(302, { "Location": "/admin/roles" });
response.end();
try {
// Check if role already exists
var existingRole = sqlTiddlerDatabase.getRole(role_name);
if(existingRole) {
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-role/error",
text: "Role already exists"
}));
response.writeHead(302, { "Location": "/admin/roles" });
response.end();
return;
}
sqlTiddlerDatabase.createRole(role_name, role_description);
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-role/success",
text: "Role created successfully"
}));
response.writeHead(302, { "Location": "/admin/roles" });
response.end();
} catch(error) {
console.error("Error creating role:", error);
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-role/error",
text: "Error creating role: " + error.message
}));
response.writeHead(302, { "Location": "/admin/roles" });
response.end();
return;
}
};
}());

View File

@ -30,62 +30,103 @@ exports.handler = function(request, response, state) {
var confirmPassword = state.data.confirmPassword;
if(!state.authenticatedUser && !state.firstGuestUser) {
response.writeHead(401, "Unauthorized", { "Content-Type": "text/plain" });
response.end("Unauthorized");
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-user/error",
text: "Unauthorized access"
}));
response.writeHead(302, { "Location": "/login" });
response.end();
return;
}
if(!username || !email || !password || !confirmPassword) {
response.writeHead(400, {"Content-Type": "application/json"});
response.end(JSON.stringify({error: "All fields are required"}));
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-user/error",
text: "All fields are required"
}));
response.writeHead(302, { "Location": "/admin/users" });
response.end();
return;
}
if(password !== confirmPassword) {
response.writeHead(400, {"Content-Type": "application/json"});
response.end(JSON.stringify({error: "Passwords do not match"}));
return;
}
// Check if user already exists
var existingUser = sqlTiddlerDatabase.getUser(username);
if(existingUser) {
response.writeHead(400, {"Content-Type": "application/json"});
response.end(JSON.stringify({error: "Username already exists"}));
return;
}
var hasUsers = sqlTiddlerDatabase.listUsers().length > 0;
var hashedPassword = crypto.createHash("sha256").update(password).digest("hex");
// Create new user
var userId = sqlTiddlerDatabase.createUser(username, email, hashedPassword);
if(!hasUsers) {
// If this is the first guest user, assign admin privileges
sqlTiddlerDatabase.setUserAdmin(userId, true);
// Create a session for the new admin user
var auth = require('$:/plugins/tiddlywiki/multiwikiserver/auth/authentication.js').Authenticator;
var authenticator = auth(sqlTiddlerDatabase);
var sessionId = authenticator.createSession(userId);
// Set the session cookie and redirect
response.setHeader('Set-Cookie', `session=${sessionId}; HttpOnly; Path=/`);
response.writeHead(302, {
'Location': '/'
});
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-user/error",
text: "Passwords do not match"
}));
response.writeHead(302, { "Location": "/admin/users" });
response.end();
return;
} else {
// assign role to user
const roles = sqlTiddlerDatabase.listRoles();
const roleId = roles.find(role => role.role_name.toUpperCase() !== "ADMIN")?.role_id;
if (roleId) {
sqlTiddlerDatabase.addRoleToUser(userId, roleId);
}
try {
// Check if user already exists
var existingUser = sqlTiddlerDatabase.getUser(username);
if(existingUser) {
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-user/error",
text: "Username already exists"
}));
response.writeHead(302, { "Location": "/admin/users" });
response.end();
return;
}
response.writeHead(302, {"Location": "/admin/users/"+userId});
var hasUsers = sqlTiddlerDatabase.listUsers().length > 0;
var hashedPassword = crypto.createHash("sha256").update(password).digest("hex");
// Create new user
var userId = sqlTiddlerDatabase.createUser(username, email, hashedPassword);
if(!hasUsers) {
try {
// If this is the first guest user, assign admin privileges
sqlTiddlerDatabase.setUserAdmin(userId, true);
// Create a session for the new admin user
var auth = require('$:/plugins/tiddlywiki/multiwikiserver/auth/authentication.js').Authenticator;
var authenticator = auth(sqlTiddlerDatabase);
var sessionId = authenticator.createSession(userId);
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-user/success",
text: "Admin user created successfully"
}));
response.setHeader('Set-Cookie', `session=${sessionId}; HttpOnly; Path=/`);
response.writeHead(302, {'Location': '/'});
response.end();
return;
} catch (adminError) {
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-user/error",
text: "Error creating admin user"
}));
response.writeHead(302, { "Location": "/admin/users" });
response.end();
return;
}
} else {
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-user/success",
text: "User created successfully"
}));
// assign role to user
const roles = sqlTiddlerDatabase.listRoles();
const roleId = roles.find(role => role.role_name.toUpperCase() !== "ADMIN")?.role_id;
if (roleId) {
sqlTiddlerDatabase.addRoleToUser(userId, roleId);
}
response.writeHead(302, {"Location": "/admin/users/"+userId});
response.end();
}
} catch (error) {
$tw.mws.store.adminWiki.addTiddler(new $tw.Tiddler({
title: "$:/temp/mws/post-user/error",
text: "Error creating user: " + error.message
}));
response.writeHead(302, { "Location": "/admin/users" });
response.end();
return;
}
};

View File

@ -19,6 +19,18 @@ title: $:/plugins/tiddlywiki/multiwikiserver/templates/add-user-form
<input type="password" id="confirmPassword" name="confirmPassword" class="form-input" required>
</div>
<$list filter="[[$:/temp/mws/post-user/error]!is[missing]]" variable="errorTiddler">
<div class="tc-error-message">
<$text text={{{[<errorTiddler>get[text]]}}}/>
</div>
</$list>
<$list filter="[[$:/temp/mws/post-user/success]!is[missing]]" variable="successTiddler">
<div class="tc-success-message">
<$text text={{{[<successTiddler>get[text]]}}}/>
</div>
</$list>
<div class="form-actions">
<$button class="btn btn-primary">
Add User
@ -90,4 +102,16 @@ title: $:/plugins/tiddlywiki/multiwikiserver/templates/add-user-form
.btn-primary:hover {
background-color: #0056b3;
}
.tc-error-message {
color: red;
font-weight: bold;
margin-top: 1rem;
}
.tc-success-message {
color: green;
font-weight: bold;
margin-top: 1rem;
}
</style>

View File

@ -80,6 +80,17 @@ title: $:/plugins/tiddlywiki/multiwikiserver/templates/manage-roles
<form method="POST" action="/admin/post-role" class="add-role-form">
<input name="role_name" type="text" placeholder="Role Name" required/>
<input name="role_description" type="text" placeholder="Role Description" required/>
<$list filter="[[$:/temp/mws/post-role/error]!is[missing]]" variable="errorTiddler">
<div class="tc-error-message">
<$text text={{{[<errorTiddler>get[text]]}}}/>
</div>
</$list>
<$list filter="[[$:/temp/mws/post-role/success]!is[missing]]" variable="successTiddler">
<div class="tc-success-message">
<$text text={{{[<successTiddler>get[text]]}}}/>
</div>
</$list>
<button type="submit" class="tc-btn-invisible btn-add">Add Role</button>
</form>
</$list>
@ -179,6 +190,18 @@ title: $:/plugins/tiddlywiki/multiwikiserver/templates/manage-roles
margin-bottom: 1rem;
color: #333;
}
.tc-error-message {
color: red;
font-weight: bold;
margin-top: 1rem;
}
.tc-success-message {
color: green;
font-weight: bold;
margin-top: 1rem;
}
@media (max-width: 768px) {
.roles-container {
flex-direction: column;

View File

@ -14,8 +14,14 @@ title: $:/plugins/tiddlywiki/multiwikiserver/templates/mws-header
<div class="mws-admin-dropdown">
<button class="mws-admin-dropbtn">⚙️</button>
<div class="mws-admin-dropdown-content">
<a href="/admin/users">Manage Users</a>
<a href="/admin/roles">Manage Roles</a>
<form action="/admin/users" method="get" class="mws-admin-form">
<input type="hidden" name="q" value="*" />
<input type="submit" value="Manage Users" class="mws-admin-form-button"/>
</form>
<form action="/admin/roles" method="get" class="mws-admin-form">
<input type="hidden" name="q" value="*" />
<input type="submit" value="Manage Roles" class="mws-admin-form-button"/>
</form>
<form action="/admin/anon" method="post" class="mws-admin-form">
<input type="submit" value="Reconfigure Anonymous Access" class="mws-admin-form-button"/>
</form>