Skip to content

Commit def5346

Browse files
committed
update formatting & fix some small access bugs
1 parent 1c61134 commit def5346

File tree

4 files changed

+63
-59
lines changed

4 files changed

+63
-59
lines changed

src/alembic/versions/243190df5588_create_election_tables.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020

2121

2222
def upgrade() -> None:
23-
op.create_table("election",
23+
op.create_table(
24+
"election",
2425
sa.Column("slug", sa.String(length=32), nullable=False),
2526
sa.Column("name", sa.String(length=32), nullable=False),
2627
sa.Column("officer_id", sa.String(length=32), nullable=False),
@@ -30,7 +31,8 @@ def upgrade() -> None:
3031
sa.Column("survey_link", sa.String(length=300), nullable=True),
3132
sa.PrimaryKeyConstraint("slug")
3233
)
33-
op.create_table("election_nominee",
34+
op.create_table(
35+
"election_nominee",
3436
sa.Column("computing_id", sa.String(length=32), nullable=False),
3537
sa.Column("full_name", sa.String(length=64), nullable=False),
3638
sa.Column("facebook", sa.String(length=64), nullable=True),
@@ -41,13 +43,14 @@ def upgrade() -> None:
4143
sa.Column("discord_username", sa.String(length=32), nullable=True),
4244
sa.PrimaryKeyConstraint("computing_id")
4345
)
44-
op.create_table("nominee_application",
46+
op.create_table(
47+
"nominee_application",
4548
sa.Column("computing_id", sa.String(length=32), nullable=False),
4649
sa.Column("nominee_election", sa.String(length=32), nullable=False),
4750
sa.Column("speech", sa.Text(), nullable=True),
4851
sa.Column("position", sa.String(length=64), nullable=False),
49-
sa.ForeignKeyConstraint(["computing_id"], ["election_nominee.computing_id"], ),
50-
sa.ForeignKeyConstraint(["nominee_election"], ["election.slug"], ),
52+
sa.ForeignKeyConstraint(["computing_id"], ["election_nominee.computing_id"]),
53+
sa.ForeignKeyConstraint(["nominee_election"], ["election.slug"]),
5154
sa.PrimaryKeyConstraint("computing_id", "nominee_election")
5255
)
5356

src/elections/crud.py

Lines changed: 28 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,8 @@
77

88
import database
99
from elections.tables import Election
10-
from officers.constants import OfficerPosition
11-
from officers.tables import OfficerInfo, OfficerTerm
1210

11+
_logger = logging.getLogger(__name__)
1312

1413
@dataclass
1514
class ElectionParameters:
@@ -24,39 +23,38 @@ class ElectionParameters:
2423
end_datetime: datetime
2524
survey_link: str
2625

27-
28-
_logger = logging.getLogger(__name__)
29-
3026
async def get_election(db_session: AsyncSession, election_slug: str) -> Election | None:
31-
query = (
27+
return await db_session.scalar(
3228
sqlalchemy
3329
.select(Election)
3430
.where(Election.slug == election_slug)
3531
)
36-
result = await db_session.scalar(query)
37-
return result
3832

3933
async def create_election(db_session: AsyncSession, params: ElectionParameters) -> None:
4034
"""
4135
Creates a new election with given parameters.
4236
Does not validate if an election _already_ exists
4337
"""
44-
election = Election(slug=params.slug,
45-
name=params.name,
46-
officer_id=params.officer_id,
47-
type=params.type,
48-
start_datetime=params.start_datetime,
49-
end_datetime=params.end_datetime,
50-
survey_link=params.survey_link)
51-
db_session.add(election)
38+
db_session.add(Election(
39+
slug=params.slug,
40+
name=params.name,
41+
officer_id=params.officer_id,
42+
type=params.type,
43+
start_datetime=params.start_datetime,
44+
end_datetime=params.end_datetime,
45+
survey_link=params.survey_link
46+
))
5247

5348
async def delete_election(db_session: AsyncSession, slug: str) -> None:
5449
"""
5550
Deletes a given election by its slug.
5651
Does not validate if an election exists
5752
"""
58-
query = sqlalchemy.delete(Election).where(Election.slug == slug)
59-
await db_session.execute(query)
53+
await db_session.execute(
54+
sqlalchemy
55+
.delete(Election)
56+
.where(Election.slug == slug)
57+
)
6058

6159
async def update_election(db_session: AsyncSession, params: ElectionParameters) -> None:
6260
"""
@@ -66,7 +64,12 @@ async def update_election(db_session: AsyncSession, params: ElectionParameters)
6664
Does not validate if an election _already_ exists
6765
"""
6866

69-
election = (await db_session.execute(sqlalchemy.select(Election).filter_by(slug=params.slug))).scalar_one()
67+
election = (await db_session.execute(
68+
sqlalchemy
69+
.select(Election)
70+
# TODO: what is filter_by?
71+
.filter_by(slug=params.slug)
72+
)).scalar_one()
7073

7174
if params.start_datetime is not None:
7275
election.start_datetime = params.start_datetime
@@ -77,6 +80,9 @@ async def update_election(db_session: AsyncSession, params: ElectionParameters)
7780
if params.survey_link is not None:
7881
election.survey_link = params.survey_link
7982

80-
query = sqlalchemy.update(Election).where(Election.slug == params.slug).values(election)
81-
await db_session.execute(query)
82-
83+
await db_session.execute(
84+
sqlalchemy
85+
.update(Election)
86+
.where(Election.slug == params.slug)
87+
.values(election)
88+
)

src/elections/tables.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from datetime import datetime
2-
31
from sqlalchemy import (
42
Column,
53
DateTime,

src/elections/urls.py

Lines changed: 27 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,9 @@
1-
import base64
21
import logging
3-
import os
42
import re
5-
import urllib.parse
63
from datetime import datetime
74

8-
import requests # TODO: make this async
9-
import xmltodict
105
from crud import ElectionParameters
11-
from fastapi import APIRouter, BackgroundTasks, FastAPI, HTTPException, Request, status
6+
from fastapi import APIRouter, HTTPException, Request, status
127
from fastapi.exceptions import RequestValidationError
138
from tables import election_types
149

@@ -17,7 +12,7 @@
1712
import database
1813
import elections
1914
from constants import root_ip_address
20-
from permission import types
15+
from permission.types import ElectionOfficer
2116

2217
_logger = logging.getLogger(__name__)
2318

@@ -27,21 +22,27 @@
2722
)
2823

2924
def _slugify(
30-
text: str
25+
text: str
3126
) -> str:
3227
"""
3328
Creates a unique slug based on text passed in. Assumes non-unicode text.
3429
"""
3530
return re.sub(r"[\W_]+", "-", text)
3631

3732
async def _validate_user(
38-
db_session: database.DBSession,
39-
session_id: str
40-
) -> dict:
33+
request: Request,
34+
db_session: database.DBSession,
35+
) -> tuple[bool, str, str]:
36+
session_id = request.cookies.get("session_id", None)
37+
if session_id is None:
38+
return False, None, None
39+
4140
computing_id = await auth.crud.get_computing_id(db_session, session_id)
42-
# Assuming now user is validated
43-
result = await types.ElectionOfficer.has_permission(db_session, computing_id)
44-
return result
41+
if computing_id is None:
42+
return False, None, None
43+
44+
has_permission = await ElectionOfficer.has_permission(db_session, computing_id)
45+
return has_permission, session_id, computing_id
4546

4647
@router.get(
4748
"/create_election",
@@ -59,9 +60,11 @@ async def create_election(
5960
"""
6061
aaa
6162
"""
62-
session_id = request.cookies.get("session_id", None)
63-
user_auth = await _validate_user(db_session, session_id)
64-
if user_auth is False:
63+
if election_type not in election_types:
64+
raise RequestValidationError()
65+
66+
is_valid_user, session_id, _ = await _validate_user(request, db_session)
67+
if not is_valid_user:
6568
# let's workshop how we actually wanna handle this
6669
raise HTTPException(
6770
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -73,9 +76,6 @@ async def create_election(
7376
if start_datetime is None:
7477
start_datetime = datetime.now()
7578

76-
if election_type not in election_types:
77-
raise RequestValidationError()
78-
7979
params = ElectionParameters(
8080
_slugify(name),
8181
name,
@@ -93,17 +93,16 @@ async def create_election(
9393
return {}
9494

9595
@router.get(
96-
"/delete_election",
97-
description="Deletes an election from the database"
96+
"/delete_election",
97+
description="Deletes an election from the database"
9898
)
9999
async def delete_election(
100100
request: Request,
101101
db_session: database.DBSession,
102102
slug: str
103103
):
104-
session_id = request.cookies.get("session_id", None)
105-
user_auth = await _validate_user(db_session, session_id)
106-
if user_auth is False:
104+
is_valid_user, _, _ = await _validate_user(request, db_session)
105+
if not is_valid_user:
107106
# let's workshop how we actually wanna handle this
108107
raise HTTPException(
109108
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -130,16 +129,15 @@ async def update_election(
130129
end_datetime: datetime | None = None,
131130
survey_link: str | None = None
132131
):
133-
session_id = request.cookies.get("session_id", None)
134-
user_auth = await _validate_user(db_session, session_id)
135-
if user_auth is False:
132+
is_valid_user, session_id, _ = await _validate_user(request, db_session)
133+
if not is_valid_user:
136134
# let's workshop how we actually wanna handle this
137135
raise HTTPException(
138136
status_code=status.HTTP_401_UNAUTHORIZED,
139137
detail="You do not have permission to access this resource",
140138
headers={"WWW-Authenticate": "Basic"},
141139
)
142-
if slug is not None:
140+
elif slug is not None:
143141
params = ElectionParameters(
144142
_slugify(name),
145143
name,
@@ -152,7 +150,6 @@ async def update_election(
152150
await elections.crud.update_election(params, db_session)
153151
await db_session.commit()
154152

155-
156153
@router.get(
157154
"/test"
158155
)

0 commit comments

Comments
 (0)