Compare commits

...

2 Commits

5 changed files with 121 additions and 65 deletions

View File

@ -26,23 +26,28 @@ csrf_protection_string = None
@app.route('/')
def home():
if is_logged_in():
resp_json = requests.get(f'{database_url}/token/latest').json()
access_token = resp_json['token']['access_token']
# set session token id
session['token_id'] = resp_json['token']['id']
token_id = session.get('token_id')
resp = requests.get(f'{database_url}/token/{token_id}')
resp.raise_for_status()
resp_json = resp.json()
token = resp_json['token']
user_info = requests.get('https://api.github.com/user', headers={
'Authorization': f'Bearer {access_token}'
'Authorization': f'Bearer {token.get("access_token")}'
}).json()
return render_template('success.html', user_info=user_info)
last_synced = datetime.fromtimestamp(token.get('timestamp')).strftime('%Y-%m-%d %H:%M:%S')
next_sync = datetime.fromtimestamp(token.get('timestamp') + token.get('expiration_seconds')).strftime('%Y-%m-%d %H:%M:%S')
return render_template('home.html', user_info=user_info,
readwise_api_key=token.get('readwise_api_key', None),
last_synced=last_synced, next_sync=next_sync)
# Generate a CSRF protection string
global csrf_protection_string
csrf_protection_string = os.urandom(16).hex()
# Pass dynamic variables to the template
return render_template('index.html', client_id=client_id, redirect_uri=redirect_uri,
return render_template('login.html', client_id=client_id, redirect_uri=redirect_uri,
optional_scopes=optional_scopes, csrf_protection_string=csrf_protection_string)
@app.route('/oauth-redirect')
@ -86,15 +91,21 @@ def oauth_redirect():
response.raise_for_status()
tokens = response.json()
token = response.json()
# TEST: Github OAuth - REMOVE
tokens['refresh_token'] = 'N/A'
tokens['expires_in'] = 36000
token['refresh_token'] = 'N/A'
token['expires_in'] = 3600
# Save tokens for later use
save_tokens(tokens['access_token'], tokens['refresh_token'], tokens['expires_in'])
token_id = save_token(
token.get('email'), # for inoreader it's userEmail
token.get('access_token'),
token.get('refresh_token'),
token.get('expires_in')
)
set_session_token_id(token_id)
return redirect(url_for('home'))
# logout
@ -108,32 +119,51 @@ def logout():
# remove token_id from session
session.pop('token_id', None)
# response = requests.put(f'{database_url}/token/{token_id}', headers={
# 'Content-Type': 'application/json'
# }, json={
# 'is_logged_in': False
# })
# response.raise_for_status()
return redirect(url_for('home'))
@app.route('/readwise', methods=['POST'])
def submit_readwise_api():
token_id = session.get('token_id')
if not token_id:
return redirect(url_for('home'))
response = requests.put(f'{database_url}/token/{token_id}', headers={
'Content-Type': 'application/json'
}, json={
'is_logged_in': False
'readwise_api_key': request.form.get('readwise_api_key')
})
response.raise_for_status()
return redirect(url_for('home'))
def is_logged_in():
response = requests.get(f'{database_url}/token/latest')
response.raise_for_status()
if response.status_code == 204:
token_id = session.get('token_id')
if not token_id:
return False
elif response.status_code == 200:
resp_json = response.json()
return resp_json['token']['is_logged_in'] or False
return False
def save_tokens(access_token, refresh_token, expiration_seconds):
response = requests.get(f'{database_url}/token/{token_id}')
response.raise_for_status()
resp_json = response.json()
token = resp_json['token']
return token.get('active', False)
def save_token(email, access_token, refresh_token, expiration_seconds):
response = requests.post(
f'{database_url}/token',
headers={
'Content-Type': 'application/json'
},
json={
'email': email,
'access_token': access_token,
'refresh_token': refresh_token,
'expiration_seconds': expiration_seconds
@ -141,5 +171,10 @@ def save_tokens(access_token, refresh_token, expiration_seconds):
)
response.raise_for_status()
return response.json().get('id')
def set_session_token_id(token_id):
session['token_id'] = token_id
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, port=5000)

28
app/templates/home.html Normal file
View File

@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inoreader To Readwise</title>
</head>
<body>
<h1>Logged In as {{ user_info.login }}({{user_info.name}})</h1>
<!-- show last synced and next synced time -->
<p>Last Synced: {{ last_synced }}</p>
<p>Next Synced: {{ next_synced }}</p>
<br>
<!-- Take readiwse api key input -->
<form action="/readwise" method="POST">
<label for="api_key">Readwise API Key</label>
<input type="text" name="readwise_api_key" id="api_key", value="{{ readwise_api_key }}">
<input type="submit" value="Submit">
</form>
<!-- Logout -->
<form action="/logout" method="POST">
<input type="submit" value="Logout">
</form>
</body>
</html>

View File

@ -3,10 +3,10 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Frontend</title>
<title>Inoreader To Readwise</title>
</head>
<body>
<button onclick="redirectToOAuth()">Click Me</button>
<button onclick="redirectToOAuth()">Login using inoreader</button>
<script>
function redirectToOAuth() {

View File

@ -1,15 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Frontend</title>
</head>
<body>
<h1>Logged In as {{ user_info.login }}({{user_info.name}})</h1>
<!-- Logout -->
<form action="/logout" method="POST">
<input type="submit" value="Logout">
</form>
</body>
</html>

View File

@ -1,6 +1,7 @@
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import uuid
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tokens.db' # Use SQLite for simplicity
@ -8,11 +9,13 @@ app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Token(db.Model):
id = db.Column(db.Integer, primary_key=True)
id = db.Column(db.String(36), primary_key=True, default=str(uuid.uuid4()))
email = db.Column(db.String(255), nullable=False)
access_token = db.Column(db.String(255), nullable=False)
refresh_token = db.Column(db.String(255), nullable=False)
expiration_seconds = db.Column(db.Integer, nullable=False)
is_logged_in = db.Column(db.Boolean, default=True)
readwise_api_key = db.Column(db.String(255))
active = db.Column(db.Boolean, default=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
@ -26,46 +29,51 @@ with app.app_context():
@app.route('/token', methods=['POST'])
def create_token():
data = request.get_json()
email = data.get('email')
access_token = data.get('access_token')
refresh_token = data.get('refresh_token')
expiration_seconds = data.get('expiration_seconds')
if not access_token or not refresh_token or not expiration_seconds:
if not email or access_token or not refresh_token or not expiration_seconds:
return 'Missing required fields', 400
new_token = Token(access_token=access_token, refresh_token=refresh_token, expiration_seconds=expiration_seconds)
# unique email when active is true
existing_token = Token.query.filter_by(email=email, active=True).first()
if existing_token:
return jsonify({'error': 'An active token with this email already exists'}), 400
new_token = Token(email=email, access_token=access_token, refresh_token=refresh_token, expiration_seconds=expiration_seconds)
db.session.add(new_token)
db.session.commit()
return ('', 204)
return jsonify({'id': new_token.id}), 201
# API to get the latest token entry
@app.route('/token/latest', methods=['GET'])
def get_latest_token():
latest_token = Token.query.order_by(Token.timestamp.desc()).first()
if latest_token:
token_info = {
'id': latest_token.id,
'access_token': latest_token.access_token,
'refresh_token': latest_token.refresh_token,
'expiration_seconds': latest_token.expiration_seconds,
'is_logged_in': latest_token.is_logged_in,
'timestamp': int(latest_token.timestamp.timestamp())
}
return jsonify({'token': token_info}), 200
else:
return '', 204
# API to get the token based on the id
@app.route('/token/<id>', methods=['GET'])
def get_token_by_id(id):
token = Token.query.get_or_404(id)
token_info = {
'id': token.id,
'email': token.email,
'access_token': token.access_token,
'refresh_token': token.refresh_token,
'expiration_seconds': token.expiration_seconds,
'readwise_api_key': token.readwise_api_key,
'active': token.active,
'timestamp': int(token.timestamp.timestamp())
}
return jsonify({'token': token_info}), 200
# API to update the token based on the id
@app.route('/token/<id>', methods=['PUT'])
def update_token(id):
def update_token_by_id(id):
token = Token.query.get_or_404(id)
data = request.get_json()
token.access_token = data.get('access_token') or token.access_token
token.refresh_token = data.get('refresh_token') or token.refresh_token
token.expiration_seconds = data.get('expiration_seconds') or token.expiration_seconds
token.is_logged_in = data.get('is_logged_in')
token.access_token = data.get('access_token', token.access_token)
token.refresh_token = data.get('refresh_token', token.refresh_token)
token.expiration_seconds = data.get('expiration_seconds', token.expiration_seconds)
token.active = data.get('active', token.active)
token.readwise_api_key = data.get('readwise_api_key', token.readwise_api_key)
db.session.commit()
return '', 204