def book_appointment(db: PeeweeSession, body: hug.types.json, user: hug.directives.user):
    with db.atomic():
        try:
            assert user.coupons > 0
            if all(key in body for key in ('claim_token', 'start_date_time', 'first_name', 'name', 'phone', 'office')):
                claim_token = body['claim_token']
                start_date_time = body['start_date_time']
                start_date_time_object = datetime.fromisoformat(start_date_time)
                now = datetime.now(tz=config.Settings.tz).replace(tzinfo=None)
                if start_date_time_object < now:
                    raise ValueError("Can't claim an appointment in the past")
                time_slot = TimeSlot.get(TimeSlot.start_date_time == start_date_time_object)
                appointment = Appointment.get(
                    (Appointment.time_slot == time_slot) &
                    (Appointment.booked == False) &
                    (Appointment.claim_token == claim_token)
                )
                appointment.booked = True
                appointment.claim_token = None
                appointment.claimed_at = None
                appointment.save()
                success = False
                with db.atomic():
                    while not success:
                        secret = get_secret_token(6)
                        try:
                            SlotCode.create(date=time_slot.start_date_time.date(), secret=secret)
                            success = True
                        except IntegrityError as e:  # in the offchance that we had a collision with secret codes, retry
                            pass

                booking = Booking.create(appointment=appointment, first_name=body['first_name'], surname=body['name'],
                                         phone=body['phone'], office=body['office'], secret=secret,
                                         booked_by=user.user_name)
                booking.save()
                user.coupons -= 1
                user.save()
                return {
                    "secret": booking.secret,
                    "time_slot": time_slot.start_date_time,
                    "slot_length_min": time_slot.length_min
                }
            else:
                raise ValueError("Missing parameter")
        except DoesNotExist as e:
            raise hug.HTTPGone
        except ValueError as e:
            raise hug.HTTPBadRequest
        except AssertionError as e:
            raise hug.HTTPBadRequest
Beispiel #2
0
def leave_game(player: hug.directives.user, uuid: hug.types.text):
    """
    Leave a game you are in.

    Returns a Game dict

    Possible errors are :
        - GameNotFound : The game specified couldn't be found
        - NotInGame : You are not in this game

    """
    game = cache_store.get_game_by_uuid(uuid)
    if game:
        if player in game.players:
            game.players.remove(player)
            player.current_game = None
            logger.info(
                f"User {player.display_name} left game {game.display_name}")
        else:
            return gen_error("NotInGame",
                             "You can't leave a game you didn't joined.")

    else:
        return gen_error("GameNotFound",
                         "The selected game couldn't be found.")
Beispiel #3
0
def join_game(player: hug.directives.user, uuid: hug.types.text):
    """
    Create a new game, named. Does NOT start the game but open it for new players

    Returns a Game dict

    Possible errors are :
        - GameNotJoinable : You can't join the game because it started
        - GameNotFound : The game specified couldn't be found

    """
    game = cache_store.get_game_by_uuid(uuid)
    if game:
        if game.phase == 0:
            game.players.add(player)
            player.games.add(game)
            player.current_game = game
            logger.info(
                f"User {player.display_name} joined game {game.display_name}")
        else:
            return gen_error(
                "GameNotJoinable",
                "The selected game started and couldn't be joined.")
    else:
        return gen_error("GameNotFound",
                         "The selected game couldn't be found.")
Beispiel #4
0
def delete_booking(db: PeeweeSession, user: hug.directives.user, booking_id: hug.types.text):
    if user.role != UserRoles.ANON:
        with db.atomic():
            try:
                booking = Booking.get_by_id(booking_id)
                if user.role == UserRoles.USER and booking.booked_by != user.user_name:
                    return hug.HTTP_METHOD_NOT_ALLOWED
                appointment = booking.appointment
                appointment.booked = False
                appointment.save()
                booking.delete_instance()
            except DoesNotExist as e:
                raise hug.HTTP_NOT_FOUND
        user.coupons += 1
        user.save()
        return {"booking_id": booking_id, "deleted": "successful"}
    else:
        raise hug.HTTP_METHOD_NOT_ALLOWED
Beispiel #5
0
def patch_user(db: PeeweeSession, body: hug.types.json,
               user: hug.directives.user):
    old_user_password = body["old_user_password"]
    new_user_password = body["new_user_password"]
    new_user_password_confirm = body["new_user_password_confirm"]
    if new_user_password != new_user_password_confirm:
        raise hug.HTTPBadRequest
    with db.atomic():
        try:
            if user.password != hash_pw(user.user_name, user.salt,
                                        old_user_password):
                raise hug.HTTPBadRequest
            salt = get_random_string(2)
            secret_password = new_user_password
            hashed_password = hash_pw(user.user_name, salt, secret_password)
            user.salt = salt
            user.password = hashed_password
            user.save()
            log.info(f"updated {user.user_name}'s pw.")
            return "updated"
        except DoesNotExist as e:
            raise hug.HTTPBadRequest
        except ValueError as e:
            raise hug.HTTPBadRequest
Beispiel #6
0
def create_game(player: hug.directives.user, name: hug.types.text):
    """
    Create a new game, named. Does NOT start the game but open it for new players

    Returns a Game dict
    """
    game = obj.Game(name, player)
    cache_store.games.add(game)

    game.players.add(player)
    player.games.add(game)
    player.current_game = game

    logger.info(f"User {player.display_name} created game {game.display_name}")

    res = game.uuid

    return res
Beispiel #7
0
def whoami(user: hug.directives.user):
    return user.to_dict()
Beispiel #8
0
def profile(user: hug.directives.user, response, body=None):
    """If authenticated, give the user back their profile information."""
    return user.to_dict()
Beispiel #9
0
def who_am_i(user: hug.directives.user):
    return user.dump()