def mark_lost(self, request): """Mark that a device is lost.""" self.check_xsrf_token(self.request_state) device = _get_device(request) user_email = user_lib.get_user_email() _confirm_user_action(user_email, device) device.mark_lost(user_email=user_lib.get_user_email()) return message_types.VoidMessage()
def _run_function_as_task(all_functions_list, function_name, kwargs=None): """Runs a specific function and its kwargs as an AppEngine task. Args: all_functions_list: string list, A list with all function names that are registered as bootstrap functions on the Loaner app. function_name: string, A specific function that should be ran as a task. kwargs: dict, Optional kwargs to be passed to the function that will run. Returns: The deferred task from AppEngine taskqueue. Raises: BootstrapError: if requested bootstrap method is not allowed or does not exist. """ logging.debug('Running %s as a task.', function_name) function = all_functions_list.get(function_name) if function is None: raise BootstrapError( 'Requested bootstrap method {} does not exist.'.format( function_name)) if not kwargs: kwargs = {} kwargs['user_email'] = user.get_user_email() return deferred.defer(function, **kwargs)
def get_role(self, request): """Gets the roles for the caller of the API.""" user_email = user_lib.get_user_email() user = user_model.User.get_user(email=user_email) return user_message.UsersRoleResponse(email=user.key.id(), roles=user.roles)
def wrapper(*args, **kwargs): """Wrapper for auth check decorator.""" if constants.ON_LOCAL: logging.info( 'Application is running locally. Skipping all auth checks.' ) return function_without_auth_check(*args, **kwargs) # Get logged in user. try: user_email = user_lib.get_user_email() except user_lib.UserNotFound as err: raise endpoints.UnauthorizedException(str(err)) # Only allow domain users. _forbid_non_domain_users(user_email) # If there are no specified permissions, continue with the function. if not permission: return function_without_auth_check(*args, **kwargs) # If there are permissions get the datastore user and compare permissions. datastore_user = user_model.User.get_user(user_email) if datastore_user.superadmin or ( permission in datastore_user.get_permissions()): return function_without_auth_check(*args, **kwargs) # Logged in user does not have correct permissions. raise endpoints.ForbiddenException(_FORBIDDEN_MSG)
def get_loan(self, request): """Get the current loan for a given Chrome device.""" if not request.device_id: raise endpoints.BadRequestException(_NO_DEVICE_ID_MSG) device = device_model.Device.get(chrome_device_id=request.device_id) if not device: raise endpoints.NotFoundException(_NOT_GNG_MSG) if request.need_name: user_email = user_lib.get_user_email() directory_client = directory.DirectoryApiClient( user_email=user_email) try: given_name = directory_client.given_name(user_email=user_email) except (directory.DirectoryRPCError, directory.GivenNameDoesNotExistError): given_name = None else: given_name = None guest_enabled, max_extend_date, due_date, guest_permitted = ( device_api.get_loan_data(device)) return chrome_message.LoanResponse(due_date=due_date, max_extend_date=max_extend_date, given_name=given_name, guest_permitted=guest_permitted, guest_enabled=guest_enabled)
def audit(self, request): """Performs an audit on a shelf based on location.""" self.check_xsrf_token(self.request_state) shelf = get_shelf(request.shelf_request) user_email = user.get_user_email() devices_on_shelf = [] shelf_string_query = 'shelf: {}'.format(shelf.key.urlsafe()) devices_retrieved_on_shelf = device_model.Device.search(shelf_string_query) for device_identifier in request.device_identifiers: device = device_model.Device.get(identifier=device_identifier) if not device: raise endpoints.NotFoundException( _DEVICE_DOES_NOT_EXIST_MSG % device_identifier) if device.shelf: if device.shelf == shelf.key: devices_on_shelf.append(device.key.urlsafe()) logging.info('Device %s is already on shelf.', device.serial_number) continue try: device.move_to_shelf(shelf=shelf, user_email=user_email) devices_on_shelf.append(device.key) except device_model.UnableToMoveToShelfError as err: raise endpoints.BadRequestException(str(err)) for device in devices_retrieved_on_shelf.results: if device.doc_id not in devices_on_shelf: api_utils.get_ndb_key(device.doc_id).get().remove_from_shelf( shelf=shelf, user_email=user_email) shelf.audit(user_email=user_email) return message_types.VoidMessage()
def resume_loan(self, request): self.check_xsrf_token(self.request_state) device = _get_device(request) user_email = user_lib.get_user_email() _confirm_user_action(user_email, device) device.resume_loan(user_email=user_email) return message_types.VoidMessage()
def heartbeat(self, request): """Heartbeat check-in for devices.""" if not request.device_id: raise endpoints.BadRequestException(_NO_DEVICE_ID_MSG) user_email = user_lib.get_user_email() device = device_model.Device.get(chrome_device_id=request.device_id) is_enrolled = False start_assignment = False if device: if device.enrolled: is_enrolled = True if device.assigned_user == user_email: device.loan_resumes_if_late(user_email) else: start_assignment = True device.loan_assign(user_email) else: try: device = device_model.Device.create_unenrolled( request.device_id, user_email) except device_model.DeviceCreationError as e: raise endpoints.NotFoundException(str(e)) device.record_heartbeat() silent_onboarding = config_model.Config.get('silent_onboarding') return chrome_messages.HeartbeatResponse( is_enrolled=is_enrolled, start_assignment=start_assignment, silent_onboarding=silent_onboarding, )
def audit(self, request): """Performs an audit on a shelf based on location.""" self.check_xsrf_token(self.request_state) shelf = get_shelf(location=request.location) user_email = user.get_user_email() devices_on_shelf = [] devices_retrieved_on_shelf, next_cursor, more = ( device_model.Device.list_devices(keys_only=True, shelf=shelf.key)) del next_cursor # Unused. del more # Unused. for device_identifier in request.device_identifiers: device = device_model.Device.get(unknown_identifier=device_identifier) if not device: raise endpoints.NotFoundException( _DEVICE_DOES_NOT_EXIST_MSG % device_identifier) if device.shelf: if device.shelf.get().location is shelf.location: devices_on_shelf.append(device.key) logging.info('Device %s is already on shelf.', device.serial_number) continue try: device.move_to_shelf(shelf=shelf, user_email=user_email) devices_on_shelf.append(device.key) except device_model.UnableToMoveToShelfError as err: raise endpoints.BadRequestException(str(err)) for device in devices_retrieved_on_shelf: if device not in devices_on_shelf: device.get().remove_from_shelf(shelf=shelf, user_email=user_email) shelf.audit(user_email=user_email) return message_types.VoidMessage()
def get(self, request): """Gets user details for the logged in user.""" user = user_model.User.get_user(email=user_lib.get_user_email()) return user_messages.User(email=user.key.id(), roles=user.role_names, permissions=user.get_permissions(), superadmin=user.superadmin)
def get_device(self, request): """Gets a device using any identifier in device_messages.DeviceRequest.""" device = _get_device(request) if not device.enrolled: raise endpoints.BadRequestException( device_model.DEVICE_NOT_ENROLLED_MSG % device.identifier) user_email = user_lib.get_user_email() datastore_user = user_model.User.get_user(user_email) if (permissions.Permissions.READ_DEVICES not in datastore_user.get_permissions()): if device.assigned_user != user_email: raise endpoints.UnauthorizedException( 'You do not have the proper permission to perform this action. ' 'Please contact your IT administrator if you feel like this is in ' 'error.') directory_client = directory.DirectoryApiClient(user_email) try: given_name = directory_client.given_name(user_email) except (directory.DirectoryRPCError, directory.GivenNameDoesNotExistError): given_name = None message = api_utils.build_device_message_from_model( device, config_model.Config.get('allow_guest_mode')) message.given_name = given_name return message
def disable(self, request): """Disable a shelf by its location.""" self.check_xsrf_token(self.request_state) user_email = user.get_user_email() shelf = get_shelf(request) shelf.disable(user_email) return message_types.VoidMessage()
def enable(self, request): """Enable a shelf based on its location.""" self.check_xsrf_token(self.request_state) user_email = user.get_user_email() shelf = get_shelf(location=request.location) shelf.enable(user_email) return message_types.VoidMessage()
def update(self, request): """Get a shelf using location to update its properties.""" self.check_xsrf_token(self.request_state) user_email = user.get_user_email() shelf = get_shelf(request.shelf_request) kwargs = api_utils.to_dict(request, shelf_model.Shelf) shelf.edit(user_email=user_email, **kwargs) return message_types.VoidMessage()
def unenroll(self, request): self.check_xsrf_token(self.request_state) device = _get_device(request) user_email = user_lib.get_user_email() try: device.unenroll(user_email) except device_model.FailedToUnenrollError as error: raise endpoints.BadRequestException(str(error)) return message_types.VoidMessage()
def submit(self, request): """Submit a response to a survey question.""" user_email = user_lib.get_user_email() question = self.get_ndb_key( urlsafe_key=request.question_urlsafe_key).get() question.submit(acting_user=user_email, selected_answer=request.selected_answer, more_info_text=request.more_info_text) return message_types.VoidMessage()
def mark_damaged(self, request): """Mark that a device is damaged.""" self.check_xsrf_token(self.request_state) device = _get_device(request.device) user_email = user_lib.get_user_email() _confirm_user_action(user_email, device) device.mark_damaged(user_email=user_email, damaged_reason=request.damaged_reason) return message_types.VoidMessage()
def mark_undamaged(self, request): """Clears a device's damaged state.""" self.check_xsrf_token(self.request_state) device = _get_device(request) try: device.mark_undamaged(user_email=user_lib.get_user_email()) except device_model.UnauthorizedError as err: raise endpoints.UnauthorizedException(str(err)) return message_types.VoidMessage()
def complete_onboard(self, request): """complete onboard of a device.""" self.check_xsrf_token(self.request_state) device = _get_device(request) user_email = user_lib.get_user_email() try: device.complete_onboard(user_email=user_email) except device_model.UnauthorizedError as err: raise endpoints.UnauthorizedException(str(err)) return message_types.VoidMessage()
def list_user_devices(self, request): """Lists all devices assigned to the user.""" self.check_xsrf_token(self.request_state) user = user_lib.get_user_email() guest_permitted = config_model.Config.get('allow_guest_mode') device_messages = [] for device in device_model.Device.list_by_user(user): device_messages.append( api_utils.build_device_message_from_model(device, guest_permitted)) return device_message.ListUserDeviceResponse(devices=device_messages)
def enroll(self, request): """Enrolls a device in the program.""" self.check_xsrf_token(self.request_state) try: device_model.Device.enroll(asset_tag=request.asset_tag, serial_number=request.serial_number, user_email=user_lib.get_user_email()) except device_model.DeviceCreationError as error: raise endpoints.BadRequestException(str(error)) return message_types.VoidMessage()
def resume_loan(self, request): """Resumes a loan for a given device.""" self.check_xsrf_token(self.request_state) device = _get_device(request) user_email = user_lib.get_user_email() try: device.resume_loan(user_email=user_email) except device_model.UnauthorizedError as err: raise endpoints.UnauthorizedException(str(err)) return message_types.VoidMessage()
def mark_lost(self, request): """Marks that a device is lost.""" self.check_xsrf_token(self.request_state) device = _get_device(request) user_email = user_lib.get_user_email() try: device.mark_lost(user_email=user_email) except device_model.UnauthorizedError as err: raise endpoints.UnauthorizedException(str(err)) return message_types.VoidMessage()
def wrapper(*args, **kwargs): """Inner method.""" datastore_user = user_model.User.get_user(user_lib.get_user_email()) current_device = args[0] if current_device.assigned_user == datastore_user.key.id(): return method(*args, **kwargs) elif (permissions.Permissions.ADMINISTRATE_LOAN in datastore_user.get_permissions()): return method(*args, **kwargs) else: raise UnauthorizedError(_ASSIGNMENT_MISMATCH_MSG)
def unlock(self, request): """Unlocks a device if it is locked or has been marked as lost.""" self.check_xsrf_token(self.request_state) device = _get_device(request) user_email = user_lib.get_user_email() try: device.unlock(user_email) except (directory.DirectoryRPCError, device_model.UnableToMoveToDefaultOUError) as error: raise endpoints.BadRequestException(str(error)) return message_types.VoidMessage()
def mark_pending_return(self, request): """Marks that a device is pending return.""" self.check_xsrf_token(self.request_state) device = _get_device(request) user_email = user_lib.get_user_email() try: device.mark_pending_return(user_email=user_email) except (device_model.UnassignedDeviceError, device_model.UnauthorizedError) as err: raise endpoints.UnauthorizedException(str(err)) return message_types.VoidMessage()
def create(self, request): """Creates the """ self.check_xsrf_token(self.request_state) user_email = user_lib.get_user_email() try: checkout_model.CheckoutM.createUser(fn=request.firstName, ln="request.lastName", user_email=user_email) except (datastore_errors.BadValueError) as error: raise endpoints.BadRequestException(str(error)) return message_types.VoidMessage()
def submit(self, request): """Submits a response to a survey question.""" user_email = user_lib.get_user_email() question = api_utils.get_ndb_key( urlsafe_key=request.question_urlsafe_key).get() selected_answer = survey_models.Answer.create( text=request.selected_answer.text, more_info_enabled=request.selected_answer.more_info_enabled, placeholder_text=request.selected_answer.placeholder_text) question.submit(acting_user=user_email, selected_answer=selected_answer, more_info_text=request.more_info_text) return message_types.VoidMessage()
def extend_loan(self, request): """Extends the current loan for a given device.""" self.check_xsrf_token(self.request_state) device = _get_device(request.device) user_email = user_lib.get_user_email() try: device.loan_extend(extend_date_time=request.extend_date, user_email=user_email) return message_types.VoidMessage() except device_model.ExtendError as err: raise endpoints.BadRequestException(str(err)) except (device_model.UnassignedDeviceError, device_model.UnauthorizedError) as err: raise endpoints.UnauthorizedException(str(err))
def enable_guest_mode(self, request): """Enables Guest Mode for a given device.""" self.check_xsrf_token(self.request_state) device = _get_device(request) user_email = user_lib.get_user_email() try: device.enable_guest_mode(user_email) except device_model.EnableGuestError as err: raise endpoints.InternalServerErrorException(str(err)) except (device_model.UnassignedDeviceError, device_model.GuestNotAllowedError, device_model.UnauthorizedError) as err: raise endpoints.UnauthorizedException(str(err)) else: return message_types.VoidMessage()