async def api_get_session(request): logger.debug('get_session') session = await get_session(request) data = await request.json() await set_csrf_token_session(session) success = False token = session['csrf_token'] user = None uid = session.get('uid') if uid: user = get_user_from_session(session, request.db_session) session['tz'] = data.get('user_timezone') if user.enable: context = { 'user': user, 'db_session': request.db_session, 'ws_session': session, 'method': 'read', 'queue': request.app.queue } user = await user.serialize(context) success = True else: user.logout(session) user = None resp_data = {'success': success, 'user': user, 'token': token} return web.json_response(resp_data)
async def api_get_session(request): session = await get_session(request) data = await request.json() await set_csrf_token_session(session) success = False token = session['csrf_token'] user = None uid = session.get('uid') if uid: user = get_user_from_session(session, request.db_session) session['tz'] = data.get('user_timezone') if user.enable: context = { 'user': user, 'db_session': request.db_session, 'ws_session': session, 'method': 'read', 'queue': request.app.queue } user = await user.serialize(context) success = True else: user.logout(session) user = None resp_data = {'success': success, 'user': user, 'token': token} return web.json_response(resp_data)
async def api_admin(request): session = await get_session(request) user = get_user_from_session(session, request.db_session) context = { 'user': user, 'ws_session': session, 'db_session': request.db_session, 'method': 'read', 'queue': request.app.queue } resp_data = {'success': True, 'user': await user.serialize(context)} return web.json_response(resp_data)
async def api_confirm_email(request): logger.debug('confirm_email') try: data = await request.json() email_confirmation_token = data['token'] except: raise exceptions.InvalidRequestException('Missing json data') session = await get_session(request) user = get_user_from_session(session, request.db_session) context = { 'user': user, 'db_session': request.db_session, 'ws_session': session, 'method': 'update', 'queue': request.app.queue } token_query = request.db_session.query(Emailconfirmationtoken)\ .filter(Emailconfirmationtoken.token == email_confirmation_token) if token_query.count(): email_confirmation_token = token_query.one() context['target'] = email_confirmation_token ret = email_confirmation_token.use(context) if ret: context['data'] = {'email_confirmed': True} del context['target'] await user.validate_and_save(context) context['method'] = 'read' resp_data = { 'success': True, 'user': await user.serialize(context) } return web.json_response(resp_data) # TOKEN NOT FOUND else: raise exceptions.TokenInvalidException('token not found')
async def api_confirm_email(request): try: data = await request.json() email_confirmation_token = data['token'] except: raise exceptions.InvalidRequestException('Missing json data') session = await get_session(request) user = get_user_from_session(session, request.db_session) context = { 'user': user, 'db_session': request.db_session, 'ws_session': session, 'method': 'update', 'queue': request.app.queue } token_query = request.db_session.query(Emailconfirmationtoken)\ .filter(Emailconfirmationtoken.token == email_confirmation_token) if token_query.count(): email_confirmation_token = token_query.one() context['target'] = email_confirmation_token ret = email_confirmation_token.use(context) if ret: context['data'] = {'email_confirmed': True} del context['target'] await user.validate_and_save(context) context['method'] = 'read' resp_data = { 'success': True, 'user': await user.serialize(context) } return web.json_response(resp_data) # TOKEN NOT FOUND else: raise exceptions.TokenInvalidException('token not found')
async def post(self): session = await get_session(self.request) user = get_user_from_session(session, self.request.db_session) user.logout(session) resp_data = {'success': True} return web.json_response(resp_data)
async def post(self): actions = await self.get_json_data() session = await get_session(self.request) author = get_user_from_session(session, self.request.db_session) read_context = { 'author': author, 'db_session': self.request.db_session, 'ws_session': session, 'method': 'read', 'queue': self.request.app.queue, } action_context = { 'author': author, 'db_session': self.request.db_session, 'ws_session': session, 'queue': self.request.app.queue } success = True response_data = [] error = [] for index, action in enumerate(actions): try: # RESPONSE response_data.append(dict()) response_data[index]['success'] = True response_data[index]['results'] = [] # ACTION action_name = action.get('action') if not action_name: raise exceptions.InvalidRequestException( 'Missing action in actions[{index}]'.format( index=index)) elif action_name not in self.action_list: raise exceptions.InvalidRequestException( 'Invalid action name: "{action_name}"'.format( action_name=action_name)) action_context['method'] = action_name # IMPORT MODEL model_name = action.get('model') if not model_name: raise exceptions.InvalidRequestException( 'Missing model in action') model_class = self.import_model(model_name) # CREATE if action_name == 'create': results = [model_class()] response_data[index]['total'] = 1 # QUERY else: # READ SPECIFIC RECORD uid = action.get('uid') if uid: base_query = self.request.db_session\ .query(model_class)\ .filter(model_class.mongo_id == uid) # BATCH elif action.get('uids'): uids = action.get('uids') base_query = self.request.db_session.query(model_class) response_data[index]['total'] = len(uids) base_query = base_query.in_('mongo_id', *uids) results = base_query.all() else: filters = action.get('filters') filters_wildcard = action.get('filters_wildcard') limit = action.get('limit') skip = action.get('skip') descending = action.get('descending') ascending = action.get('ascending') base_query = self.request.db_session.query(model_class) if limit: base_query = base_query.limit(limit) if skip: base_query = base_query.skip(skip) if descending: base_query = base_query.descending(descending) if ascending: base_query = base_query.ascending(ascending) if filters: if 'uid' in filters: filters['mongo_id'] = filters['uid'] del filters['uid'] base_query = base_query.filter_by(**filters) if filters_wildcard: wildcard = [] for key, value in iter(filters_wildcard.items()): wildcard.append( getattr(model_class, key).regex('.*%s.*' % value, ignore_case=True)) base_query = base_query.or_(*wildcard) response_data[index]['total'] = base_query.count() results = base_query.all() # PROCESSING RESULTS for result in results: # AUTHORIZATION CHECK """ logger.debug( 'action_context = {action_context}' .format( action_context=action_context ) ) """ if not await result.method_autorized(action_context): raise exceptions.NotAuthorizedException( '{author} not authorized to {action_name} {result}' .format(author=author, action_name=action_name, result=result)) # APPLY ACTION # CREATE & UPDATE if action_name in ['create', 'update']: data = action.get('data') if not data: raise exceptions.InvalidRequestException( 'Missing data in action') action_context['data'] = data sane_data = await result.sanitize_data(action_context) action_context['data'] = sane_data # BEFORE HOOK await getattr( result, 'before_{action_name}'.format( action_name=action_name))(action_context) await result.validate_and_save(action_context) # AFTER HOOK await getattr( result, 'after_{action_name}'.format( action_name=action_name))(action_context) # DELETE elif action_name == 'delete': await result.before_delete(action_context) self.request.db_session.remove(result, safe=True) await result.after_delete(action_context) if not action.get('total_only', False) \ and not action_name == 'delete': # READ # NOTE the authorization check has already # been performed for the read if not action_name == 'read': """ logger.debug( 'read_context = {read_context}' .format( read_context=read_context ) ) """ if not await result.method_autorized(read_context): raise exceptions.NotAuthorizedException( '{author} not authorized to {action_name} {result}' # noqa .format( author=author, action_name=read_context.get('method'), result=result)) response_data[index]['results'].append( await result.serialize(read_context)) except Exception as e: success = False tb = traceback.format_exc() logger.error('Request HandledException<{exception}>'.format( exception=str(tb))) if isinstance(e, exceptions.ServerBaseException): error_msg = e.get_name() else: error_msg = 'ServerSideError' response_data[index] = {'success': False, 'error': error_msg} error.append(error_msg) # RESPONSE trimmed_response_data = self.trim_response_data( success, response_data, error) return web.json_response(trimmed_response_data)
async def post(self): actions = await self.get_json_data() session = await get_session(self.request) author = get_user_from_session(session, self.request.db_session) read_context = { 'author': author, 'db_session': self.request.db_session, 'ws_session': session, 'method': 'read', 'queue': self.request.app.queue, } action_context = { 'author': author, 'db_session': self.request.db_session, 'ws_session': session, 'queue': self.request.app.queue } success = True response_data = [] error = [] for index, action in enumerate(actions): try: # RESPONSE response_data.append(dict()) response_data[index]['success'] = True response_data[index]['results'] = [] # ACTION action_name = action.get('action') if not action_name: raise exceptions.InvalidRequestException( 'Missing action in actions[{index}]' .format( index=index ) ) elif action_name not in self.action_list: raise exceptions.InvalidRequestException( 'Invalid action name: "{action_name}"' .format( action_name=action_name ) ) action_context['method'] = action_name # IMPORT MODEL model_name = action.get('model') if not model_name: raise exceptions.InvalidRequestException( 'Missing model in action' ) model_class = self.import_model(model_name) # CREATE if action_name == 'create': results = [model_class()] response_data[index]['total'] = 1 # QUERY else: # READ SPECIFIC RECORD uid = action.get('uid') if uid: base_query = self.request.db_session\ .query(model_class)\ .filter(model_class.mongo_id == uid) # BATCH elif action.get('uids'): uids = action.get('uids') base_query = self.request.db_session.query(model_class) response_data[index]['total'] = len(uids) base_query = base_query.in_('mongo_id', *uids) results = base_query.all() else: filters = action.get('filters') filters_wildcard = action.get('filters_wildcard') limit = action.get('limit') skip = action.get('skip') descending = action.get('descending') ascending = action.get('ascending') base_query = self.request.db_session.query(model_class) if limit: base_query = base_query.limit(limit) if skip: base_query = base_query.skip(skip) if descending: base_query = base_query.descending(descending) if ascending: base_query = base_query.ascending(ascending) if filters: if 'uid' in filters: filters['mongo_id'] = filters['uid'] del filters['uid'] base_query = base_query.filter_by(**filters) if filters_wildcard: wildcard = [] for key, value in iter(filters_wildcard.items()): wildcard.append( getattr( model_class, key ).regex('.*%s.*' % value, ignore_case=True) ) base_query = base_query.or_(*wildcard) response_data[index]['total'] = base_query.count() results = base_query.all() # PROCESSING RESULTS for result in results: # AUTHORIZATION CHECK """ logger.debug( 'action_context = {action_context}' .format( action_context=action_context ) ) """ if not await result.method_autorized(action_context): raise exceptions.NotAuthorizedException( '{author} not authorized to {action_name} {result}' .format( author=author, action_name=action_name, result=result ) ) # APPLY ACTION # CREATE & UPDATE if action_name in ['create', 'update']: data = action.get('data') if not data: raise exceptions.InvalidRequestException( 'Missing data in action' ) action_context['data'] = data sane_data = await result.sanitize_data( action_context ) action_context['data'] = sane_data # BEFORE HOOK await getattr( result, 'before_{action_name}' .format( action_name=action_name ) )(action_context) await result.validate_and_save(action_context) # AFTER HOOK await getattr( result, 'after_{action_name}' .format( action_name=action_name ) )(action_context) # DELETE elif action_name == 'delete': await result.before_delete(action_context) self.request.db_session.remove(result, safe=True) await result.after_delete(action_context) if not action.get('total_only', False) \ and not action_name == 'delete': # READ # NOTE the authorization check has already # been performed for the read if not action_name == 'read': """ logger.debug( 'read_context = {read_context}' .format( read_context=read_context ) ) """ if not await result.method_autorized(read_context): raise exceptions.NotAuthorizedException( '{author} not authorized to {action_name} {result}' # noqa .format( author=author, action_name=read_context.get('method'), result=result ) ) response_data[index]['results'].append( await result.serialize(read_context) ) except Exception as e: success = False tb = traceback.format_exc() logger.error( 'Request HandledException<{exception}>' .format(exception=str(tb)) ) if isinstance(e, exceptions.ServerBaseException): error_msg = e.get_name() else: error_msg = 'ServerSideError' response_data[index] = { 'success': False, 'error': error_msg } error.append(error_msg) # RESPONSE trimmed_response_data = self.trim_response_data( success, response_data, error ) return web.json_response(trimmed_response_data)