Skip to content
This repository has been archived by the owner on Jul 7, 2024. It is now read-only.

Commit

Permalink
fix: get json POST handling functional
Browse files Browse the repository at this point in the history
Signed-off-by: CyberFlame <[email protected]>
  • Loading branch information
CyberFlameGO committed Oct 19, 2023
1 parent 44307a8 commit 4538ecc
Show file tree
Hide file tree
Showing 15 changed files with 111 additions and 67 deletions.
5 changes: 5 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"rules": {
"space-before-function-paren": "off"
}
}
6 changes: 6 additions & 0 deletions .idea/DTSCodingDB.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/cssdialects.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion .idea/jsLibraryMappings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions .idea/runConfigurations/Run_project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion .jshintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"esversion": 11
"esversion": 11,
"browser": true
}
3 changes: 2 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
"trailingComma": "es5",
"tabWidth": 4,
"semi": true,
"singleQuote": true
"singleQuote": true,
"bracketSpacing": false
}
1 change: 0 additions & 1 deletion .stylelintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@
"stylelint-config-standard"
],
"rules": {

}
}
25 changes: 11 additions & 14 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class Endpoint(Enum):
"""
Enum of endpoints
"""

GAMES = "games"
LOGIN = "login"
REGISTER = "register"
Expand Down Expand Up @@ -90,8 +91,8 @@ async def home(request: Request):

@app.post("/token", response_model=Token)
async def authenticate(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
session: Session,
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
session: Session,
):
user = await Auth.authenticate_user(session, form_data.username, form_data.password)
if not user:
Expand All @@ -101,23 +102,17 @@ async def authenticate(
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=Auth.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = Auth.create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
access_token = Auth.create_access_token(data={"sub": user.username}, expires_delta=access_token_expires)
return {"access_token": access_token, "token_type": "bearer"}


@app.get("/users/me/", response_model=PydanticUser)
async def read_users_me(
current_user: Current_Active_User
):
async def read_users_me(current_user: Current_Active_User):
return current_user


@app.get("/users/me/items/")
async def read_own_items(
current_user: Current_Active_User
):
async def read_own_items(current_user: Current_Active_User):
return [{"item_id": "Foo", "owner": current_user.username}]


Expand All @@ -132,7 +127,7 @@ async def records_list(request: Request, session: Session, endpoint: str):
"""
model, endpoint_type = classify(endpoint)
if model is None:
return Response(status_code = status.HTTP_404_NOT_FOUND)
return Response(status_code=status.HTTP_404_NOT_FOUND)
context: dict = {
"request": request,
}
Expand Down Expand Up @@ -173,15 +168,17 @@ async def new_record(request: Request, session: Session, endpoint: str):
first_name=form.get("first_name"),
last_name=form.get("last_name"),
year_level=form.get("year_level"),
house=form.get("house")
house=form.get("house"),
)
case _:
return Response(status_code=status.HTTP_404_NOT_FOUND)
try:
await db.insert(session, model_instance)
except IntegrityError:
return Response(status_code=status.HTTP_409_CONFLICT)
return JSONResponse(content={"redirectUrl": f"/{endpoint}"}, status_code=status.HTTP_303_SEE_OTHER)
if endpoint_type == Endpoint.REGISTER:
return JSONResponse(content={"redirectUrl": f"/"}, status_code=status.HTTP_303_SEE_OTHER)
return JSONResponse(content={"redirectUrl": f"/{endpoint_type.value}"}, status_code=status.HTTP_303_SEE_OTHER)


@app.patch("/{endpoint}/{identifier}", response_class=HTMLResponse)
Expand Down
20 changes: 10 additions & 10 deletions pdm.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 37 additions & 1 deletion static/js/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,49 @@ export default class ResourceManager {
// The methods in this class are designed to have one point return for readability purposes.
// This is noted here to explain the redundant-looking code in the methods below.

static handleFormSubmission(formId, conflictMessage) {
// This particular method has status codes hard-coded on purpose.
const HTTP_409_CONFLICT = 409;
const HTTP_303_SEE_OTHER = 303;
// Store reference to "this" context
const that = this;
document
.getElementById(formId)
.addEventListener('submit', async function (e) {
e.preventDefault();
const form = this;
try {
const response = await that.sendRequest(
form.action,
'POST',
new FormData(form)
);
if (response.status === HTTP_409_CONFLICT) {
alert(conflictMessage);
} else if (response.status === HTTP_303_SEE_OTHER) {
const data = await response.json();
console.log(data);
const redirectUrl = await data['redirectUrl']; // jshint ignore:line
console.log(redirectUrl);
if (redirectUrl) {
window.location.href = redirectUrl;
}
}
} catch (error) {
console.error('Error:', error);
}
});
}

static async sendRequest(url, httpMethod, body) {
const options = {
method: httpMethod,
headers: {},
};

if (body) {
if (body instanceof FormData) {
options.body = body;
} else if (body) {
options.body = JSON.stringify(body);
options.headers['Content-Type'] = 'application/json';
}
Expand Down
18 changes: 3 additions & 15 deletions templates/games.html
Original file line number Diff line number Diff line change
Expand Up @@ -63,21 +63,9 @@
}
}
};
</script>
<script>
document.addEventListener('DOMContentLoaded', (event) => {
const HTTP_409_CONFLICT = 409;
document.getElementById('submitNewGame').addEventListener('submit', function() {
fetch(event.target.action, {
method: 'POST',
body: new FormData(this),
}).then(function(response) {
if (!response.ok && response.status === HTTP_409_CONFLICT) {
alert('You cannot add a game with a name that already exists in the database!');
// TODO: abstract this into utility class, and handle the response
}
});
});
document.addEventListener('DOMContentLoaded', () => {
ResourceManager.handleFormSubmission('submitNewGame',
'You cannot add a game with a name that already exists in the database!');
});
</script>
{% endblock %}
Expand Down
32 changes: 11 additions & 21 deletions templates/register.html
Original file line number Diff line number Diff line change
@@ -1,22 +1,12 @@
{% extends 'base.html' %}

{% block head %}
<script>
document.getElementById('submitNewUser').addEventListener('submit', async function(event) {
event.preventDefault();
const response = await fetch(event.target.action, {
method: 'POST',
body: new FormData(this),
});
if (!response.ok && response.status === HTTP_409_CONFLICT) {
alert('You cannot add a user with an email or username that already exists in the database!');
} else if (response.ok) {
const data = await response.json();
const redirectUrl = data['redirectUrl'];
if (redirectUrl) {
window.location.href = redirectUrl;
}
}
<script type = 'module'>
import ResourceManager from '../static/js/utils.js';

document.addEventListener('DOMContentLoaded', () => {
ResourceManager.handleFormSubmission('submitNewUser',
'You cannot add a user with an email or username that already exists in the database!');
});
</script>
{% endblock %}
Expand All @@ -26,22 +16,22 @@ <h1>User Registration</h1>

<form id = "submitNewUser" action = "/register" method = "post">
<label for = "email">Email</label>
<input type = "email" id = "email" name = "email" required><br>
<input type = "email" id = "email" name = "email" autocomplete = 'email' required><br>

<label for = "username">Username</label>
<input type = "text" id = "username" name = "username" required><br>
<input type = "text" id = "username" name = "username" autocomplete = 'username' required><br>

<label for = "password">Password</label>
<input type = "password" id = "password" name = "password" required><br>
<input type = "password" id = "password" name = "password" autocomplete = 'new-password' required><br>

<label for = "role">Role</label>
<input type = "text" id = "role" name = "role" required><br>

<label for = "first_name">First Name</label>
<input type = "text" id = "first_name" name = "first_name" required><br>
<input type = "text" id = "first_name" name = "first_name" autocomplete = 'given-name' required><br>

<label for = "last_name">Last Name</label>
<input type = "text" id = "last_name" name = "last_name" required><br>
<input type = "text" id = "last_name" name = "last_name" autocomplete = 'family-name' required><br>

<label for = "year_level">Year Level</label>
<input type = "number" id = "year_level" name = "year_level"><br>
Expand Down

0 comments on commit 4538ecc

Please sign in to comment.