Beispiel #1
0
    def put(self, username):
        # gets current identity (username, password, admin, super_user)
        identity = current_identity
        # loads json data and parses looking for args
        data = User.parser.parse_args()

        # existing user needed to query if a change being made to username already exists
        existing_user = UserModel.find_by_username(data['username'])

        # looks for current username passed in '/user/<name>' exists and if not create
        user = UserModel.find_by_username(username)
        if identity.super_user == 0 and identity.username != username:
            return {'message': 'You are not authorized.'}, 403
        if user is None:
            user = UserModel(data['username'].lower(), data['password'],
                             data['site_location'].lower(), data['admin'],
                             data['super_user'], identity.username.lower())
        else:
            # it existed, now we must check a few other things to update a record
            # user is admin and no existing user
            if identity.super_user == 1 and existing_user is None:
                user.username = data['username'].lower()
                user.password = data['password']
                user.site_location = data['site_location'].lower()
                user.admin = data['admin']
                user.super_user = data['super_user']

                user.created_by = identity.username.lower()
            # user is updating his record but changing his username
            elif identity.username == username and existing_user is None:
                user.username = data['username'].lower()
                user.password = data['password']
                user.site_location = data['site_location'].lower()
                user.admin = user.admin
                user.super_user = user.super_user

                user.created_by = identity.username.lower()
            # user is updating his user record without a name change
            elif identity.username == existing_user.username:
                user.username = data['username'].lower()
                user.password = data['password']
                user.site_location = data['site_location'].lower()
                if identity.super_user == 1:
                    user.admin = data['admin']
                    user.super_user = data['super_user']
                else:
                    user.admin = user.admin
                    user.super_user = user.super_user

                user.created_by = identity.username.lower()
            else:
                return {'message': 'Username is already in use'}, 400

        user.save_to_db()

        return user.json()
    def put(self, event_id):
        data = parser.parse_args()

        owner = UserModel.find_by_username(get_jwt_identity())
        event: EventModel = EventModel.find_by_id(event_id)

        if not event:
            abort(400, message=EVENT_DOESNT_EXIST)

        if owner != event.owner:
            abort(401, message=UNAUTHORIZED)

        if not data['end'] > data['start']:
            abort(400, message=END_MUST_BE_AFTER_START)

        event.title = data['title']
        event.description = data['description']
        event.start = data['start']
        event.end = data['end']

        try:
            event.persist()
            return event, 200
        except:
            abort(500, message=INTERNAL_SERVER_ERROR)
Beispiel #3
0
    def post(self):
        data = invitation_parser.parse_args()

        user = UserModel.find_by_username(data['user'])
        community = CommunityModel.find_by_id(data['community'])

        if not user:
            abort(404, message=USER_DOESNT_EXIST)

        if not community:
            abort(404, message=COMMUNIY_DOESNT_EXIST)

        if user in community.users:
            abort(400, message=USER_ALREADY_INVITED)

        new_community_user_link = CommunityUserLinkModel(
            user_id=user.id,
            community_id=community.id,
            invitation_accepted=False,
            is_owner=False)

        try:
            new_community_user_link.persist()
            return SimpleMessage(COMMUNIY_INVITATION_SENT), 200
        except:
            abort(500, message=INTERNAL_SERVER_ERROR)
Beispiel #4
0
    def post(self):
        data = post_parser.parse_args()

        founder = UserModel.find_by_username(get_jwt_identity())
        car = CarModel.find_by_id(data['car'])

        if not car:
            abort(404, message=CAR_DOESNT_EXIST)

        if not car.owner.id == founder.id:
            abort(400, message=CANNOT_CREATE_COMMUNITY_WITH_FOREIGN_CAR)

        if CommunityModel.find_by_car_id(car.id):
            abort(400, message=COMMUNIY_WITH_THIS_CAR_ALREADY_EXISTS)

        new_community = CommunityModel(name=data['name'],
                                       car=car,
                                       users=[founder])

        try:
            new_community.persist()
            faved_community: CommunityUserLinkModel = assure_favourite_community(
                founder.id)
            if faved_community and faved_community.community_id == new_community.id:
                new_community.is_favourite = faved_community.is_favourite
            return new_community, 201
        except:
            abort(500, message=INTERNAL_SERVER_ERROR)
Beispiel #5
0
    def post(self, community_id):
        data = parser.parse_args()

        owner = UserModel.find_by_username(get_jwt_identity())
        community: CommunityModel = CommunityModel.find_by_id(community_id)

        if not community:
            abort(400, message=COMMUNIY_DOESNT_EXIST)

        if owner.id not in [u.id for u in community.users]:
            abort(401, message=UNAUTHORIZED)

        new_refuel = RefuelModel(
            owner=owner,
            community=community,
            costs=round(data['costs'], 2),
            liters=data['liters'],
            gas_station_name=data['gas_station_name'],
        )

        try:
            new_refuel.persist()
            return new_refuel, 201
        except:
            abort(500, message=INTERNAL_SERVER_ERROR)
Beispiel #6
0
    def post(self, username):
        data = self.parser.parse_args()
        required_access = 3
        current_user = current_identity  # type: UserModel
        admin = AdminModel.find_by_id(current_user.id)
        if not admin:
            return {'message': 'No admin access.'}, 400

        if admin.access_level < required_access:
            return {
                'message': f'Access level {required_access} required.'
            }, 400

        other_user = UserModel.find_by_username(username)

        if not other_user:
            return {'message': f'User {username} doesn\'t exist.'}, 400

        if other_user.is_admin():
            return {'message': f'User {username} is already admin.'}, 400

        access_level = data['access_level']
        if admin.access_level <= access_level:
            return {'message': 'Access level must be lower than self.'}, 400

        if access_level < 1:
            return {'message' 'Invalid access level.'}, 400

        new_admin = AdminModel(other_user.id, access_level)
        new_admin.save()
        return {'admin': new_admin.json()}, 201
Beispiel #7
0
    def put(self, community_id, id):
        data = finish_tour_parser.parse_args()

        tour = TourModel.find_by_id(id)
        user = UserModel.find_by_username(get_jwt_identity())
        community: CommunityModel = CommunityModel.find_by_id(community_id)
        community_member_ids = [m.id for m in community.users]

        if not tour:
            abort(404, message=TOUR_NOT_FOUND)

        if not user.id == tour.owner.id:
            abort(401, message=UNAUTHORIZED)

        if tour.end_km:
            abort(400, message=TOUR_HAS_ALREADY_BEEN_FINISHED)

        passengers = []
        if data['passengers']:
            for passenger_id in set(data['passengers']):
                if passenger_id not in community_member_ids:
                    abort(400, message=PASSENGERS_MUST_BE_COMMUNITY_MEMBERS)
                else:
                    passengers.append([u for u in community.users if u.id == passenger_id][0])

        tour.end_time = datetime.datetime.now(pytz.utc)
        tour.passengers = passengers
        tour.end_km = data['end_km']
        tour.comment = data['comment']
        tour.parking_position = data['parking_position']
        tour.persist()

        create_km_triggered_task_instances(community_id, tour.end_km)

        return tour, 200
    def post(self, community_id):
        data = parser.parse_args()

        owner = UserModel.find_by_username(get_jwt_identity())
        community: CommunityModel = CommunityModel.find_by_id(community_id)
        community_member_ids = [m.id for m in community.users]

        if not community:
            abort(400, message=COMMUNIY_DOESNT_EXIST)

        if owner.id not in community_member_ids:
            abort(401, message=UNAUTHORIZED)

        if not data['end'] > data['start']:
            abort(400, message=END_MUST_BE_AFTER_START)

        new_event = EventModel(owner=owner,
                               title=data['title'],
                               description=data['description'],
                               start=data['start'],
                               end=data['end'],
                               community_id=community.id)

        try:
            new_event.persist()
            return new_event, 201
        except:
            abort(500, message=INTERNAL_SERVER_ERROR)
 def post(self):
     user_data = UserRegister.parser.parse_args()
     if UserModel.find_by_username(username=user_data['username']):
         return {'message': 'A user with username already exists'}, 400
     user = UserModel(user_data['username'], user_data['password'])
     user.save_to_db()
     return {"message": "user created successfully"}, 201
Beispiel #10
0
    def get(self):
        user = UserModel.find_by_username(get_jwt_identity())
        cul = CommunityUserLinkModel.find_favourite_by_user(user.id)

        if not cul:
            abort(404, message=NO_FAVOURITE_COMMUNITY_FOUND)

        return cul.community, 200
Beispiel #11
0
    def get(self, community_id):
        user = UserModel.find_by_username(get_jwt_identity())
        community = CommunityModel.find_by_id(community_id)

        if user not in community.users:
            abort(401, message=UNAUTHORIZED)

        return community.users, 200
Beispiel #12
0
    def test_register_user(self):
        with self.app() as c:
            with self.app_context():
                r = c.post('/register', data={'username': '******', 'password': '******'})

                self.assertEqual(r.status_code, 201)
                self.assertIsNotNone(UserModel.find_by_username('test'))
                self.assertDictEqual(d1={'message': 'User created successfully.'},
                                     d2=json.loads(r.data))
Beispiel #13
0
    def post(self):
        data = request.json
        if UserModel.find_by_username(data['username']):
            return {'message': 'A user with that username already exists'}, 400

        user = UserModel(data['username'], data['password'])
        user.save_to_db()

        return 201
Beispiel #14
0
    def get(self, username):
        identity = current_identity
        if identity == None:
            return {"message": "You are not logged in"}, 400
        if identity.username != username and identity.super_user != 1:
            return {'message': "You are not authorized."}, 403

        user = UserModel.find_by_username(username)
        return user.json()
Beispiel #15
0
    def post(self):
        data = _user_parser.parse_args()
        if UserModel.find_by_username(data['username']):
            return {'message': 'username is already exists'}, 400

        user = UserModel(**data)
        user.save_to_db()

        return {'message': 'User created successully.'}, 201
Beispiel #16
0
    def post(self):
        data = UserRegister.parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return {"message": "Un utilizator cu acest nume deja exista"}, 400

        user = UserModel(**data)
        user.save_to_db()
        return {"message": "Utilizatorul a fost creat."}, 201
Beispiel #17
0
    def post(self):
        data = _user_parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return {"message": "A user with that username already exists"}, 400

        user = UserModel(data['username'], data['password'])
        user.save_to_db()

        return {"message": "User created successfully."}, 201
Beispiel #18
0
    def post(self):
        data = UserRegister.parser.parse_args()
        if UserModel.find_by_username(data['username']) is not None:
            return {"message": "User with this name already exists!"}, 400

        password_hash = generate_password_hash(data['password'])
        user = UserModel(data['username'], password_hash)
        user.save_to_db()

        return {"message": "User created successfully"}, 201
Beispiel #19
0
    def post(self):
        data = self.parser.parse_args()
        username = data['username']

        if username == "admin":
            if UserModel.set_master_admin(data['password'], 4):
                return {
                    'user': UserModel.find_by_username(username).json()
                }, 201
            else:
                return {'message': 'Admin already set.'}, 400

        if UserModel.find_by_username(username):
            return {"message": f"User {username} already exists."}, 400

        user = UserModel(**data)
        user.save()

        return {"message": f"User {username} registered."}, 201
Beispiel #20
0
    def test_crud(self):
        with self.app_context():
            user = UserModel('test_username', 'A12345678')

            self.assertIsNone(
                UserModel.find_by_username('test_username'),
                "Found an user with name 'test_username' before save_to_db")
            self.assertIsNone(UserModel.find_by_id(1),
                              "Found an user with id '1' before save_to_db")

            user.save_to_db()

            self.assertIsNotNone(
                UserModel.find_by_username('test_username'),
                "Did not find an user with name 'test_username' after save_to_db"
            )
            self.assertIsNotNone(
                UserModel.find_by_id(1),
                "Did not find an user with id '1' after save_to_db")
Beispiel #21
0
    def post(self):
        user = UserModel.find_by_username(ns.payload.get('username'))
        if not user:
            ns.abort(404)

        if safe_str_cmp(user.password, ns.payload.get('password')):
            return dict(access_token=create_access_token(user.id),
                        refresh_token=create_refresh_token(user.id))
        else:
            ns.abort(403)
Beispiel #22
0
    def get(self, community_id, id):
        user = UserModel.find_by_username(get_jwt_identity())
        refuel = RefuelModel.find_by_id(id)

        if not refuel:
            abort(404, message=REFUEL_DOESNT_EXIST)

        if user.id not in [u.id for u in refuel.community.users]:
            abort(401, message=UNAUTHORIZED)

        return refuel, 200
Beispiel #23
0
    def post(self):
        request_data = request.get_json()
        username = request_data['username']
        password = request_data['password']
        user = UserModel.find_by_username(username)
        # check the SHA256 hash of given and stored to password to see if they match
        if user and check_password_hash(user.password, password):
            access_token = create_access_token(identity=user.id)
            return {"access_token": access_token}, 200

        return {"message": "Invalid Login data"}, 400
Beispiel #24
0
    def get(self, community_id):

        user = UserModel.find_by_username(get_jwt_identity())
        community = CommunityModel.find_by_id(community_id)

        if not community:
            abort(400, message=COMMUNIY_DOESNT_EXIST)

        if user.id not in [u.id for u in community.users]:
            abort(401, message=UNAUTHORIZED)

        return TourModel.find_running_by_community(community_id), 200
Beispiel #25
0
    def get(self, community_id, id):

        tour = TourModel.find_by_id(id)
        user = UserModel.find_by_username(get_jwt_identity())

        if not tour:
            abort(404, message=TOUR_NOT_FOUND)

        if user.id not in [u.id for u in tour.community.users]:
            abort(401, message=UNAUTHORIZED)

        return tour, 200
    def get(self, community_id):
        tasks: List[TaskModel] = TaskModel.find_by_community(community_id)
        community: CommunityModel = CommunityModel.find_by_id(community_id)
        community_member_ids = [m.id for m in community.users]
        user = UserModel.find_by_username(get_jwt_identity())

        if user.id not in community_member_ids:
            abort(401, message=UNAUTHORIZED)

        set_km_to_next_instance(tasks)

        return tasks, 200
Beispiel #27
0
 def post(cls):
     data = _user_parser.parse_args()
     user = UserModel.find_by_username(data['username'])
     # this is what 'authenticate used to do
     if user and safe_str_cmp(user.password, data['password']):
         # identity = what the 'identity' function used to do
         access_token = create_access_token(identity=user.id, fresh=True)
         refresh_token = create_refresh_token(user.id)
         return {
             'access_token': access_token,
             'refresh_token': refresh_token
         }, 200
     return {'message': 'Invalid credentials.'}, 401
Beispiel #28
0
    def get(self, id):
        community = CommunityModel.find_by_id(id)
        user = UserModel.find_by_username(get_jwt_identity())

        if not community:
            abort(404, message=COMMUNIY_DOESNT_EXIST)

        if user.id not in [u.id for u in community.users]:
            abort(401, message=UNAUTHORIZED)

        debts = DebtModel.find_unsettled_by_community(id)

        return debts, 200
Beispiel #29
0
    def delete(self, username):
        identity = current_identity
        if identity.super_user != 1:
            return {'message': 'You are not authorized.'}, 403

        if identity.username == username:
            return {'message': 'You cannot delete yourself.'}, 500

        user = UserModel.find_by_username(username)
        if user:
            user.delete_from_db()

        return {'message': 'User deleted.'}
    def get(self):
        user = UserModel.find_by_username(get_jwt_identity())
        all_communities = CommunityModel.return_all()
        user_communities = [
            c for c in all_communities if user.id in [u.id for u in c.users]
        ]

        task_instances = []
        for c in user_communities:
            task_instances += TaskInstanceModel.find_by_community(c.id)
        open_task_instances = [i for i in task_instances if i.is_open]

        return open_task_instances, 200