Example #1
0
 def on_get(self, request, response):
     Logger.info(LOCATION,
                 INCOMING_REQUEST + METHOD_GET + ' ' + PAIRING_ENDPOINT)
     configuration = self.configuration_store.get()
     if configuration.get_device_status() is not DeviceStatus.NEW:
         error = 'Device is already paired.'
         Logger.error(LOCATION, error)
         raise falcon.HTTPForbidden(description=error)
     device_information = configuration.get_device_information()
     response.media = json.dumps(device_information)
     subprocess.Popen(['make', 'pair'])
Example #2
0
    def on_patch(self, req: falcon.Request, resp: falcon.Response,
                 primary_key: str):
        """Write attributes."""
        user = req.context.get('user')
        if user is None:
            raise falcon.HTTPForbidden()

        self.view.update_details(user, primary_key, req.media)
        if primary_key == user['primaryKey']:
            resp.media = self.token_generator(user['primaryKey'])
        resp.status = falcon.HTTP_200
Example #3
0
 def _get_data(self, cleaned, id, *args, **kwargs):
     data = cleaned['data']['attributes']
     model = self.database_model
     try:
         return model.objects.update_from_data(id, self.request.user,
                                               data)
     except model.DoesNotExist:
         raise falcon.HTTPNotFound
     except DuplicateSubscriptionName:
         raise falcon.HTTPForbidden(
             'Subscription with given name already exist')
    def on_get(self, req, resp, username: str):
        '/user/application/{username}'
        # If account have permission, can review all username.
        jwt_payload = req.context['user']['user']
        if jwt_payload['username'] != username and jwt_payload['permission_level'] < 1:
            raise falcon.HTTPForbidden(description=":)")

        resp.body = f'{{"data": {self.review_service.get_user_application(username=username)}}}'
        resp.media = falcon.MEDIA_JSON
        resp.status = falcon.HTTP_200
        return True
Example #5
0
    def clean(self, request, locations=None):
        cleaned = super().clean(request, locations=locations)
        usr = User.objects.get_or_none(email=cleaned['email'].strip())
        if usr:
            raise falcon.HTTPForbidden(
                description=_('Account for this email already exist'))

        # Model validation
        usr = User(**cleaned)
        self.clean_model(usr)
        return cleaned
Example #6
0
 def _check_permissions(self, user: Dict[str, Any], writing: bool):
     if not writing:
         if not self._read_permissions:
             return
         for permission in self._read_permissions:
             if user[permission]:
                 return
     for permission in self._permissions:
         if user[permission]:
             return
     raise falcon.HTTPForbidden(description="Insufficient permissions")
Example #7
0
 def clean(self, *args, **kwargs):
     chart = self._get_instance(*args, **kwargs)
     if not chart.can_be_updated_by(self.request.user):
         raise falcon.HTTPForbidden(
             title='You have no permission to update the resource!')
     self.deserializer.context.update({
         'chart': chart,
         'resource': chart.resource,
         'user': self.request.user,
     })
     return super().clean(validators=None, *args, **kwargs)
    def login(self, username: str, password: str, fcm_token=None) -> str:
        """basic login function

        Args:
            username (str): username
            password (str): password

        Raises:
            falcon.HTTPUnauthorized: 401, username or password error

        Returns:
            str: jwt payload.

        JWT_Payload:
            {
                username
                permission_level
            }
            permission_level:
            - 0 is user
            - 1 is editor/reviewer
            - 2 is admin
        """
        if self.redis_account.exists(username):
            user_data = json.loads(self.redis_account.get(username))
            s = hashlib.sha256()
            s.update(password.encode('utf-8'))
            _password = s.hexdigest()

            if self.is_banned(username):
                raise falcon.HTTPForbidden(
                    title="banned",
                    description=
                    "Your account is banned, any question please ask Facebook fan page."
                )

            if user_data['password'] == _password:
                _user_level = 0
                if username in ADMIN:
                    _user_level = 2
                elif username in self.get_editor_list():
                    _user_level = 1

                jwt_string = self.jwt_auth.get_auth_token(
                    user_payload={
                        "username": username,
                        "login_type": "General",
                        "permission_level": _user_level,
                        "fcm": fcm_token
                    })

                return jwt_string

        raise falcon.HTTPUnauthorized()
Example #9
0
def user_required(req, resp, resource, params, user_type):

    if 'user_session' not in req.cookies:
        raise falcon.HTTPUnauthorized()

    user = get_user(req.cookies['user_session'])

    if not user or user.type != user_type:
        raise falcon.HTTPForbidden()

    resource.user = user
    def google_oauth_login(self, code: str, fcm_token=None) -> str:

        user_info_by_google = google_sign_in(code=code)

        if user_info_by_google.get("verified_email", False) == False:
            falcon.HTTPForbidden("Your email need verified.")
        user_mail = user_info_by_google.get('email', False)
        if user_mail is False:
            falcon.HTTPServiceUnavailable(
                description="Get user email error :(")
        user_mail = user_mail.lower()
        if APPLICANT_HOSTNAME_LIMIT != [] and user_mail not in self.get_editor_list(
        ):
            user_mail_parse = address.parse(user_mail, addr_spec_only=True)
            if user_mail_parse is not None:
                if isinstance(user_mail_parse, address.EmailAddress) and \
                        user_mail_parse.hostname not in APPLICANT_HOSTNAME_LIMIT:
                    raise falcon.HTTPForbidden(
                        title="mail organization not allow")

        if self.is_banned(user_mail):
            raise falcon.HTTPForbidden(
                title="banned",
                description=
                "Your account is banned, any question please ask Facebook fan page."
            )

        _user_level = 0
        if user_mail in ADMIN:
            _user_level = 2
        elif user_mail in self.get_editor_list():
            _user_level = 1

        jwt_string = self.jwt_auth.get_auth_token(
            user_payload={
                "username": user_mail,
                "login_type": "Oauth2",
                "permission_level": _user_level,
                "fcm": fcm_token
            })
        return jwt_string
    def apple_sign_in_by_id_token(self,
                                  id_token: str,
                                  bundle_id=None,
                                  fcm_token=None) -> str:
        jwt_payload = apple_verify_id_token(id_token=id_token,
                                            bundle_id=bundle_id)
        if jwt_payload.get("email", False) == False:
            falcon.HTTPServiceUnavailable(
                description="Get user email error :(")

        user_mail = jwt_payload.get("email", "").lower()
        print(user_mail)
        if APPLICANT_HOSTNAME_LIMIT != [] and user_mail not in self.get_editor_list(
        ):
            user_mail_parse = address.parse(user_mail, addr_spec_only=True)
            if user_mail_parse is not None:
                if isinstance(user_mail_parse, address.EmailAddress) and \
                        user_mail_parse.hostname not in APPLICANT_HOSTNAME_LIMIT:
                    raise falcon.HTTPForbidden(
                        title="mail organization not allow")
        if self.is_banned(user_mail):
            raise falcon.HTTPForbidden(
                title="banned",
                description=
                "Your account is banned, any question please ask Facebook fan page."
            )

        _user_level = 0
        if user_mail in ADMIN:
            _user_level = 2
        elif user_mail in self.get_editor_list():
            _user_level = 1

        jwt_string = self.jwt_auth.get_auth_token(
            user_payload={
                "username": user_mail,
                "login_type": "Apple_sign_in",
                "permission_level": _user_level,
                "fcm": fcm_token
            })
        return jwt_string
Example #12
0
    def execute(self, req, resp, params):
        auth_header = req.get_header('Authorization')
        # import pdb; pdb.set_trace()
        if not auth_header:
            raise falcon.HTTPUnauthorized(
                title='401 Unauthorized',
                description=_('Missing authorization header'),
                code='token_missing'
            )
        user_payload = decode_jwt_token(auth_header)['user']
        if not set(('session_key', 'email')) <= set(user_payload):
            raise falcon.HTTPUnauthorized(
                title='401 Unauthorized',
                description=_('Invalid authorization header'),
                code='token_error'
            )
        req.session = session_store(user_payload['session_key'])
        user = get_user(req)
        if not user or (hasattr(user, 'is_anonymous') and user.is_anonymous):
            raise falcon.HTTPUnauthorized(
                title='401 Unauthorized',
                description=_('Invalid token data'),
                code='authentication_error'
            )
        if user.email != user_payload['email']:
            raise falcon.HTTPUnauthorized(
                title='401 Unauthorized',
                description=_('Invalid token data'),
                code='authentication_error'
            )
        if user.state != 'active':
            if user.state not in settings.USER_STATE_LIST or user.state == 'deleted':
                raise falcon.HTTPUnauthorized(
                    title='401 Unauthorized',
                    description=_('Cannot login'),
                    code='account_unavailable'
                )

            if user.state in ('draft', 'blocked'):
                raise falcon.HTTPUnauthorized(
                    title='401 Unauthorized',
                    description=_('Account is blocked'),
                    code='account_unavailable'
                )

            if user.state == 'pending':
                raise falcon.HTTPForbidden(
                    title='403 Forbidden',
                    description=_('Email addres not confirmed'),
                    code='account_inactive'
                )

        req.user = user
Example #13
0
    def on_post(self, req, resp, corpus_id: str = None, corpus_property: str = None, property_value: str = None):
        if req.user.role != UserKind.ADMINISTRATOR.value and req.user.role != UserKind.STAFF.value:
            raise falcon.HTTPForbidden("Must be admin or staff")

        if not corpus_id:
            self.create_corpus(req, resp)
        elif corpus_property == "assets" and property_value:
            self.create_asset(req, resp, corpus_id, property_value)
        elif corpus_property == "questions":
            self.create_question(req, resp, corpus_id)
        else:
            raise falcon.HTTPNotFound()
Example #14
0
    def on_put(self, req, resp, id):
        original_id = req.recover_int64_field(id)
        if req.user.role == UserKind.ADMINISTRATOR.value or original_id == req.user.id:
            # User's changing their own password, or they're an administrator
            if "oldPassword" in req.body:
                old_password = req.body["oldPassword"]
            else:
                old_password = None
            new_password = req.body["newPassword"]

            should_check_password = req.user.id == original_id

            u = UserController(req.session)
            user = u.get_user_from_id(original_id)
            errors = u.change_password(user, old_password, new_password, should_check_password)
            if errors:
                resp.obj = errors
                raise falcon.HTTPForbidden()
            resp.status = falcon.HTTP_202
        else:
            raise falcon.HTTPForbidden()
 def _get_instance(self, *args, **kwargs):
     instance = getattr(self, '_cached_instance', None)
     if not instance:
         try:
             self._cached_instance = UserSchedule.objects.published(
             ).get(pk=kwargs['id'])
         except UserSchedule.DoesNotExist:
             raise falcon.HTTPNotFound
         if self._cached_instance.schedule.state == 'archival':
             raise falcon.HTTPForbidden(
                 title='You cannot add new item to archival schedule!')
     return self._cached_instance
Example #16
0
        def _get_data(self, cleaned, activation_code, *args, **kwargs):
            try:
                instance = self.database_model.objects.get(
                    activation_code=activation_code, is_active=False)
            except self.database_model.DoesNotExist:
                raise falcon.HTTPForbidden(
                    title=_('Invalid action!'),
                    description=_('The activation link has expired'))

            instance.confirm_subscription()
            instance.refresh_from_db()
            return instance
Example #17
0
    def on_post(self, req: falcon.Request, res: falcon.Response):
        if not req.media:
            raise falcon.HTTPBadRequest("Bad or missing user payload")
        user = req.media
        if 'email' not in user or 'alias' not in user or 'password' not in user or 'captcha' not in user \
                or 'code' not in user:
            raise falcon.HTTPBadRequest(
                "Missing fields for user. Requires email, alias, password, captcha, and code"
            )
        captcha = user['captcha']
        if not captcha['id'] or not captcha['answer']:
            raise falcon.HTTPBadRequest(
                "Missing captcha fields. Required id and answer")

        c = self._db.cursor()
        row = c.execute("SELECT [answer] FROM [captcha_tokens] WHERE id = ?",
                        (captcha["id"], )).fetchone()
        if row is None:
            raise falcon.HTTPBadRequest("No captcha with id {} found".format(
                captcha["id"]))
        c.execute(
            "DELETE FROM [captcha_tokens] WHERE id = ? OR [time] <  date('now', '-1 hour')",
            (captcha["id"], ))
        self._db.commit()
        if row[0] != captcha["answer"]:
            raise falcon.HTTPForbidden(
                "Captcha answer incorrect. Please try again")

        row = c.execute(
            "SELECT [campaign_id] FROM campaign_referral WHERE code=?",
            (user['code'], )).fetchone()
        if not row:
            raise falcon.HTTPBadRequest("referral code not found")
        campaign_id = row[0]

        hash_pw = bcrypt.hashpw(user['password'].encode(), bcrypt.gensalt())
        new_id = generate_new_id()
        try:
            c.execute(
                "INSERT INTO [user] ([id], [email], [alias], [password]) VALUES (?, ?, ?, ?)",
                (new_id, user['email'], user['alias'], hash_pw))
        except sqlite3.IntegrityError:
            raise falcon.HTTPBadRequest("Email already exists")
        logging.info("Created new user with email [{}]".format(user['email']))
        # Create an empty profile, to be populated later
        c.execute("INSERT INTO [profile] ([user_id]) VALUES (?)", (new_id, ))
        # For now, all new users auto-join the two campaigns until campaign support is added
        c.execute(
            """
        INSERT INTO [user_campaign_map] ([user_id], [campaign_id]) 
        VALUES (?, ?), (?, ?)""", (new_id, 1, new_id, campaign_id))
        self._db.commit()
        res.status = falcon.HTTP_CREATED
Example #18
0
    def on_post(self, req, resp):

        username = req.media.get('username')
        password = req.media.get('password')

        if not self.dao.login(username, password):
            msg = "User has not provided valid credentials"
            raise falcon.HTTPForbidden("Invalid Credentials", msg)

        doc = {"apiKey": self.dao._get_key(username)}

        resp.body = json.dumps(doc, ensure_ascii=False)
Example #19
0
def check_owner(req, resp, params):
    """
    Check that the requester is the resource owner. Must run after check_avatar and check_authorization.

    :param req:
    :param resp:
    :param params:
    :return:
    """
    if req.context['sub'] != params['aid']:
        raise falcon.HTTPForbidden(title="Access Denied",
                                   description="Only owner can access.")
Example #20
0
    def authenticate(self, req, resp):
        """
        Method should be overriden with specific a specific authentication
        call for an implementation.

        :param req: Request instance that will be passed through.
        :type req: falcon.Request
        :param resp: Response instance that will be passed through.
        :type resp: falcon.Response
        :raises: falcon.HTTPForbidden
        """
        raise falcon.HTTPForbidden('Forbidden', 'Forbidden')
Example #21
0
    def on_post(self, req, resp, source, target):
        """
        post demo

        demo for `query`, `data`, `resp`, `x`
        """
        print(f'{source} => {target}')
        print(req.context.query)
        print(req.context.data)
        if random() < 0.5:
            raise falcon.HTTPForbidden("Bad luck. You're fobidden.")
        return Response(label=int(10 * random()), score=random())
Example #22
0
 def on_post(self, req, resp):
     if self.fedora_repo and (self.fuseki or self.elastic_search):
         raise falcon.HTTPForbidden(
             "Services Already Running",
             "Elastic Search, Fedora 4, and Fuseki already running")
     self.__start_services__()
     resp.status = falcon.HTTP_201
     resp.body = json.dumps({"services": {
         "elastic-search": {"pid": self.elastic_search.pid},
         "fedora4": {"pid": self.fedora_repo.pid},
      #   "fedora4-messenger": {"pid": self.fedora_messenger.pid},
         "fuseki": {"pid": self.fuseki.pid}}})
Example #23
0
    def process_resource(self, req, resp, resource, params):
        ''' Raise Forbidden if JWT Token is invalid in Authorization Header.

        Expected header
        ----------------------------------------
        Authorization: Bearer <token>


        If resource not require authentication, set `auth` dict with method
        to False (Its true by default.)

        ```
        class Resource:
            auth = {'get': False}
            def on_get(self, req, resp):
                'Dont need auth.'
                pass

            def on_post(self, req, resp):
                'Need auth.'
                pass
        ```
        '''
        auth_map = getattr(resource, 'auth', {})
        if auth_map.get(req.method.lower(), True):
            authorization_header = req.auth
            # check if authorizacion header exists
            if not authorization_header:
                raise falcon.HTTPUnauthorized('Login required')

            # check if authorization is Bearer
            if not authorization_header.startswith('Bearer '):
                raise falcon.HTTPForbidden('Invalid Authorization header')

            # check if is valid token
            token = authorization_header.split()[-1]
            if utils.is_valid_token(token):
                req.user = utils.get_user(token)
            else:
                raise falcon.HTTPForbidden('Invalid token')
 def _get_instance(self, id, *args, **kwargs):
     instance = getattr(self, '_cached_instance', None)
     if not instance:
         try:
             self._cached_instance = self.database_model.objects.get(
                 pk=id)
         except self.database_model.DoesNotExist:
             raise falcon.HTTPNotFound
         if self._cached_instance not in self.request.user.notifications.all(
         ):
             raise falcon.HTTPForbidden(
                 title='You have no permission to update the resource.')
     return self._cached_instance
Example #25
0
    def on_post(self, req, res):
        """Validate authentication credentials, issuing a new token and cookie
        if valid."""

        username = req.media.get('username')
        password = req.media.get('password')
        if auth_user(username, password):
            new_token = req.context['encode_token']({'username': username})
            res.set_cookie('token', new_token)
            res.media = {'token': new_token}
        else:
            logzero.logger.warning('Log In Failed')
            raise falcon.HTTPForbidden()
Example #26
0
    def wrapped(self, req, resp, *args, **kwargs):
        authority = kwargs.get("ca")

        # Parse remote IPv4/IPv6 address
        remote_addr = ipaddress.ip_network(req.env["REMOTE_ADDR"])

        # Check for administration subnet whitelist
        print("Comparing:", authority.admin_subnets, "To:", remote_addr)
        for subnet in authority.admin_subnets:
            if subnet.overlaps(remote_addr):
                break
        else:
            raise falcon.HTTPForbidden("Forbidden", "Remote address %s not whitelisted" % remote_addr)

        # Check for username whitelist
        kerberos_username, kerberos_realm = kwargs.get("user")
        if kerberos_username not in authority.admin_users:
            raise falcon.HTTPForbidden("Forbidden", "User %s not whitelisted" % kerberos_username)

        # Retain username, TODO: Better abstraction with username, e-mail, sn, gn?
        kwargs["user"] = kerberos_username
        return func(self, req, resp, *args, **kwargs)
Example #27
0
def permission_required(req, resp, resource, params):
    login_required(req, resp, resource, params)
    # Backdoor for stage development
    if req.context['env']['config'] == 'stage' and \
            req.headers.get('MAGIC-CODE') == 'WHOSYOURDADDY':
        return
    session = req.context['session']
    user = req.context['session'].user
    permissions = req.context['session'].permissions
    if not Permission.check_permissions(
            req.relative_uri, Permission.Action.name_to_num(req.method),
            permissions):
        raise falcon.HTTPForbidden('No permission to proceed')
Example #28
0
    def wrapped(resource, req, resp, *args, **kwargs):
        buf = req.get_header("X-SSL-CERT")
        if not buf:
            logger.info(
                "No TLS certificate presented to access administrative API call"
            )
            raise falcon.HTTPForbidden(
                "Forbidden", "Machine not authorized to perform the operation")

        header, _, der_bytes = pem.unarmor(
            buf.replace("\t", "").encode("ascii"))
        cert = x509.Certificate.load(der_bytes)  # TODO: validate serial
        for extension in cert["tbs_certificate"]["extensions"]:
            if extension["extn_id"].native == "extended_key_usage":
                if "server_auth" in extension["extn_value"].native:
                    req.context["machine"] = cert.subject.native["common_name"]
                    return func(resource, req, resp, *args, **kwargs)
        logger.info(
            "TLS authenticated machine '%s' not authorized to access administrative API",
            cert.subject.native["common_name"])
        raise falcon.HTTPForbidden(
            "Forbidden", "Machine not authorized to perform the operation")
def only_owner_modify(
        review_service: ReviewService,
        application_id: str,
        applicant_username: str):

    origin_application = review_service.get_application_by_id(
        application_id=application_id
    )
    if origin_application is None:
        raise falcon.HTTPNotFound()

    if json.loads(origin_application)['applicant'] != applicant_username:
        raise falcon.HTTPForbidden(title="no permission to update")
Example #30
0
def payment_required(req, resp, resource, params):
    if 'user_session' not in req.cookies:
        raise falcon.HTTPUnauthorized()

    user = get_user(req.cookies['user_session'])

    if not user:
        raise falcon.HTTPUnauthorized()

    if not user.payment_complete:
        raise falcon.HTTPForbidden()

    resource.user = user