Ejemplo n.º 1
0
    def post(self):
        """
        Creating new user
        """
        data = request.json

        # check existence of user by email
        if User.is_exists_by_email(data['email']):
            raise ErrorResource(409, message="Email is already in use.")

        # create user
        user = User(**data)
        db.session.add(user)
        db.session.commit()

        # scheduling registration email
        MailTask.send(to=user.email,
                      template="mail/welcome",
                      params={
                          'first_name': user.firstName,
                          'last_name': user.lastName,
                          'host_name': app.config['SERVER_NAME']
                      })

        return response(user.to_dict(), status_code=201)
Ejemplo n.º 2
0
    def login(self):
        """
        """
        # TODO(vojta) save success login, improve token stuff
        data = request.json

        # find user by email and if is not existing or passwd
        # is incorect will raise error 403
        user = User.query.filter_by(email=data['email']).first()
        if user is None or user.compare_password(data['password']) is False:
            raise ErrorResource(403, message="Invalid password or email.")

        # non active users are not allowed
        if user.isActive is False:
            raise ErrorResource(403, message="Account is not active.")

        # create user token for user
        token = None
        agent = request.headers.get('User-Agent')
        if agent is not None:
            token = UserToken.query \
                        .filter_by(userId=user.id) \
                        .filter_by(agent=agent) \
                        .first()
        if token is None:
            token = UserToken(userId=user.id, agent=agent)
            db.session.add(token)
            db.session.commit()

        # create payload response
        return response({
            'uuid': user.uuid,
            'token': token.token
        },
                        status_code=200)
Ejemplo n.º 3
0
        def on_validation_error(error):
            payload = None
            message, errors = get_validation_data(error)
            if errors is not None:
                payload = {'errors': errors}

            return response(payload, status_code=400, message=message)
Ejemplo n.º 4
0
        def on_validation_error(error):
            payload = None
            message, errors = get_validation_data(error)
            if errors is not None:
                payload = { 'errors': errors }

            return response(payload, status_code=400, message=message)
Ejemplo n.º 5
0
    def index(self, **kwargs):
        """
        Getting list of all users, only with admin privileges
        """
        users = User.query.order_by(User.lastName.asc()).all()

        return response([user.to_dict() for user in users])
Ejemplo n.º 6
0
    def post(self):
        """
        Creating new user
        """
        data = request.json

        # check existence of user by email
        if User.is_exists_by_email(data['email']):
            raise ErrorResource(409, message="Email is already in use.")

        # create user
        user = User(**data)
        db.session.add(user)
        db.session.commit()

        # scheduling registration email
        MailTask.send(to=user.email,
                      template="mail/welcome",
                      params={
                          'first_name': user.firstName,
                          'last_name': user.lastName,
                          'host_name': app.config['SERVER_NAME']
                      })

        return response(user.to_dict(), status_code=201)
Ejemplo n.º 7
0
    def index(self, **kwargs):
        """
        Getting list of all users, only with admin privileges
        """
        users = User.query.order_by(User.lastName.asc()).all()

        return response([user.to_dict() for user in users])
Ejemplo n.º 8
0
    def index(self, **kwargs):
        """
        Getting list of user's templates
        """
        user = kwargs.get('user')
        templates = user.templates.order_by(Template.label.asc())

        return response([template.to_dict() for template in templates])
Ejemplo n.º 9
0
        def on_sql_alchemy_error(error):
            """ Error handler for sqlalchemy IntegrityError exception """
            # do rollback
            db.session.rollback()
            # log it
            current_app.logger.error(traceback.format_exc())

            return response(None, status_code=500)
Ejemplo n.º 10
0
    def delete(self, user, **kwargs):
        """
        Delete user
        """
        db.session.delete(user)
        db.session.commit()

        return response(user.to_dict())
Ejemplo n.º 11
0
    def index(self, **kwargs):
        """
        Getting list of user's templates
        """
        user = kwargs.get('user')
        templates = user.templates.order_by(Template.label.asc())

        return response([template.to_dict() for template in templates])
Ejemplo n.º 12
0
        def on_sql_alchemy_error(error):
            """ Error handler for sqlalchemy IntegrityError exception """
            # do rollback
            db.session.rollback()
            # log it
            current_app.logger.error(traceback.format_exc())

            return response(None, status_code=500)
Ejemplo n.º 13
0
    def index(self, **kwargs):
        """
        Returning list of applications for specific user
        """
        user = kwargs.get('user')
        applications = user.applications.order_by(Application.label.asc()).all()

        return response([app.to_dict() for app in applications])
Ejemplo n.º 14
0
    def delete(self, user, **kwargs):
        """
        Delete user
        """
        db.session.delete(user)
        db.session.commit()

        return response(user.to_dict())
Ejemplo n.º 15
0
    def put(self, **kwargs):
        """
        Updateing existing template
        """
        template = kwargs.get('template')
        template.update(request.json)
        db.session.commit()

        return response(template.to_dict())
Ejemplo n.º 16
0
    def regenerate(self, **kwargs):
        """
        Regenerate API token
        """
        application = kwargs.get('application')
        application.regenerate_token()
        db.session.commit()

        return response(application.to_dict(['uuid', 'token']))
Ejemplo n.º 17
0
    def put(self, **kwargs):
        """
        Updateing existing template
        """
        template = kwargs.get('template')
        template.update(request.json)
        db.session.commit()

        return response(template.to_dict())
Ejemplo n.º 18
0
    def index(self, **kwargs):
        """
        Getting list of outbox messages
        """
        user = kwargs.get('user')
        app = kwargs.get('application')
        groups = Outbox.get_all(user_id=user.id,
                                application_id=app.id if app else None)

        return response(groups)
Ejemplo n.º 19
0
    def delete(self, **kwargs):
        """
        Delete template
        """
        # delete template
        template = kwargs.get('template')
        db.session.delete(template)
        db.session.commit()

        return response(template.to_dict())
Ejemplo n.º 20
0
    def index(self, **kwargs):
        """
        Returning list of sent items
        """
        user = kwargs.get('user')
        app = kwargs.get('application')
        messages = SentItem.get(user_id=user.id,
                                application_id=app.id if app else None)

        return response(messages)
Ejemplo n.º 21
0
    def index(self, **kwargs):
        """
        Returning list of sent items
        """
        user = kwargs.get('user')
        app = kwargs.get('application')
        messages = SentItem.get(user_id=user.id,
                                application_id=app.id if app else None)

        return response(messages)
Ejemplo n.º 22
0
    def delete(self, **kwargs):
        """
        Delete template
        """
        # delete template
        template = kwargs.get('template')
        db.session.delete(template)
        db.session.commit()

        return response(template.to_dict())
Ejemplo n.º 23
0
    def index(self, **kwargs):
        """
        Getting list of outbox messages
        """
        user = kwargs.get('user')
        app = kwargs.get('application')
        groups = Outbox.get_all(user_id=user.id,
                                application_id=app.id if app else None)

        return response(groups)
Ejemplo n.º 24
0
    def delete(self, **kwargs):
        """
        Delete user contact
        """
        contact = kwargs.get('contact')

        # delete template
        db.session.delete(contact)
        db.session.commit()

        return response(contact.to_dict())
Ejemplo n.º 25
0
    def delete(self, **kwargs):
        """
        Delete user contact
        """
        tag = kwargs.get('tag')

        # delete template
        db.session.delete(tag)
        db.session.commit()

        return response(tag.to_dict())
Ejemplo n.º 26
0
    def delete(self, **kwargs):
        """
        Delete user application
        """
        application = kwargs.get('application')

        # delete template
        db.session.delete(application)
        db.session.commit()

        return response(application.to_dict())
Ejemplo n.º 27
0
    def put(self, **kwargs):
        """
        Updating user contact
        """
        contact = kwargs.get('contact')

        # save to db
        contact.update(request.json)
        db.session.commit()

        return response(contact.to_dict())
Ejemplo n.º 28
0
    def delete(self, **kwargs):
        """
        Delete user contact
        """
        contact = kwargs.get('contact')

        # delete template
        db.session.delete(contact)
        db.session.commit()

        return response(contact.to_dict())
Ejemplo n.º 29
0
    def put(self, **kwargs):
        """
        Updating user contact
        """
        contact = kwargs.get('contact')

        # save to db
        contact.update(request.json)
        db.session.commit()

        return response(contact.to_dict())
Ejemplo n.º 30
0
    def post(self, **kwargs):
        """
        Creating new user template
        """
        user = kwargs.get('user')

        # create and save template
        template = Template(**request.json)
        template.userId = user.id
        db.session.add(template)
        db.session.commit()

        return response(template.to_dict(), status_code=201)
Ejemplo n.º 31
0
    def post(self, **kwargs):
        """
        Creating new user template
        """
        user = kwargs.get('user')

        # create and save template
        template = Template(**request.json)
        template.userId = user.id
        db.session.add(template)
        db.session.commit()

        return response(template.to_dict(), status_code=201)
Ejemplo n.º 32
0
class TagsResource(FlaskView):
    """ Tags endpoints """

    route_base = '/users/<uuid:user_uuid>/tags/'

    @decorators.auth()
    def index(self, **kwargs):
        """
        Returning list of tags for specific user
        """
        user = kwargs.get('user')

        # search or not
        search = request.args.get('search')
        tags = user.tags
        if search is not None:
            like = "%{0}%".format(search)
            tags = tags.filter(Tag._label.like(like))

        tags = tags.order_by(Tag._label.asc())

        return response([tag.to_dict() for tag in tags.all()])


    @route('/<uuid:tag_uuid>/')
    @decorators.auth()
    def get(self, **kwargs):
        """
        Get user tag
        """
        tag = kwargs.get('tag')
        return response(tag.to_dict())


    @decorators.auth()
    @decorators.jsonschema_validate(post.schema)
    def post(self, **kwargs):
        """
        Creating user tag
        """
        try:
            # save tag
            user = kwargs.get('user')
            tag = Tag(userId=user.id, **request.json)
            db.session.add(tag)
            db.session.commit()
        except IntegrityError, e:
            db.session.rollback()
            raise ErrorResource(409, message="Tag is already exists.")

        return response(tag.to_dict(), status_code=201)
Ejemplo n.º 33
0
    def get(self, group, **kwargs):
        """
        Getting outbox group
        """
        user = kwargs.get('user')
        app = kwargs.get('application')
        group = Outbox.get(group=group,
                           user_id=user.id,
                           application_id=app.id if app else None)
        if group is None:
            raise ErrorResource(message='Outbox group not found.',
                                status_code=404)

        return response(group)
Ejemplo n.º 34
0
    def delete(self, sentitem, **kwargs):
        """
        Delete sent message
        """
        user = kwargs.get('user')
        app = kwargs.get('application')

        SentItem.remove(uuid=sentitem,
                        user_id=user.id,
                        application_id=app.id if app else None)

        db.session.commit()

        return response({'uuid': sentitem})
Ejemplo n.º 35
0
    def get(self, group, **kwargs):
        """
        Getting outbox group
        """
        user = kwargs.get('user')
        app = kwargs.get('application')
        group = Outbox.get(group=group,
                           user_id=user.id,
                           application_id=app.id if app else None)
        if group is None:
            raise ErrorResource(message='Outbox group not found.',
                                status_code=404)

        return response(group)
Ejemplo n.º 36
0
    def post(self, **kwargs):
        """
        Creating user contact
        """
        user = kwargs.get('user')

        # create and save contact
        # TODO(vojta) handling unique contacts ?
        contact = Contact(userId=user.id, **request.json)
        contact.tags = request.json.get('tags')
        db.session.add(contact)
        db.session.commit()

        return response(contact.to_dict(), status_code=201)
Ejemplo n.º 37
0
    def post(self, **kwargs):
        """
        Creating user contact
        """
        user = kwargs.get('user')

        # create and save contact
        # TODO(vojta) handling unique contacts ?
        contact = Contact(userId=user.id, **request.json)
        contact.tags = request.json.get('tags')
        db.session.add(contact)
        db.session.commit()

        return response(contact.to_dict(), status_code=201)
Ejemplo n.º 38
0
    def delete(self, group, **kwargs):
        """
        Delete outbox message
        """
        app = kwargs.get('application')
        app_id = app.id if app else None

        Outbox.query \
              .filter(Outbox.group == group) \
              .filter(Outbox.applicationId == app_id) \
              .delete()
        db.session.commit()

        return response({'id': group})
Ejemplo n.º 39
0
    def delete(self, **kwargs):
        """
        Delete user contact
        """
        user = kwargs.get('user', request.user)
        inbox = kwargs.get('inbox')

        # admin check, to be sure that non admin users can delete inboxes
        if inbox.userId != user.id and not user.is_admin():
            raise ErrorResource(message='Not have permissions.', status_code=403)

        db.session.delete(inbox)
        db.session.commit()

        return response(inbox.to_dict())
Ejemplo n.º 40
0
    def messages(self, **kwargs):
        """
        GET stats count for inbox, sent and outbox
        """
        user = kwargs.get('user')
        app = kwargs.get('application')
        payload = {}
        elements = {'sent': SentItem, 'inbox': Inbox, 'outbox': Outbox}

        for key, model in elements.iteritems():
            query = model.query.filter_by(userId=user.id)
            if app:
                query = query.filter_by(applicationId=app.id)
            payload[key] = query.count()

        return response(payload)
Ejemplo n.º 41
0
    def delete(self, sentitem, **kwargs):
        """
        Delete sent message
        """
        user = kwargs.get('user')
        app = kwargs.get('application')

        SentItem.remove(uuid=sentitem,
                        user_id=user.id,
                        application_id=app.id if app else None)

        db.session.commit()

        return response({
            'uuid': sentitem
        })
Ejemplo n.º 42
0
    def delete(self, group, **kwargs):
        """
        Delete outbox message
        """
        app = kwargs.get('application')
        app_id = app.id if app else None

        Outbox.query \
              .filter(Outbox.group == group) \
              .filter(Outbox.applicationId == app_id) \
              .delete()
        db.session.commit()

        return response({
            'id': group
        })
Ejemplo n.º 43
0
    def delete(self, **kwargs):
        """
        Delete user contact
        """
        user = kwargs.get('user', request.user)
        inbox = kwargs.get('inbox')

        # admin check, to be sure that non admin users can delete inboxes
        if inbox.userId != user.id and not user.is_admin():
            raise ErrorResource(message='Not have permissions.',
                                status_code=403)

        db.session.delete(inbox)
        db.session.commit()

        return response(inbox.to_dict())
Ejemplo n.º 44
0
    def index(self, **kwargs):
        """
        Returning list of tags for specific user
        """
        user = kwargs.get('user')

        # search or not
        search = request.args.get('search')
        tags = user.tags
        if search is not None:
            like = "%{0}%".format(search)
            tags = tags.filter(Tag._label.like(like))

        tags = tags.order_by(Tag._label.asc())

        return response([tag.to_dict() for tag in tags.all()])
Ejemplo n.º 45
0
    def external(self, application):
        """
        Creating new message in outbox via application token key
        """
        data = request.json
        send_at = str_to_datetime(data.get('send')) if data.get('send') \
                                                    else datetime.utcnow()

        # put message to queue
        outbox = Outbox.send(user=application.user,
                             application_id=application.id,
                             group=random_string(8),
                             destination_number=data.get('phoneNumber'),
                             message=data.get('message'),
                             send=send_at)

        return response(outbox.to_dict(), status_code=201)
Ejemplo n.º 46
0
    def index(self, **kwargs):
        """
        Returning list of contacts for specific user
        """
        user = kwargs.get('user')

        # search or not
        search = request.args.get('search')
        contacts = user.contacts
        if search is not None:
            like = "%{0}%".format(search)
            contacts = contacts.filter(or_(Contact.firstName.ilike(like),
                                           Contact.lastName.ilike(like)))

        contacts = contacts.order_by(Contact.lastName.asc()).all()

        return response([contact.to_dict() for contact in contacts])
Ejemplo n.º 47
0
    def index(self, **kwargs):
        """
        Returning list of contacts for specific user
        """
        user = kwargs.get('user')

        # search or not
        search = request.args.get('search')
        contacts = user.contacts
        if search is not None:
            like = "%{0}%".format(search)
            contacts = contacts.filter(
                or_(Contact.firstName.ilike(like),
                    Contact.lastName.ilike(like)))

        contacts = contacts.order_by(Contact.lastName.asc()).all()

        return response([contact.to_dict() for contact in contacts])
Ejemplo n.º 48
0
class ApplicationsResource(FlaskView):
    """ Applications endpoints """

    route_base = '/users/<uuid:user_uuid>/applications/'

    @decorators.auth()
    def index(self, **kwargs):
        """
        Returning list of applications for specific user
        """
        user = kwargs.get('user')
        applications = user.applications.order_by(Application.label.asc()).all()

        return response([app.to_dict() for app in applications])


    @route('/<uuid:application_uuid>/')
    @decorators.auth()
    def get(self, **kwargs):
        """
        Get user application
        """
        application = kwargs.get('application')
        return response(application.to_dict())


    @decorators.auth()
    @decorators.jsonschema_validate(post.schema)
    def post(self, **kwargs):
        """
        Creating new user application
        """
        try:
            # create and save application
            user = kwargs.get('user')
            application = Application(**request.json)
            application.userId = user.id
            db.session.add(application)
            db.session.commit()
        except IntegrityError, e:
            db.session.rollback()
            raise ErrorResource(409, message="Prefix is already exists.")

        return response(application.to_dict(), status_code=201)
Ejemplo n.º 49
0
    def messages_range(self, interval, **kwargs):
        """
        GET stats count for inbox, sent and outbox per time intervals
        """
        user = kwargs.get('user')
        app = kwargs.get('application')
        utcnow = datetime.utcnow()
        payload = {}
        elements = {
            'sent': SentItem,
            'inbox': Inbox,
            'outbox': Outbox
        }
        intervals = {
            'lastweek': 7,
            'lastmonth': 31
        }

        # looking for each date stats
        for x in range(0, intervals[interval]):
            date = utcnow.date() - timedelta(days=x)

            # constructing query to get stats for 3 tables at query
            queries = []
            for key, model in elements.iteritems():
                query = db.session \
                          .query(func.count()) \
                          .filter(getattr(model, 'userId') == user.id) \
                          .filter(cast(getattr(model, 'created'), Date) == date)
                if app:
                    query = query.filter(getattr(model, 'applicationId') == app.id)

                query = query.limit(1).label(key)
                queries.append(query)

            counts = db.session.query(*tuple(queries)).one()

            payload[date.isoformat()] = {
                'sent': counts.sent,
                'inbox': counts.inbox,
                'outbox': counts.outbox,
            }

        return response(payload)
Ejemplo n.º 50
0
    def index(self, **kwargs):
        """
        Returning list items in inbox
        """
        user = kwargs.get('user')
        app = kwargs.get('application')
        query = None

        if user is None:
            query = Inbox.query
            if not request.user.is_admin():
                raise ErrorResource(message='Not have permissions.',
                                    status_code=403)
        else:
            query = app.inbox if app else user.inbox

        messages = query.order_by(Inbox.received.desc()).all()

        return response([message.to_dict() for message in messages])
Ejemplo n.º 51
0
    def external(self, application):
        """
        Creating new message in outbox via application token key
        """
        data = request.json
        send_at = str_to_datetime(data.get('send')) if data.get('send') \
                                                    else datetime.utcnow()

        # put message to queue
        outbox = Outbox.send(
            user=application.user,
            application_id=application.id,
            group=random_string(8),
            destination_number=data.get('phoneNumber'),
            message=data.get('message'),
            send=send_at
        )

        return response(outbox.to_dict(), status_code=201)
Ejemplo n.º 52
0
    def messages(self, **kwargs):
        """
        GET stats count for inbox, sent and outbox
        """
        user = kwargs.get('user')
        app = kwargs.get('application')
        payload = {}
        elements = {
            'sent': SentItem,
            'inbox': Inbox,
            'outbox': Outbox
        }

        for key, model in elements.iteritems():
            query = model.query.filter_by(userId=user.id)
            if app:
                query = query.filter_by(applicationId=app.id)
            payload[key] = query.count()

        return response(payload)
Ejemplo n.º 53
0
    def index(self, **kwargs):
        """
        Returning list items in inbox
        """
        user = kwargs.get('user')
        app = kwargs.get('application')
        query = None

        if user is None:
            query = Inbox.query
            if not request.user.is_admin():
                raise ErrorResource(
                    message='Not have permissions.',
                    status_code=403
                )
        else:
            query = app.inbox if app else user.inbox

        messages = query.order_by(Inbox.received.desc()).all()

        return response([message.to_dict() for message in messages])
Ejemplo n.º 54
0
    def login(self):
        """
        """
        # TODO(vojta) save success login, improve token stuff
        data = request.json

        # find user by email and if is not existing or passwd
        # is incorect will raise error 403
        user = User.query.filter_by(email=data['email']).first()
        if user is None or user.compare_password(data['password']) is False:
            raise ErrorResource(
                403,
                message="Invalid password or email."
            )

        # non active users are not allowed
        if user.isActive is False:
            raise ErrorResource(403, message="Account is not active.")

        # create user token for user
        token = None
        agent = request.headers.get('User-Agent')
        if agent is not None:
            token = UserToken.query \
                        .filter_by(userId=user.id) \
                        .filter_by(agent=agent) \
                        .first()
        if token is None:
            token = UserToken(userId=user.id, agent=agent)
            db.session.add(token)
            db.session.commit()

        # create payload response
        return response({
            'uuid': user.uuid,
            'token': token.token
        }, status_code=200)
Ejemplo n.º 55
0
    def resetPassword(self, token=None, **kwargs):
        """
        Reseting user password
        """
        # get data from payload
        data = request.json
        email = data.get('email')
        password = data.get('password')

        # user
        payload = None
        message = None
        user = None
        if email is not None:
            # find user
            user = User.get_one(email=email)
            if user is None:
                raise ErrorResource(404, message="Invalid email address.")

            # delete all existing tokens
            UserForgotPassword.query.filter_by(userId=user.id).delete()

            # create new token
            expired = datetime.utcnow() + timedelta(minutes=30)
            forgot_password = UserForgotPassword(userId=user.id,
                                                 expired=expired)
            db.session.add(forgot_password)
            db.session.commit()

            # send email
            from smsgw.tasks.mail import MailTask
            MailTask().apply_async(**{
                'kwargs': {
                    'to': [user.email],
                    'template': 'mail/forgotten_password',
                    'params': {
                        'first_name': user.firstName,
                        'last_name': user.lastName,
                        'token': forgot_password.token
                    }
                }
            })

            # set up payload
            message = "On your email has been sent link for change passowrd."

        elif token is not None and password is not None:
            # find request for user password
            forgot_password = UserForgotPassword.get_one(token=token)
            if forgot_password is None:
                raise ErrorResource(404, message="Invalid token.")

            # update password
            user = forgot_password.user
            user.password = password

            # delete token
            db.session.remove(forgot_password)
            db.session.commit()

            # set up payload
            message = "Your passsword has been successfuly changed."

        else:
            # we dont have email, token or password, so we are not
            # able to reset password
            raise ErrorResource(400, message="Not able to reset password.")

        return response(payload, message=message)