Ejemplo n.º 1
0
def register_user():
    # get post data
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    username = post_data.get('username')
    email = post_data.get('email')
    password = post_data.get('password')
    if not password or not username or not email:
        raise InvalidPayload()
    # check for existing user
    user = User.first(or_(User.username == username, User.email == email))
    if not user:
        # add new user to db
        new_user = User(username=username, email=email, password=password)
        with session_scope(db.session) as session:
            session.add(new_user)

        # need another scope if not new_user does not exists yet
        with session_scope(db.session) as session:
            token = new_user.encode_email_token()
            new_user.email_token_hash = bcrypt.generate_password_hash(
                token, current_app.config.get('BCRYPT_LOG_ROUNDS')).decode()

        if not current_app.testing:
            from project.api.common.utils.mails import send_registration_email
            send_registration_email(new_user, token.decode())

        # save the device
        if all(x in request.headers for x in [
                Constants.HttpHeaders.DEVICE_ID,
                Constants.HttpHeaders.DEVICE_TYPE
        ]):
            device_id = request.headers.get(Constants.HttpHeaders.DEVICE_ID)
            device_type = request.headers.get(
                Constants.HttpHeaders.DEVICE_TYPE)
            with session_scope(db.session):
                Device.create_or_update(device_id=device_id,
                                        device_type=device_type,
                                        user=user)
        # generate auth token
        auth_token = new_user.encode_auth_token()
        return {
            'status': 'success',
            'message': 'Successfully registered.',
            'auth_token': auth_token.decode()
        }, 201
    else:
        # user already registered, set False to device.active
        if Constants.HttpHeaders.DEVICE_ID in request.headers:
            device_id = request.headers.get(Constants.HttpHeaders.DEVICE_ID)
            device = Device.first_by(device_id=device_id)
            if device:
                with session_scope(db.session):
                    device.active = False
        raise BusinessException(message='Sorry. That user already exists.')
Ejemplo n.º 2
0
def register_device():
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    device_id = post_data.get('device_id')
    device_type = post_data.get('device_type')
    if not device_id or not device_type:
        raise InvalidPayload()
    pn_token = post_data.get('pn_token')
    with session_scope(db.session):
        Device.create_or_update(device_id=device_id,
                                device_type=device_type,
                                pn_token=pn_token)
    return {'status': 'success', 'message': 'Device successfully registered.'}
Ejemplo n.º 3
0
def connect_device_with_logged_in_user(user_id: int, device_id: str):
    user = User.get(user_id)
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    device_type = post_data.get('device_type')
    if not device_type:
        raise InvalidPayload()
    pn_token = post_data.get('pn_token')
    with session_scope(db.session):
        Device.create_or_update(device_id=device_id,
                                device_type=device_type,
                                user=user,
                                pn_token=pn_token)
    return {'status': 'success', 'message': 'Device successfully registered.'}
Ejemplo n.º 4
0
def send_notification_to_user(user: User, message_title: str,
                              message_body: str):
    active_devices = Device.query_active_devices_for_user(user).all()
    pn_tokens = [device.pn_token for device in active_devices]
    send_async_push_notifications.delay(message_title=message_title,
                                        message_body=message_body,
                                        pn_tokens=pn_tokens)
Ejemplo n.º 5
0
    def test_device_registration(self):
        with self.client:
            user = add_user('test', '*****@*****.**', 'test', roles=UserRole.USER)
            resp_login = self.client.post(
                '/v1/auth/login',
                data=json.dumps(dict(
                    email='*****@*****.**',
                    password='******'
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json')]
            )
            device_id = uuid.uuid4().hex
            pn_token = uuid.uuid4().hex
            response = self.client.put(
                f'/v1/devices/{device_id}',
                data=json.dumps(dict(
                    device_id=device_id,
                    device_type='apple',
                    pn_token=pn_token
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json'), (Constants.HttpHeaders.AUTHORIZATION, 'Bearer ' + json.loads(resp_login.data.decode())['auth_token'])]
            )
            data = json.loads(response.data.decode())
            self.assertEqual(data['status'], 'success')
            self.assertEqual(data['message'], 'Device successfully registered.')
            self.assertEqual(response.content_type, 'application/json')
            self.assertEqual(response.status_code, 200)

            device = Device.first_by(device_id=device_id)
            self.assertEqual(device.pn_token, pn_token)
            self.assertEqual(device.device_type, 'apple')
            self.assertEqual(device.active, True)
            self.assertEqual(device.user_id, user.id)
Ejemplo n.º 6
0
def logout_user(_):
    if Constants.HttpHeaders.DEVICE_ID in request.headers:
        device_id = request.headers.get(Constants.HttpHeaders.DEVICE_ID)
        device = Device.first_by(device_id=device_id)
        if device:
            with session_scope(db.session):
                device.active = False
    return {'status': 'success', 'message': 'Successfully logged out.'}
Ejemplo n.º 7
0
def login_user():
    # get post data
    post_data = request.get_json()
    if not post_data:
        raise InvalidPayload()
    email = post_data.get('email')
    password = post_data.get('password')
    if not password:
        raise InvalidPayload()

    user = User.first_by(email=email)
    if user and bcrypt.check_password_hash(user.password, password):
        # register device if needed
        if all(x in request.headers for x in [
                Constants.HttpHeaders.DEVICE_ID,
                Constants.HttpHeaders.DEVICE_TYPE
        ]):
            device_id = request.headers.get(Constants.HttpHeaders.DEVICE_ID)
            device_type = request.headers.get(
                Constants.HttpHeaders.DEVICE_TYPE)
            with session_scope(db.session):
                Device.create_or_update(device_id=device_id,
                                        device_type=device_type,
                                        user=user)
        auth_token = user.encode_auth_token()
        return {
            'status': 'success',
            'message': 'Successfully logged in.',
            'auth_token': auth_token.decode()
        }
    else:
        # user is not logged in, set False to device.active
        if Constants.HttpHeaders.DEVICE_ID in request.headers:
            device_id = request.headers.get(Constants.HttpHeaders.DEVICE_ID)
            device = Device.first_by(device_id=device_id)
            if device:
                with session_scope(db.session):
                    device.active = False
        raise NotFoundException(message='User does not exist.')
Ejemplo n.º 8
0
def add_device(device_id: str,
               device_type: str,
               active: bool = True,
               pn_token: str = None,
               user: User = None,
               created_at: datetime = datetime.datetime.utcnow()):
    device = Device(device_id=device_id,
                    device_type=device_type,
                    pn_token=pn_token,
                    active=active,
                    user=user,
                    created_at=created_at)
    db.session.add(device)
    db.session.commit()
    return device
Ejemplo n.º 9
0
 def push_notification_data(self):
     event_descriptor = self.event_descriptor
     message_template = event_descriptor.description
     if self.entity_description:
         message_template = message_template.replace(
             "{1}", self.entity_description)
     if self.entity_2_description:
         message_template = message_template.replace(
             "{2}", self.entity_2_description)
     if self.entity_3_description:
         message_template = message_template.replace(
             "{3}", self.entity_3_description)
     devices = Device.query_active_devices_for_group(
         group=self.group, discard_user_ids=[self.creator_id]).all()
     pn_tokens = [device.pn_token for device in devices]
     return "Hi", message_template, pn_tokens
Ejemplo n.º 10
0
 def test_add_user_duplicate_device_id(self):
     add_device(device_id="device_id", device_type="apple")
     duplicate_device = Device(device_id="device_id", device_type="android")
     db.session.add(duplicate_device)
     self.assertRaises(IntegrityError, db.session.commit)