forked from PeterSurda/inoreader2readwise
Compare commits
2 Commits
715cb7d046
...
a181602e85
Author | SHA1 | Date |
---|---|---|
Swapnil | a181602e85 | |
Swapnil | 6a4c3b23b9 |
77
app/main.py
77
app/main.py
|
@ -26,23 +26,28 @@ csrf_protection_string = None
|
||||||
@app.route('/')
|
@app.route('/')
|
||||||
def home():
|
def home():
|
||||||
if is_logged_in():
|
if is_logged_in():
|
||||||
resp_json = requests.get(f'{database_url}/token/latest').json()
|
token_id = session.get('token_id')
|
||||||
access_token = resp_json['token']['access_token']
|
resp = requests.get(f'{database_url}/token/{token_id}')
|
||||||
|
resp.raise_for_status()
|
||||||
# set session token id
|
resp_json = resp.json()
|
||||||
session['token_id'] = resp_json['token']['id']
|
token = resp_json['token']
|
||||||
|
|
||||||
user_info = requests.get('https://api.github.com/user', headers={
|
user_info = requests.get('https://api.github.com/user', headers={
|
||||||
'Authorization': f'Bearer {access_token}'
|
'Authorization': f'Bearer {token.get("access_token")}'
|
||||||
}).json()
|
}).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
|
# Generate a CSRF protection string
|
||||||
global csrf_protection_string
|
global csrf_protection_string
|
||||||
csrf_protection_string = os.urandom(16).hex()
|
csrf_protection_string = os.urandom(16).hex()
|
||||||
|
|
||||||
# Pass dynamic variables to the template
|
# 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)
|
optional_scopes=optional_scopes, csrf_protection_string=csrf_protection_string)
|
||||||
|
|
||||||
@app.route('/oauth-redirect')
|
@app.route('/oauth-redirect')
|
||||||
|
@ -86,15 +91,21 @@ def oauth_redirect():
|
||||||
|
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|
||||||
tokens = response.json()
|
token = response.json()
|
||||||
|
|
||||||
# TEST: Github OAuth - REMOVE
|
# TEST: Github OAuth - REMOVE
|
||||||
tokens['refresh_token'] = 'N/A'
|
token['refresh_token'] = 'N/A'
|
||||||
tokens['expires_in'] = 36000
|
token['expires_in'] = 3600
|
||||||
|
|
||||||
# Save tokens for later use
|
# 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'))
|
return redirect(url_for('home'))
|
||||||
|
|
||||||
# logout
|
# logout
|
||||||
|
@ -108,32 +119,51 @@ def logout():
|
||||||
# remove token_id from session
|
# remove token_id from session
|
||||||
session.pop('token_id', None)
|
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={
|
response = requests.put(f'{database_url}/token/{token_id}', headers={
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
}, json={
|
}, json={
|
||||||
'is_logged_in': False
|
'readwise_api_key': request.form.get('readwise_api_key')
|
||||||
})
|
})
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|
||||||
return redirect(url_for('home'))
|
return redirect(url_for('home'))
|
||||||
|
|
||||||
def is_logged_in():
|
def is_logged_in():
|
||||||
response = requests.get(f'{database_url}/token/latest')
|
token_id = session.get('token_id')
|
||||||
response.raise_for_status()
|
if not token_id:
|
||||||
if response.status_code == 204:
|
|
||||||
return False
|
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(
|
response = requests.post(
|
||||||
f'{database_url}/token',
|
f'{database_url}/token',
|
||||||
headers={
|
headers={
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
json={
|
json={
|
||||||
|
'email': email,
|
||||||
'access_token': access_token,
|
'access_token': access_token,
|
||||||
'refresh_token': refresh_token,
|
'refresh_token': refresh_token,
|
||||||
'expiration_seconds': expiration_seconds
|
'expiration_seconds': expiration_seconds
|
||||||
|
@ -141,5 +171,10 @@ def save_tokens(access_token, refresh_token, expiration_seconds):
|
||||||
)
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
|
|
||||||
|
return response.json().get('id')
|
||||||
|
|
||||||
|
def set_session_token_id(token_id):
|
||||||
|
session['token_id'] = token_id
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
app.run(host='0.0.0.0', debug=True, port=5000)
|
app.run(host='0.0.0.0', debug=True, port=5000)
|
|
@ -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>
|
|
@ -3,10 +3,10 @@
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
<title>Simple Frontend</title>
|
<title>Inoreader To Readwise</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<button onclick="redirectToOAuth()">Click Me</button>
|
<button onclick="redirectToOAuth()">Login using inoreader</button>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
function redirectToOAuth() {
|
function redirectToOAuth() {
|
|
@ -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>
|
|
|
@ -1,6 +1,7 @@
|
||||||
from flask import Flask, jsonify, request
|
from flask import Flask, jsonify, request
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
import uuid
|
||||||
|
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tokens.db' # Use SQLite for simplicity
|
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)
|
db = SQLAlchemy(app)
|
||||||
|
|
||||||
class Token(db.Model):
|
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)
|
access_token = db.Column(db.String(255), nullable=False)
|
||||||
refresh_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)
|
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)
|
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
|
@ -26,46 +29,51 @@ with app.app_context():
|
||||||
@app.route('/token', methods=['POST'])
|
@app.route('/token', methods=['POST'])
|
||||||
def create_token():
|
def create_token():
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
|
email = data.get('email')
|
||||||
access_token = data.get('access_token')
|
access_token = data.get('access_token')
|
||||||
refresh_token = data.get('refresh_token')
|
refresh_token = data.get('refresh_token')
|
||||||
expiration_seconds = data.get('expiration_seconds')
|
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
|
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.add(new_token)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
return ('', 204)
|
return jsonify({'id': new_token.id}), 201
|
||||||
|
|
||||||
# API to get the latest token entry
|
# API to get the token based on the id
|
||||||
@app.route('/token/latest', methods=['GET'])
|
@app.route('/token/<id>', methods=['GET'])
|
||||||
def get_latest_token():
|
def get_token_by_id(id):
|
||||||
latest_token = Token.query.order_by(Token.timestamp.desc()).first()
|
token = Token.query.get_or_404(id)
|
||||||
|
token_info = {
|
||||||
if latest_token:
|
'id': token.id,
|
||||||
token_info = {
|
'email': token.email,
|
||||||
'id': latest_token.id,
|
'access_token': token.access_token,
|
||||||
'access_token': latest_token.access_token,
|
'refresh_token': token.refresh_token,
|
||||||
'refresh_token': latest_token.refresh_token,
|
'expiration_seconds': token.expiration_seconds,
|
||||||
'expiration_seconds': latest_token.expiration_seconds,
|
'readwise_api_key': token.readwise_api_key,
|
||||||
'is_logged_in': latest_token.is_logged_in,
|
'active': token.active,
|
||||||
'timestamp': int(latest_token.timestamp.timestamp())
|
'timestamp': int(token.timestamp.timestamp())
|
||||||
}
|
}
|
||||||
return jsonify({'token': token_info}), 200
|
return jsonify({'token': token_info}), 200
|
||||||
else:
|
|
||||||
return '', 204
|
|
||||||
|
|
||||||
# API to update the token based on the id
|
# API to update the token based on the id
|
||||||
@app.route('/token/<id>', methods=['PUT'])
|
@app.route('/token/<id>', methods=['PUT'])
|
||||||
def update_token(id):
|
def update_token_by_id(id):
|
||||||
token = Token.query.get_or_404(id)
|
token = Token.query.get_or_404(id)
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
token.access_token = data.get('access_token') or token.access_token
|
token.access_token = data.get('access_token', token.access_token)
|
||||||
token.refresh_token = data.get('refresh_token') or token.refresh_token
|
token.refresh_token = data.get('refresh_token', token.refresh_token)
|
||||||
token.expiration_seconds = data.get('expiration_seconds') or token.expiration_seconds
|
token.expiration_seconds = data.get('expiration_seconds', token.expiration_seconds)
|
||||||
token.is_logged_in = data.get('is_logged_in')
|
token.active = data.get('active', token.active)
|
||||||
|
token.readwise_api_key = data.get('readwise_api_key', token.readwise_api_key)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return '', 204
|
return '', 204
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue