Example #1
0
    def signin(self, email, password, hasSessionContext=True):
        from octoprint.server import userManager
        from astroprint.network.manager import networkManager
        user = None
        userLoggedIn = False

        online = networkManager().isOnline()

        if online:
            private_key = self.get_private_key(email, password)

            if private_key:
                public_key = self.get_public_key(email, private_key)

                if public_key:
                    #Let's protect the box now:
                    user = userManager.findUser(email)

                    if user:
                        userManager.changeUserPassword(email, password)
                        userManager.changeCloudAccessKeys(
                            email, public_key, private_key)
                    else:
                        user = userManager.addUser(email, password, public_key,
                                                   private_key, True)

                    userLoggedIn = True

        else:
            user = userManager.findUser(email)
            userLoggedIn = user and user.check_password(
                userManager.createPasswordHash(password))

        if userLoggedIn:
            if hasSessionContext:
                login_user(user, remember=True)

            userId = user.get_id()

            self.settings.set(["cloudSlicer", "loggedUser"], userId)
            self.settings.save()

            boxrouterManager().boxrouter_connect()

            if hasSessionContext:
                identity_changed.send(current_app._get_current_object(),
                                      identity=Identity(userId))

            #let the singleton be recreated again, so new credentials are taken into use
            global _instance
            _instance = None

            eventManager().fire(Events.LOCK_STATUS_CHANGED, userId)

            return True

        elif not online:
            raise AstroPrintCloudNoConnectionException()

        return False
Example #2
0
	def signin(self, email, password, hasSessionContext = True):
		from octoprint.server import userManager
		from astroprint.network.manager import networkManager
		user = None
		userLoggedIn = False

		online = networkManager().isOnline()

		if online:
			private_key = self.get_private_key(email, password)

			if private_key:
				public_key = self.get_public_key(email, private_key)

				if public_key:
					#Let's protect the box now:
					user = userManager.findUser(email)

					if user:
						userManager.changeUserPassword(email, password)
						userManager.changeCloudAccessKeys(email, public_key, private_key)
					else:
						user = userManager.addUser(email, password, public_key, private_key, True)

					userLoggedIn = True

		else:
			user = userManager.findUser(email)
			userLoggedIn = user and user.check_password(userManager.createPasswordHash(password))

		if userLoggedIn:
			if hasSessionContext:
				login_user(user, remember=True)

			userId = user.get_id()

			self.settings.set(["cloudSlicer", "loggedUser"], userId)
			self.settings.save()

			boxrouterManager().boxrouter_connect()

			if hasSessionContext:
				identity_changed.send(current_app._get_current_object(), identity=Identity(userId))

			#let the singleton be recreated again, so new credentials are taken into use
			global _instance
			_instance = None

			eventManager().fire(Events.LOCK_STATUS_CHANGED, userId)

			return True

		elif not online:
			raise AstroPrintCloudNoConnectionException()

		return False
Example #3
0
    def validatePassword(self, email, password):
        from octoprint.server import userManager
        user = None
        userValidated = False

        online = networkManager().isOnline()

        if online:
            try:
                data_private_key = self.get_private_key(email, password)

                if data_private_key:
                    private_key = data_private_key['private_key']
                    public_key = self.get_public_key(email, private_key)
                    orgId = data_private_key['organization_id']
                    groupId = data_private_key['group_id']

                    if public_key:
                        #Let's update the box now:
                        user = userManager.findUser(email)
                        if user:
                            userManager.changeUserPassword(email, password)
                            userManager.changeCloudAccessKeys(
                                email, public_key, private_key, orgId, groupId)
                        else:
                            user = userManager.addUser(email, password,
                                                       public_key, private_key,
                                                       orgId, groupId, True)

                        userValidated = True

                    else:
                        return False

                else:
                    return False

            except ConnectionError as e:
                self._logger.error(
                    'Connection error when trying to validate password: %s' %
                    e)

        # was offline or couldn't reach astroprint.com
        if not userValidated:
            user = userManager.findUser(email)
            userValidated = user and user.check_password(
                userManager.createPasswordHash(password))

        if userValidated:
            userId = user.get_id()
            self.settings.set(["cloudSlicer", "loggedUser"], userId)
            self.settings.save()

        return userValidated
Example #4
0
def updateUser(username):
    if userManager is None:
        return jsonify(SUCCESS)

    #add by kevin, for manage default users
    if userManager.isDefaultUsers(username):
        return make_response(("Forbidden", 403, []))
    #add end

    user = userManager.findUser(username)
    if user is not None:
        if "application/json" in request.headers["Content-Type"]:
            data = request.json

            # change roles
            roles = ["user"]
            if "admin" in data.keys() and data["admin"]:
                roles.append("admin")
            userManager.changeUserRoles(username, roles)

            # change activation
            if "active" in data.keys():
                userManager.changeUserActivation(username, data["active"])
        return getUsers()
    else:
        abort(404)
Example #5
0
def updateUser(username):
	if not userManager.enabled:
		return jsonify(SUCCESS)

	user = userManager.findUser(username)
	if user is not None:
		if not "application/json" in request.headers["Content-Type"]:
			return make_response("Expected content-type JSON", 400)

		try:
			data = request.json
		except BadRequest:
			return make_response("Malformed JSON body in request", 400)

		# change roles
		roles = ["user"]
		if "admin" in data.keys() and data["admin"]:
			roles.append("admin")
		userManager.changeUserRoles(username, roles)

		# change activation
		if "active" in data.keys():
			userManager.changeUserActivation(username, data["active"])
		return getUsers()
	else:
		abort(404)
Example #6
0
def updateUser(username):
    if not userManager.enabled:
        return jsonify(SUCCESS)

    user = userManager.findUser(username)
    if user is not None:
        if not "application/json" in request.headers["Content-Type"]:
            return make_response("Expected content-type JSON", 400)

        try:
            data = request.json
        except BadRequest:
            return make_response("Malformed JSON body in request", 400)

        # change roles
        roles = ["user"]
        if "admin" in data.keys() and data["admin"]:
            roles.append("admin")
        userManager.changeUserRoles(username, roles)

        # change activation
        if "active" in data.keys():
            userManager.changeUserActivation(username, data["active"])
        return getUsers()
    else:
        abort(404)
Example #7
0
    def boxrouter_connect(self):
        if not networkManager().isOnline():
            return False

        if not self.connected:
            from octoprint.server import userManager
            loggedUser = self._settings.get(['cloudSlicer', 'loggedUser'])
            if loggedUser:
                user = userManager.findUser(loggedUser)

                if user:
                    self._publicKey = user.publicKey
                    self._privateKey = user.privateKey

                    if self._publicKey and self._privateKey:
                        self.status = self.STATUS_CONNECTING
                        self._eventManager.fire(Events.ASTROPRINT_STATUS,
                                                self.status)

                        try:
                            self._ws = AstroprintBoxRouterClient(
                                self._address, self)
                            self._ws.connect()
                            self.connected = True

                        except Exception as e:
                            self._logger.error(
                                "Error connecting to boxrouter: %s" % e)
                            self._doRetry(
                                False)  #This one should not be silent

                        return True

        return False
Example #8
0
	def boxrouter_connect(self):
		if not networkManager().isOnline():
			return False

		if not self.connected:
			from octoprint.server import userManager
			
			loggedUser = self._settings.get(['cloudSlicer', 'loggedUser'])
			if loggedUser and userManager:
				user = userManager.findUser(loggedUser)

				if user:
					self._publicKey = user.publicKey
					self._privateKey = user.privateKey

					if self._publicKey and self._privateKey:
						self.status = self.STATUS_CONNECTING
						self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status);

						try:
							self._ws = AstroprintBoxRouterClient(self._address, self)
							self._ws.connect()
							self.connected = True

						except Exception as e:
							self._logger.error("Error connecting to boxrouter: %s" % e)
							self._doRetry(False) #This one should not be silent

						return True

		return False
Example #9
0
	def validatePassword(self, email, password):
		from octoprint.server import userManager
		from astroprint.network.manager import networkManager
		user = None
		userValidated = False

		online = networkManager().isOnline()

		if online:
			try:
				private_key = self.get_private_key(email, password)

				if private_key:
					public_key = self.get_public_key(email, private_key)

					if public_key:
						#Let's update the box now:
						user = userManager.findUser(email)
						if user:
							userManager.changeUserPassword(email, password)
							userManager.changeCloudAccessKeys(email, public_key, private_key)
						else:
							user = userManager.addUser(email, password, public_key, private_key, True)

						userValidated = True

					else:
						return False

				else:
					return False

			except ConnectionError as e:
				self._logger.error('Connection error when trying to validate password: %s' % e)

		# was offline or couldn't reach astroprint.com
		if not userValidated:
			user = userManager.findUser(email)
			userValidated = user and user.check_password(userManager.createPasswordHash(password))

		if userValidated:
			userId = user.get_id()
			self.settings.set(["cloudSlicer", "loggedUser"], userId)
			self.settings.save()

		return userValidated
Example #10
0
	def updateFleetInfo(self, orgId, groupId):
		loggedUser = self.settings.get(['cloudSlicer', 'loggedUser'])
		if loggedUser:
			from octoprint.server import userManager
			user = userManager.findUser(loggedUser)
			if(user and user.groupId != groupId):
				self._logger.info("Box is part of fleet [%s] in group [%s]" % (orgId, groupId))
				userManager.changeUserFleetInfo(loggedUser, orgId, groupId)
				self.hmacAuth.updateFleetInfo(orgId, groupId)
Example #11
0
    def boxrouter_connect(self):
        if not networkManager().isOnline():
            return False

        if not self.connected:
            from octoprint.server import userManager

            loggedUser = self._settings.get(['cloudSlicer', 'loggedUser'])
            if loggedUser and userManager:
                user = userManager.findUser(loggedUser)

                if user and user.is_authenticated:
                    self._publicKey = user.publicKey
                    self._privateKey = user.privateKey

                    if self._publicKey and self._privateKey:
                        self.status = self.STATUS_CONNECTING
                        self._eventManager.fire(Events.ASTROPRINT_STATUS,
                                                self.status)

                        try:
                            if self._retryTimer:
                                #This is in case the user tried to connect and there was a pending retry
                                self._retryTimer.cancel()
                                self._retryTimer = None
                                #If it fails, the retry sequence should restart
                                self._retries = 0

                            if self._ws and not self._ws.terminated:
                                self._ws.terminate()

                            self._ws = AstroprintBoxRouterClient(
                                self._address, self)
                            self._ws.connect()
                            self.connected = True

                        except Exception as e:
                            self._logger.error(
                                "Error connecting to boxrouter [%s]: %s" %
                                (self._address, e))
                            self.connected = False
                            self.status = self.STATUS_ERROR
                            self._eventManager.fire(Events.ASTROPRINT_STATUS,
                                                    self.status)

                            if self._ws:
                                self._ws.terminate()
                                self._ws = None

                            self._doRetry(
                                False)  #This one should not be silent

                        return True

        return False
Example #12
0
def getUser(username):
	if userManager is None:
		return jsonify(SUCCESS)

	if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
		user = userManager.findUser(username)
		if user is not None:
			return jsonify(user.asDict())
		else:
			abort(404)
	else:
		abort(403)
Example #13
0
    def getAccessKeys(self, data, sendResponse):
        publicKey = email = accessKey = None

        if 'email' in data:
            email = data['email']

        if 'accessKey' in data:
            accessKey = data['accessKey']

        userLogged = settings().get(["cloudSlicer", "loggedUser"])
        ####
        # - nobody logged: None
        # - any log: email

        if email and accessKey:  #somebody is logged in the remote client
            if userLogged:  #Somebody logged in Astrobox
                if userLogged == email:  #I am the user logged
                    online = networkManager().isOnline()

                    if online:
                        publicKey = astroprintCloud().get_public_key(
                            email, accessKey)

                        if not publicKey:
                            self._logger.error('error getting public key',
                                               exc_info=True)
                            sendResponse('error_getting_public_key', True)
                            return

                    else:
                        user = userManager.findUser(email)
                        if user.get_private_key() != accessKey:
                            self._logger.error('incorrect logged user',
                                               exc_info=True)
                            sendResponse('incorrect_logged_user', True)
                            return

                else:  #I am NOT the logged user
                    self._logger.error('incorrect logged user', exc_info=True)
                    sendResponse('incorrect_logged_user', True)
                    return

        else:  #nodody is logged in the remote client
            if userLogged:
                self._logger.error('any user logged', exc_info=True)
                sendResponse('no_user_logged', True)
                return

        sendResponse({
            'api_key': UI_API_KEY,
            'ws_token': create_ws_token(publicKey)
        })
Example #14
0
def getUser(username):
    if not userManager.enabled:
        return jsonify(SUCCESS)

    if current_user is not None and not current_user.is_anonymous() and (
            current_user.get_name() == username or current_user.is_admin()):
        user = userManager.findUser(username)
        if user is not None:
            return jsonify(user.asDict())
        else:
            abort(404)
    else:
        abort(403)
Example #15
0
	def boxrouter_connect(self):
		if not networkManager().isOnline():
			return False

		if not self.connected:
			from octoprint.server import userManager

			loggedUser = self._settings.get(['cloudSlicer', 'loggedUser'])
			if loggedUser and userManager:
				user = userManager.findUser(loggedUser)

				if user and user.is_authenticated:
					self._publicKey = user.publicKey
					self._privateKey = user.privateKey

					if self._publicKey and self._privateKey:
						self.status = self.STATUS_CONNECTING
						self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)

						try:
							if self._retryTimer:
								#This is in case the user tried to connect and there was a pending retry
								self._retryTimer.cancel()
								self._retryTimer = None
								#If it fails, the retry sequence should restart
								self._retries = 0

							if self._ws and not self._ws.terminated:
								self._ws.terminate()

							self._ws = AstroprintBoxRouterClient(self._address, self)
							self._ws.connect()
							self.connected = True

						except Exception as e:
							self._logger.error("Error connecting to boxrouter: %s" % e)
							self.connected = False
							self.status = self.STATUS_ERROR
							self._eventManager.fire(Events.ASTROPRINT_STATUS, self.status)

							if self._ws:
								self._ws.terminate()
								self._ws = None

							self._doRetry(False) #This one should not be silent

						return True

		return False
Example #16
0
	def validatePassword(self, email, password):
		from octoprint.server import userManager
		from astroprint.network.manager import networkManager
		user = None
		userValidated = False

		online = networkManager().isOnline()

		if online:
			private_key = self.get_private_key(email, password)

			if private_key:
				public_key = self.get_public_key(email, private_key)

				if public_key:
					#Let's update the box now:
					user = userManager.findUser(email)
					if user:
						userManager.changeUserPassword(email, password)
						userManager.changeCloudAccessKeys(email, public_key, private_key)
					else:
						user = userManager.addUser(email, password, public_key, private_key, True)

					userValidated = True

		else:
			user = userManager.findUser(email)
			userValidated = user and user.check_password(userManager.createPasswordHash(password))

		if userValidated:
			userId = user.get_id()
			self.settings.set(["cloudSlicer", "loggedUser"], userId)
			self.settings.save()


		return userValidated
Example #17
0
	def __init__(self):
		self.settings = settings()
		self.hmacAuth = None

		loggedUser = self.settings.get(['cloudSlicer', 'loggedUser'])
		if loggedUser:
			from octoprint.server import userManager
			
			user = userManager.findUser(loggedUser)

			if user and user.publicKey and user.privateKey:
				self.hmacAuth = HMACAuth(user.publicKey, user.privateKey)

		self.apiHost = self.settings.get(['cloudSlicer', 'apiHost'])
		self._print_file_store = None
		self._sm = softwareManager()
		self._logger = logging.getLogger(__name__)
Example #18
0
    def __init__(self):
        self.settings = settings()
        self.hmacAuth = None

        loggedUser = self.settings.get(['cloudSlicer', 'loggedUser'])
        if loggedUser:
            from octoprint.server import userManager

            user = userManager.findUser(loggedUser)

            if user and user.publicKey and user.privateKey:
                self.hmacAuth = HMACAuth(user.publicKey, user.privateKey)

        self.apiHost = self.settings.get(['cloudSlicer', 'apiHost'])
        self._print_file_store = None
        self._sm = softwareManager()
        self._logger = logging.getLogger(__name__)
Example #19
0
def updateUser(username):
    if userManager is None:
        return jsonify(SUCCESS)

    user = userManager.findUser(username)
    if user is not None:
        if "application/json" in request.headers["Content-Type"]:
            data = request.json

            # change roles
            roles = ["user"]
            if "admin" in data.keys() and data["admin"]:
                roles.append("admin")
            userManager.changeUserRoles(username, roles)

            # change activation
            if "active" in data.keys():
                userManager.changeUserActivation(username, data["active"])
        return getUsers()
    else:
        abort(404)
Example #20
0
def updateUser(username):
	if userManager is None:
		return jsonify(SUCCESS)

	user = userManager.findUser(username)
	if user is not None:
		if "application/json" in request.headers["Content-Type"]:
			data = request.json

			# change roles
			roles = ["user"]
			if "admin" in data.keys() and data["admin"]:
				roles.append("admin")
			userManager.changeUserRoles(username, roles)

			# change activation
			if "active" in data.keys():
				userManager.changeUserActivation(username, data["active"])
		return getUsers()
	else:
		abort(404)
Example #21
0
	def __init__(self):
		self.settings = settings()
		self._eventManager = eventManager()
		self.hmacAuth = None
		self.boxId = boxrouterManager().boxId

		self.tryingLoggingTimes = 0

		self.apiHost = roConfig('cloud.apiHost')
		self._print_file_store = None
		self._sm = softwareManager()
		self._logger = logging.getLogger(__name__)

		loggedUser = self.settings.get(['cloudSlicer', 'loggedUser'])
		if loggedUser:
			from octoprint.server import userManager

			user = userManager.findUser(loggedUser)

			if user and user.publicKey and user.privateKey:
				self.hmacAuth = HMACAuth(user.publicKey, user.privateKey, self.boxId, user.orgId, user.groupId)
Example #22
0
def getSoftwarePin():
    s = settings()
    email = s.get(["cloudSlicer", "loggedUser"])

    if email:
        loggedUser = userManager.findUser(email)

        if loggedUser:
            if request.method == 'POST':
                validated = False
                data = request.json
                mode = data.get('mode')
                currentPin = data.get('current_pin')

                if currentPin:
                    validated = loggedUser.check_pin(currentPin)

                try:
                    if mode == 'clear':
                        if validated:
                            userManager.changeUserPin(email, None)
                        else:
                            return make_response("invalid_pin", 401)

                    elif mode == 'set':
                        newPin = data.get('new_pin')

                        if not loggedUser.has_pin() and newPin is not None:
                            userManager.changeUserPin(email, newPin)
                        else:
                            make_response("Invalid request", 400)

                    elif mode == 'change':
                        if validated:
                            newPin = data.get('new_pin')

                            if newPin is not None:
                                userManager.changeUserPin(email, newPin)
                            else:
                                make_response("Mising data", 400)
                        else:
                            return make_response("invalid_pin", 401)

                    else:
                        return make_response("Invalid mode", 400)

                except InvalidPinException:
                    return make_response("invalid_pin_format", 400)

            response = {'pin_enabled': loggedUser.has_pin()}

            r = make_response(json.dumps(response), 200)
            r.headers['Content-Type'] = 'application/json'

        else:
            r = make_response("Invalid user User", 400)

    else:
        r = make_response("No user", 404)

    return r
def hook(apikey, *args, **kwargs):
	from octoprint.server import userManager
	return userManager.findUser(userid=apikey)