def register(self, invoice_items): ''' Registers new invoice. :param invoice_items: :return: ''' if invoice_items is None or len(invoice_items) <= 0: raise InvoiceException('At least one item should be included.') current_user = get_current_user() store = get_current_transaction_store() invoice = InvoiceEntity() invoice.invoice_consumer_user_id = current_user.id invoice.invoice_date = datetime.datetime.now() invoice.invoice_status = InvoiceEntity.InvoiceStatusEnum.ORDERED invoice.invoice_id = unicode(unique_id_services.get_id('uuid')) store.add(invoice) counter = 1 result = DynamicObject(entity_to_dic(invoice)) result.invoice_items = [] for item in invoice_items: item_entity = InvoiceItemEntity() item_entity.invoice_id = invoice.invoice_id item_entity.item_color = unicode(item.get('color')) item_entity.item_size = unicode(item.get('size')) item_entity.item_brand = unicode(item.get('brand')) item_entity.item_id = unicode(unique_id_services.get_id('uuid')) item_entity.item_price = Decimal(str(item.get('price'))) item_entity.item_quantity = int(item.get('quantity')) item_entity.item_row = counter item_entity.item_product_id = unicode(item.get('product_id')) products_services.decrease_product_counter( item_entity.item_product_id) product = products_services.get(item_entity.item_product_id, fetch_details=False) if (product.product_whole_sale_type == ProductsEntity.ProductWholesaleTypeEnum.WHOLESALE and current_user.user_production_type != UserEntity.UserProductionTypeEnum.PRODUCER): raise InvoiceException( "User [{0} - {1}] is not producer one and can not register " "product [{2}] which is wholesale product type.".format( current_user.user_id, current_user.user_name, product.product_name)) counter += 1 store.add(item_entity) result.invoice_items.append( DynamicObject(entity_to_dic(item_entity))) return result
def __init__(self, ticket=None, user=None, client_ip=None, lifetime=None): self._ticket = ticket self._state = Session.StateEnum.INACTIVE self._create_date = time.time() self._id = unique_id_services.get_id('session_id') self._context = SessionContext(self) self._user_id = user.id self._client_ip = client_ip self._client_request = None self._lifetime = lifetime # millisecond
def get_id(generator_name, **options): ''' Returns an unique ID using corresponded registered generator. @param generator_name: unique ID generator name. @param **options: unique ID generator options @return: object ''' return unique_id.get_id(generator_name, **options)
def create_internal_session(self, user): ''' Creates an internal session and returns it ''' ticket = unique_id_services.get_id('session_id') session = InternalSession(ticket, user) self._sessions[session.get_ticket()] = session for hook in self.get_hooks(): hook.create(session) return session
def create_session(self, user, client_ip, **options): ''' Creates a session and returns it ''' ticket = options.get('ticket') if ticket is None: ticket = unique_id_services.get_id('session_id') session = Session(ticket, user, client_ip, options.get('lifetime')) self._sessions[session.get_ticket()] = session for hook in self.get_hooks(): hook.create(session) return session
def write_history(self, product, colors, sizes, brands, **options): """ Writes product history. :param product: :param colors: :param sizes: :param brands: :param options: :return: """ history = ProductsHistoryEntity() history.product_history_edit_date = datetime.datetime.now() history.product_history_id = unicode(unique_id_services.get_id('uuid')) history.product_id = product.product_id history.product_history_name = product.product_name history.product_history_price = product.product_price history.product_history_category = product.product_category history.product_history_image = product.product_image history.product_history_status = product.product_status history.product_history_unique_name = product.product_unique_name if colors is not None and len(colors) > 0: history.product_history_colors = '-'.join(colors) if sizes is not None and len(sizes) > 0: history.product_history_sizes = '-'.join(sizes) if brands is not None and len(brands) > 0: history.product_history_brands = '-'.join(brands) history.product_history_counter = product.product_counter history.product_history_age_category = product.product_age_category history.product_history_gender = product.product_gender history.product_history_comment = product.product_comment history.product_history_editor_id = get_current_user().id store = get_current_transaction_store() store.add(history)
def _write_user_log(self, user, status, **options): """ Writes down user activity log. @param dict user: user info @param int status: user status """ if user is None: return with transaction_services.begin_root(): store = transaction_services.get_current_transaction_store() history = UserHistoryEntity() history.id = unicode(unique_id_services.get_id("uuid")) history.user_id = user.id current_session = session_services.get_current_session() if current_session is not None: history.user_history_client_ip = current_session.get_client_request().ip history.user_history_date = datetime.now() history.user_history_status = status history.user_history_message = unicode(options.get("message")) store.add(history)
def _get_certificate(self, channel_id, **options): ''' Returns certificate content. @param channel_id: cannel id. @param **options: certificate_required: determines whether certificate verification is required. (Default is True) @rtype: string @return: certificate content. ''' file_name = '{0}.cert'.format(channel_id).lower() settings_path = os.path.join(get_application_dir(), 'settings') certificate_path = os.path.join(settings_path, 'certificates') certificate_file = os.path.join(certificate_path, file_name) certificate_required = options.get('certificate_required') if certificate_required is None: certificate_required = True message = 'Loading certificate file [{0}]' ChannelManager.LOGGER.debug(message.format(certificate_file)) if not os.path.exists(certificate_file): message = 'Checking certificate required flag is [{0}] for channel [{1}]' ChannelManager.LOGGER.debug( message.format(certificate_required, channel_id)) if certificate_required: message = 'Certificate file [{0}] not found.' raise CertificateFileNotFoundException( message.format(certificate_file)) return unique_id_services.get_id('uuid') certificate = open(certificate_file, 'rb').read() return certificate
def update(self, id, **options): """ Updates product. :param id: :param options: :return: """ entity = self._get(id) store = get_current_transaction_store() new_name = options.get('name') if new_name is not None and new_name.strip() != "": self._validate_product_unique_name(new_name, entity.product_category) entity.product_name = new_name entity.product_unique_name = generate_product_unique_name( new_name, entity.product_category) new_price = options.get('price') if new_price is not None and new_price >= 0: entity.product_price = new_price new_image = options.get('image_data') if new_image is not None: entity.product_image = buffer(new_image) new_status = options.get('status') if new_status is None: entity.product_status = new_status colors = options.get('colors') if colors is not None and len('colors') > 0: already_colors = store.find( ProductsColorsEntity, ProductsColorsEntity.product_id == entity.product_id) to_delete = [] for c in already_colors: if c.product_color_hex not in colors: to_delete.append(c) to_insert = [] for c in colors: if c not in [a.product_color_hex for a in already_colors]: to_insert.append(c) for d in to_delete: store.remove(d) for i in to_insert: color_entity = ProductsColorsEntity() color_entity.product_color_id = unicode( unique_id_services.get('uuid')) color_entity.product_id = entity.product_id color_entity.product_color_hex = unicode(i) store.add(color_entity) sizes = options.get('sizes') if sizes is not None and len(sizes) > 0: already_sizes = store.find( ProductsSizesEntity, ProductsSizesEntity.product_id == entity.product_id) to_delete = [] for s in already_sizes: if s.product_size not in sizes: to_delete.append(s) to_insert = [] for s in sizes: if s not in [a.product_size for a in already_sizes]: to_insert.append(s) for d in to_delete: store.remove(d) for i in to_insert: size_entity = ProductsSizesEntity() size_entity.product_size_id = unicode( unique_id_services.get_id('uuid')) size_entity.product_id = entity.product_id size_entity.product_size = unicode(i) store.add(size_entity) brands = options.get('brands') if brands is not None and len(brands) > 0: already_brands = store.find( ProductsBrandsEntity, ProductsBrandsEntity.product_id == entity.product_id) to_delete = [] for b in already_brands: if b.product_brand not in brands: to_delete.append(b) to_insert = [] for b in brands: if b not in [a.product_brand for a in already_brands]: to_insert.append(b) for d in to_delete: store.remove(d) for i in to_insert: brand_entity = ProductsBrandsEntity() brand_entity.product_brand_id = unicode( unique_id_services.get_id('uuid')) brand_entity.product_id = entity.product_id brand_entity.product_brand = unicode(i) store.add(brand_entity) product = DynamicObject(entity_to_dic(entity)) product.sizes = [] product.colors = [] product.brands = [] history_services.write_history(entity, colors, sizes, brands, **options) return product
def create(self, name, price, category, colors, sizes, brands, **options): """ Creates product. :param name: :param price: :param category: :param colors: :param sizes: :param brands: :param options: :return: """ if name is None or name.strip() == "": raise ProductsException("Product name could not be nothing.") if price is None or price <= 1000: raise ProductsException( "Product price could not be nothing or invalid.") if colors is None or len(colors) <= 0: raise ProductsException( "At least one color for product should be selected.") if sizes is None or len(sizes) <= 0: raise ProductsException( "At least one size for product should be selected.") if brands is None or len(brands) <= 0: raise ProductsException( "At least one brand for product should be selected.") current_user = get_current_user() if current_user.user_production_type != UserEntity.UserProductionTypeEnum.PRODUCER: raise ProductsException("Consumer user can not create product.") self._validate_product_unique_name(name, category) product = ProductsEntity() product.product_id = unicode(unique_id_services.get_id('uuid')) product.product_name = name product.product_price = Decimal(price) product.product_category = category product.product_producer_user_id = current_user.id product.product_unique_name = unicode( generate_product_unique_name(name, category)) product.product_creation_date = datetime.datetime.now() product_image = options.get('image') if product_image not in (None, ""): product.product_image = str(product_image) status = options.get('status') if status is None: status = ProductsEntity.ProductStatusEnum.IN_STOCK product.product_status = status counter = options.get('counter') if counter is None: counter = 0 product.product_counter = counter age_category = options.get('age_category') if age_category is None: age_category = ProductsEntity.ProductAgeCategoryEnum.ADULT product.product_age_category = age_category gender = options.get('gender') if gender is None: gender = ProductsEntity.ProductGenderEnum.BOTH product.product_gender = gender wholesale_type = options.get('wholesale_type') if wholesale_type is None: wholesale_type = ProductsEntity.ProductWholesaleTypeEnum.RETAIL product.product_whole_sale_type = wholesale_type comment = options.get("comment") if comment is not None and len(comment) > 0: product.product_comment = comment store = get_current_transaction_store() store.add(product) for color in colors: if color == "": continue color_entity = ProductsColorsEntity() color_entity.product_color_id = unicode( unique_id_services.get_id('uuid')) color_entity.product_id = product.product_id color_entity.product_color_hex = unicode(color.strip()) store.add(color_entity) for size in sizes: if size == "": continue size_entity = ProductsSizesEntity() size_entity.product_size_id = unicode( unique_id_services.get_id('uuid')) size_entity.product_id = product.product_id size_entity.product_size = unicode(size.strip()) store.add(size_entity) for brand in brands: if brand == "": continue brand_entity = ProductsBrandsEntity() brand_entity.product_brand_id = unicode( unique_id_services.get_id('uuid')) brand_entity.product_id = product.product_id brand_entity.product_brand = unicode(brand.strip()) store.add(brand_entity) history_services.write_history(product, colors, sizes, brands, **options) return DynamicObject(entity_to_dic(product))
def handle_request(raw_request, **options): ''' Processes the request. @param request: client request @return: Response ''' request_dict = raw_request.get_request_dict() # Converting client request to the type we expected. type_converter = raw_request.get_converter() if type_converter is not None: request_dict = type_converter.to_internal(request_dict) options = type_converter.to_internal(options) # Filling missing fields. if request_dict.get('id') is None: request_dict['id'] = unique_id_services.get_id('uuid') if request_dict.get('request_date') is None: request_dict['request_date'] = datetime.datetime.now() client_request = ClientRequest.from_dict(request_dict) # logging request. process_start_time = time.time() LOGGER.info(('[{command}],[{request_id}],[{user}@{ip}:{ticket}],trace_id[{trace_id}] received. ' 'params: [{params}], context: [{context}]').format(command=client_request.command_key, request_id=client_request.id, trace_id=client_request.trace_id, user=client_request.user_name, ip=client_request.ip, ticket=client_request.ticket, params=(client_request.command_args, client_request.command_kwargs), context=client_request.context)) # Authenticating sessions authentication_options = {} if client_request.context is not None and IP_ADDRESS_OPTION_KEY in client_request.context: authentication_options[IP_ADDRESS_OPTION_KEY] = client_request.context[IP_ADDRESS_OPTION_KEY] session = authenticate(client_request.ticket, client_request.user_name, client_ip=client_request.ip, **authentication_options) # Activating session session.active(client_request) # Getting timeout value timeout = client_request.timeout if timeout is None: timeout = get_timeout() client_request.timeout = timeout try: # Getting command parameters _args = client_request.command_args if len(client_request.command_args) == 1: if isinstance(client_request.command_args[0], tuple): _args = client_request.command_args[0] # Setting request timeout in current thread request_processor_helper_services.set_request_timeout(timeout) # Making a loop and informing hooks to prepare before executing the service for hook in get_request_processor_hooks(): hook.on_process(client_request, **options) # Executing the command result = \ commander_services.execute(client_request.command_key, *_args, **client_request.command_kwargs) # Creating response object response = Response(client_request, result, session.get_call_context()) # Making a loop and informing hooks to complete their actions for hook in reversed(get_request_processor_hooks()): hook.on_process_completed(client_request, response, **options) # Logging result. LOGGER.info(('[{command}],[{request_id}],[{user}@{ip}:{ticket}],trace_id[{trace_id}] ' 'executed in time [{execution_time}]').format(command=client_request.command_key, request_id=client_request.id, trace_id=client_request.trace_id, user=client_request.user_name, ip=client_request.ip, ticket=client_request.ticket, execution_time=time.time() - process_start_time)) LOGGER.debug(('[{command}],[{request_id}],[{user}@{ip}:{ticket}],trace_id[{trace_id}] executed. ' 'result: [{result}], context: [{context}]').format(command=client_request.command_key, request_id=client_request.id, trace_id=client_request.trace_id, user=client_request.user_name, ip=client_request.ip, ticket=client_request.ticket, result=result, context=response.context)) # Converting the result to the type Communicator expected. if type_converter is not None: response = type_converter.to_external(response) return response except Exception as error: LOGGER.error('Error while executing [{command}],[{request_id}]: [{traceback}]'.format(command=client_request.command_key, request_id=client_request.id, traceback=traceback.format_exc())) # Making a loop and informing hooks to handle the occurred error for hook in get_request_processor_hooks(): hook.on_process_failed(client_request, error, **options) raise finally: # Deactivating alarm if timeout is not None and timeout > 0:######insert signal.alarm(0) # Cleaning up the session session.cleanup()
def create_user(self, id, password, fullname, **options): """ Creates a new user. @param id: user ID @param password: password @param fullname: full name """ if id is None or id.strip() == "": raise UserSecurityException("Use id can not be nothing.") if password is None or password.strip() == "": raise UserSecurityException("Use password can not be nothing.") if fullname is None or fullname.strip() == "": raise UserSecurityException("Use name can not be nothing.") self._check_invalid_user_names(id) user = UserEntity() user.id = unicode(unique_id_services.get_id('uuid')) user.user_id = id user.user_full_name = fullname user.user_password = unicode(encrypt_sha512(password)) status = options.get('status') if status is None: status = UserEntity.UserStatusEnum.USER_REGISTERED user.user_status = status type = options.get('type') if type is None: type = UserEntity.UserTypeEnum.NORMAL_USER user.user_type = type mobile = options.get('mobile') if mobile is None: mobile = "" user.user_mobile = unicode(mobile) phone = options.get('phone') if phone is None: phone = "" user.user_phone = unicode(phone) email = options.get('email') if email is None: raise UserSecurityException("User email can not be nothing.") user.user_email = unicode(email) address = options.get('address') if address is None: address = "" user.user_address = unicode(address) work_address = options.get('work_address') if work_address is None: work_address = "" user.user_work_address = unicode(work_address) national_code = options.get('national_code') if national_code is None: national_code = "0" user.user_national_code = unicode(national_code) production_type = options.get('production_type') if production_type is None: production_type = UserEntity.UserProductionTypeEnum.CONSUMER user.user_production_type = production_type production_package = options.get('production_package') if production_package is None: production_type = UserEntity.UserProductionPackageEnum.FREE if production_type == UserEntity.UserProductionTypeEnum.PRODUCER: user.user_production_package = production_package user_image = options.get('image') if user_image not in (None, ""): user.user_image = str(user_image) user.user_last_login_date = datetime.datetime(datetime.MINYEAR, 1, 1, 0, 0, 0, 0) store = get_current_transaction_store() store.add(user) self.activate_user(user.user_id, True) return DynamicObject(entity_to_dic(user))
def change_password(self, user_id, current_password, new_password, **options): """ Changes password of current user. @param current_password: user current password @param new_password: user new password """ self._check_invalid_user_names(user_id) user = self.get_user_by_id(user_id) if user is None: raise UserNotFoundException(user_id) if not self.is_active(user.id): raise UserSecurityException("User is not activated.") store = get_current_transaction_store() activation_data = options.get('activation_data') statement = \ Select(columns=[UserActionEntity.id, UserActionEntity.user_action_data, UserActionEntity.user_action_date], where=And(UserActionEntity.user_id == user.id, UserActionEntity.user_action == UserActionEntity.UserActionEnum.CHANGE_USER_PASSWORD, UserActionEntity.user_action_status == UserActionEntity.UserActionStatusEnum.ACTION_CREATED), tables=[UserActionEntity]) result = store.execute(statement).get_one() if result is None: if activation_data not in (None, ""): return newly_generated_data = str(uuid.uuid4())[:8] entity = UserActionEntity() entity.id = unicode(unique_id_services.get_id('uuid')) entity.user_action = UserActionEntity.UserActionEnum.CHANGE_USER_PASSWORD entity.user_action_data = unicode(newly_generated_data) entity.user_action_date = datetime.datetime.now() entity.user_action_status = UserActionEntity.UserActionStatusEnum.ACTION_CREATED entity.user_id = user.id store.add(entity) email_services.send_change_password_email(user.user_full_name, user.user_email, newly_generated_data) return newly_generated_data else: entity_id, user_action_data, user_action_date = result if user_action_date < datetime.datetime.now() - datetime.timedelta( days=1): entity = store.get(UserActionEntity, entity_id) entity.user_action_status = UserActionEntity.UserActionStatusEnum.ACTION_EXPIRED return if unicode(user_action_data) != unicode(activation_data): raise UserSecurityException("Security change code is wrong.") if new_password in (None, "") or new_password.strip() == "": raise UserSecurityException("Password is not valid.") self.update_user(user_id, password=new_password) entity = store.get(UserActionEntity, entity_id) entity.user_action_status = UserActionEntity.UserActionStatusEnum.ACTION_COMPLETED
def activate_user(self, id, flag, **options): """ Active or inactive specified user. @param id: user ID @param flag: activation flag(True or False) """ user = self.get_user_by_id(id) if user is None: raise UserNotFoundException(id) self._check_invalid_user_names(id) store = get_current_transaction_store() activation_data = options.get('activation_data') statement = \ Select(columns=[UserActionEntity.id, UserActionEntity.user_action_data, UserActionEntity.user_action_date], where=And(UserActionEntity.user_id == user.id, UserActionEntity.user_action == UserActionEntity.UserActionEnum.ACTIVATE_USER, UserActionEntity.user_action_status == UserActionEntity.UserActionStatusEnum.ACTION_CREATED), tables=[UserActionEntity]) result = store.execute(statement).get_one() if self.is_active(user.id): raise UserSecurityException("User is already activated.") else: if activation_data is None or activation_data.strip() == "": if result is None: now_date = datetime.datetime.now() activation_date = datetime.datetime( now_date.year, now_date.month, now_date.day, now_date.hour, now_date.minute, now_date.second) activation_data = self._generate_activation_data( user, activation_date) activation_data = encrypt_aes("{0}${1}".format( user.user_id, activation_data)) action_entity = UserActionEntity() action_entity.id = unicode( unique_id_services.get_id('uuid')) action_entity.user_action = UserActionEntity.UserActionEnum.ACTIVATE_USER action_entity.user_action_data = unicode(activation_data) action_entity.user_action_date = activation_date action_entity.user_id = user.id action_entity.user_action_status = UserActionEntity.UserActionStatusEnum.ACTION_CREATED store.add(action_entity) email_services.send_activation_email( user.user_full_name, user.user_email, "http://{0}:{1}/activate/{2}".format( "185.94.99.134", "5001", activation_data)) return activation_data else: actions_id, user_action_data, user_action_date = result email_services.send_activation_email( user.user_full_name, user.user_email, "http://{0}:{1}/activate/{2}".format( "185.94.99.134", "5001", user_action_data)) return user_action_data if result is None: raise UserSecurityException("User Activation Error") actions_id, user_action_data, user_action_date = result if (user_action_data != activation_data or not self._verify_activation_data(user, user_action_date, activation_data)): action_entity = store.get(UserActionEntity, actions_id) action_entity.user_action_status = UserActionEntity.UserActionStatusEnum.ACTION_FAILED raise UserSecurityException("User Activation Error") if (datetime.datetime.now() - user_action_date).total_seconds() > 24 * 3600: action_entity = store.get(UserActionEntity, actions_id) action_entity.user_action_status = UserActionEntity.UserActionStatusEnum.ACTION_EXPIRED raise UserSecurityException("User Activation Expired") user_entity = self._get(user.id) user_entity.user_status = UserEntity.UserStatusEnum.USER_ACTIVATED action_entity = store.get(UserActionEntity, actions_id) action_entity.user_action_status = UserActionEntity.UserActionStatusEnum.ACTION_COMPLETED