Exemple #1
0
    def verify_token(self, encoded_token):
        principal = CASPrincipal.load(encoded_token)
        member = DBSession.query(Member) \
            .filter(Member.reference_id == principal.reference_id) \
            .one_or_none()
        if not member and not 'HTTP_X_OAUTH2_ACCESS_TOKEN' in context.environ:
            raise HTTPBadRequest()

        access_token = context.environ['HTTP_X_OAUTH2_ACCESS_TOKEN'] \
            if 'HTTP_X_OAUTH2_ACCESS_TOKEN' in context.environ \
            else member.access_token

        cas_member = CASClient().get_member(access_token)
        if cas_member['email'] != principal.email:
            raise HTTPBadRequest()

        if member:
            if member.title != cas_member['title']:
                member.title = cas_member['title']

            if member.first_name != cas_member['firstName']:
                member.first_name = cas_member['firstName']

            if member.avatar != cas_member['avatar']:
                member.avatar = cas_member['avatar']

            if member.last_name != cas_member['lastName']:
                member.last_name = cas_member['lastName']

        DBSession.commit()
        return principal
Exemple #2
0
    def paginate_by_request(cls, query):

        try:
            take = int(
                context.query.get('take') \
                or context.environ.get(cls.__take_header_key__) \
                or cls.__max_take__
            )

            skip = int(
                context.query.get('skip') \
                or context.environ.get(cls.__skip_header_key__) \
                or 0
            )
        except ValueError:
            raise HTTPBadRequest()

        if take > cls.__max_take__:
            raise HTTPBadRequest()

        context.response_headers.add_header('X-Pagination-Take', str(take))
        context.response_headers.add_header('X-Pagination-Skip', str(skip))
        context.response_headers.add_header('X-Pagination-Count',
                                            str(query.count()))
        return query.offset(skip).limit(take)
 def login(self):
     principal = context.application.__authenticator__.login(
         (context.form['email'], context.form['password'])
     )
     if principal:
         return dict(token=principal.dump())
     raise HTTPBadRequest()
Exemple #4
0
    def safe_member_lookup(condition):
        query = DBSession.query(Member)
        member = Member.exclude_deleted(query).filter(condition).one_or_none()
        if member is None:
            raise HTTPBadRequest()

        return member
Exemple #5
0
    def claim(self):
        email = context.form.get('email')
        email_pattern = r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)'
        if not email:
            raise HTTPBadRequest()

        if not re.match(email_pattern, email):
            raise HTTPStatus('701 Invalid email format.')

        if DBSession.query(Member.email).filter(Member.email == email).count():
            raise HTTPStatus(
                '601 The requested email address is already registered.')

        # FIXME: Token should be put in payload
        serializer = \
            itsdangerous.URLSafeTimedSerializer(settings.activation.secret)
        token = serializer.dumps(email)
        DBSession.add(
            ActivationEmail(to=email,
                            subject='Activate your NueMD Coder account',
                            body={
                                'activation_token': token,
                                'activation_url': settings.activation.url
                            }))
        return dict(email=email)
Exemple #6
0
    def authenticate_request(self):
        if self.token_key not in context.environ:
            self.bad()
            return

        encoded_token = context.environ[self.token_key]
        if encoded_token is None or not encoded_token.strip():
            self.bad()
            return

        try:
            self.ok(self.verify_token(encoded_token))

        except itsdangerous.SignatureExpired as ex:
            # The token has expired. So we're trying to restore it using
            # refresh-token.
            session_id = ex.payload.get('sessionId')
            if session_id:
                self.try_refresh_token(session_id)
            else:
                self.bad()
                raise HTTPUnauthorized()
        except itsdangerous.BadData:
            # The token is Malformed
            self.bad()
            raise HTTPBadRequest()
    def delete(self, id_: int):
        """
        @api {delete} /note/:id Delete a note
        @apiGroup Note
        @apiVersion 1
        @apiPermission none
        """
        if int(id_) > 999:
            raise HTTPBadRequest('Invalid ID')

        raise HTTPNoContent
Exemple #8
0
    def extract_data_from_request(cls):
        for c in cls.iter_json_columns(
                include_protected_columns=True,
                include_readonly_columns=False
        ):
            info = cls.get_column_info(c)
            param_name = info.get('json')

            if param_name in context.form:

                if hasattr(c, 'property') and hasattr(c.property, 'mapper'):
                    raise HTTPBadRequest('Invalid attribute')

                value = context.form[param_name]

                # Ensuring the python type, and ignoring silently if the
                # python type is not specified
                try:
                    type_ = c.type.python_type
                except NotImplementedError:
                    yield c, value
                    continue

                # Parsing date and or time if required.
                if type_ in (datetime, date, time):
                    try:
                        if type_ == time:
                            yield c, parse_time(value)

                        elif type_ == datetime:
                            yield c, parse_datetime(value)

                        elif type_ == date:
                            yield c, parse_date(value)

                    except ValueError:
                        raise HTTPBadRequest(f'Invalid date or time: {value}')

                else:
                    yield c, value
    def try_refresh_token(self, session_id):
        morsel = context.cookies.get(self.refresh_token_key)
        if not morsel:
            return self.bad()

        if settings.jwt.refresh_token.secure \
                and context.request_scheme != 'https':
            raise HTTPBadRequest('not allowed')

        if morsel.value is None or not morsel.value.strip():
            return self.bad()

        refresh_token_encoded = morsel.value
        # Decoding the refresh token
        try:
            refresh_principal = JWTRefreshToken.load(refresh_token_encoded)
            self.ok(self.create_principal(member_id=refresh_principal.id,
                                          session_id=session_id),
                    setup_header=True)
        except itsdangerous.SignatureExpired:
            self.bad()
        except itsdangerous.BadData:
            self.bad()
            raise HTTPBadRequest()
Exemple #10
0
    def ensure(self):
        if not 'HTTP_X_OAUTH2_ACCESS_TOKEN' in context.environ:
            raise HTTPBadRequest()

        access_token = context.environ['HTTP_X_OAUTH2_ACCESS_TOKEN']

        member = DBSession.query(Member) \
            .filter(Member.reference_id == context.identity.reference_id) \
            .one_or_none()

        if not member:
            member = Member(email=context.identity.email,
                            title=context.identity.payload['title'],
                            reference_id=context.identity.reference_id,
                            access_token=access_token)
            DBSession.add(member)
        else:
            member.access_token = access_token

        DBSession.add(member)
        return member
Exemple #11
0
 def bad():
     raise HTTPBadRequest('Invalid email or password')
Exemple #12
0
 def run():
     db_session = db.get_session("db2")
     tag = Tag()
     db_session.add(tag)
     raise HTTPBadRequest("Oh, dementors here!")
Exemple #13
0
    def _filter_by_column_value(cls, query, column, value):
        def return_(e):
            return query.filter(e)

        import_value = getattr(cls, 'import_value')
        if not isinstance(value, str):
            raise HTTPBadRequest()

        in_operator_match = FILTERING_IN_OPERATOR_REGEX.match(value)
        if in_operator_match:
            not_ = value.startswith('!')
            items = in_operator_match.groupdict()['items'].split(',')
            items = [i for i in items if i.strip() != '']
            if not len(items):
                raise HTTPBadRequest('Invalid query string: %s' % value)
            expression = column.in_([import_value(column, j) for j in items])
            if not_:
                expression = ~expression

            return return_(expression)

        between_operator_match = FILTERING_BETWEEN_OPERATOR_REGEX.match(value)
        if between_operator_match:
            not_ = value.startswith('!')
            groups = between_operator_match.groupdict()
            start, end = groups['min'].strip(), groups['max'].strip()
            if not (start and end):
                raise HTTPBadRequest('Invalid query string: %s' % value)

            expression = between(column, start, end)
            if not_:
                expression = ~expression

            return return_(expression)

        if value == '\x00':
            expression = column.is_(None)
        elif value == '!\x00':
            expression = column.isnot(None)
        elif value.startswith('!'):
            expression = column != import_value(column, value[1:])
        elif value.startswith('>='):
            expression = column >= import_value(column, value[2:])
        elif value.startswith('>'):
            expression = column > import_value(column, value[1:])
        elif value.startswith('<='):
            expression = column <= import_value(column, value[2:])
        elif value.startswith('<'):
            expression = column < import_value(column, value[1:])

        # LIKE
        elif '%' in value:
            func, actual_value = \
                (column.ilike, value[1:]) if value.startswith('~') \
                else (column.like, value)
            expression = func(import_value(column, actual_value))

        # EQUAL
        else:
            expression = column == import_value(column, value)

        return return_(expression)
Exemple #14
0
        def handler(self):
            if context.query['roomId'] == 'bad':
                raise HTTPBadRequest()

            raise HTTPNoContent()
Exemple #15
0
 def data(self):
     raise HTTPBadRequest()
Exemple #16
0
 def index(self):
     raise HTTPBadRequest()