feat: authorization

dependabot/pip/requests-2.31.0
Pierre-Louis Guhur 1 year ago committed by guhur
parent 56216b0ccc
commit cdcdbe78b2

@ -152,13 +152,16 @@ def create_vote(db: Session, vote: schemas.BallotCreate) -> schemas.BallotGet:
db_election = get_election(db, election_id)
if db_election is None:
raise errors.NotFoundError("Unknown election.")
if db_election.private:
if db_election.restricted:
raise errors.BadRequestError(
"The election is private. You can not create new votes"
"The election is restricted. You can not create new votes"
)
db_votes = [models.Vote(**v.dict()) for v in vote.votes]
db.bulk_save_objects(db_votes, return_defaults=True)
db.add_all(db_votes)
db.commit()
for v in db_votes:
db.refresh(v)
votes_get = [schemas.VoteGet.from_orm(v) for v in db_votes]
vote_ids = [v.id for v in votes_get]

@ -16,7 +16,7 @@ class Election(Base):
date_start = Column(DateTime)
date_end = Column(DateTime)
hide_results = Column(Boolean, default=False)
private = Column(Boolean, default=False)
restricted = Column(Boolean, default=False)
grades = relationship("Grade", back_populates="election")
candidates = relationship("Candidate", back_populates="election")

@ -159,7 +159,7 @@ class ElectionBase(BaseModel):
date_end: datetime = Field(default_factory=_in_a_long_time)
hide_results: bool = True
force_close: bool = False
private: bool = False
restricted: bool = False
_valid_date = _causal_dates_validator("date_created", "date_modified")
_valid_date = _causal_dates_validator("date_start", "date_end")

@ -52,6 +52,7 @@ class RandomElection(t.TypedDict):
name: str
candidates: list[dict[str, str]]
grades: list[dict[str, int | str]]
restricted: t.NotRequired[bool]
def _random_election(num_candidates: int, num_grades: int) -> RandomElection:
@ -166,8 +167,21 @@ def test_create_vote():
assert v2["election_id"] == election_id
def test_cannot_create_vote_on_private_election():
assert False
def test_cannot_create_vote_on_restricted_election():
"""
On a restricted election, we are not allowed to create new votes
"""
# Create a random election
body = _random_election(10, 5)
body["restricted"] = True
response = client.post("/elections", json=body)
data = response.json()
# We create votes using the ID
votes = _generate_votes_from_response("id", data)
response = client.post(f"/votes", json={"votes": votes})
data = response.json()
assert response.status_code == 400, data
def test_get_results():
@ -179,9 +193,9 @@ def test_get_results():
# We create votes using the ID
votes = _generate_votes_from_response("id", data)
for vote in votes * 2:
response = client.post(f"/votes", json=vote)
data = response.json()
response = client.post(f"/votes", json={"votes": votes})
data = response.json()
assert response.status_code == 200, data
# Now we get the results
response = client.get(f"/results/{election_id}")

Loading…
Cancel
Save