Example #1
0
    def delete(self):
        try:
            self.request.user.buddies_to_self.remove(self.request.context)
        except ValueError:
            # It's possible that the relationship only existed one way
            # which means one will raise a key error
            pass

        try:
            self.request.user.self_to_buddies.remove(self.request.context)
        except ValueError:
            # It's possible that the relationship only existed one way
            # which means one will raise a key error
            pass

        try:
            persist(self.request.user)
        except:
            log.critical("Something went wrong deleting a buddy",
                         exc_info=True)
            rollback()
        finally:
            commit()

        # Invalidate the cached recommended buddies
        RedisSession().session.delete(self.redis_key)
        raise HTTPNoContent
Example #2
0
    def post(self):
        try:
            result, errors = OAuthClientSchema(
                strict=True,
                only=('name', 'client_type')).load(self.request.json_body)
        except ValidationError as e:
            raise HTTPBadRequest(json=str(e))

        response_body = {
            "client_id": uuid.uuid4(),
            "client_secret": get_secure_token()
        }

        result.update(response_body)

        client = OAuthClient()
        client.set_fields(result)

        try:
            persist(client)
        except:
            log.critical("Something went wrong saving the client",
                         exc_info=True)
            rollback()
        finally:
            commit()

        self.request.response.status_code = 201
        return response_body
    def post(self):
        schema = DeviceSchema(strict=True, only=('name', 'device_address',
                                                 'device_class'))
        try:
            # The device address should first be validated to check if no
            # device already exists with the same address.
            schema.validate_device_address(self.request.json_body)
            result, errors = schema.load(self.request.json_body)
        except (ValidationError, NotUniqueException) as e:
            raise HTTPBadRequest(json={'message': str(e)})

        device = Device()
        device.id = uuid.uuid4()
        device.user = self.request.user
        device.set_fields(result)
        response_body = DeviceSchema().dump(device).data

        try:
            persist(device)
        except:
            log.critical("Something went wrong saving the device",
                         exc_info=True)
            rollback()
            raise HTTPInternalServerError
        finally:
            commit()

        self.request.response.status_code = 201

        return response_body
Example #4
0
def login(request):
    _logout(request)
    schema = LoginSchema(strict=True)
    try:
        result, errors = schema.load(request.json_body)
    except ValidationError as e:
        raise HTTPBadRequest(json={'message': str(e)})

    try:
        user = get_user_by_email(email=result['email'])
    except NoResultFound:
        raise HTTPBadRequest(
            json={"message": "Email address and password don't match"})

    if not check_password(result['password'], user.password_hash,
                          user.password_salt):
        raise HTTPBadRequest(
            json={"message": "Username or password incorrect"})

    headers = remember(request, str(user.id))
    user.last_login = datetime.datetime.now()
    try:
        persist(user)
    except:
        log.critical("something went wrong updating the user login date",
                     exc_info=True)
        rollback()
    finally:
        commit()

    # Continue logging in the user. Being unable to update the login date
    # should not prevent the user from logging in.
    request.response.headerlist.extend(headers)
Example #5
0
    def post(self):
        schema = DeviceSchema(strict=True,
                              only=('name', 'device_address', 'device_class'))
        try:
            # The device address should first be validated to check if no
            # device already exists with the same address.
            schema.validate_device_address(self.request.json_body)
            result, errors = schema.load(self.request.json_body)
        except (ValidationError, NotUniqueException) as e:
            raise HTTPBadRequest(json={'message': str(e)})

        device = Device()
        device.id = uuid.uuid4()
        device.user = self.request.user
        device.set_fields(result)
        response_body = DeviceSchema().dump(device).data

        try:
            persist(device)
        except:
            log.critical("Something went wrong saving the device",
                         exc_info=True)
            rollback()
            raise HTTPInternalServerError
        finally:
            commit()

        self.request.response.status_code = 201

        return response_body
Example #6
0
    def post(self):
        try:
            result, errors = OAuthClientSchema(
                strict=True,
                only=('name', 'client_type')).load(self.request.json_body)
        except ValidationError as e:
            raise HTTPBadRequest(json=str(e))

        response_body = {
            "client_id": uuid.uuid4(),
            "client_secret": get_secure_token()
        }

        result.update(response_body)

        client = OAuthClient()
        client.set_fields(result)

        try:
            persist(client)
        except:
            log.critical("Something went wrong saving the client",
                         exc_info=True)
            rollback()
        finally:
            commit()

        self.request.response.status_code = 201
        return response_body
Example #7
0
def login(request):
    _logout(request)
    schema = LoginSchema(strict=True)
    try:
        result, errors = schema.load(request.json_body)
    except ValidationError as e:
        raise HTTPBadRequest(json={'message': str(e)})

    try:
        user = get_user_by_email(email=result['email'])
    except NoResultFound:
        raise HTTPBadRequest(
            json={"message": "Email address and password don't match"})

    if not check_password(result['password'], user.password_hash,
                          user.password_salt):
        raise HTTPBadRequest(
            json={"message": "Username or password incorrect"})

    headers = remember(request, str(user.id))
    user.last_login = datetime.datetime.now()
    try:
        persist(user)
    except:
        log.critical("something went wrong updating the user login date",
                     exc_info=True)
        rollback()
    finally:
        commit()

    # Continue logging in the user. Being unable to update the login date
    # should not prevent the user from logging in.
    request.response.headerlist.extend(headers)
    def checkin(self):
        schema = DeviceSchema(strict=True)
        try:
            result, errors = schema.load(self.request.json_body)
            device = self.request.context.get_checkin_device(
                result['device_address'])

        except ValidationError as e:
            raise HTTPBadRequest(json={'message': str(e)})
        except NoResultFound as e:
            raise HTTPNotFound(json={'message': str(e)})

        device.last_used = datetime.datetime.now()

        activity = device.user.active_activity
        response = {
            "user": "******".format(
                device.user.first_name, device.user.last_name)
        }

        # if there's an active activy for the user the user needs to be checked
        # out
        if activity:
            activity.end_date = datetime.datetime.now()
            response["status"] = "checked out"

        else:
            activity = UserActivity()
            activity.start_date = datetime.datetime.now()
            activity.user = device.user
            activity.gym = get_gym_by_MAC_address(result['client_address'])
            response["status"] = "checked in"

            r = get_weather(self.settings, activity.gym)
            weather = Weather()
            if r.get('rain'):
                weather.raining_outside = True
            try:
                weather.temperature = r['main']['temp']
            except KeyError:
                log.warn('Temparature not found')

            activity.weather = weather

        try:
            persist(device)
            persist(activity)
        except:
            log.critical("Something went wrong checking in",
                         exc_info=True)
            rollback()
        finally:
            commit()
        return response
Example #9
0
    def checkin(self):
        schema = DeviceSchema(strict=True)
        try:
            result, errors = schema.load(self.request.json_body)
            device = self.request.context.get_checkin_device(
                result['device_address'])

        except ValidationError as e:
            raise HTTPBadRequest(json={'message': str(e)})
        except NoResultFound as e:
            raise HTTPNotFound(json={'message': str(e)})

        device.last_used = datetime.datetime.now()

        activity = device.user.active_activity
        response = {
            "user": "******".format(device.user.first_name,
                                   device.user.last_name)
        }

        # if there's an active activy for the user the user needs to be checked
        # out
        if activity:
            activity.end_date = datetime.datetime.now()
            response["status"] = "checked out"

        else:
            activity = UserActivity()
            activity.start_date = datetime.datetime.now()
            activity.user = device.user
            activity.gym = get_gym_by_MAC_address(result['client_address'])
            response["status"] = "checked in"

            r = get_weather(self.settings, activity.gym)
            weather = Weather()
            if r.get('rain'):
                weather.raining_outside = True
            try:
                weather.temperature = r['main']['temp']
            except KeyError:
                log.warn('Temparature not found')

            activity.weather = weather

        try:
            persist(device)
            persist(activity)
        except:
            log.critical("Something went wrong checking in", exc_info=True)
            rollback()
        finally:
            commit()
        return response
Example #10
0
    def save(self, music_preference):
        try:
            result, errors = MusicPreferenceSchema(strict=True).load(
                self.request.json_body)
        except ValidationError as e:
            raise HTTPBadRequest(json={'message': str(e)})

        music_preference.set_fields(result)
        try:
            persist(music_preference)
        except:
            log.critical("Something went wrong saving the music_preference",
                         exc_info=True)
            rollback()
            raise HTTPInternalServerError
        finally:
            commit()
Example #11
0
    def save(self, sport_schedule):
        try:
            result, errors = SportScheduleSchema(strict=True).load(
                self.request.json_body)
        except ValidationError as e:
            raise HTTPBadRequest(json={'message': str(e)})

        sport_schedule.user = self.request.user
        sport_schedule.set_fields(result)

        try:
            persist(sport_schedule)
        except:
            log.critical("Something went wrong saving the sport schedule",
                         exc_info=True)
            rollback()
            raise HTTPInternalServerError
        finally:
            commit()
    def save(self, user_activity):
        try:
            result, errors = UserActivitySchema(strict=True, only=(
                'end_date')).load(
                self.request.json_body)
        except ValidationError as e:
            raise HTTPBadRequest(json={'message': str(e)})

        user_activity.set_fields(result)

        try:
            persist(user_activity)
        except:
            log.critical("Something went wrong saving the user_activity",
                         exc_info=True)
            rollback()
            raise HTTPInternalServerError
        finally:
            commit()
Example #13
0
    def post(self):
        try:
            result, errors = OAuthAccessTokenSchema(strict=True).load(
                self.request.json_body)
            grant_type = result['grant_type']
        except ValidationError as e:
            raise HTTPBadRequest(json=str(e))

        client = self.request.context.get_client(grant_type)

        if (grant_type == 'client_credentials'
                and client.client_type != 'confidential'):
            raise HTTPBadRequest(
                json={
                    "invalid_client":
                    "Client not authorized\
                    to use this grant type"
                })

        token = OAuthAccessToken()
        token.access_token = get_secure_token()
        token.client = client
        token.expiry_date = (datetime.datetime.now(datetime.timezone.utc) +
                             datetime.timedelta(hours=1))
        token.token_type = 'Bearer'

        try:
            persist(token)
            response_body = OAuthAccessTokenSchema().dump(token).data
        except:
            log.critical("Something went wrong saving the token",
                         exc_info=True)
            rollback()
            raise HTTPInternalServerError
        finally:
            commit()

        # response headers according to RFC 6749
        self.request.response.cache_control = 'no-store'
        self.request.response.pragma = 'no-cache'

        return response_body
Example #14
0
    def post(self):
        try:
            result, errors = OAuthAccessTokenSchema(strict=True).load(
                self.request.json_body)
            grant_type = result['grant_type']
        except ValidationError as e:
            raise HTTPBadRequest(json=str(e))

        client = self.request.context.get_client(grant_type)

        if (grant_type == 'client_credentials' and
                client.client_type != 'confidential'):
            raise HTTPBadRequest(json={
                    "invalid_client": "Client not authorized\
                    to use this grant type"
                })

        token = OAuthAccessToken()
        token.access_token = get_secure_token()
        token.client = client
        token.expiry_date = (datetime.datetime.now(datetime.timezone.utc) +
                             datetime.timedelta(hours=1))
        token.token_type = 'Bearer'

        try:
            persist(token)
            response_body = OAuthAccessTokenSchema().dump(token).data
        except:
            log.critical("Something went wrong saving the token",
                         exc_info=True)
            rollback()
            raise HTTPInternalServerError
        finally:
            commit()

        # response headers according to RFC 6749
        self.request.response.cache_control = 'no-store'
        self.request.response.pragma = 'no-cache'

        return response_body
Example #15
0
    def put(self):
        schema = BuddySchema(strict=True)

        try:
            result, errors = schema.load(self.request.json_body)
            schema.validate_user_id(result, self.request.user)
        except ValidationError as e:
            raise HTTPBadRequest(json={'message': str(e)})

        new_buddy = get_user(result['user_id'])

        if not new_buddy:
            raise HTTPNotFound(json={
                'message': 'Could not find the new buddy'
            })

        new_buddy_id = str(new_buddy.id)

        # add the new buddy to the user's existing buddies
        self.request.user.self_to_buddies.append(new_buddy)

        try:
            persist(self.request.user)
            response_body = UserSchema().dump(new_buddy).data
        except:
            log.critical("Something went wrong adding a new buddy",
                         exc_info=True)
            rollback()
        finally:
            commit()

        # If the new buddy was a recommended one we have to search for a new
        # recommendatation
        cached_recommendations = RedisSession().session.get(self.redis_key)
        if (cached_recommendations and
                new_buddy_id in cached_recommendations.decode('utf-8')):
            # Invalidate the cached recommended buddies
            RedisSession().session.delete(self.redis_key)

        return response_body
    def save(self, cardio_activity):
        try:
            result, errors = CardioActivitySchema(strict=True).load(
                self.request.json_body)
        except ValidationError as e:
            raise HTTPBadRequest(json={'message': str(e)})

        cardio_activity.set_fields(result)

        try:
            persist(cardio_activity)
            flush()
            data = CardioActivitySchema().dump(cardio_activity).data
        except:
            log.critical('Something went wrong saving the cardio activity',
                         exc_info=True)
            rollback()
            raise HTTPInternalServerError
        finally:
            commit()

        return data
    def save(self, cardio_activity):
        try:
            result, errors = CardioActivitySchema(strict=True).load(
                self.request.json_body)
        except ValidationError as e:
            raise HTTPBadRequest(json={'message': str(e)})

        cardio_activity.set_fields(result)

        try:
            persist(cardio_activity)
            flush()
            data = CardioActivitySchema().dump(cardio_activity).data
        except:
            log.critical('Something went wrong saving the cardio activity',
                         exc_info=True)
            rollback()
            raise HTTPInternalServerError
        finally:
            commit()

        return data