def submitMessage(self, phone, message):
        """
        write the message down to the given file

        :param phone: given phone number
        :param message: the provided message, containing the otp
        """
        ret = False

        msisdn = 'true' in ('%r' % self.config.get('MSISDN', 'false')).lower()
        if msisdn:
            phone = self._get_msisdn_phonenumber(phone)

        filename = self.config.get('file', '')
        here = self.config.get('here', '')

        if here:
            filename = "%s%s%s" % (here, os.path.sep, filename)
        try:
            with open(filename, "w") as f:
                msg = u"%s:%s" % (str2unicode(phone), str2unicode(message))
                f.write(msg.encode('utf-8'))
            ret = True
        except Exception as exx:
            log.exception(exx)
            ret = False
        finally:
            return ret
Example #2
0
    def _submitMessage(self, phone, message):
        """
        write the message down to the given file

        :param phone: given phone number
        :param message: the provided message, containing the otp
        """
        ret = False

        filename = self.config.get("file", "")
        here = self.config.get("here", "")

        if here:
            filename = "%s%s%s" % (here, os.path.sep, filename)
        try:
            with open(filename, "w") as f:
                msg = "%s:%s" % (str2unicode(phone), str2unicode(message))
                f.write(msg)
            ret = True

        except Exception as exx:
            log.error("Failed to open file %r", filename)
            raise ProviderNotAvailable("Failed to open file %r" % filename)

        return ret
Example #3
0
    def _submitMessage(self, phone, message):
        """
        write the message down to the given file

        :param phone: given phone number
        :param message: the provided message, containing the otp
        """
        ret = False

        filename = self.config.get('file', '')
        here = self.config.get('here', '')

        if here:
            filename = "%s%s%s" % (here, os.path.sep, filename)
        try:
            with open(filename.encode('utf-8'), "w") as f:
                msg = u"%s:%s" % (str2unicode(phone), str2unicode(message))
                f.write(msg.encode('utf-8'))
            ret = True

        except Exception as exx:
            log.exception("Failed to open file %r", filename)
            raise ProviderNotAvailable("Failed to open file %r" % filename)


        return ret
Example #4
0
    def authenticate(self, environ, identity):
        log.info("[authenticate] entering repoze authenticate function.")
        # log.debug( identity )
        username = None
        realm = None
        authUser = None
        try:
            if isSelfTest():
                if ('login' not in identity
                        and 'repoze.who.plugins.auth_tkt.userid' in identity):

                    uid = identity.get('repoze.who.plugins.auth_tkt.userid')
                    identity['login'] = uid
                    identity['password'] = uid

            if getRealmBox():
                username = identity['login']
                realm = identity['realm']
            else:
                log.info("[authenticate] no realmbox")
                if '@' in identity['login']:
                    if getSplitAtSign():
                        log.debug("trying to split the loginname")
                        username, _at_, realm = identity['login'].rpartition(
                            '@')
                    else:
                        log.debug("no split for the @ of the loginname")
                        username = identity['login']
                        realm = identity.get('realm', getDefaultRealm())

                else:
                    username = identity['login']
                    realm = getDefaultRealm()

            log.info("[authenticate]: username: %r, realm: %r" %
                     (username, realm))
            password = identity['password']

        except KeyError as e:
            log.error("[authenticate] Keyerror in identity: %r." % e)
            log.error("[authenticate] %s" % traceback.format_exc())
            return None

        # as repoze does not run through the std pylons middleware, we have to
        # convert the input which might be UTF8 to unicode
        username = str2unicode(username)
        password = str2unicode(password)

        # check username/realm, password
        if isSelfTest():
            authUser = "******" % (username, realm)
        else:
            authUser = get_authenticated_user(username, realm, password)

        return authUser
Example #5
0
    def authenticate(self, environ, identity):
        log.info("[authenticate] entering repoze authenticate function.")
        # log.debug( identity )
        username = None
        realm = None
        authUser = None
        try:
            if isSelfTest():
                if ('login' not in identity and
                    'repoze.who.plugins.auth_tkt.userid' in identity):

                    uid = identity.get('repoze.who.plugins.auth_tkt.userid')
                    identity['login'] = uid
                    identity['password'] = uid

            if getRealmBox():
                username = identity['login']
                realm = identity['realm']
            else:
                log.info("[authenticate] no realmbox")
                if '@' in identity['login']:
                    if getSplitAtSign():
                        log.debug("trying to split the loginname")
                        username, _at_, realm = identity['login'].rpartition('@')
                    else:
                        log.debug("no split for the @ of the loginname")
                        username = identity['login']
                        realm = identity.get('realm', getDefaultRealm())

                else:
                    username = identity['login']
                    realm = getDefaultRealm()

            log.info("[authenticate]: username: %r, realm: %r"
                     % (username, realm))
            password = identity['password']

        except KeyError as e:
            log.error("[authenticate] Keyerror in identity: %r." % e)
            log.error("[authenticate] %s" % traceback.format_exc())
            return None

        # as repoze does not run through the std pylons middleware, we have to
        # convert the input which might be UTF8 to unicode
        username = str2unicode(username)
        password = str2unicode(password)

        # check username/realm, password
        if isSelfTest():
            authUser = "******" % (username, realm)
        else:
            authUser = get_authenticated_user(username, realm, password)

        return authUser
Example #6
0
    def test_successful_File_SMS(self):
        '''
        Successful test of the File SMS Provider
        '''
        # locate the lookup file in the servers home
        here = self.appconf.get('here', None)

        # create a temporary filename, to avoid conflicts
        f = tempfile.NamedTemporaryFile(delete=False, dir=here)
        filename = f.name
        sms_conf = {"file": filename}

        params = {
            'name': 'test_successful_File_SMS',
            'config': json.dumps(sms_conf),
            'timeout': '100',
            'type': 'sms',
            'class': 'smsprovider.FileSMSProvider.FileSMSProvider',
        }

        with DefaultProvider(self, params):

            response = self.make_validate_request('check',
                                                  params={
                                                      'user': '******',
                                                      'pass': '******',
                                                      'message': 'Täst<otp>'
                                                  })

            self.assertTrue('"message": "sms submitted"' in response, response)
            self.assertTrue('"state"' in response, response)

            with open(filename, 'r') as f:
                line = f.read()

            line = str2unicode(line)
            self.assertTrue(u'Täst' in line, u"'Täst' not found in line")

            _left, otp = line.split(u'Täst')
            response = self.make_validate_request('check',
                                                  params={
                                                      'user': '******',
                                                      'pass': '******' % otp
                                                  })

            self.assertTrue('"value": true' in response, response)

            import os
            os.remove(filename)

        return
Example #7
0
    def _submitMessage(self, phone, message):
        """
        write the message down to the given file

        :param phone: given phone number
        :param message: the provided message, containing the otp
        """
        ret = False

        filename = self.config.get('file', '')
        here = self.config.get('here', '')

        if here:
            filename = "%s%s%s" % (here, os.path.sep, filename)
        try:
            with open(filename.encode('utf-8'), "w") as f:
                msg = u"%s:%s" % (str2unicode(phone), str2unicode(message))
                f.write(msg.encode('utf-8'))
            ret = True
        except Exception as exx:
            log.exception(exx)
            ret = False
        finally:
            return ret
Example #8
0
    def test_successful_File_SMS(self):
        """
        Successful test of the File SMS Provider
        """

        # create a temporary filename, to avoid conflicts
        with tempfile.NamedTemporaryFile() as f:
            filename = f.name
            sms_conf = {"file": filename}

            params = {
                "name": "test_successful_File_SMS",
                "config": json.dumps(sms_conf),
                "timeout": "100",
                "type": "sms",
                "class": "smsprovider.FileSMSProvider.FileSMSProvider",
            }

            with DefaultProvider(self, params):

                response = self.make_validate_request(
                    "check",
                    params={
                        "user": "******",
                        "pass": "******",
                        "message": "Täst<otp>",
                    },
                )

                assert "state" in response.json["detail"], response
                assert ("sms submitted"
                        in response.json["detail"]["message"]), response

                with open(filename, "r") as f:
                    line = f.read()

                line = str2unicode(line)
                assert "Täst" in line, "'Täst' not found in line"

                _left, otp = line.split("Täst")
                response = self.make_validate_request("check",
                                                      params={
                                                          "user": "******",
                                                          "pass":
                                                          "******" % otp
                                                      })

                assert response.json["result"]["value"], response
Example #9
0
    def test_successful_File_SMS(self):
        '''
        Successful test of the File SMS Provider
        '''
        # locate the lookup file in the servers home
        here = self.appconf.get('here', None)

        # create a temporary filename, to avoid conflicts
        f = tempfile.NamedTemporaryFile(delete=False, dir=here)
        filename = f.name
        sms_conf = {"file": filename}

        params = {'name': 'test_successful_File_SMS',
                  'config': json.dumps(sms_conf),
                  'timeout': '100',
                  'type': 'sms',
                  'class': 'smsprovider.FileSMSProvider.FileSMSProvider',
                  }

        with DefaultProvider(self, params):

            response = self.make_validate_request('check',
                        params={'user': '******',
                                'pass': '******',
                                'message': 'Täst<otp>'})

            self.assertTrue('"message": "sms submitted"' in response, response)
            self.assertTrue('"state"' in response, response)

            with open(filename, 'r') as f:
                line = f.read()

            line = str2unicode(line)
            self.assertTrue(u'Täst' in line, u"'Täst' not found in line")

            _left, otp = line.split(u'Täst')
            response = self.make_validate_request('check',
                                                  params={'user': '******',
                                                          'pass': '******' % otp})

            self.assertTrue('"value": true' in response, response)

            import os
            os.remove(filename)

        return
Example #10
0
    def document(self):
        """Render the error document"""
        resp = request.environ.get('pylons.original_response')
        if resp is not None:
            unicode_body = str2unicode(resp.body)
            content = literal(unicode_body)
        else:
            message = request.GET.get('message',
                                      request.POST.get('message', ''))
            content = cgi.escape(message)

        code = request.GET.get(
            'code', request.POST.get('code', unicode(resp.status_int)))

        page = error_document_template % \
            dict(prefix=request.environ.get('SCRIPT_NAME', ''),
                 code=cgi.escape(code),
                 message=content)
        return page
Example #11
0
    def document(self):
        """Render the error document"""
        resp = request.environ.get('pylons.original_response')
        if resp is not None:
            unicode_body = str2unicode(resp.body)
            content = literal(unicode_body)
        else:
            message = request.GET.get('message',
                                      request.POST.get('message', ''))
            content = cgi.escape(message)

        code = request.GET.get('code',
                               request.POST.get('code',
                                               unicode(resp.status_int)))

        page = error_document_template % \
            dict(prefix=request.environ.get('SCRIPT_NAME', ''),
                 code=cgi.escape(code),
                 message=content)
        return page
Example #12
0
    def document(self):
        """Render the error document"""

        # TODO: this will break - adjust to flask response

        resp = request.environ.get("pylons.original_response")
        if resp is not None:
            unicode_body = str2unicode(resp.body)
            content = literal(unicode_body)
        else:
            message = request.GET.get("message",
                                      request.POST.get("message", ""))
            content = escape(message)

        code = request.GET.get("code",
                               request.POST.get("code", str(resp.status_int)))

        page = error_document_template % dict(
            prefix=request.environ.get("SCRIPT_NAME", ""),
            code=escape(code),
            message=content,
        )
        return page
Example #13
0
    def loadFile(self):

        """
          init loads the /etc/passwd
            user and uid as a dict for /
            user loginname lookup
        """

        if (self.fileName == ""):
            self.fileName = "/etc/passwd"

        log.info('[loadFile] loading users from file %s' % (self.fileName))

        fileHandle = open(self.fileName, "r")

        line = fileHandle.readline()

        ID = self.sF["userid"]
        NAME = self.sF["username"]
        PASS = self.sF["cryptpass"]
        DESCRIPTION = self.sF["description"]

        while line:
            line = line.strip()
            if len(line) == 0:
                continue

            line = str2unicode(line)
            fields = line.split(":", 7)
            self.nameDict["%s" % fields[NAME]] = fields[ID]

            ## for speed reason - build a revers lookup
            self.reversDict[fields[ID]] = "%s" % fields[NAME]

            ## for full info store the line
            self.descDict[fields[ID]] = fields

            ## store the crypted password
            self.passDict[fields[ID]] = fields[PASS]

            ## store surname, givenname and phones
            descriptions = fields[DESCRIPTION].split(",")
            name = descriptions[0]
            names = name.split(' ', 1)
            self.givennameDict[fields[ID]] = names[0]
            self.surnameDict[fields[ID]] = ""
            self.officePhoneDict[fields[ID]] = ""
            self.homePhoneDict[fields[ID]] = ""
            self.emailDict[fields[ID]] = ""
            if len(names) >= 2:
                self.surnameDict[fields[ID]] = names[1]
            if len(descriptions) >= 4:
                self.officePhoneDict[fields[ID]] = descriptions[2]
                self.homePhoneDict[fields[ID]] = descriptions[3]
            if len(descriptions) >= 5:
                for field in descriptions[4:]:
                    # very basic e-mail regex
                    email_match = re.search('.+@.+\..+', field)
                    if email_match:
                        self.emailDict[fields[ID]] = email_match.group(0)

            """ print ">>" + key[0] + "<< " + key[2] """
            line = fileHandle.readline()