Esempio n. 1
0
 def __init__(self):
     super().__init__()
     self.msgQueue = messagequeue.MessageQueue.getInstance()
     self.userManager = UserManager()
     self.interval = 3
     self.dispatchClose = False
     self.publishInfo = dict()
Esempio n. 2
0
class MessageDispatcher(threading.Thread):
    def __init__(self):
        super().__init__()
        self.msgQueue = messagequeue.MessageQueue.getInstance()
        self.userManager = UserManager()
        self.interval = 3
        self.dispatchClose = False
        self.publishInfo = dict()

    def run(self):
        while True:
            if not self.dispatcher():
                time.sleep(self.interval)

    def dispatcher(self):
        self.dispatchClose = sysmonitor.SysMonitor.getInstance(
        ).checkNeedPersistData()
        if self.dispatchClose:
            return False
        obj = self.msgQueue.popFront()
        if obj is not None:
            if obj.owner not in self.publishInfo:
                self.publishInfo[obj.owner] = dict()
                self.publishInfo[obj.owner]['dispatchTotal'] = 0
            self.publishInfo[obj.owner]['dispatchTotal'] += 1
            self.publishInfo[obj.owner]['maxMsgNo'] = obj.msgNo
            self.userManager.dispatcher(obj)
            return True
        return False

    def getPublishInfo(self):
        return self.publishInfo
Esempio n. 3
0
    def __init__(self, app_title, app_banner, theme, target, assets_manager_service, mail_sender_service):
        """
        In:
         - ``target`` -- DataUser instance
         - ``mail_sender_service`` -- MailSender service
        """
        super(UserForm, self).__init__(target, self.fields)

        self.app_title = app_title
        self.app_banner = app_banner
        self.theme = theme
        self.mail_sender = mail_sender_service
        self.assets_manager = assets_manager_service
        self.username.validate(self.validate_username)
        self.fullname.validate(validators.validate_non_empty_string)

        # Add other properties (email to confirm, passwords...)
        self.email_to_confirm = editor.Property(
            target.email).validate(validators.validate_email)
        self.old_password = editor.Property(
            '').validate(self.validate_old_password)
        self.password = editor.Property('').validate(self.validate_password)
        self.password_repeat = editor.Property(
            '').validate(self.validate_passwords_match)
        self.user_manager = UserManager()
 def test_create_user(self):
     ret = UserManager.create_user('testosteroni', '@!!$testosteroni',
                                   'test', 'osterone')
     if ret:
         ret = UserManager.create_user('testosteroni', '@!!$testosteroni',
                                       'test', 'osterone')
     self.assertEqual(ret, None)
Esempio n. 5
0
    def __init__(self):
        # just in case
        locale.setlocale(locale.LC_ALL, 'en_US.utf-8')

        # This object is created once for all users
        self.user_manager = UserManager(settings.SERVICE_DB, settings.PWD_SALT)

        # locale path
        self.locale_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'locale')

        # Streamer lists
        self.block_streamers = list()
        self.inline_streamers = list()
    def __init__(self, config_file_path):
        config = ConfigParser.RawConfigParser()
        config.read(config_file_path)

        self._logger = logging.getLogger(__name__)
        self._ui = UI("lazzormanagement\nbooting...")

        user_config_file_path = os.path.dirname(config_file_path) + \
                os.path.sep + config.get('Users', 'users_file')
        self._user_manager = UserManager(user_config_file_path)
        self._lazzor = Lazzor()
 
        while True:
            try:
                self._upay_session_manager = nupay.SessionManager(config)
                break
            except nupay.SessionConnectionError as e:
                self._logger.warning("Can not reach the database")
                self._ui.warning_database_connection(timeout = 5)
            except nupay.TimeoutError as e:
                self._logger.warning("Timeout while connection to the database")
                self._ui.warning_database_connection(timeout = 5)

            self._ui.notify_try_again()


        self._token_reader = nupay.USBTokenReader()
Esempio n. 7
0
class Client(sleekxmpp.ClientXMPP):

    def __init__(self, jid, password):
        sleekxmpp.ClientXMPP.__init__(self, jid, password)
        self.register_plugin('xep_0030') # Service Discovery
        self.register_plugin('xep_0047', {
            'accept_stream': self.accept_stream
        }) # In-band Bytestreams
        self.eventhandler = EventHandler(self)
        self.usermanager = UserManager()

    def accept_stream(self, iq):
        return True

    def sendToOther(self, jid, message):
        j = JID(jid)
        jid = j.user + "@" + j.domain
        name = self.client_roster[jid]["name"]
        if (name == ""):
            name = jid
        for toj in self.usermanager.getUserJids(self):
            if (toj == jid):
                continue
            self.sendTo(toj, "[" + name + "]" + message)

    def sendTo(self, jid, message):
        if (isinstance(jid, JID)):
            jid = jid.user + "@" + jid.domain
        self.send_message(mto=jid.strip(),
                mbody=message,
                mtype="chat")
Esempio n. 8
0
    def __init__(self, app_title, app_banner, custom_css, target, assets_manager_service, mail_sender_service):
        """
        In:
         - ``target`` -- DataUser instance
         - ``mail_sender_service`` -- MailSender service
        """
        super(UserForm, self).__init__(target, self.fields)

        self.app_title = app_title
        self.app_banner = app_banner
        self.custom_css = custom_css
        self.mail_sender = mail_sender_service
        self.assets_manager = assets_manager_service
        self.username.validate(self.validate_username)
        self.fullname.validate(validators.validate_non_empty_string)

        # Add other properties (email to confirm, passwords...)
        self.email_to_confirm = editor.Property(
            target.email).validate(validators.validate_email)
        self.old_password = editor.Property(
            '').validate(self.validate_old_password)
        self.password = editor.Property('').validate(self.validate_password)
        self.password_repeat = editor.Property(
            '').validate(self.validate_passwords_match)
        self.user_manager = UserManager()
Esempio n. 9
0
 def __init__(self, jid, password):
     sleekxmpp.ClientXMPP.__init__(self, jid, password)
     self.register_plugin('xep_0030') # Service Discovery
     self.register_plugin('xep_0047', {
         'accept_stream': self.accept_stream
     }) # In-band Bytestreams
     self.eventhandler = EventHandler(self)
     self.usermanager = UserManager()
Esempio n. 10
0
    def __init__(self):
        # just in case
        locale.setlocale(locale.LC_ALL, 'en_US.utf-8')

        # This object is created once for all users
        self.user_manager = UserManager(settings.SERVICE_DB, settings.PWD_SALT)

        # locale path
        self.locale_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'locale')

        # Streamer lists
        self.block_streamers = list()
        self.inline_streamers = list()
Esempio n. 11
0
class DWWikiEngine(object):
    def __init__(self):
        # just in case
        locale.setlocale(locale.LC_ALL, 'en_US.utf-8')

        # This object is created once for all users
        self.user_manager = UserManager(settings.SERVICE_DB, settings.PWD_SALT)

        # locale path
        self.locale_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)), 'locale')

        # Streamer lists
        self.block_streamers = list()
        self.inline_streamers = list()

        # Here we add our parsers. This should be made
        # easily extendable for custom parsers
        #self.streamer.add_block_parser(sqltablestreamer.SqlTableStreamer())
        #self.streamer.add_block_parser(sqlbarchartstreamer.SqlBarChartStreamer())
        #self.streamer.add_block_parser(sqllinechartstreamer.SqlLineChartStreamer())
        #self.streamer.add_inline_parser(SqlInlineStreamer())
        # security
        #self.guard = SecurityGuard('fileaccess.cfg', 'userlist.cfg')

    def register_block_streamer(self, streamer):
        self.block_streamers.append(streamer)

    def register_inline_streamer(self, streamer):
        self.inline_streamers.append(streamer)

    def get_streamer(self):
        """ Creates a new streamer per each request for thread safety.
        And returns it.
        """
        res = mdstreamer.MdStreamer()

        # Here we add all our streamers.
        for streamer in self.block_streamers:
            res.add_block_parser(streamer.factory())

        for streamer in self.inline_streamers:
            res.add_inline_parser(streamer.factory())

        #res.add_block_parser(SqlTableStreamer())
        #res.add_block_parser(SqlBarChartStreamer())
        #res.add_block_parser(SqlLineChartStreamer())
        #res.add_inline_parser(SqlInlineStreamer())

        return res

    def check_access(self, action, *vpath):
        """ Check access to some resource with security guard.
        Returns True if granted, False otherwise
        """
        user = cherrypy.session.get('user', '')
        rep_dir = self.reports_dir()
        #access_file = os.path.join(rep_dir, 'fileaccess.conf')
        quick_guard = SecurityGuard(settings.ACCESS_FILE, self.user_manager)
        res = quick_guard.request_access(user, action, *vpath)
        return res

    def goto_login(self, *vpath, **params):
        """ Redirects to login if user is not logged in
        """
        base = cherrypy.config.get('tools.proxy.base', '')
        get_params = cherrypy.request.request_line.split()[1]

        #user = cherrypy.session.get('user', '')
        #if user == '':
        # redirect here to login
        # url requested in the first place will be put
        # into session variable report_requested_at_login
        # the root report is not needed
        if len(vpath) == 0:
            cherrypy.session['report_requested_at_login'] = ''
        else:
            cherrypy.session['report_requested_at_login'] = base + get_params

        # login to specific language
        lang = settings.DEFAULT_LANGUAGE
        #if (len(vpath) > 0) and (vpath[0] in settings.SUPPORTED_LANGUAGES):
        #    lang = vpath[0]

        #raise cherrypy.HTTPRedirect(base + '/' + lang + "/login")
        raise cherrypy.HTTPRedirect(base + '/login')
        #else:
        # user logged in and access denied
        #raise cherrypy.HTTPError(403, "Access to requested URL denied.")

    def check_access_or_goto_login(self, action, *vpath):
        """ Check access to resource. If access denied but user is logged
        in, redirect to login page with message.
        Does not return anything, just raises an exception if needed
        """
        base = cherrypy.config.get('tools.proxy.base', '')
        get_params = cherrypy.request.request_line.split()[1]

        #user = cherrypy.session.get('user', '')
        result = self.check_access(action, *vpath)
        if result == False:
            if user == '':
                # redirect here to login
                # url requested in the first place will be put
                # into session variable report_requested_at_login
                # the root report is not needed
                if len(vpath) == 0:
                    cherrypy.session['report_requested_at_login'] = ''
                else:
                    cherrypy.session[
                        'report_requested_at_login'] = base + get_params

                raise cherrypy.HTTPRedirect(base + "/login")
            else:
                # user logged in and access denied
                raise cherrypy.HTTPError(403,
                                         "Access to requested URL denied.")

    def set_lang(self, lang):
        """Sets current language for user based on sesseion variable
        """
        t = gettext.translation('messages',
                                localedir=self.locale_path,
                                languages=[lang])
        # all strings will be in utf-8. no unicode
        t.install(unicode=False)

    def set_lang_from_vpath(self, *vpath):
        #        "set current language depending on language element in path"
        lang = settings.DEFAULT_LANGUAGE
        #        if len(vpath) > 0:
        #            # we may have language mark
        #            if vpath[0] in settings.SUPPORTED_LANGUAGES:
        #                lang = vpath[0]
        #
        # The language for messages is set
        self.set_lang(lang)

    def reports_dir(self):
        """ Returns absolute path for reports storage
        """
        return cherrypy.config['dwwiki.wikidir']

    def find_real_file(self, *vpath):
        """ Finds real file from http path
        returns path to a real file or None if it's not found.
        Accounts for lang
        """
        final_path = None
        # Extract the path
        real_path = self.reports_dir()  # this should exist
        lang_path = real_path
        if len(vpath) > 0:
            for el in vpath:
                real_path = os.path.join(real_path, el)
                lang_path = os.path.join(lang_path, el)
#            for el in vpath:
#                # try for language
#                if el in settings.SUPPORTED_LANGUAGES:
#                    lang_path = os.path.join(lang_path, el)
#                else:
#                    real_path = os.path.join(real_path, el)
#                    lang_path = os.path.join(lang_path, el)

# make it absolute just in case
        real_path = os.path.abspath(real_path)
        lang_path = os.path.abspath(lang_path)

        # first try the lang path
        if os.path.isdir(lang_path):
            lang_path = os.path.join(lang_path, 'index.markdown')
        else:
            lang_path += '.markdown'

        if not os.path.exists(lang_path):
            # fall back to path without lang

            if os.path.isdir(real_path):
                # The path can possibly lead not to a file as such,
                # but to a directory. In that case we should return index.markdown
                # if one is present in a directory
                real_path = os.path.join(real_path, 'index.markdown')
            else:
                # it can be a file but witout extension or a nonexistent path
                real_path += '.markdown'

            if not os.path.exists(real_path):
                real_path = None
            final_path = real_path
        else:
            # lang_path exists
            final_path = lang_path

        return final_path

    @cherrypy.expose
    def default(self, *vpath, **params):
        base = cherrypy.config.get('tools.proxy.base', '')

        #redirect_to_lang = cherrypy.config.get('dwwiki.langredirect', False)
        #if len(vpath) == 0 and redirect_to_lang is True:
        #    lang = settings.DEFAULT_LANGUAGE
        #    target = base + '/' + lang + '/'
        #    raise cherrypy.HTTPRedirect(target)

        # This is path starting from base and including all params
        get_params = cherrypy.request.request_line.split()[1]
        user = cherrypy.session.get('user', '')

        # The language for messages is set
        self.set_lang_from_vpath(*vpath)

        # -------------------------------------
        # Next thing is to establish the action the user requires.
        # The user may want to do one of the following:
        # 1. Execute a report. It means there should be just a name of report
        #    without .markdown extension. Some parameters that are used in
        #    report generation may follow. E.g.:
        #    http://dwworks.ru/dwwiki/samplereport?year=2016
        #
        # 2. View report source. Just report source without any editing.
        #    In this case it should be just a path to report file. Like this:
        #    http://dwworks.ru/dwwiki/samplereport.markdown
        #    And no other params?
        #
        # 3. Edit report. That means view report in the editor. If the user
        #    has permission to 'read' report, it should be displayed, even if
        #    the user doesn't have permission to 'write' it. On an attempt
        #    to actually save it, it would be denied.
        #    Here we use a special reserved parameter - 'action'. Like this:
        #    http://dwworks.ru/dwwiki/samplereport?action=edit
        #
        # All above are meant to use GET request method.
        # If we have a POST request method, it means the user tries to

        # possible actions - 'action=xxx' understood by server
        URL_PARAM_ACTION = 'action'
        URL_ACTION_EDIT = 'edit'

        MARKDOWN_EXT = '.markdown'

        # what should we do?
        # execute
        #
        FINAL_ACTION_UNKNOWN = 0
        FINAL_ACTION_EXECUTE = 1
        FINAL_ACTION_VIEW_SOURCE = 2
        FINAL_ACTION_VIEW_EDITOR = 3
        # var
        final_action = FINAL_ACTION_UNKNOWN

        if cherrypy.request.method == 'GET':

            # if we have no params and file name ends with
            # .markdown, that means read raw text
            if len(vpath) > 0:
                # try for login/logout
                # try for read
                fn = vpath[-1]
                if fn == 'login':
                    method = getattr(self, 'login', None)
                    return method(*vpath, **params)
                elif fn == 'logout':
                    method = getattr(self, 'logout', None)
                    return method(*vpath, **params)

                if fn[-len(MARKDOWN_EXT):] == MARKDOWN_EXT:
                    final_action = FINAL_ACTION_VIEW_SOURCE

            # no result yet
            if final_action == FINAL_ACTION_UNKNOWN:
                # try for edit
                edit = params.get(URL_PARAM_ACTION, '')
                if edit == URL_ACTION_EDIT:
                    final_action = FINAL_ACTION_VIEW_EDITOR
                # nothing. try execute
                else:
                    final_action = FINAL_ACTION_EXECUTE

            # Now just feed the request to specific handlers
            if final_action == FINAL_ACTION_EXECUTE:
                method = getattr(self, 'mkdown', None)
                return method(*vpath, **params)
            elif final_action == FINAL_ACTION_VIEW_SOURCE:
                method = getattr(self, 'display_report_source', None)
                return method(*vpath, **params)
            elif final_action == FINAL_ACTION_VIEW_EDITOR:
                method = getattr(self, 'display_report_editor', None)
                return method(*vpath, **params)
        # end of GET method
        elif cherrypy.request.method == 'POST':
            if len(vpath) > 0:
                # try for login/logout
                # try for read
                fn = vpath[-1]
                if fn == 'login':
                    method = getattr(self, 'login', None)
                    return method(*vpath, **params)
            # maybe a user tried to save the edited report
            # in which case we have in our request line 'action=edit'
            # because the edited form is posted to the same URL
            # it was received from

            # params** here contains both params in url, like 'action=edit' and 'month=2'
            # and form fields too. like editor='report source text'
            action_param = params.get('action', '')
            if action_param == 'edit':
                method = getattr(self, 'save_report_editor', None)
                return method(*vpath, **params)
            else:
                # POST request without action=edit is not allowed
                # exception
                raise cherrypy.HTTPError(
                    405, "Post method with these parameters not implemented.")

    # declare streaming for default page
    default._cp_config = {'response.stream': True}

    # This routine shows the login page
    #@cherrypy.expose
    def login(self, *vpath, **params):
        self.set_lang_from_vpath(*vpath)
        #user = cherrypy.session['user']
        #if user == None:
        user = '******'
        base = cherrypy.config.get('tools.proxy.base', '')

        if cherrypy.request.method == 'GET':
            # show the form
            # format subheader
            # get requested login
            target_report = params.get('target', '')
            # in case it requests just the top of the server
            if target_report == '/':
                target_report = ''
            if target_report == base + '/':
                target_report = ''

            page_template = utils.get_report_template('loginform.html', *vpath)

            page_menu = utils.make_page_menu(langs=True)
            #subheader = htmlconstants.PAGE_LOGO.format(base=base)

            #result = loginform.LOGIN_PAGE_HEADER.format(base=base)
            #result += subheader

            # check for invalid logins
            notice = ''
            if cherrypy.session.get('last_login_incorrect', False):
                # show login incorrect
                notice = loginform.LOGIN_INCORRECT.format(
                    invalid_username=_('LC_INVALID_USERNAME'))

            page = page_template.format(
                base=base,
                title="login",
                notice=notice,
                lc_login_to_dw_wiki=_('LC_LOGIN_TO_DW_WIKI'),
                lc_user_name=_('LC_USER_NAME'),
                lc_password=_('LC_PASSWORD'),
                lc_navigate_to=_('LC_NAVIGATE_TO'),
                lc_log_in=_('LC_LOG_IN'),
                target_report=target_report,
                page_menu=page_menu)

            return page
        elif cherrypy.request.method == 'POST':
            base = cherrypy.config.get('tools.proxy.base', '')
            get_params = cherrypy.request.request_line.split()[1]
            # try to log the user in

            user = ''
            psswrd = ''
            target = ''

            if 'user' in params:
                user = params['user']
            if 'psswrd' in params:
                psswrd = params['psswrd']
            if 'target' in params:
                target = params['target']

            user_access = False

            ud = self.user_manager.get_user_data(user)
            if ud is not None:
                user_access = self.user_manager.check_password(ud, psswrd)

            if user_access is True:
                # ok. store user in session and redirect to report
                cherrypy.session['user'] = user
                if target == '':
                    #lang = settings.DEFAULT_LANGUAGE
                    #if len(vpath) > 0:
                    #    if vpath[0] in settings.SUPPORTED_LANGUAGES:
                    #        lang = vpath[0]
                    #target = base + '/' + lang + '/'
                    target = base + '/'

                # remove target from session.
                cherrypy.session['target'] = ''
                # remove invalid logins
                cherrypy.session['invalid_logins'] = 0
                # remove last login incorrect
                cherrypy.session['last_login_incorrect'] = False
                raise cherrypy.HTTPRedirect(target)
            else:
                # TODO unknown user/password.
                # redirect to itself again. target remains in session

                # Track invalid logins to lock user
                invalid_logins = 0
                if 'invalid_logins' in cherrypy.session:
                    invalid_logins = cherrypy.session['invalid_logins']
                invalid_logins += 1
                cherrypy.session['invalid_logins'] = invalid_logins
                cherrypy.session['last_login_incorrect'] = True

                #target = base + '/login'
                # TODO base and get_params base may include some get params
                #raise cherrypy.HTTPRedirect(base + get_params)
                raise cherrypy.HTTPRedirect(get_params)

            raise cherrypy.HTTPError(405, "Method not implemented.")
        else:
            raise cherrypy.HTTPError(405, "Method not implemented.")

    login._cp_config = {'response.stream': True}

    # routine used for logout
    @cherrypy.expose
    def logout(self, *vpath, **params):
        base = cherrypy.config.get('tools.proxy.base', '/')
        user = cherrypy.session.get('user', '')
        # if user is set, redirect to base.
        # Anyway, just redirect in any case
        cherrypy.session['user'] = ''
        # remove target from session.
        cherrypy.session['target'] = ''
        cherrypy.lib.sessions.expire()
        # TODO generally we should log all login-logout attempts
        lang = '/'
        raise cherrypy.HTTPRedirect(base)
#        if len(vpath) > 0:
#            if vpath[0] in settings.SUPPORTED_LANGUAGES:
#                lang = '/' + vpath[0] + '/'
#        raise cherrypy.HTTPRedirect(base + lang)

    def display_report_source(self, *vpath, **params):
        """ Display a markdown file as is.
        Security should be checked before calling this, for
        it is not checked. Nor does this function check
        for correct file extension. Just returns it as text/plain
        """
        real_path = self.reports_dir()
        # vpath should point to existing file. Otherwise we
        # generate 404 not found
        if len(vpath) > 0:
            for el in vpath:
                real_path = os.path.join(real_path, el)
        # make it absolute just in case
        real_path = os.path.abspath(real_path)
        if os.path.isdir(real_path):
            raise cherrypy.HTTPError(404, "Requested URL does not exist")
        else:
            # real_path is a file
            if not os.path.exists(real_path):
                raise cherrypy.HTTPError(404, "Requested URL does not exist")
            else:
                # file exists
                # TODO exceptions. file may not open
                cherrypy.response.headers[
                    'Content-Type'] = 'text/plain; charset=utf-8'
                input_file = codecs.open(real_path, mode="r", encoding="utf-8")
                result = input_file.read()
                input_file.close()
                return result

    def save_report_editor(self, *vpath, **params):
        """ Saves a reports that has been edited and returns
        may do one of the following:
        1. Return to a page the editor was called from
        2. Just save the report, inform user and stay on the same page
        3. Inform user that a report could not be saved for some reason
           and stay on the same page, displaying edited text
        """
        # try to save
        # check for allowance first
        new_file = False
        base = cherrypy.config.get('tools.proxy.base', '')
        get_params = cherrypy.request.request_line.split()[1]
        user = cherrypy.session.get('user', '')
        access_granted = self.check_access('write', *vpath)

        if access_granted:
            # Find a real file if there is one
            # A real filename is stored in url
            real_path = self.find_real_file(*vpath)

            if real_path is None:
                # we are about to create a new file
                rd = self.reports_dir()
                for el in vpath[:-1]:
                    rd = os.path.join(rd, el)
                if os.path.exists(rd) and os.path.isdir(rd):
                    # check if the name is good
                    fn = vpath[-1]
                    fn = fn.replace('.markdown', '')
                    # now check
                    # 1-new-report is good
                    # NewReport is bad, as is 1_new_report
                    p = re.compile(u'^[a-z,0-9]+[a-z,0-9,-]+[a-z,0-9]+$')
                    m = p.match(fn)
                    if m is None:
                        raise cherrypy.HTTPError(404,
                                                 _("LC_URL_DOES_NOT_EXIST"))

                    # file name is good. directory exists. go ahead, create a new file
                    # set flags here
                    new_file = True
                    new_file_name = fn + '.markdown'
                    real_path = os.path.join(rd, new_file_name)
                else:
                    raise cherrypy.HTTPError(404, _("LC_URL_DOES_NOT_EXIST"))

            # now access granted, file exists or will be created. Check if we have an editor param
            if not 'editor' in params:
                raise cherrypy.HTTPError(400, "Bad request")

            # now editor text is present.
            edit_text = params.get('editor', u'').encode('utf-8')

            # now remove CRLF and set LF instead
            edit_text = edit_text.replace("\r\n", '\n')
            # edit_text now is unicode
            # check if it's empty
            #if edit_text.strip() == '':
            #raise cherrypy.HTTPError(405, "Report text is an empty string. This is not allowed.")

            # now at last now we can save it
            # file may not be allowed for writing
            # with current server permissions
            try:
                # TODO here we must call version control after writing file
                f = open(real_path, 'w')
                f.write(edit_text)
                f.close()
            except Exception, e:
                # TODO don't return exception. Return back to editor
                raise cherrypy.HTTPError(405, _('LC_ERROR_WRITING_TO_FILE'))

            # Now redirect to the same URL the editor was called from
            # to test the file contents
            #back_link = base + get_params
            back_link = get_params

            # remove action=edit
            back_link = back_link.replace('&action=edit', '')
            back_link = back_link.replace('?action=edit', '')
            if back_link[-1:] in ['?', '&']:
                back_link = back_link[0:-1]

            # set the message

            cherrypy.session['info_message'] = _(
                'LC_INFO_REPORT_CHANGES_SAVED')
            # do the redirection

            # if just save, redirect to itself
            if 'save' in params:
                #raise cherrypy.HTTPRedirect(base + get_params)
                raise cherrypy.HTTPRedirect(get_params)
            # this is saveandclose
            else:
                raise cherrypy.HTTPRedirect(back_link)
        else:
Esempio n. 12
0
class DWWikiEngine(object):
    def __init__(self):
        # just in case
        locale.setlocale(locale.LC_ALL, 'en_US.utf-8')

        # This object is created once for all users
        self.user_manager = UserManager(settings.SERVICE_DB, settings.PWD_SALT)

        # locale path
        self.locale_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'locale')

        # Streamer lists
        self.block_streamers = list()
        self.inline_streamers = list()

        # Here we add our parsers. This should be made
        # easily extendable for custom parsers
        #self.streamer.add_block_parser(sqltablestreamer.SqlTableStreamer())
        #self.streamer.add_block_parser(sqlbarchartstreamer.SqlBarChartStreamer())
        #self.streamer.add_block_parser(sqllinechartstreamer.SqlLineChartStreamer())
        #self.streamer.add_inline_parser(SqlInlineStreamer())
        # security
        #self.guard = SecurityGuard('fileaccess.cfg', 'userlist.cfg')

    def register_block_streamer(self, streamer):
        self.block_streamers.append(streamer)

    def register_inline_streamer(self, streamer):
        self.inline_streamers.append(streamer)

    def get_streamer(self):
        """ Creates a new streamer per each request for thread safety.
        And returns it.
        """
        res = mdstreamer.MdStreamer()

        # Here we add all our streamers.
        for streamer in self.block_streamers:
            res.add_block_parser(streamer.factory())

        for streamer in self.inline_streamers:
            res.add_inline_parser(streamer.factory())

        #res.add_block_parser(SqlTableStreamer())
        #res.add_block_parser(SqlBarChartStreamer())
        #res.add_block_parser(SqlLineChartStreamer())
        #res.add_inline_parser(SqlInlineStreamer())

        return res


    def check_access(self, action, *vpath):
        """ Check access to some resource with security guard.
        Returns True if granted, False otherwise
        """
        user = cherrypy.session.get('user', '')
        rep_dir = self.reports_dir()
        #access_file = os.path.join(rep_dir, 'fileaccess.conf')
        quick_guard = SecurityGuard(settings.ACCESS_FILE, self.user_manager)
        res = quick_guard.request_access(user, action, *vpath)
        return res

    def goto_login(self, *vpath, **params):
        """ Redirects to login if user is not logged in
        """
        base = cherrypy.config.get('tools.proxy.base', '')
        get_params = cherrypy.request.request_line.split()[1]

        #user = cherrypy.session.get('user', '')
        #if user == '':
        # redirect here to login
        # url requested in the first place will be put
        # into session variable report_requested_at_login
        # the root report is not needed
        if len(vpath) == 0:
            cherrypy.session['report_requested_at_login'] = ''
        else:
            cherrypy.session['report_requested_at_login'] = base + get_params

        # login to specific language
        lang = settings.DEFAULT_LANGUAGE
        #if (len(vpath) > 0) and (vpath[0] in settings.SUPPORTED_LANGUAGES):
        #    lang = vpath[0]

        #raise cherrypy.HTTPRedirect(base + '/' + lang + "/login")
        raise cherrypy.HTTPRedirect(base + '/login')
        #else:
            # user logged in and access denied
            #raise cherrypy.HTTPError(403, "Access to requested URL denied.")

    def check_access_or_goto_login(self, action, *vpath):
        """ Check access to resource. If access denied but user is logged
        in, redirect to login page with message.
        Does not return anything, just raises an exception if needed
        """
        base = cherrypy.config.get('tools.proxy.base','')
        get_params = cherrypy.request.request_line.split()[1]

        #user = cherrypy.session.get('user', '')
        result = self.check_access(action, *vpath)
        if result == False:
            if user == '':
                # redirect here to login
                # url requested in the first place will be put
                # into session variable report_requested_at_login
                # the root report is not needed
                if len(vpath) == 0:
                    cherrypy.session['report_requested_at_login'] = ''
                else:
                    cherrypy.session['report_requested_at_login'] = base + get_params
                        
                raise cherrypy.HTTPRedirect(base + "/login")
            else:
                # user logged in and access denied
                raise cherrypy.HTTPError(403, "Access to requested URL denied.")

    def set_lang(self, lang):
        """Sets current language for user based on sesseion variable
        """
        t = gettext.translation('messages', localedir=self.locale_path, languages=[lang])
        # all strings will be in utf-8. no unicode
        t.install(unicode=False)

    def set_lang_from_vpath(self, *vpath):
#        "set current language depending on language element in path"
        lang = settings.DEFAULT_LANGUAGE
#        if len(vpath) > 0:
#            # we may have language mark
#            if vpath[0] in settings.SUPPORTED_LANGUAGES:
#                lang = vpath[0]
#
        # The language for messages is set
        self.set_lang(lang)
        
    def reports_dir(self):
        """ Returns absolute path for reports storage
        """
        return cherrypy.config['dwwiki.wikidir']

    def find_real_file(self, *vpath):
        """ Finds real file from http path
        returns path to a real file or None if it's not found.
        Accounts for lang
        """
        final_path = None
        # Extract the path
        real_path = self.reports_dir() # this should exist
        lang_path = real_path
        if len(vpath) > 0:
            for el in vpath:
                real_path = os.path.join(real_path, el)
                lang_path = os.path.join(lang_path, el)
#            for el in vpath:
#                # try for language
#                if el in settings.SUPPORTED_LANGUAGES:
#                    lang_path = os.path.join(lang_path, el)
#                else:
#                    real_path = os.path.join(real_path, el)
#                    lang_path = os.path.join(lang_path, el)
 
        # make it absolute just in case
        real_path = os.path.abspath(real_path)
        lang_path = os.path.abspath(lang_path)

        # first try the lang path
        if os.path.isdir(lang_path):
            lang_path = os.path.join(lang_path, 'index.markdown')
        else:
            lang_path += '.markdown'

        if not os.path.exists(lang_path):
            # fall back to path without lang

            if os.path.isdir(real_path):
                # The path can possibly lead not to a file as such,
                # but to a directory. In that case we should return index.markdown
                # if one is present in a directory
                real_path = os.path.join(real_path, 'index.markdown')
            else:
                # it can be a file but witout extension or a nonexistent path
                real_path += '.markdown'
        
            if not os.path.exists(real_path):
                real_path = None
            final_path = real_path
        else:
            # lang_path exists
            final_path = lang_path

        return final_path

    @cherrypy.expose
    def default(self, *vpath, **params):
        base = cherrypy.config.get('tools.proxy.base','')

        #redirect_to_lang = cherrypy.config.get('dwwiki.langredirect', False)
        #if len(vpath) == 0 and redirect_to_lang is True: 
        #    lang = settings.DEFAULT_LANGUAGE
        #    target = base + '/' + lang + '/'
        #    raise cherrypy.HTTPRedirect(target)


        # This is path starting from base and including all params
        get_params = cherrypy.request.request_line.split()[1]
        user = cherrypy.session.get('user', '')

        # The language for messages is set
        self.set_lang_from_vpath(*vpath)

        # -------------------------------------
        # Next thing is to establish the action the user requires.
        # The user may want to do one of the following:
        # 1. Execute a report. It means there should be just a name of report
        #    without .markdown extension. Some parameters that are used in 
        #    report generation may follow. E.g.:
        #    http://dwworks.ru/dwwiki/samplereport?year=2016
        #
        # 2. View report source. Just report source without any editing.
        #    In this case it should be just a path to report file. Like this:
        #    http://dwworks.ru/dwwiki/samplereport.markdown
        #    And no other params?
        #
        # 3. Edit report. That means view report in the editor. If the user
        #    has permission to 'read' report, it should be displayed, even if
        #    the user doesn't have permission to 'write' it. On an attempt
        #    to actually save it, it would be denied.
        #    Here we use a special reserved parameter - 'action'. Like this:
        #    http://dwworks.ru/dwwiki/samplereport?action=edit
        # 
        # All above are meant to use GET request method.
        # If we have a POST request method, it means the user tries to

        # possible actions - 'action=xxx' understood by server
        URL_PARAM_ACTION = 'action'
        URL_ACTION_EDIT = 'edit'

        MARKDOWN_EXT = '.markdown'

        # what should we do?
        # execute
        #
        FINAL_ACTION_UNKNOWN = 0
        FINAL_ACTION_EXECUTE = 1
        FINAL_ACTION_VIEW_SOURCE = 2
        FINAL_ACTION_VIEW_EDITOR = 3
        # var
        final_action = FINAL_ACTION_UNKNOWN

        if cherrypy.request.method == 'GET':

            # if we have no params and file name ends with
            # .markdown, that means read raw text
            if len(vpath) > 0:
                # try for login/logout
                # try for read
                fn = vpath[-1]
                if fn == 'login':
                    method = getattr(self, 'login', None)
                    return method(*vpath, **params)
                elif fn == 'logout':
                    method = getattr(self, 'logout', None)
                    return method(*vpath, **params)
                    

                if fn[-len(MARKDOWN_EXT):] == MARKDOWN_EXT:
                    final_action = FINAL_ACTION_VIEW_SOURCE

            # no result yet
            if final_action == FINAL_ACTION_UNKNOWN:
                # try for edit
                edit = params.get(URL_PARAM_ACTION, '')
                if edit == URL_ACTION_EDIT:
                    final_action = FINAL_ACTION_VIEW_EDITOR
                # nothing. try execute
                else:
                    final_action = FINAL_ACTION_EXECUTE
            
            # Now just feed the request to specific handlers    
            if final_action == FINAL_ACTION_EXECUTE:
                method = getattr(self, 'mkdown', None)
                return method(*vpath, **params)
            elif final_action == FINAL_ACTION_VIEW_SOURCE:
                method = getattr(self, 'display_report_source', None)
                return method(*vpath, **params)
            elif final_action == FINAL_ACTION_VIEW_EDITOR:
                method = getattr(self, 'display_report_editor', None)
                return method(*vpath, **params)
        # end of GET method
        elif cherrypy.request.method == 'POST':
            if len(vpath) > 0:
                # try for login/logout
                # try for read
                fn = vpath[-1]
                if fn == 'login':
                    method = getattr(self, 'login', None)
                    return method(*vpath, **params)
            # maybe a user tried to save the edited report
            # in which case we have in our request line 'action=edit'
            # because the edited form is posted to the same URL
            # it was received from

            # params** here contains both params in url, like 'action=edit' and 'month=2'
            # and form fields too. like editor='report source text'
            action_param = params.get('action', '')
            if action_param == 'edit':
                method = getattr(self, 'save_report_editor', None)
                return method(*vpath, **params)
            else:
                # POST request without action=edit is not allowed
                # exception
                raise cherrypy.HTTPError(405, "Post method with these parameters not implemented.")


    # declare streaming for default page
    default._cp_config = {'response.stream': True}


    # This routine shows the login page
    #@cherrypy.expose
    def login(self, *vpath, **params):
        self.set_lang_from_vpath(*vpath)
        #user = cherrypy.session['user']
        #if user == None:
        user = '******'
        base = cherrypy.config.get('tools.proxy.base','')

        if cherrypy.request.method == 'GET':
            # show the form
            # format subheader
            # get requested login
            target_report = params.get('target', '')
            # in case it requests just the top of the server
            if target_report == '/':
                target_report = ''
            if target_report == base + '/':
                target_report = ''


            page_template = utils.get_report_template('loginform.html', *vpath)


            page_menu = utils.make_page_menu(langs=True)
            #subheader = htmlconstants.PAGE_LOGO.format(base=base)
        
            #result = loginform.LOGIN_PAGE_HEADER.format(base=base)
            #result += subheader

            # check for invalid logins
            notice = ''
            if cherrypy.session.get('last_login_incorrect',False):
                # show login incorrect
                notice = loginform.LOGIN_INCORRECT.format(invalid_username=_('LC_INVALID_USERNAME'))

            page = page_template.format(base=base,
                                        title="login",
                                        notice=notice,
                                        lc_login_to_dw_wiki=_('LC_LOGIN_TO_DW_WIKI'),
                                        lc_user_name=_('LC_USER_NAME'),
                                        lc_password=_('LC_PASSWORD'),
                                        lc_navigate_to=_('LC_NAVIGATE_TO'),
                                        lc_log_in=_('LC_LOG_IN'),
                                        target_report=target_report,
                                        page_menu=page_menu)

            return page
        elif cherrypy.request.method == 'POST':
            base = cherrypy.config.get('tools.proxy.base','')
            get_params = cherrypy.request.request_line.split()[1]
            # try to log the user in

            user = ''
            psswrd = ''
            target = ''
            
            if 'user' in params:
                user = params['user']
            if 'psswrd' in params:
                psswrd = params['psswrd']
            if 'target' in params:
                target = params['target']

            user_access = False

            ud = self.user_manager.get_user_data(user)
            if ud is not None:
                user_access = self.user_manager.check_password(ud, psswrd)

            if user_access is True:
                # ok. store user in session and redirect to report
                cherrypy.session['user'] = user
                if target == '':
                    #lang = settings.DEFAULT_LANGUAGE
                    #if len(vpath) > 0:
                    #    if vpath[0] in settings.SUPPORTED_LANGUAGES:
                    #        lang = vpath[0]
                    #target = base + '/' + lang + '/'
                    target = base + '/'

                # remove target from session.
                cherrypy.session['target'] = ''
                # remove invalid logins
                cherrypy.session['invalid_logins'] = 0
                # remove last login incorrect
                cherrypy.session['last_login_incorrect'] = False
                raise cherrypy.HTTPRedirect(target)
            else:
                # TODO unknown user/password.
                # redirect to itself again. target remains in session

                # Track invalid logins to lock user
                invalid_logins = 0
                if 'invalid_logins' in cherrypy.session:
                    invalid_logins = cherrypy.session['invalid_logins']
                invalid_logins += 1
                cherrypy.session['invalid_logins'] = invalid_logins
                cherrypy.session['last_login_incorrect'] = True

                    
                #target = base + '/login'
                # TODO base and get_params base may include some get params
                #raise cherrypy.HTTPRedirect(base + get_params)
                raise cherrypy.HTTPRedirect(get_params)



            raise cherrypy.HTTPError(405, "Method not implemented.")
        else:
            raise cherrypy.HTTPError(405, "Method not implemented.")
            
    login._cp_config = {'response.stream': True}

    # routine used for logout
    @cherrypy.expose
    def logout(self, *vpath, **params):
        base = cherrypy.config.get('tools.proxy.base','/')
        user = cherrypy.session.get('user', '')
        # if user is set, redirect to base.
        # Anyway, just redirect in any case
        cherrypy.session['user'] = ''
        # remove target from session.
        cherrypy.session['target'] = ''
        cherrypy.lib.sessions.expire()
        # TODO generally we should log all login-logout attempts
        lang = '/'
        raise cherrypy.HTTPRedirect(base)
#        if len(vpath) > 0:
#            if vpath[0] in settings.SUPPORTED_LANGUAGES:
#                lang = '/' + vpath[0] + '/'
#        raise cherrypy.HTTPRedirect(base + lang)


    
    def display_report_source(self, *vpath, **params):
        """ Display a markdown file as is.
        Security should be checked before calling this, for
        it is not checked. Nor does this function check
        for correct file extension. Just returns it as text/plain
        """
        real_path = self.reports_dir()
        # vpath should point to existing file. Otherwise we
        # generate 404 not found
        if len(vpath) > 0:
            for el in vpath:
                real_path = os.path.join(real_path, el)
        # make it absolute just in case
        real_path = os.path.abspath(real_path)
        if os.path.isdir(real_path):
            raise cherrypy.HTTPError(404, "Requested URL does not exist")
        else:
            # real_path is a file
            if not os.path.exists(real_path):
                raise cherrypy.HTTPError(404, "Requested URL does not exist")
            else:
                # file exists
                # TODO exceptions. file may not open
                cherrypy.response.headers['Content-Type'] = 'text/plain; charset=utf-8'
                input_file = codecs.open(real_path, mode="r", encoding="utf-8")
                result = input_file.read()
                input_file.close()
                return result


    def save_report_editor(self, *vpath, **params):
        """ Saves a reports that has been edited and returns
        may do one of the following:
        1. Return to a page the editor was called from
        2. Just save the report, inform user and stay on the same page
        3. Inform user that a report could not be saved for some reason
           and stay on the same page, displaying edited text
        """
        # try to save
        # check for allowance first
        new_file = False
        base = cherrypy.config.get('tools.proxy.base','')
        get_params = cherrypy.request.request_line.split()[1]
        user = cherrypy.session.get('user', '')
        access_granted = self.check_access('write', *vpath)

        if access_granted:
            # Find a real file if there is one
            # A real filename is stored in url
            real_path = self.find_real_file(*vpath)
    
            if real_path is None:
                # we are about to create a new file
                rd = self.reports_dir()
                for el in vpath[:-1]:
                    rd = os.path.join(rd, el)
                if os.path.exists(rd) and os.path.isdir(rd):
                    # check if the name is good
                    fn = vpath[-1]
                    fn = fn.replace('.markdown', '')
                    # now check
                    # 1-new-report is good
                    # NewReport is bad, as is 1_new_report
                    p = re.compile(u'^[a-z,0-9]+[a-z,0-9,-]+[a-z,0-9]+$')
                    m = p.match(fn)
                    if m is None:
                        raise cherrypy.HTTPError(404, _("LC_URL_DOES_NOT_EXIST"))

                    # file name is good. directory exists. go ahead, create a new file
                    # set flags here
                    new_file = True
                    new_file_name = fn + '.markdown'
                    real_path = os.path.join(rd, new_file_name)    
                else:
                    raise cherrypy.HTTPError(404, _("LC_URL_DOES_NOT_EXIST"))

            # now access granted, file exists or will be created. Check if we have an editor param
            if not 'editor' in params:
                raise cherrypy.HTTPError(400, "Bad request")

            # now editor text is present.
            edit_text = params.get('editor', u'').encode('utf-8')

            # now remove CRLF and set LF instead
            edit_text = edit_text.replace("\r\n", '\n')
            # edit_text now is unicode
            # check if it's empty
            #if edit_text.strip() == '':
                #raise cherrypy.HTTPError(405, "Report text is an empty string. This is not allowed.")

            # now at last now we can save it
            # file may not be allowed for writing
            # with current server permissions
            try:
                # TODO here we must call version control after writing file
                f = open(real_path, 'w')
                f.write(edit_text)
                f.close()
            except Exception, e:
                # TODO don't return exception. Return back to editor
                raise cherrypy.HTTPError(405, _('LC_ERROR_WRITING_TO_FILE'))
                
            # Now redirect to the same URL the editor was called from
            # to test the file contents
            #back_link = base + get_params
            back_link = get_params
            
            # remove action=edit
            back_link = back_link.replace('&action=edit', '')
            back_link = back_link.replace('?action=edit', '')
            if back_link[-1:] in ['?', '&']:
                back_link = back_link[0:-1]

            # set the message


            cherrypy.session['info_message'] = _('LC_INFO_REPORT_CHANGES_SAVED')
            # do the redirection

            # if just save, redirect to itself
            if 'save' in params:
                #raise cherrypy.HTTPRedirect(base + get_params)
                raise cherrypy.HTTPRedirect(get_params)
            # this is saveandclose
            else:
                raise cherrypy.HTTPRedirect(back_link)
        else:
Esempio n. 13
0
import binascii
import struct
import time
import zlib

from constants import *
from charactermanager import CharacterManager
from entitymanager import EntityManager
from groupserver import GroupServer
from usermanager import UserManager
from zoneserver import ZoneServer

characterManager = CharacterManager()
entityManager = EntityManager()
groupServer = GroupServer()
userManager = UserManager()
zoneServer = ZoneServer()


class GatewayServer(asyncio.Protocol):
    def connection_made(self, transport):
        self.transport = transport
        self.client = (
            transport.get_extra_info('peername')[0] + ":"  # IP
            + str(transport.get_extra_info('peername')[1]))  # port
        print("Connection from: " + self.client)

        self.msgSource = b'\xdd' + b'\x00\x7b'[::-1]
        self.msgDest = b'\x01' + b'\x00\x32'[::-1]

        self.characterManager = characterManager
Esempio n. 14
0
from flask_seasurf import SeaSurf

from usermanager import UserManager
from blogmanager import BlogManager

SESSION_USERNAME = "******"

app = Flask(__name__)

app.config.update(DEBUG=True,
                  SECRET_KEY=secrets.token_hex(32),
                  SESSION_TYPE="filesystem",
                  SESSION_COOKIE_HTTPONLY=False)

Session(app)
usermanager = UserManager("users.json")
blogmanager = BlogManager("blogs.json")

csrf = SeaSurf(app)


def login_user(username):
    session[SESSION_USERNAME] = username
    return redirect("/", code=302)


def logged_in():
    return session.get(SESSION_USERNAME)


def sanitize(text):
		parser.add_option("-G", "--primaryGroup", dest="primarygroup",default=None,
		                  help="the user's primary group", metavar="PRIMARYGROUP")
		parser.add_option("-p", "--password", dest="password",default=None,
		                  help="users password - avoid using this we dont like passwords in clear text!",
		                  metavar="PASSWORD")
		(options, args) = parser.parse_args()
		
		if len(args)<2:
			print "Missing username for createuser operation"
			exit(0)
		username = check_username(args[1])
		if not username:
			print "The given username is invalid."
			exit(0)
		
		um = UserManager()
		if um.user_exists(username):
			print "The user %s already exists" % username
			exit(0)
		
		if not options.givenname:
			options.givenname = raw_input("Input the user's given name (first name): ")
		if not options.familyname:
			options.familyname = raw_input("Input the user's family name (last name): ")
		if not options.usertype:
			options.usertype = raw_input("Input the user's account type (teacher,student,parent or other): ")
		
		options.usertype = userdef.usertype_as_id(options.usertype)
		if not options.usertype:
			print "Invalid usertype"
			exit(0)
class LazzorManager(object):
    def __init__(self, config_file_path):
        config = ConfigParser.RawConfigParser()
        config.read(config_file_path)

        self._logger = logging.getLogger(__name__)
        self._ui = UI("lazzormanagement\nbooting...")

        user_config_file_path = os.path.dirname(config_file_path) + \
                os.path.sep + config.get('Users', 'users_file')
        self._user_manager = UserManager(user_config_file_path)
        self._lazzor = Lazzor()
 
        while True:
            try:
                self._upay_session_manager = nupay.SessionManager(config)
                break
            except nupay.SessionConnectionError as e:
                self._logger.warning("Can not reach the database")
                self._ui.warning_database_connection(timeout = 5)
            except nupay.TimeoutError as e:
                self._logger.warning("Timeout while connection to the database")
                self._ui.warning_database_connection(timeout = 5)

            self._ui.notify_try_again()


        self._token_reader = nupay.USBTokenReader()

    def _login(self):
        while True:
            user = self._ui.choose_user(self._user_manager.users)

            passcode = self._ui.get_passcode(user.username)
            
            passcode_ok = self._user_manager.check_passcode(user, passcode)

            if passcode_ok == False:
                self._ui.notify_bad_passcode(user.timeout)
            elif user.active == False:
                self._ui.notify_inactive_user(user.username)
            else:
                self._logger.debug("Leaving user selection mode")
                return user
    
    def _activate_laser(self, user):

        def ui_update(session):
            if session.credit % 5 == 0:
                self._ui.update_credit(session.credit)

        self._logger.info("Waiting for USB stick with purse")
        self._ui.notify_waiting_for_usb()
        
        while True: 
            try:
                tokens = self._token_reader.read_tokens()
                break
            except nupay.NoTokensAvailableError:
                if self._ui.check_button_pressed():
                    self._ui.wait_for_buttons()
                    return
                time.sleep(1)

        self._logger.info("Read %d tokens"%len(tokens))
        self._ui.notify_credit()
        try:
            with self._upay_session_manager.create_session() as session:
                session.validate_tokens(tokens, ui_update)
                self._ui.update_credit(session.credit)
                self._logger.info("Balance is %.02f Eur" % session.credit)
                self._ui.wait_for_ok()
                if session.credit > 0:
                    self._run_payment_loop(session)
        
        except nupay.SessionConnectionError as e:
            self._logger.warning("Databse connection could not be estalished")
            self._ui.warning_database_connection(timeout = 5)
        except nupay.TimeoutError:
            self._logger.warning("Databse connection timed out")
            self._ui.warning_database_connection(timeout = 5)
        finally:
            self._lazzor.lock_laser()

    def _run_payment_loop(self, session):
        total_on_time = 0
        prev_on_time = 0

        paid_time = 0
        minute_cost = Decimal(0.5)
        sub_total = Decimal(0)

        self._ui.active_screen()

        self._lazzor.lock_laser()
        self._lazzor.reset_consumption_timer()

        while self._token_reader.medium_valid:
            if total_on_time > paid_time:
                self._logger.info("Getting more money")
                try:
                    session.cash(minute_cost)
                    sub_total += minute_cost
                    paid_time += 60
                except nupay.NotEnoughCreditError:
                    self._lazzor.sound_alarm_tone()
                    self._logger.warning("Not enough credit available")
                    self._ui.warning_low_credit(timeout = 30)
                    self._lazzor.silence_alarm_tone()
                    break
                except nupay.TimeoutError:
                    self._logger.warning("Databse connection timed out")
                    self._lazzor.sound_alarm_tone()
                    self._ui.warning_database_connection(timeout = 30)
                    self._lazzor.silence_alarm_tone()
                    break

            if not self._lazzor.is_laser_unlocked and self._ui.is_turn_on_key_pressed:
                self._logger.info("Laser is locked, user wants to turn it on")
                self._lazzor.unlock_laser()
                sub_total = 0

            if self._lazzor.is_laser_unlocked and self._ui.is_turn_off_key_pressed:
                self._logger.info("Laser is unlocked, user wants to turn it off")
                self._lazzor.lock_laser()
                prev_on_time += self._lazzor.get_consumption_timer()
                self._lazzor.reset_consumption_timer()
            
            if self._ui.is_exit_key_pressed:
                break

            time.sleep(.1)
            total_on_time = self._lazzor.get_consumption_timer() + prev_on_time
            self._ui.update_active_screen(self._lazzor.get_consumption_timer(), total_on_time,
                    sub_total, session.total, session.credit, self._lazzor.is_laser_unlocked)
    
        if not self._token_reader.medium_valid:
            self._logger.warning("Token medium vanished. Aborting.")

    def _change_passcode(self, user):
        pass

    def run(self):
        while True:
            user = self._login()
            while True:
                options = ["Activate Laser", "Logout", "Change Passcode"]

                option = self._ui.choose_option("Action:", options)
                if option == "Logout":
                    break
                if option == "Activate Laser":
                    self._activate_laser(user)
                if option == "Change Passcode":
                    self._change_passcode(user)
Esempio n. 17
0
class UserForm(BasicUserForm):

    def __init__(self, app_title, app_banner, theme, target, assets_manager_service, mail_sender_service):
        """
        In:
         - ``target`` -- DataUser instance
         - ``mail_sender_service`` -- MailSender service
        """
        super(UserForm, self).__init__(target, self.fields)

        self.app_title = app_title
        self.app_banner = app_banner
        self.theme = theme
        self.mail_sender = mail_sender_service
        self.assets_manager = assets_manager_service
        self.username.validate(self.validate_username)
        self.fullname.validate(validators.validate_non_empty_string)

        # Add other properties (email to confirm, passwords...)
        self.email_to_confirm = editor.Property(
            target.email).validate(validators.validate_email)
        self.old_password = editor.Property(
            '').validate(self.validate_old_password)
        self.password = editor.Property('').validate(self.validate_password)
        self.password_repeat = editor.Property(
            '').validate(self.validate_passwords_match)
        self.user_manager = UserManager()

    def validate_username(self, value):
        """Check username

        In:
         - ``value`` -- username (must be unique)
        Return:
         - username value if username is unique (else raise an exception)
        """
        value = validators.validate_identifier(value)
        # check that this user name does not exist
        user = self.user_manager.get_by_username(value)
        if user:
            raise ValueError(_("Username %s is not available. Please choose another one.")
                             % value)
        return value

    def validate_password(self, value):
        """Check new password

        In:
         - ``value`` -- new password (must be greater than 6 chars)
        Return:
         - password value if password is ok (else raise an exception)
        """
        # check password complexity
        min_len = 6

        if len(value) < min_len and len(value) > 0:
            raise ValueError(_("Password too short: should have at least %d characters")
                             % min_len)
        return value

    def validate_old_password(self, value):
        """Check old password

        In:
         - ``value`` -- old password
        Return:
         - password value if value is the old password
        """
        if len(value) == 0 or security.get_user().data.check_password(value):
            return self.validate_password(value)
        raise ValueError(_("This password doesn't match the old one."))

    def validate_passwords_match(self, value):
        """Check if confirmation password and password are equals

        In:
         - ``value`` -- confirmation password
        Return:
         - password value if confirmation password and password are equals
        """
        if self.password.value == value:
            return value
        else:
            raise ValueError(_("The two passwords don't match"))

    def _create_email_confirmation(self, application_url):
        """Create email confirmation"""
        confirmation_url = '/'.join(
            (application_url, 'new_mail', self.username()))
        return registation_forms.EmailConfirmation(self.app_title, self.app_banner, self.theme, lambda: security.get_user().data, confirmation_url)

    def commit(self, application_url):
        """ Commit method

        If email changes, send confirmation mail to user
        If password changes, check passwords rules
        """
        if not self.is_validated(self.fields):
            return
        # Test if email_to_confirm has changed
        if (self.target.email_to_confirm != self.email_to_confirm() and
                self.target.email != self.email_to_confirm()):
            # Change target email_to_confirm (need it to send mail)
            self.target.email_to_confirm = self.email_to_confirm()
            confirmation = self._create_email_confirmation(application_url)
            confirmation.send_email(self.mail_sender)
            self.email_to_confirm.info = _(
                "A confirmation email has been sent.")
        # Test if password has changed
        if (len(self.password()) > 0 and
                not(self.old_password.error) and
                not(self.password_repeat.error)):
            user = security.get_user()
            user.data.change_password(self.password())
            user.update_password(self.password())
            self.password_repeat.info = _("The password has been changed")
        super(BasicUserForm, self).commit(self.fields)

    def set_picture(self, new_file):
        uid = self.target.username
        self.picture.error = None
        error = None

        # No value, exit
        if new_file == '':
            return None

        try:
            validators.validate_file(
                new_file, self.assets_manager.max_size, _(u'File must be less than %d KB'))
        except ValueError, e:
            error = e.message
        if imghdr.what(new_file.file) is None:
            error = _(u'Invalid image file')

        if error:
            self.picture.error = error
            return None

        # Remove old value
        if self.target.picture:
            self.assets_manager.delete(uid)

        # Save new value
        self.assets_manager.save(new_file.file.read(), file_id=uid, metadata={
            'filename': new_file.filename, 'content-type': new_file.type}, thumb_size=(100, 100))
        self.picture(self.assets_manager.get_image_url(uid, size='thumb'))
 def tearDown(self):
     UserManager.create_user('testosteroni', '@!!$testosteroni', 'test',
                             'osterone')
 def test_retrieve_user_info_vs_original(self):
     # User ID of Ryan Paulos
     user_manager_data = UserManager.retrieve_user_info(12)
     ret_data = old.retrieve_user_info(12)
     self.assertEqual(user_manager_data, ret_data)
 def test_retrieve_users_against_original_functions(self):
     user_manager_data = UserManager.retrieve_users()
     ret_data = old.retrieve_all_user_objects(1)
     self.assertEqual(user_manager_data, ret_data)
 def test_user_edit_login(self):
     person = copy.deepcopy(TestUser.user)
     ret = person.edit_login('testosteroniIsKing')
     self.assertEqual(True, ret)
     tes = UserManager.search_person_id('@!!$testosteroni')
     self.assertEqual(tes['sis_login_id'], 'testosteroniIsKing')
 def setUp(self):
     CouncilConnect.init_session()
     TestUser.user = user.User(3081, 'test osterone', '@!!$testosteroni',
                               '*****@*****.**')
     UserManager.create_enrollment(3081, 15, 'TeacherEnrollment', '13')
     UserManager.create_enrollment(3081, 1, 'TeacherEnrollment', '13')
 def test_search_person_id(self):
     # Person ID of Ryan Paulos
     ret = UserManager.search_person_id(
         '1EF69564-83D7-463A-B3F7-F1CFAA076554')
     self.assertEqual(ret['id'], 12)
 def test_delete_person(self):
     # user is created
     UserManager.delete_user(3081)
     search = UserManager.search_person_id(3081)
     self.assertEqual(None, search)
Esempio n. 25
0
class UserForm(BasicUserForm):

    def __init__(self, app_title, app_banner, custom_css, target, assets_manager_service, mail_sender_service):
        """
        In:
         - ``target`` -- DataUser instance
         - ``mail_sender_service`` -- MailSender service
        """
        super(UserForm, self).__init__(target, self.fields)

        self.app_title = app_title
        self.app_banner = app_banner
        self.custom_css = custom_css
        self.mail_sender = mail_sender_service
        self.assets_manager = assets_manager_service
        self.username.validate(self.validate_username)
        self.fullname.validate(validators.validate_non_empty_string)

        # Add other properties (email to confirm, passwords...)
        self.email_to_confirm = editor.Property(
            target.email).validate(validators.validate_email)
        self.old_password = editor.Property(
            '').validate(self.validate_old_password)
        self.password = editor.Property('').validate(self.validate_password)
        self.password_repeat = editor.Property(
            '').validate(self.validate_passwords_match)
        self.user_manager = UserManager()

    def validate_username(self, value):
        """Check username

        In:
         - ``value`` -- username (must be unique)
        Return:
         - username value if username is unique (else raise an exception)
        """
        value = validators.validate_identifier(value)
        # check that this user name does not exist
        user = self.user_manager.get_by_username(value)
        if user:
            raise ValueError(_("Username %s is not available. Please choose another one.")
                             % value)
        return value

    def validate_password(self, value):
        """Check new password

        In:
         - ``value`` -- new password (must be greater than 6 chars)
        Return:
         - password value if password is ok (else raise an exception)
        """
        # check password complexity
        min_len = 6

        if len(value) < min_len and len(value) > 0:
            raise ValueError(_("Password too short: should have at least %d characters")
                             % min_len)
        return value

    def validate_old_password(self, value):
        """Check old password

        In:
         - ``value`` -- old password
        Return:
         - password value if value is the old password
        """
        if len(value) == 0 or security.get_user().data.check_password(value):
            return self.validate_password(value)
        raise ValueError(_("This password doesn't match the old one."))

    def validate_passwords_match(self, value):
        """Check if confirmation password and password are equals

        In:
         - ``value`` -- confirmation password
        Return:
         - password value if confirmation password and password are equals
        """
        if self.password.value == value:
            return value
        else:
            raise ValueError(_("The two passwords don't match"))

    def _create_email_confirmation(self, application_url):
        """Create email confirmation"""
        confirmation_url = '/'.join(
            (application_url, 'new_mail', self.username()))
        return registation_forms.EmailConfirmation(self.app_title, self.app_banner, self.custom_css, lambda: security.get_user().data, confirmation_url)

    def commit(self, application_url):
        """ Commit method

        If email changes, send confirmation mail to user
        If password changes, check passwords rules
        """
        if not self.is_validated(self.fields):
            return
        # Test if email_to_confirm has changed
        if (self.target.email_to_confirm != self.email_to_confirm() and
                self.target.email != self.email_to_confirm()):
            # Change target email_to_confirm (need it to send mail)
            self.target.email_to_confirm = self.email_to_confirm()
            confirmation = self._create_email_confirmation(application_url)
            confirmation.send_email(self.mail_sender)
            self.email_to_confirm.info = _(
                "A confirmation email has been sent.")
        # Test if password has changed
        if (len(self.password()) > 0 and
                not(self.old_password.error) and
                not(self.password_repeat.error)):
            user = security.get_user()
            user.data.change_password(self.password())
            user.update_password(self.password())
            self.password_repeat.info = _("The password has been changed")
        super(BasicUserForm, self).commit(self.fields)

    def set_picture(self, new_file):
        uid = self.target.username
        self.picture.error = None
        error = None

        # No value, exit
        if new_file == '':
            return None

        try:
            validators.validate_file(
                new_file, self.assets_manager.max_size, _(u'File must be less than %d KB'))
        except ValueError, e:
            error = e.message
        if imghdr.what(new_file.file) is None:
            error = _(u'Invalid image file')

        if error:
            self.picture.error = error
            return None

        # Remove old value
        if self.target.picture:
            self.assets_manager.delete(uid)

        # Save new value
        self.assets_manager.save(new_file.file.read(), file_id=uid, metadata={
            'filename': new_file.filename, 'content-type': new_file.type}, thumb_size=(100, 100))
        self.picture(self.assets_manager.get_image_url(uid, size='thumb'))
 def test_create_enrollment(self):
     # Enrolling Ryan Paulos into the accreditation course with 'Employee' permissions
     req = UserManager.create_enrollment(12, 15, 'TeacherEnrollment', 13)
     self.assertEqual(200, req.status_code)
Esempio n. 27
0
from councilconnect import CouncilConnect
from usermanager import UserManager
import os

import usermanager

if __name__ == "__main__":

    #CouncilConnect.url('https://councils.clark.edu/')  # The trailing slash is required
    #CouncilConnect.token(os.getenv('CCtoken'))  # Will require explanation in the docs
    CouncilConnect.alert_recipient(
        '*****@*****.**')  # where failure alerts will be sent
    CouncilConnect.init_session()  # Gets things ready. MUST be called.

    #user = UserManager.search_person_id('@!!$testosteroni')
    #users = UserManager.retrieve_users()

    UserManager.search_person_id('@!!$testosteroni')
Esempio n. 28
0
    :return:
    '''
    # Allowing own user ID name
    user_ID_choice = raw_input('Please choose an ID name? ')
    userManager.create_user(user_ID_choice)
    print 'thank you ' + user_ID_choice +'. You are now a library user.'


if __name__ == "__main__":
    '''
    Script to run the manage the library users and their accounts.
    '''
    # here we call the library controller class.
    libraryController = LibraryController(verbose=True)
    itemManager = ItemManager()
    userManager = UserManager()

    # set library controller
    itemManager.set_library_controller(libraryController)
    userManager.set_library_controller(libraryController)
    # initiating the item database.
    itemManager.create_database('top100t.txt')

    # code to add user.
    # first need to ask, are you a user

    while raw_input('Create new user (yes/no) ? ') == 'yes':
        # will generate a new user
        new_user_query(userManager)

    # function to perform operation