Skip to content

Commit

Permalink
has_attachment field & PDF key endpoint added.
Browse files Browse the repository at this point in the history
  • Loading branch information
geekdinazor committed Jan 17, 2022
1 parent bde3a14 commit 0235183
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 16 deletions.
22 changes: 14 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,29 @@ Access token will persist in cookie for future use.
## Environment Variables


- `OAUTHLIB_INSECURE_TRANSPORT`: Set `True` for non-https environments
- `OAUTHLIB_INSECURE_TRANSPORT`: Set `True` for non-https environments

- `__SERVICE_SQLALCHEMY_DATABASE_URI`: Database URI. Ex. `sqlite:///db.sqlite`
- `__SERVICE_SQLALCHEMY_DATABASE_URI`: Database URI. Ex. `sqlite:///db.sqlite`

- `__SERVICE_ACTUATOR_BASE_URI`: Full URL for actuator endpoint.

- `__SERVICE_SSO_DISCOVERY_URL`: OpenID configuration endpoint of SSO tool.
- `__SERVICE_SSO_DISCOVERY_URL`: OpenID configuration endpoint of SSO tool.

- `__SERVICE_SSO_CLIENT_ID`: SSO Client ID
- `__SERVICE_SSO_CLIENT_ID`: SSO Client ID

- `__SERVICE_SSO_CLIENT_SECRET`: SSO Client Secret
- `__SERVICE_SSO_CLIENT_SECRET`: SSO Client Secret

- `__SERVICE_JWT_COOKIE_NAME`: JWT token cookie name
- `__SERVICE_SSO_TARGET_AUDIENCE`: SSO Audience for JWT validation.

- `__SERVICE_FILE_SERVICE_UPLOAD_URL`: File service api url for uploading attachment
- `__SERVICE_JWT_COOKIE_NAME`: JWT token cookie name

- `__SERVICE_AUTHORIZED_GROUP`: Set group name in SSO (Put / before it for Keycloak.)
- `__SERVICE_FILE_SERVICE_UPLOAD_URL`: File service api url for uploading attachment

- `__SERVICE_FILE_SERVICE_DOWNLOAD_URL`: File service api url for downloading attachment

- `__SERVICE_PDF_SERVICE_KEY_URL`: PDF service api url for securely previewing the note attachments

- `__SERVICE_AUTHORIZED_GROUP`: Set group name in SSO (Put / before it for Keycloak.)

Other application settings in [config.py](src/note_service/config.py) could be overrided with environment variables with `__SERVICE_` prefix.

2 changes: 1 addition & 1 deletion src/note_service/modules/rest/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from note_service.modules.rest import errors

26 changes: 25 additions & 1 deletion src/note_service/modules/rest/business.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
def create_note(files, args, username):
tag = args.get('tag')
note_info = args.get('note_info')
note = Notes(tag, note_info, None, created_date=datetime.now(), created_by=username)
note = Notes(tag, note_info, False, None, created_date=datetime.now(), created_by=username)
db.session.add(note)
if files:
try:
Expand All @@ -25,6 +25,7 @@ def create_note(files, args, username):
file_service_upload_url = current_app.config.get('FILE_SERVICE_UPLOAD_URL')
r = requests.post(file_service_upload_url, files={"file": (attachment.filename, f, attachment.mimetype)})
attachment_file_key = r.json()["key"]
note.has_attachment = True
note.attachment_file_key = attachment_file_key
db.session.add(note)
except Exception as e:
Expand Down Expand Up @@ -89,3 +90,26 @@ def delete_note(note_id):
abort(HTTPStatus.BAD_GATEWAY, message="Note couldn't deleted.", exc=e)

return ResponseObject(message="Note successfully deleted.", status=HTTPStatus.OK)


def get_pdf_key(note_id):
try:
note = Notes.query.filter(Notes.id == note_id).one()
except NoResultFound as e:
abort(HTTPStatus.NOT_FOUND, message="Note not found.", exc=e)
pass

if not note.has_attachment:
abort(HTTPStatus.NOT_FOUND, message="Note has no attachment.", exc=e)

file_service_download_url = current_app.config.get('FILE_SERVICE_DOWNLOAD_URL')
pdf_service_key_url = current_app.config.get('PDF_SERVICE_KEY_URL')
r = requests.post(
pdf_service_key_url,
json={'url': f'{file_service_download_url}/{note.attachment_file_key}?contentDisposition=inline'}
)

if r.status_code == 200 or r.status_code == 201:
return ResponseObject(data={"pdfKey": r.text}, status=HTTPStatus.OK)
else:
return ResponseObject(message="Pdf key couldn't generated.", exc=e)
7 changes: 4 additions & 3 deletions src/note_service/modules/rest/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@ def _parse_jwt_user(token):
jwks_client = PyJWKClient(jwks_url)
signing_key = jwks_client.get_signing_key_from_jwt(token)

decoded_jwt = jwt.decode(token, signing_key.key, algorithms=["RS256"], audience="account",
sso_target_audience = current_app.config.get("SSO_TARGET_AUDIENCE")
decoded_jwt = jwt.decode(token, signing_key.key, algorithms=["RS256"], audience=sso_target_audience,
options={"verify_exp": True})


username = decoded_jwt.get("sub")
return username

Expand Down
6 changes: 5 additions & 1 deletion src/note_service/modules/rest/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,24 @@
from sqlalchemy_utils import UUIDType
from sqlalchemy_utils import ScalarListType


class Notes(db.Model):
id = db.Column(UUIDType(binary=False), primary_key=True)
tag = db.Column(ScalarListType(str))
note_info = db.Column(db.Text)
has_attachment = db.Column(db.Boolean)
attachment_file_key = db.Column(db.String)
created_date = db.Column(db.TIMESTAMP)
updated_date = db.Column(db.TIMESTAMP)
created_by = db.Column(db.String)
updated_by = db.Column(db.String)

def __init__(self, tag, note_info, attachment_file_key, created_date=None, updated_date=None, created_by=None, updated_by=None):
def __init__(self, tag, note_info, has_attachment, attachment_file_key, created_date=None, updated_date=None,
created_by=None, updated_by=None):
self.id = uuid.uuid4()
self.tag = tag
self.note_info = note_info
self.has_attachment = has_attachment
self.attachment_file_key = attachment_file_key
self.created_date = created_date
self.updated_date = updated_date
Expand Down
1 change: 1 addition & 0 deletions src/note_service/modules/rest/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class Note(Schema):
id = fields.UUID(dump_only=True)
tag = fields.List(fields.String, required=True)
note_info = fields.String(required=True, validate=validate.Length(min=2))
has_attachment = fields.Boolean(dump_only=True)
attachment_file_key = fields.UUID(dump_only=True)
created_date = fields.DateTime(dump_only=True)
updated_date = fields.DateTime(dump_only=True)
Expand Down
12 changes: 10 additions & 2 deletions src/note_service/modules/rest/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from flask.views import MethodView
from flask_smorest import Blueprint

from note_service.modules.rest.business import search_notes, create_note, fetch_note, update_note, delete_note
from note_service.modules.rest.business import search_notes, create_note, fetch_note, update_note, delete_note, \
get_pdf_key
from note_service.modules.rest.decorators import token_required
from note_service.modules.rest.schemas import Note, NoteFile, NotesResponse, NoteResponse, BaseResponse, NoteSearch

Expand Down Expand Up @@ -60,5 +61,12 @@ def delete(self, note_id, **kwargs):
"""ID bilgisi verilen notu silmek için kullanılır"""
return delete_note(note_id)


@notes.route("/<uuid:note_id>/pdfKey")
class NoteItemCollection(MethodView):
@token_required
@notes.response(HTTPStatus.OK, BaseResponse)
@notes.alt_response(status_code=HTTPStatus.NOT_FOUND, success=False, schema=BaseResponse)
def get(self, note_id, **kwargs):
"""Not'un ekini görüntülenmek için pdf anahtarı oluşturur """
return get_pdf_key(note_id)

0 comments on commit 0235183

Please sign in to comment.