def put(self, mongoid=None): update_data = json_util.loads(dumps(post_put_args().parse_args())) if "_id" in update_data["data"]: del update_data["data"]["_id"] try: result = self.controller.update(mongoid, update_data['data']) return SoftRestResponse.single_item( item_id=str(result.id), item=result.to_mongo(), document_name=self.controller.main_model.__name__, created=False) except DoesNotExist as e: return SoftRestResponse.error(message='RECORD_NOT_FOUND', detail=e.args, code=404) except NotUniqueError as e: return SoftRestResponse.error(message='UNIQUE_ERROR', detail=e.args, code=406) except Exception as e: app.logger.error( "*** SERVER_ERROR_PUT data: {}\n*ERROR: {}".format( update_data, e.with_traceback)) return SoftRestResponse.error(message='SERVER_ERROR', detail=e.args, code=500)
def checkLogin(self): if 'liftnec-token' in request.headers: token = request.headers['liftnec-token'] if not token: return SoftRestResponse.error(message='TOKEN_NOT_FOUND', detail='Oturum bulunamadı!', code=401) try: data = jwt.decode(token, app.config['SECRET_KEY']) current_user = User.objects.get(id=data['id']) session["current_user_id"] = data['id'] session["current_org_id"] = str(current_user.organization.id) except Exception as e: return SoftRestResponse.error(message='TOKEN_NOT_FOUND', detail='Oturum bulunamadı!', code=401)
def show(self, db_id, get_args): try: result, result_id = self.controller.show(db_id, get_args) if result: return SoftRestResponse.single_item( item_id=result_id, item=result, document_name=self.controller.main_model.__name__, created=False) return SoftRestResponse.error( message='RECORD_NOT_FOUND', detail='Aradağınız kriterlere uygun kayıt bulunamadı', code=404) except Exception as e: app.logger.error( "*** {} method show occurred an exception: {}".format( self.controller.main_model.__name__, [e.with_traceback, e, e.args])) return SoftRestResponse.error(message='SERVER_ERROR', detail=e.args, code=500)
def get(self, db_id=None): get_params = get_args().parse_args() if db_id: return self.show(db_id, get_params) try: result, total_count = self.controller.get(get_args=get_params) return SoftRestResponse.index( list_result=result, total_count=total_count, per_page=get_params['limit'], current_page=get_params['page'], document_name=self.controller.main_model.__name__, ) except Exception as e: app.logger.error( "*** {} method get occurred an exception: {}".format( self.controller.main_model.__name__, [e.with_traceback, e, e.args])) return SoftRestResponse.error(message='SERVER_ERROR', detail=e.args, code=500)
def delete(self, db_id=None): args_delete = delete_args().parse_args() try: self.controller.delete(db_id, args_delete) return SoftRestResponse.delete( item_id=str(db_id), document_name=self.controller.main_model.__name__) except DoesNotExist as e: return SoftRestResponse.error(message='RECORD_NOT_FOUND', detail=e.args, code=404) except OperationError as e: matchObj = re.match(".*\({1}([a-z|A-Z]+).{1}.*", e.args[0], flags=0) return SoftRestResponse.error(message='RECORD_NOT_DELETED', detail=matchObj.group(1), code=406) except Exception as e: return SoftRestResponse.error(message='SERVER_ERROR', detail=e.args, code=500)
def put(self, mongoid): app.logger.debug( ("***{} fired as PUT request").format(self.__class__.__name__)) putRequestArgs = putArgs().parse_args() putRequestArgs = putRequestArgs['data'] # remove _id javascript field putRequestArgs.pop("_id", None) app.logger.debug(("***putRequestArgs" + str(putRequestArgs))) try: retUser = self.jobs.update(mongoid, putRequestArgs) return SoftRestResponse.single_item(item_id=str(retUser.id), item=retUser.to_mongo(), document_name='User', created=False) except DoesNotExist as e: return SoftRestResponse.error(message='RECORD_NOT_FOUND', detail=e.args, code=404) except Exception as e: return SoftRestResponse.error(message='SERVER_ERROR_PUT', detail=e.args, code=500)
def post(self): create_data = json_util.loads(dumps(post_put_args().parse_args())) has_bulk_list = create_data['data'].pop('bulk_list', None) if has_bulk_list: return self.bulk_create(bulk_list=has_bulk_list) try: result = self.controller.create(create_data['data']) return SoftRestResponse.single_item( item_id=str(result.id), item=result.to_mongo(), document_name=self.controller.main_model.__name__, created=True) except NotUniqueError as e: return SoftRestResponse.error(message='UNIQUE_ERROR', detail=e.args, code=406) except Exception as e: app.logger.error( "*** SERVER_ERROR_POST data: {}\n*ERROR: {}".format( create_data, e.with_traceback)) return SoftRestResponse.error(message='SERVER_ERROR', detail=e.args, code=500)
def get(self) -> object: auth = request.authorization if not auth or not auth.username or not auth.password: return SoftRestResponse.error( message='NOT_ACCEPTABLE', detail='Kullanıcı adı veya şifre eksik!', code=406) user = User.objects(email=auth.username).first() if not user: return SoftRestResponse.error( message='RECORD_NOT_FOUND', detail='Böyle bir kullanıcı bulunmamaktadır!', code=404) if not user.organization.is_enabled: return SoftRestResponse.error(message='ORG_IS_PASSIVE', detail='Firmanız pasif durumdadır', code=403) if check_password_hash(user.password, auth.password): token = jwt.encode( { 'id': str(user.id), 'exp': datetime.datetime.now() + datetime.timedelta(minutes=3600) }, app.config['SECRET_KEY']) message = { 'liftnec-token': token.decode('UTF-8'), 'user': user.to_mongo() } return SoftRestResponse.single_item(item_id=str(user.id), item=message, document_name='Login', created=True) return SoftRestResponse.error( message='WRONG_PASSWORD', detail='Kullanıcı adı ve şifreniz uyuşmamaktadır', code=403)
def bulk_create(self, bulk_list): result = self.controller.bulk_create(bulk_list) return SoftRestResponse.bulk_create(**result)
def create(self, data): """ Create a new record :param data: dict :return: dict """ try: org_name = data.pop("organizationName") firstTime = True except Exception as e: org_name = None try: """login korumalı degil metod""" control = self.checkLogin() firstTime = False if control: return control if session['current_org_id']: org_id = session['current_org_id'] else: org_id = data.pop("organizationId") except Exception as e: org_id = None app.logger.debug('*** {}.create method fired'.format( self.__class__.__name__)) app.logger.debug(data) if isinstance(data, dict) is True: # Check if company exists on db try: if org_name: company_record = Organization.objects(name=org_name) if company_record: return SoftRestResponse.error( message='SERVER_ERROR_POST', detail= 'Firma zaten var.\nKullanıcı kayıdı için firma yöneticiniz ile görüşün', code=500) # unpack dict data for User constructor elif org_id: company_record = Organization.objects.get(id=org_id) if not company_record: return SoftRestResponse.error( message='SERVER_ERROR_POST', detail= 'Firma bulunamadı.\nKullanıcı kayıdı için firma yöneticiniz ile görüşün', code=500) else: return SoftRestResponse.error( message='SERVER_ERROR_POST', detail='Firma bilgisi zorunludur', code=500) email = data.get("email") user_records = User.objects(email=email) if len(user_records) > 0: return SoftRestResponse.error( message='SERVER_ERROR_POST', detail= 'Kullanıcı oluşturulamadı.\nKullanıcı email kaydı zaten var', code=500) user_to_insert = User(**data) # enable user for login user_to_insert.is_enabled = True if not user_to_insert.password: user_to_insert.password = str(uuid.uuid4()) # encrypt password field hashed_password = generate_password_hash( user_to_insert.password, method='sha256') if firstTime: user_to_insert.password = hashed_password user_to_insert.roles = [EnumPermission.FIRMA_ADMIN.value] else: # Eğer kullanıcı şirket yöneticisi tarafından # oluşturulmuşsa şifre oluşturması için eşsiz değer oluştur user_to_insert.password = hashed_password user_to_insert.roles = [ EnumPermission.SIRKET_CALISANI.value ] if not user_to_insert.roles else user_to_insert.roles pass if not company_record: # instantiate Company object with Sistem Value company_record = Organization( name=org_name, type=EnumOrganization.SISTEM.value) company_record.save() self.cont_permission.create_default(company_record) user_to_insert.organization = company_record user_to_insert.save() currency = None try: currency = Currency.objects.get(code=CURRENCY_TRY) except: pass if not currency: currency = Currency(code=CURRENCY_TRY, name=CURRENCY_TRY_DESCRIPTION).save() company_record._key_currency = currency company_record._key_created_user = user_to_insert.pk company_record._key_last_modified_user = user_to_insert.pk company_record._key_owner_user = user_to_insert.pk company_record.save() token = jwt.encode( { 'id': str(user_to_insert.id), 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=3600) }, app.config['SECRET_KEY']) if firstTime: message = { 'liftnec-token': token.decode('UTF-8'), 'user': user_to_insert.to_mongo() } return SoftRestResponse.single_item( item_id=str(user_to_insert.id), item=token.decode('UTF-8'), document_name='Login', created=True) else: owner = User.objects.get(id=session["current_user_id"]) # Eğer kullanıcı şirket yöneticisi tarafından oluşturulmuşsa davetiye bildirimi oluştur send_user_created_by_owner_email(user_to_insert, owner.full_name, 'Liftnec Davetiye', token) return SoftRestResponse.single_item( item_id=str(user_to_insert.id), item={ 'message': 'Kullanıcı yaratıldı, parola oluşturma mail\'i gönderildi' }, document_name='User', created=True) except KeyError as e: app.logger.error("***User org key don't exist") app.logger.exception(e) return SoftRestResponse.error( message='ORG_KEY_NOT_FOUND', detail='Firma bilgisi zorunludur', code=403) # if company doesnt exist on db except Exception as e: app.logger.error('*** {}.create occurred an error'.format( self.__class__.__name__)) app.logger.exception(e) return Response(dumps({'message': e.args}), status=500, mimetype='application/json')