Exemplo n.º 1
0
    def get(self):
        session = SessionHandler()
        session.logout()

        clear_cookie(self, name="_ut_")

        if self.GET("r"):
            url = urllib.unquote(str(self.GET("r")))
        else:
            url = self.request.referer

        self.redirect(url)
Exemplo n.º 2
0
    def get(self):
        """
            Handles the /logout endpoint.
            Logs out users.
        """
        session = SessionHandler()
        session.logout()

        clear_cookie(self, name="_ut_")

        success = "You have logged out successfully!"
        success_message(self, success)
        self.redirect("/login")
Exemplo n.º 3
0
    def _configure(self, config_name, action, contents):
        """
        The main configuration for volttron central.  This is where validation
        will occur.

        Note this method is called:

            1. When the agent first starts (with the params from packaged agent
               file)
            2. When 'store' is called through the volttron-ctl config command
               line with 'config' as the name.

        Required Configuration:

        The volttron central requires a user mapping.

        :param config_name:
        :param action:
        :param contents:
        """
        config = self._default_config.copy()

        config.update(contents)

        users = config.get("users", None)

        if self._authenticated_sessions:
            self._authenticated_sessions.clear()

        if users is None:
            users = {}
            _log.warn("No users are available for logging in!")

        # Unregister all routes for vc and then re-add down below.
        self.vip.web.unregister_all_routes()

        self._authenticated_sessions = SessionHandler(Authenticate(users))

        self.vip.web.register_endpoint(r'/vc/jsonrpc', self.jsonrpc)

        self.vip.web.register_websocket(r'/vc/ws',
                                        self.open_authenticate_ws_endpoint,
                                        self._ws_closed,
                                        self._ws_received)

        self.vip.web.register_path(r'^/vc/.*',
                                   config.get('webroot'))

        # Start scanning for new platforms connections as well as for
        # disconnects that happen.
        self._scan_platform_connect_disconnect()
Exemplo n.º 4
0
    def __init__(self, request=None, response=None):
        self.initialize(request, response)
        self.tv = {}
        self.tv["user"] = None
        self.tv["local"] = APP_IS_LOCAL
        self.tv["show_breadcrumb"] = True
        self.tv["show_add_dataset"] = True

        self.tv["v"] = os.environ.get('CURRENT_VERSION_ID')

        self.user = None
        self.GET = self.request.get
        self.POST = self.request.POST.get

        try:
            self.user = SessionHandler().owner
            global_vars.user = self.user
        except Exception, e:
            self.user = None
Exemplo n.º 5
0
    def configure_main(self, config_name, action, contents):
        """
        The main configuration for volttron central.  This is where validation
        will occur.

        Note this method is called:

            1. When the agent first starts (with the params from packaged agent
               file)
            2. When 'store' is called through the volttron-ctl config command
               line with 'config' as the name.

        Required Configuration:

        The volttron central requires a user mapping.

        :param config_name:
        :param action:
        :param contents:
        """

        _log.debug('Main config updated')
        _log.debug('ACTION IS {}'.format(action))
        _log.debug('CONTENT IS {}'.format(contents))
        if action == 'DELETE':
            # Remove the registry and keep the service running.
            self.runtime_config = None
            # Now stop the exposition of service.
        else:
            self.runtime_config = self.default_config.copy()
            self.runtime_config.update(contents)

            problems = self._validate_config_params(self.runtime_config)

            if len(problems) > 0:
                _log.error(
                    "The following configuration problems were detected!")
                for p in problems:
                    _log.error(p)
                sys.exit(INVALID_CONFIGURATION_CODE)
            else:
                _log.info('volttron central webroot is: {}'.format(
                    self.runtime_config.get('webroot')))

                users = self.runtime_config.get('users')
                self.web_sessions = SessionHandler(Authenticate(users))

            _log.debug('Querying router for addresses and serverkey.')
            q = Query(self.core)

            external_addresses = q.query('addresses').get(timeout=5)
            self.runtime_config['local_external_address'] = external_addresses[
                0]

        self.vip.web.register_websocket(r'/vc/ws',
                                        self.open_authenticate_ws_endpoint,
                                        self._ws_closed, self._ws_received)
        self.vip.web.register_endpoint(r'/jsonrpc', self.jsonrpc)
        self.vip.web.register_path(r'^/.*', self.runtime_config.get('webroot'))

        # Start scanning for new platforms connections as well as for
        # disconnects that happen.
        self._scan_for_platforms()
Exemplo n.º 6
0
    def post(self):
        """
            Handles the /login endpoint.
            Logs in users.
        """
        if self.POST("email") and self.POST("password"):
            url = "/login"
            redirect = None
            email = self.POST("email").strip().lower()
            query = User.query()
            query = query.filter(User.current_email == email)
            user = query.get()

            if self.POST("redirect"):
                redirect = urllib.quote(self.POST("redirect"))
                url += "?redirect=" + str(redirect)

            if not user:
                error = "Invalid email or password."
                error_message(self, error)
                self.redirect(url)
                return

            if user.hashed_password:
                if not user.verify_password(self.POST("password")):
                    error = "Invalid email or password."
                    error_message(self, error)
                    self.redirect(url)
                    return
            else:
                password = hp(email=email, password=self.POST("password"))
                if user.password != password:
                    error = "Invalid email or password."
                    error_message(self, error)
                    self.redirect(url)
                    return
                else:
                    user.hashed_password = user.hash_password(
                        self.POST("password"))
                    user.put()

            if user.status == "PENDING":
                error = "Your account has not been verified. "
                error += "Please verify your account by opening the "
                error += "verification email we sent you. "
                error_message(self, error)
                self.redirect(url)
                return

            if user.status == "DISABLED":
                error = "Your account has been disabled. "
                error += "Please contact the Geostore Admin."
                error_message(self, error)
                self.redirect(url)
                return

            if user.role in ["AGENCYADMIN", "USER"]:
                if user.status == "VERIFIED":
                    error = "Your account is still pending approval. "
                    error += "Once your account is approved, you will be able "
                    error += "to login. You will receive an email once your "
                    error += "account is approved."
                    error_message(self, error)
                    self.redirect(url)
                    return

                if user.status == "DISAPPROVED":
                    error = "Your account has been disapproved. "
                    error += "Please contact the Geostore Admin."
                    error_message(self, error)
                    self.redirect(url)
                    return

            user.csrf_token = generate_token()
            session = SessionHandler(user)
            session.login()
            code = session.generate_login_code()
            if self.POST("redirect"):
                self.redirect(urllib.unquote(str(self.POST("redirect"))))
            else:
                self.redirect("/dashboard")
            return

        error = "Please enter your email and password."
        error_message(self, error)
        self.redirect("/login")
Exemplo n.º 7
0
    def __init__(self, config_path, **kwargs):
        """ Creates a `VolttronCentralAgent` object to manage instances.

         Each instances that is registered must contain a running
         `VolttronCentralPlatform`.  Through this conduit the
         `VolttronCentralAgent` is able to communicate securly and
         efficiently.

        :param config_path:
        :param kwargs:
        :return:
        """
        _log.info("{} constructing...".format(self.__name__))

        # This is a special object so only use it's identity.
        identity = kwargs.pop("identity", None)
        identity = VOLTTRON_CENTRAL

        super(VolttronCentralAgent, self).__init__(identity=identity, **kwargs)
        # Load the configuration into a dictionary
        self._config = utils.load_config(config_path)

        # Expose the webroot property to be customized through the config
        # file.
        self._webroot = self._config.get('webroot', DEFAULT_WEB_ROOT)
        if self._webroot.endswith('/'):
            self._webroot = self._webroot[:-1]
        _log.debug('The webroot is {}'.format(self._webroot))

        # Required users
        self._user_map = self._config.get('users', None)

        _log.debug("User map is: {}".format(self._user_map))
        if self._user_map is None:
            raise ValueError('users not specified within the config file.')

        # Search and replace for topics
        # The difference between the list and the map is that the list
        # specifies the search and replaces that should be done on all of the
        # incoming topics.  Once all of the search and replaces are done then
        # the mapping from the original to the final is stored in the map.
        self._topic_replace_list = self._config.get('topic_replace_list', [])
        self._topic_replace_map = defaultdict(str)
        _log.debug('Topic replace list: {}'.format(self._topic_replace_list))

        # A resource directory that contains everything that can be looked up.
        self._resources = ResourceDirectory()
        self._registry = self._resources.platform_registry

        # This has a dictionary mapping the platform_uuid to an agent
        # connected to the vip-address of the registered platform.  If the
        # registered platform is None then that means we were unable to
        # connect to the platform the last time it was tried.
        self._pa_agents = {}

        # if there is a volttron central agent on this instance then this
        # will be resolved.
        self._peer_platform = None

        # An object that allows the checking of currently authenticated
        # sessions.
        self._sessions = SessionHandler(Authenticate(self._user_map))
        self.webaddress = None
        self._web_info = None

        # A flag that tels us that we are in the process of updating already.
        # This will allow us to not have multiple periodic calls at the same
        # time which could cause unpredicatable results.
        self._flag_updating_deviceregistry = False

        self._setting_store = load_create_store(
            os.path.join(os.environ['VOLTTRON_HOME'], 'data',
                         'volttron.central.settings'))

        self._request_store = load_create_store(
            os.path.join(os.environ['VOLTTRON_HOME'], 'data',
                         'volttron.central.requeststore'))
Exemplo n.º 8
0
    def get(self):
        self.tv["show_breadcrumb"] = False
        if self.user:
            session = SessionHandler().session
            query = LoginCode.query()
            query = query.filter(LoginCode.session == session.key)
            code = query.get()

            logging.info(query)
            logging.info(code)

            if self.GET("r"):
                if get_cookie(self, name="_lt_"):
                    self.tv["logged_in"] = True
                    url = urllib.unquote(self.GET("r"))
                    url_split = url.split("?")
                    logging.info(url_split)
                    base_url = url_split[0]
                    logging.info(base_url)
                    base_url += "?code=" + get_cookie(self, name="_lt_")
                    logging.info(base_url)

                    if len(url_split) > 1:
                        parameters = url_split[1]
                        logging.info(parameters)
                        # if "?" in parameters:
                        #     parameters.replace("?", "&")
                        #     logging.info(parameters)

                        # base_url += "&" + parameters
                        # logging.info(base_url)
                        for i in parameters.split("&"):
                            i = "=".join([
                                i.split("=")[0],
                                urllib.quote(i.split("=")[1])
                            ])

                            if "?" not in base_url:
                                base_url += "?" + i
                            else:
                                base_url += "&" + i

                    self.tv["verify_url"] = base_url
                    clear_cookie(self, name="_lt_")
                    self.tv["hide_footer"] = True
                    self.render("login-api.html")
                else:
                    if self.GET("w"):
                        self.tv["logged_in"] = True
                        self.tv["hide_footer"] = True
                        url = urllib.unquote(self.GET("r"))
                        url_split = url.split("?")
                        logging.info(url_split)
                        base_url = url_split[0]
                        logging.info(base_url)
                        base_url += "?code=" + code.login_code
                        logging.info(base_url)

                        if len(url_split) > 1:
                            parameters = url_split[1]
                            logging.info(parameters)
                            # if "?" in parameters:
                            #     parameters.replace("?", "&")
                            #     logging.info(parameters)

                            # base_url += "&" + parameters
                            # logging.info(base_url)
                            for i in parameters.split("&"):
                                i = "=".join([
                                    i.split("=")[0],
                                    urllib.quote(i.split("=")[1])
                                ])

                                if "?" not in base_url:
                                    base_url += "?" + i
                                else:
                                    base_url += "&" + i

                        self.tv["verify_url"] = base_url
                        self.render("login-api.html")
                    else:
                        url = urllib.unquote(self.GET("r"))
                        if code:
                            url += "?code=" + code.login_code

                        if len(url.split("?")) > 1:
                            if code:
                                url += "&" + urllib.quote(
                                    str(url.split("?")[1]))
                            else:
                                url += "?" + urllib.quote(
                                    str(url.split("?")[1]))

                        self.redirect(str(url))
            else:
                url = self.request.referer
                if code:
                    url += "?code=" + code.login_code

                if len(url.split("?")) > 1:
                    if code:
                        url += "&" + urllib.quote(str(url.split("?")[1]))
                    else:
                        url += "?" + urllib.quote(str(url.split("?")[1]))

                self.redirect(url)
            return
        else:
            if self.GET("admin"):
                self.tv["admin"] = True

            # Redirect URL from the login geostore button
            if self.GET("r"):
                self.tv["redirect"] = self.GET("r")
            else:
                self.tv["redirect"] = self.request.referer

            if self.GET("w"):
                self.tv["hide_footer"] = True
                self.render("login-api.html")
            else:
                self.render("login.html")
Exemplo n.º 9
0
    def post(self):
        """
            Handles the /login endpoint.
            Logs in users.
        """
        url = "/login/authorize"

        if self.POST("email") and self.POST("password"):
            redirect = None
            email = self.POST("email").strip().lower()
            query = User.query()
            query = query.filter(User.current_email == email)
            user = query.get()

            if self.POST("redirect"):
                redirect = urllib.quote(self.POST("redirect"))
                if redirect:
                    url += "?r=" + str(redirect)

            if self.POST("login_window"):
                url += "?r=" + urllib.quote(self.POST("url"))
                url += "&w=popup"

            if not user:
                error = "Invalid email or password."
                error_message(self, error)
                self.redirect(url)
                return

            if user.verify_password(self.POST("password")):
                error = "Invalid email or password."
                error_message(self, error)
                self.redirect(url)
                return

            if user.status == "PENDING":
                error = "Your account has not been verified. "
                error += "Please verify your account by opening the "
                error += "verification email we sent you. "
                error_message(self, error)
                self.redirect(url)
                return

            if user.role in ["AGENCYADMIN", "USER"]:
                if user.status == "VERIFIED":
                    error = "Your account is still pending approval. "
                    error += "Once your account is approved, you will be able "
                    error += "to login. You will receive an email once your "
                    error += "account is approved."
                    error_message(self, error)
                    self.redirect(url)
                    return

                if user.status == "DISAPPROVED":
                    error = "Your account has been disapproved. "
                    error += "Please contact the Geostore Admin."
                    error_message(self, error)
                    self.redirect(url)
                    return

            session = SessionHandler(user)
            session.login()

            code = session.generate_login_code()

            expires = datetime.datetime.now()
            expires += datetime.timedelta(hours=8)

            if not self.POST("login_window"):
                set_cookie(self, name="_ut_", value=code, expires=expires)

            if self.POST("redirect"):
                url = str(urllib.unquote(self.POST("redirect")))
            elif self.POST("login_window"):
                url = urllib.quote(self.POST("url"))
                url = "/login/authorize?r=" + url
                set_cookie(self, name="_lt_", value=code, expires=expires)
                self.redirect(url)
                return
            else:
                url = self.request.referer

            logging.info(url)

            if len(url.split("?")) > 1:
                url += "&code" + code
            else:
                url += "?code=" + code

            self.redirect(url)
            return

        error = "Please enter your email and password."
        error_message(self, error)
        self.redirect(url)
Exemplo n.º 10
0
    def post(self):
        """
            Handles the /password/reset endpoint.
            Resets password of the user.
        """
        if self.POST("email"):
            email = self.POST("email").lower().strip()

            query = User.query()
            query = query.filter(User.current_email == email)
            user = query.get()

            if user:
                user.password_token = generate_token()
                user.put()

                content = {
                    "token": user.password_token,
                    "uid": str(user.key.id()),
                    "receiver_name": user.first_name,
                    "receiver_email": user.current_email,
                    "subject": "Reset Password",
                    "email_type": "password_reset"
                }

                taskqueue.add(url="/tasks/email/send",
                              params=content,
                              method="POST")

                success = "We sent an email to "
                success += self.POST("email") + ". Please open the "
                success += "email and click on the password reset link "
                success += "to reset your password."
                success_message(self, success)
                self.redirect("/password/reset")
            else:
                error = "Sorry, " + self.POST("email")
                error += " does not belong to an existing account."
                error_message(self, error)
                self.redirect("/password/reset")
        elif self.POST("new_password") and self.POST("confirm_password") \
             and self.GET("uid") and self.GET("password_token"):
            if self.POST("new_password") == self.POST("confirm_password"):
                user = User.get_by_id(int(self.GET("uid")))
                if user:
                    if user.password_token == self.GET("password_token"):
                        password = user.hash_password(
                            self.POST("new_password"))
                        user.password_token = generate_token()
                        user.previous_passwords.append(password)
                        user.password_update = datetime.datetime.now()
                        user.hashed_password = password
                        user.put()

                        session = SessionHandler(user)
                        session.login()
                        code = session.generate_login_code()
                        if self.POST("redirect"):
                            self.redirect(
                                urllib.unquote(str(self.POST("redirect"))))
                        else:
                            self.redirect("/dashboard")
                        return
                    else:
                        error = "Sorry, your password reset request has expired."
                        error += " Please create a new request."
                        error_message(self, error)
                        self.redirect("/password/reset")
                else:
                    error = "Sorry, we couldn't process your request. "
                    error += "Please try again."
                    error_message(self, error)
                    self.redirect("/password/reset")
            else:
                error = "Passwords do not match."
                error_message(self, error)
                url = "/password/reset?password_token=" + self.POST(
                    "password_token")
                url += "&uid=" + self.POST("uid")
                self.redirect(url)
        else:
            error = "Please fill all required fields."
            error_message(self, error)
            self.redirect("/password/reset")