Skip to content

Commit

Permalink
Adding json-output for api-like functionality (#147)
Browse files Browse the repository at this point in the history
* adding json-template for api-like functionality

* removing content-block

* adding test

* changing to flask.jsonify

* deleting template

* change from POST-param to Accept-Header
  • Loading branch information
mr-deamon authored Apr 11, 2022
1 parent 4b1ee0c commit 3fbc018
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
7 changes: 5 additions & 2 deletions snappass/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import redis

from cryptography.fernet import Fernet
from flask import abort, Flask, render_template, request
from flask import abort, Flask, render_template, request, jsonify
from redis.exceptions import ConnectionError
from werkzeug.urls import url_quote_plus
from werkzeug.urls import url_unquote_plus
Expand Down Expand Up @@ -177,7 +177,10 @@ def handle_password():
if URL_PREFIX:
base_url = base_url + URL_PREFIX.strip("/") + "/"
link = base_url + url_quote_plus(token)
return render_template('confirm.html', password_link=link)
if request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html:
return jsonify(link=link, ttl=ttl)
else:
return render_template('confirm.html', password_link=link)


@app.route('/<password_key>', methods=['GET'])
Expand Down
16 changes: 16 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import time
import unittest
import uuid
import json
from unittest import TestCase

from cryptography.fernet import Fernet
Expand Down Expand Up @@ -138,6 +139,21 @@ def test_set_password(self):

frozen_time.move_to("2020-05-22 12:00:00")
self.assertIsNone(snappass.get_password(key))

def test_set_password_json(self):
with freeze_time("2020-05-08 12:00:00") as frozen_time:
password = 'my name is my passport. verify me.'
rv = self.app.post('/', headers={'Accept': 'application/json'}, data={'password': password, 'ttl': 'two weeks'})

json_content = rv.get_json()
key = re.search(r'https://localhost/([^"]+)', json_content['link']).group(1)
key = unquote(key)

frozen_time.move_to("2020-05-22 11:59:59")
self.assertEqual(snappass.get_password(key), password)

frozen_time.move_to("2020-05-22 12:00:00")
self.assertIsNone(snappass.get_password(key))


if __name__ == '__main__':
Expand Down

0 comments on commit 3fbc018

Please sign in to comment.