예제 #1
0
 def parse_request(self):
     rfile = self.conn.makefile('rb')
     method, target, ver = self.parse_request_line(rfile)
     headers = self.parse_headers(rfile)
     host = headers.get('Host')
     if not host:
         raise HTTPError(400, 'Bad request', 'Host header is missing')
     if host not in (self._server_name,
                     f'{self._server_name}:{self._port}'):
         raise HTTPError(404, 'Not found')
     return Request(method, target, ver, headers, rfile)
예제 #2
0
    def parse_request_line(self, rfile):
        raw = rfile.readline(MAX_LINE + 1)
        if len(raw) > MAX_LINE:
            raise HTTPError(400, 'Bad request', 'Request line is too long')

        req_line = str(raw, 'iso-8859-1')
        words = req_line.split()
        if len(words) != 3:
            raise HTTPError(400, 'Bad request', 'Malformed request line')

        method, target, ver = words
        if ver != 'HTTP/1.1':
            raise HTTPError(505, 'HTTP Version Not Supported')
        return method, target, ver
예제 #3
0
    def handle_login_user(self, req: Request) -> Union[Response, HTTPError]:
        user_from_req = self.read_user_from_request_body(req)
        user_from_db = self._users.get_by_login(user_from_req.login)

        if user_from_db is None:
            # user not found, 404
            return HTTPError(404, 'Not Found')

        if user_from_db.password != user_from_req.password:
            # forbidden, 403
            return HTTPError(403, 'Forbidden')

        ts = int(time.time())
        token = Token.as_authorization(user_from_db.login, ts + 3600)
        return Response(200, 'OK', headers={"Authorization": token})
예제 #4
0
    def parse_headers(self, rfile):
        headers = []
        while True:
            line = rfile.readline(MAX_LINE + 1)
            if len(line) > MAX_LINE:
                raise HTTPError(494, 'Request header too large')

            if line in (b'\r\n', b'\n', b''):
                break

            headers.append(line)
            if len(headers) > MAX_HEADERS:
                raise HTTPError(494, 'Too many headers')
        # Using standart decode function
        sheaders = b''.join(headers).decode('iso-8859-1')
        return Parser().parsestr(sheaders)
예제 #5
0
 def handle_post_users(self, req):
     user = self.read_user_from_request_body(req)
     _ = self._users.put(user)
     user = user.copy()
     if _ == -1:
         return HTTPError(403, 'Forbidden')
     user.password = None
     return Response(204, 'Created', body=user)
예제 #6
0
    def handle_get_user(self, req, user_id):
        user = self._users.get(int(user_id))
        if not user:
            raise HTTPError(404, 'Not found')

        accept = req.headers.get('Accept')
        if 'application/json' in accept:
            contentType = 'application/json; charset=utf-8'
            body = json.dumps(user)

        else:
            # https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/406
            return HTTPError(406, 'Not Acceptable')

        body = body.encode('utf-8')
        headers = {'Content-Type': contentType, 'Content-Length': len(body)}
        return Response(200, 'OK', headers, body)
예제 #7
0
 def handle_del_cafe_media(self, req, login: str):
     file_id = req.query["file_id"][0]
     cafe_id = req.query["cafe_id"][0]
     id_check = self._cafes._owner_login.get(login)
     # print("id = "+str(id_check))
     if id_check != int(cafe_id):
         return HTTPError(403, 'Forbidden')
     self._media_files.delete_by_cafeid(int(cafe_id), int(file_id))
     return Response(204, 'Deleted')
예제 #8
0
 def handle_add_cafe_media(self, req, login: str):
     tp = req.query["type"][0]
     cafe_id = req.query["cafe_id"][0]
     id_check = self._cafes._owner_login.get(login)
     #print("id = "+str(id_check))
     if id_check != int(cafe_id):
         return HTTPError(403, 'Forbidden')
     mf = MediaFile(int(cafe_id), tp)
     mf = self._media_files.put(mf, req.body())
     return Response(204, 'Created', body=mf)
예제 #9
0
    def handle_request(self, req: Request):
        user_login = None
        if "Authorization" in req.headers:
            try:
                user_login = Token.as_token(req.headers["Authorization"])
            except KeyError as ke:
                return HTTPError(403, "Forbidden", body=("token must have key " + str(ke)).encode())
            except Exception as e:
                return HTTPError(403, "Forbidden", body=str(e).encode())

        print(req.path, req.query, req.url)

        if req.path == '/users' and req.method == 'POST':#REGISTRATION
            return self.handle_post_users(req)

        if req.path == '/login' and req.method == 'POST':#LOGIN
            return self.handle_login_user(req)

        if req.path == '/users' and req.method == 'GET': #GET ALL USERS LIST
            if user_login is None:
                return HTTPError(403, "Forbidden", body="authorization header is absent".encode())
            return self.handle_get_users(req, user_login)


        if req.path == '/cafes' and req.method == 'GET': #TODO # withMeanStars
            if user_login is None:
                return HTTPError(403, "Forbidden", body="authorization header is absent".encode())
            return self.handle_get_cafes(req)

        if req.path == '/cafe/media' and req.method == 'GET': #TODO
            if user_login is None:
                return HTTPError(403, "Forbidden", body="authorization header is absent".encode())
            return self.handle_get_cafe_media(req)

        if req.path == '/cafe/media' and req.method == 'POST':
            if user_login is None:
                return HTTPError(403, "Forbidden", body="authorization header is absent".encode())
            return self.handle_add_cafe_media(req, user_login)

        if req.path == '/cafe/media' and req.method == 'DELETE': #TODO
            if user_login is None:
                return HTTPError(403, "Forbidden", body="authorization header is absent".encode())
            return self.handle_del_cafe_media(req)

        if req.path == '/cafe' and req.method == 'POST':
            if user_login is None:
                return HTTPError(403, "Forbidden", body="authorization header is absent".encode())
            return self.handle_put_cafe(req, user_login)

        # if req.path == '/cafe' and req.method == 'POST':
        #     if user_login is None:
        #         return HTTPError(403, "Forbidden", body="authorization header is absent".encode())
        #     return self.handle_edit_cafe(req)

        if req.path == '/cafe/review' and req.method == 'GET':
            if user_login is None:
                return HTTPError(403, "Forbidden", body="authorization header is absent".encode())
            return self.handle_get_reviews(req)

        if req.path == '/cafe/review' and req.method == 'POST':
            if user_login is None:
                return HTTPError(403, "Forbidden", body="authorization header is absent".encode())
            return self.handle_add_review(req, user_login)

        if req.path == '/cafe/review' and req.method == 'DELETE': #TODO
            if user_login is None:
                return HTTPError(403, "Forbidden", body="authorization header is absent".encode())
            return self.handle_del_review(req, user_login)

        """if req.path.startswith('/users/'):
            user_id = req.path[len('/users/'):]
            if user_id.isdigit():
                return self.handle_get_user(req, user_id)"""

        raise HTTPError(404, 'Not found')