def user_auth(request: http.Request): ''' :param request: JSONを渡す {"id": ID, "password": PASSWORD} :return: トークン ''' try: user = json.loads(request.body) except: # JSON パースエラー return Response({"status": "err", "reason": "JSON Parse error"}, 403) db_data = DB.user.find_one({"id": user['id']}) if not db_data: # データなし return Response({"status": "err", "reason": "user not found"}, 403) if not db_data['password'] == hashlib.sha256().update(db_data['salt'] + user['password']): return Response({"status": "err", "reason": "login failed"}, 403) return JWT.encode({ "id": user['id'], "email": user['email'], "name": user['name'] })
def api_delete(cls, session:Session, record_id: int): res = cls.get_by_id(record_id) if res: success = res.delete(session) if success: return Response(status=204) else: return Response(status=500) else: return Response(status=404)
def get_bibliography(eid, session: CondorSession) -> Response: """ List the bibliography that has the specified eid from the database. """ bibliography = Bibliography.find_by_eid(session, eid) if not bibliography: return Response( {'message': 'The especified eid is not found on database'}, status=404, ) return Response(sc.Bibliography(bibliography))
def get_document(eid, session: CondorSession) -> Response: """ List the document that has the specified eid from the database. """ document = Document.find_by_eid(session, eid) if not document: return Response( {'message': 'The especified eid is not found on database'}, status=404, ) return Response(sc.Document(document))
def get_matrix(eid, session: CondorSession) -> Response: """ List the matrix that has the specified eid from the database. """ matrix = TermDocumentMatrix.find_by_eid(session, eid) if not matrix: return Response( {'message': 'The especified eid is not found on database'}, status=404, ) return Response(sc.Matrix(matrix))
def get_ranking(eid, session: CondorSession) -> Response: """ List the ranking that has the specified eid from the database. """ ranking = RankingMatrix.find_by_eid(session, eid) if not ranking: return Response( {'message': 'The especified eid is not found on database'}, status=404, ) return Response(sc.Ranking(ranking))
def get_all_documents(bibliography: Param, session: CondorSession) -> Response: """ List all documents that are related to a specific bibliography from the the database. """ if not bibliography: return Response( {'message': 'The especified eid is not found on database'}, status=400, ) documents = [ sc.Document(doc) for doc in Document.list(session, bibliography) ] return Response(documents)
async def listening(slack_event: http.RequestData, crypto_bot: CryptoBot, settings: Settings): """ The Slack API event handler. Also handles the Slack challenge request. """ print("SLACK EVENT listening: %s" % pformat(slack_event)) slack_event = slack_event or {} logger.debug("SLACK EVENT listening: %s", pformat(slack_event)) logger.debug("SLACK EVENT api: %s", crypto_bot) # ============= Slack URL Verification ============ # # In order to verify the url of our endpoint, Slack will send a challenge # token in a request and check for this token in the response our endpoint # sends back. # For more info: https://api.slack.com/events/url_verification if "challenge" in slack_event: return {'challenge': slack_event['challenge']} # ============ Slack Token Verification =========== # # We can verify the request is coming from Slack by checking that the # verification token in the request matches our app's settings if crypto_bot.verification != slack_event.get("token"): # By adding "X-Slack-No-Retry" : 1 to our response headers, we turn off # Slack's automatic retries during development. headers = {} if settings.get('DEBUG'): headers['X-Slack-No-Retry'] = '1' return Response('Invalid Slack verification token', status=403, headers=headers) # ====== Process Incoming Events from Slack ======= # # If the incoming request is an Event we've subcribed to if "event" in slack_event: return await crypto_bot.dispatch_event(slack_event) # event_type = slack_event["event"]["type"] # If our bot hears things that are not events we've subscribed to, # send a quirky but helpful error response headers = {} if settings.get('DEBUG'): headers['X-Slack-No-Retry'] = '1' return Response( "[NO EVENT IN SLACK REQUEST] These are not the droids you're looking for.", status=404, headers=headers)
def name(self, body: http.Body): """ Searching for a name in the DB. :return: """ payload = json.loads(body.decode()) if payload['name'] is None: return Response({'message': 'The name property is empty'}, status=401) # Get the search text. text = payload['name'] # Init the query operation. profile = Profile() profiles = profile \ .getTable() \ .filter( lambda document: document['name'].match(text) | document['current_position'].match(text) | document['current_title'].match(text) | document['summary'].match(text) ) \ .run(profile.r) # Search in the text in the name, title, position, summary. results = [] for profile in profiles: results.append(profile) return results
def skills(self, body: http.Body): """ Searching for a user in the DB. :return: """ payload = json.loads(body.decode()) if payload['skill'] is None: return Response({'message': 'The skill property is empty'}, status=401) # Get the search text. text = payload['skill'] # Init the query operation. profile = Profile() profiles = profile \ .getTable() \ .filter( lambda document: document['skills'].contains(lambda skills: skills['skill'].match(text)) ) \ .run(profile.r) # Search in the text in the name, title, position, summary. results = [] for profile in profiles: profile['match'] = self.calculate_score(text, profile) results.append(profile) return results
def patients_create(session: Session, patient: PatientCreateSchema) -> Response: """ create patients """ new_patient = session.Patient.objects.create(**patient) return Response(PatientSchema(new_patient), status=201)
def javascript_schema(schema: Schema, templates: Templates) -> Response: codec = coreapi.codecs.CoreJSONCodec() base64_schema = base64.b64encode(codec.encode(schema)).decode('latin1') template = templates.get_template('apistar/schema.js') content = template.render(base64_schema=base64_schema).encode('utf-8') return Response(content, content_type='application/javascript')
def submit_annotation( message_id, annotation: Annotation, repository: repo.Repository, auth: Auth, ) -> Submission: document = repository.get_document(message_id) annotation = document.update_annotation( annotation['program'], auth.get_user_id(), ) annotation_url = reverse_url( 'retrieve_annotation', message_id=annotation.message_id, revision=annotation.revision, ) return Response( Submission(annotation_url=annotation_url), # This should be SEE_OTHER, but apistar misrenders the response. See # <https://github.com/encode/apistar/issues/317>. status=HTTPStatus.OK, headers={ 'Location': annotation_url, }, )
def api_documentation(schema: Schema, templates: Templates) -> Response: index = templates.get_template('apistar/docs/index.html') langs = ['python', 'javascript', 'shell'] def render_form(link: coreapi.Link) -> str: properties = dict([ (field.name, field.schema or coreschema.String()) for field in link.fields ]) required = [] # type: typing.List[str] schema = coreschema.Object(properties=properties, required=required) return coreschema.render_to_form(schema) def get_fields(link: coreapi.Link, location: str) -> typing.List[coreapi.Field]: return [ field for field in link.fields if field.location == location ] content = index.render( document=schema, langs=langs, get_fields=get_fields, render_form=render_form ).encode('utf-8') return Response(content, content_type='text/html; charset=utf-8')
def create_validated_transcription(session: Session, request_data: http.RequestData): try: db.create_validated_transcription(session, request_data) except Exception as e: console.echo(e) return Response(status=500) return {}
def create_project(): """Create a project with 201 CREATED status code By returning a Response object """ data = {'name': 'new project', 'id': 123} headers = {'location': 'http://chen.rotemlevy.name/project/123'} return Response(data, status=201, headers=headers)
def questions_post(request: http.Request): ''' :param request: JSON :return: 成功かどうかのステータスを返す ''' # 型 {} if not auth_check(request.headers.get("Authorization")): return Response({"status": 'error', 'reason': 'not authorized'}, 400)
def questions_get(request: http.Request): ''' :return Response: 全問題の概要のみを返す ''' return Response([{ "id": str(question['_id']), "title": question['title'], 'description': question['description'] } for question in DB.questions.find()], 200)
def register(data: http.RequestData) -> Response: try: validate(data, schema) db.user.insert(data) except DuplicateKeyError: return error(400, {'error': 'username already exists'}) except ValidationError: return error(400, {'error': 'wrong json schema'}) return Response(format_json(True, 'Success'), status=200, headers={})
def getPhoto(self): try: self.login() except ValueError: print(ValueError) exit() aux = "insta.getSelfUsernameInfo()" data = {"res": aux} return Response(data, status=200, headers={'location': '/'})
def get_all_players(request: http.Request): players = get_players() player_list = [{'name': player, 'url': reverse_url( 'get_player_details', player_name=player)} for player in players] data = {'players': player_list} # print(type(data)) # return data headers = {'this_is_my_url': request.url} return Response(data, headers=headers, status=200)
def new_user(user: CreateUser): """Create a User within the default_domain. Default domain is 'public.example.com'.""" default_domain = 'public.example.com' if 'default_domain' not in user else user[ 'default_domain'] try: app = get_kanban_application() user = app.new_user(name=user['name'], password=user['password'], email=user['email'], default_domain=default_domain) except KeyError as e: error = {"error": "MissingRequiredParameterError", "message": str(e)} return Response(error, 400) except AttributeError as e: error = {"error": "AttributeError", "message": str(e)} return Response(error, 400) else: data = {"data": User(user)} return Response(data, 202)
def question_get(question_id, request: http.Request): ''' :param question_id: :return Response: 1問のデータを全て返す ''' if not auth_check(request.headers.get("Authorization")): return Response({"status": 'error', 'reason': 'not authorized'}, 400) try: question = DB.questions.find_one({"id": question_id}) except: return Response({"status": 'error', 'reason': 'not found'}, 404) return Response( { "id": str(question['_id']), "title": question['title'], 'description': question['description'], 'questions': question['question'] }, 200)
async def reservation_delete(session: Session, reservation_id: int) -> Response: obj = session.query(Reservation).filter( Reservation.id == reservation_id ).first() if not obj: raise NotFound session.delete(obj) return Response({'status': 'ok'})
def login(session: Session, auth_credentials: AuthCredentials) -> AuthResponse: """ Login user and exchange credentials for an API token. """ user = authenticate(**auth_credentials) if not user: return Response({'error': 'Invalid credentials'}, status=401) token, _ = session.Token.objects.get_or_create(user=user) return AuthResponse(user=user, token=token.key)
def login(user: str, pwd: str, settings: Settings) -> Response: user_logged = authenticate(username=user, password=pwd) if not user_logged: raise Forbidden("Utilisateur inactif, mauvais login/mot de passe") SECRET = settings['JWT'].get('SECRET') payload = get_payload(user_logged, settings['JWT'].get('PAYLOAD_DURATION')) token = JWT.encode(payload, secret=SECRET) return Response({'token': token}, status=201)
def create_matrix(descriptor: sc.MatrixDescriptor, session: CondorSession) -> Response: """ Create a term document matrix. """ bibliography = Bibliography.find_by_eid(session, descriptor.get('bibliography')) if bibliography is None: return Response( { 'message': 'The especified bibliography eid is not found on database' }, status=404, ) td_matrix = TermDocumentMatrix.from_bibliography_set( bibliography, regularise=descriptor.get('regularise'), fields=descriptor.get('fields')) session.add(td_matrix) session.commit() return Response(sc.Matrix(td_matrix))
def add_event(authorization: http.Header, data: http.RequestData) -> Response: cred = check_token(authorization) if isinstance(cred, int): if cred == 1: try: validate(data, schema) db.event.insert(data) return Response(format_json(True, "Success"), status=200, headers={}) except ValidationError: return error(400, {'error': 'wrong json schema'}) else: return error(400, {'error': 'unauthorized'}) return cred
def user_join(request: http.Request): ''' :param request: JSONを渡す {"id": ID, "password": PASSWORD, "email": EMAIL} :return: トークン ''' try: user = json.loads(request.body) except: # JSON パースエラー return Response({"status": "err", "reason": "JSON Parse error"}, 403) # ここでは当該IDのデータが存在「してはならない」 if DB.user.find_one({"id": user['id']}): # データ「あり」 return Response({"status": "err", "reason": "user not found"}, 403) salt = ''.join([ random.choice(string.ascii_letters + string.digits) for i in range(32) ]) DB.user.insert_one({ "id": user['id'], "email": user['email'], "name": user['name'], "join_at": datetime.datetime.now(), "password": hashlib.sha256().update(salt + user['password']), "salt": salt }) return JWT.encode({"id": user['id'], "name": user['name']})
def acte_update(obj_id: int, new_data: actes_schemas[self.model].updater, auth: Auth) -> Response: # check against empty data if not new_data: raise BadRequest("empty query") obj = self.model.objects.get(id=obj_id) try: obj.update(**new_data) except AttributeError as e: # request should be for valide fields raise BadRequest from e return Response(actes_schemas[self.model].getter(obj), status=201)