Browse Source

bugfix: fixed everlasting location.reload on wrong credentials

master
parent
commit
210a8fe573
  1. 13
      pages/base.html
  2. 100
      pages/index.html
  3. 59
      scripts/api.js
  4. 1
      src/db/db.go
  5. 24
      src/db/todo.go
  6. 6
      src/db/user.go
  7. 1
      src/server/api.go

13
pages/base.html

@ -44,12 +44,13 @@
</html> </html>
<script src="/scripts/auth.js"></script> <script src="/scripts/auth.js"></script>
<script src="/scripts/api.js"></script>
<script> <script>
document.addEventListener('DOMContentLoaded', async function() { document.addEventListener('DOMContentLoaded', async function() {
let username = getUsername(); let username = getUsername();
let password = getUserPassword(); let password = getUserPassword();
if (username == null | username == "" | password == null | password == "") { if (username == null | username == "" | password == null | password == "") {
if (window.location.pathname != "/about" && window.location.pathname != "/login" && window.location.pathname != "/register") { if (window.location.pathname != "/about" && window.location.pathname != "/login" && window.location.pathname != "/register") {
window.location.replace("/about"); window.location.replace("/about");
} }
@ -57,14 +58,7 @@
} }
// Check if auth info is indeed valid // Check if auth info is indeed valid
let response = await fetch("/api/user", { let response = await get_user(username, password);
method: "GET",
headers: {
"EncryptedBase64": "false",
"Auth": username + "<-->" + password
},
});
if (response.ok) { if (response.ok) {
let barAuth = document.getElementById("bar-auth"); let barAuth = document.getElementById("bar-auth");
barAuth.innerHTML = "<b>" + username + "</b>" + " | "; barAuth.innerHTML = "<b>" + username + "</b>" + " | ";
@ -75,6 +69,7 @@
window.location.replace("/about"); window.location.replace("/about");
}); });
} else { } else {
forgetAuthInfo();
window.location.replace("/about"); window.location.replace("/about");
} }
}, false) }, false)

100
pages/index.html

@ -154,31 +154,44 @@
</form> </form>
</div> --> </div> -->
<form> <form action="javascript:void(0);">
<div class="mb-3"> <div class="mb-3">
<label for="new-todo-text" class="form-label">TODO</label> <label for="new-todo-text" class="form-label">TODO</label>
<input type="text" class="form-control" id="new-todo-text"> <input type="text" class="form-control" id="new-todo-text">
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="new-todo-due" class="form-label">Due</label> <label for="new-todo-due" class="form-label">Due</label>
<input type="datetime-local" class="form-control" id="new-todo-due"> <input type="datetime-local" class="form-control" id="new-todo-due">
</div> </div>
<button id="new-todo-submit" class="btn btn-primary">Add</button> <button id="new-todo-submit" class="btn btn-primary">Add</button>
</form> </form>
<div id="todos">
</div> <div id="groups">
<div id="groups"> </div>
<div id="todos">
</div>
</div>
<script> <script>
document.addEventListener('DOMContentLoaded', async function() { document.addEventListener('DOMContentLoaded', async function() {
let username = getUsername();
let password = getUserPassword();
// Make "Add" button to send
document.getElementById("new-todo-submit").addEventListener("click", async (event) => { document.getElementById("new-todo-submit").addEventListener("click", async (event) => {
let newTodoTextInput = document.getElementById("new-todo-text"); let newTodoTextInput = document.getElementById("new-todo-text");
let newTodoText = newTodoTextInput.value; let newTodoText = newTodoTextInput.value;
if (newTodoText.length < 1) {
newTodoTextInput.setCustomValidity("At least one character is needed!");
return;
} else {
newTodoTextInput.setCustomValidity("");
}
newTodoTextInput.value = ""; newTodoTextInput.value = "";
let newTodoDueInput = document.getElementById("new-todo-due"); let newTodoDueInput = document.getElementById("new-todo-due");
@ -186,57 +199,34 @@
newTodoDueInput.value = 0; newTodoDueInput.value = 0;
// Make a request // Make a request
let response = await fetch("/api/group", { let response = await post_new_todo(username, password, {text: newTodoText});
method: "GET", if (response.ok) {
headers: { location.reload();
"EncryptedBase64": "false", }
"Auth": username + "<-->" + password
},
});
});
let groups = [];
let todos = [];
let username = getUsername();
let password = getUserPassword();
// TODO groups
let response = await fetch("/api/group", {
method: "GET",
headers: {
"EncryptedBase64": "false",
"Auth": username + "<-->" + password
},
}); });
let groupsJson = await response.json();
if (response.ok) {
let groupsDiv = document.getElementById("groups");
groupsJson.forEach((item) => {
groupsDiv.innerHTML += "<p>" + item.Name + "</p>";
});
}
// TODOs
response = await fetch("/api/todo", {
method: "GET",
headers: {
"EncryptedBase64": "false",
"Auth": username + "<-->" + password
},
});
// Fetch and display TODOs
response = await get_todos(username, password);
let todosJson = await response.json(); let todosJson = await response.json();
if (response.ok) { if (response.ok && todosJson != null) {
let todosDiv = document.getElementById("todos"); let todosDiv = document.getElementById("todos");
todosJson.forEach((item) => { todosJson.forEach((item) => {
todosDiv.innerHTML += "<p>" + item.Text + "</p>"; console.log(item);
let todo_complete_btn_id = "btn-complete-" + String(item.id);
todosDiv.innerHTML += "<p>" + item.text +
"<small><button class='btn btn-success' id='" + todo_complete_btn_id + "'>" +
"Done</button></small></p>";
document.getElementById(todo_complete_btn_id).addEventListener("click", async (event) => {
response = await delete_todo(username, password, item);
if (response.ok) {
location.reload();
}
});
}); });
// for (let i = 0; i < todosJson.length; i++) {
// console.log(todosJson[i]);
// todosDiv.innerHTML += "<p>" + todosJson[i].text + "</p>";
// }
} }
}, false) }, false)
</script> </script>

59
scripts/api.js

@ -0,0 +1,59 @@
/*
Copyright (c) 2023 Kasyanov Nikolay Alexeyevich (Unbewohnte)
*/
async function post_new_todo(username, password, new_todo) {
return fetch("/api/todo", {
method: "POST",
headers: {
"EncryptedBase64": "false",
"Auth": username + "<-->" + password,
"Content-Type": "application/json",
},
body: JSON.stringify(new_todo),
});
}
async function get_todos(username, password) {
return fetch("/api/todo", {
method: "GET",
headers: {
"EncryptedBase64": "false",
"Auth": username + "<-->" + password
},
});
}
async function get_todo_groups(username, password) {
return fetch("/api/group", {
method: "GET",
headers: {
"EncryptedBase64": "false",
"Auth": username + "<-->" + password
},
});
}
async function delete_todo(username, password, todo) {
return fetch("/api/todo", {
method: "DELETE",
headers: {
"EnctyptedBase64": "false",
"Auth": username + "<-->" + password,
body: JSON.stringify(todo),
},
});
}
async function get_user(username, password) {
return fetch("/api/user", {
method: "GET",
headers: {
"EncryptedBase64": "false",
"Auth": username + "<-->" + password
},
});
}

1
src/db/db.go

@ -40,6 +40,7 @@ func setUpTables(db *DB) error {
id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
group_id INTEGER NOT NULL, group_id INTEGER NOT NULL,
text TEXT NOT NULL, text TEXT NOT NULL,
time_created_unix INTEGER,
due_unix INTEGER, due_unix INTEGER,
owner_username TEXT NOT NULL, owner_username TEXT NOT NULL,
FOREIGN KEY(group_id) REFERENCES todo_groups(id), FOREIGN KEY(group_id) REFERENCES todo_groups(id),

24
src/db/todo.go

@ -4,20 +4,20 @@ import "database/sql"
// Todo group structure // Todo group structure
type TodoGroup struct { type TodoGroup struct {
ID uint64 `json: "id"` ID uint64 `json:"id"`
Name string `json: "name"` Name string `json:"name"`
TimeCreatedUnix uint64 `json: "timeCreatedUnix` TimeCreatedUnix uint64 `json:"timeCreatedUnix"`
OwnerUsername string `json: "ownerUsername` OwnerUsername string `json:"ownerUsername"`
} }
// Todo structure // Todo structure
type Todo struct { type Todo struct {
ID uint64 `json: "id"` ID uint64 `json:"id"`
GroupID uint64 `json: "groupId"` GroupID uint64 `json:"groupId"`
Text string `json: "text"` Text string `json:"text"`
TimeCreatedUnix uint64 `json: "timeCreatedUnix"` TimeCreatedUnix uint64 `json:"timeCreatedUnix"`
DueUnix uint64 `json: "dueUnix"` DueUnix uint64 `json:"dueUnix"`
OwnerUsername string `json: "ownerUsername"` OwnerUsername string `json:"ownerUsername"`
} }
// Creates a new TODO group in the database // Creates a new TODO group in the database
@ -115,6 +115,7 @@ func scanTodo(rows *sql.Rows) (*Todo, error) {
&newTodo.ID, &newTodo.ID,
&newTodo.GroupID, &newTodo.GroupID,
&newTodo.Text, &newTodo.Text,
&newTodo.TimeCreatedUnix,
&newTodo.DueUnix, &newTodo.DueUnix,
&newTodo.OwnerUsername, &newTodo.OwnerUsername,
) )
@ -169,9 +170,10 @@ func (db *DB) GetTodos() ([]*Todo, error) {
// Creates a new TODO in the database // Creates a new TODO in the database
func (db *DB) CreateTodo(todo Todo) error { func (db *DB) CreateTodo(todo Todo) error {
_, err := db.Exec( _, err := db.Exec(
"INSERT INTO todos(group_id, text, due_unix, owner_username) VALUES(?, ?, ?, ?)", "INSERT INTO todos(group_id, text, time_created_unix, due_unix, owner_username) VALUES(?, ?, ?, ?, ?)",
todo.GroupID, todo.GroupID,
todo.Text, todo.Text,
todo.TimeCreatedUnix,
todo.DueUnix, todo.DueUnix,
todo.OwnerUsername, todo.OwnerUsername,
) )

6
src/db/user.go

@ -4,9 +4,9 @@ import "database/sql"
// User structure // User structure
type User struct { type User struct {
Username string `json: "username"` Username string `json:"username"`
Password string `json: "password"` Password string `json:"password"`
TimeCreatedUnix uint64 `json: "timeCreatedUnix"` TimeCreatedUnix uint64 `json:"timeCreatedUnix"`
} }
func scanUser(rows *sql.Rows) (*User, error) { func scanUser(rows *sql.Rows) (*User, error) {

1
src/server/api.go

@ -198,6 +198,7 @@ func (s *Server) TodoEndpoint(w http.ResponseWriter, req *http.Request) {
err = s.db.CreateTodo(newTodo) err = s.db.CreateTodo(newTodo)
if err != nil { if err != nil {
http.Error(w, "Failed to create TODO", http.StatusInternalServerError) http.Error(w, "Failed to create TODO", http.StatusInternalServerError)
logger.Error("[Server] Failed to put a new todo (%+v) into the db: %s", newTodo, err)
return return
} }

Loading…
Cancel
Save