<commit_before># -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This module contains classes for authenticating the user."""

from twisted.internet import defer

from synapse.api.constants import Membership, JoinRules
from synapse.api.errors import AuthError, StoreError, Codes, SynapseError
from synapse.api.events.room import (
    RoomMemberEvent, RoomPowerLevelsEvent, RoomRedactionEvent,
    RoomJoinRulesEvent, InviteJoinEvent,
    RoomCreateEvent,
)
from synapse.util.logutils import log_function

import logging

logger = logging.getLogger(__name__)


class Auth(object):

    def __init__(self, hs):
        self.hs = hs
        self.store = hs.get_datastore()

    def check(self, event, raises=False):
        """ Checks if this event is correctly authed.

        Returns:
            True if the auth checks pass.
        Raises:
            AuthError if there was a problem authorising this event. This will
            be raised only if raises=True.
        """
        try:
            if hasattr(event, "room_id"):
                if event.old_state_events is None:
                    # Oh, we don't know what the state of the room was, so we
                    # are trusting that this is allowed (at least for now)
                    logger.warn("Trusting event: %s", event.event_id)
                    return True

                if hasattr(event, "outlier") and event.outlier is True:
                    # TODO (erikj): Auth for outliers is done differently.
                    return True

                is_state = hasattr(event, "state_key")

                if event.type == RoomCreateEvent.TYPE:
                    # FIXME
                    return True

                if event.type == RoomMemberEvent.TYPE:
                    self._can_send_event(event)
                    allowed = self.is_membership_change_allowed(event)
                    if allowed:
                        logger.debug("Allowing! %s", event)
                    else:
                        logger.debug("Denying! %s", event)
                    return allowed

                self._can_send_event(event)

                if event.type == RoomPowerLevelsEvent.TYPE:
                    self._check_power_levels(event)

                if event.type == RoomRedactionEvent.TYPE:
                    self._check_redaction(event)

                logger.debug("Allowing! %s", event)
                return True
            else:
                raise AuthError(500, "Unknown event: %s" % event)
        except AuthError as e:
            logger.info("Event auth check failed on event %s with msg: %s",
                        event, e.msg)
            logger.info("Denying! %s", event)
            if raises:
                raise e

        return False
<commit_msg>Neaten things up a bit<commit_after># -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This module contains classes for authenticating the user."""

from twisted.internet import defer

from synapse.api.constants import Membership, JoinRules
from synapse.api.errors import AuthError, StoreError, Codes, SynapseError
from synapse.api.events.room import (
    RoomMemberEvent, RoomPowerLevelsEvent, RoomRedactionEvent,
    RoomJoinRulesEvent, InviteJoinEvent,
    RoomCreateEvent,
)
from synapse.util.logutils import log_function

import logging

logger = logging.getLogger(__name__)


class Auth(object):

    def __init__(self, hs):
        self.hs = hs
        self.store = hs.get_datastore()

    def check(self, event, raises=False):
        """ Checks if this event is correctly authed.

        Returns:
            True if the auth checks pass.
        Raises:
            AuthError if there was a problem authorising this event. This will
            be raised only if raises=True.
        """
        try:
            if hasattr(event, "room_id"):
                if event.old_state_events is None:
                    # Oh, we don't know what the state of the room was, so we
                    # are trusting that this is allowed (at least for now)
                    logger.warn("Trusting event: %s", event.event_id)
                    return True

                if hasattr(event, "outlier") and event.outlier is True:
                    # TODO (erikj): Auth for outliers is done differently.
                    return True

                if event.type == RoomCreateEvent.TYPE:
                    # FIXME
                    return True

                self._can_send_event(event)

                if event.type == RoomMemberEvent.TYPE:
                    allowed = self.is_membership_change_allowed(event)
                    if allowed:
                        logger.debug("Allowing! %s", event)
                    else:
                        logger.debug("Denying! %s", event)
                    return allowed

                if event.type == RoomPowerLevelsEvent.TYPE:
                    self._check_power_levels(event)

                if event.type == RoomRedactionEvent.TYPE:
                    self._check_redaction(event)

                logger.debug("Allowing! %s", event)
                return True
            else:
                raise AuthError(500, "Unknown event: %s" % event)
        except AuthError as e:
            logger.info("Event auth check failed on event %s with msg: %s",
                        event, e.msg)
            logger.info("Denying! %s", event)
            if raises:
                raise e

        return False

{'fraction_non_alphanumeric': 0.07493540051679587, 'fraction_numerical': 0.00364797081623347, 'mean_word_length': 1.8733624454148472, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5244923', 'n_tokens_mistral': 1735, 'n_tokens_neox': 1613, 'n_words': 592}