from urllib.parse import urlparse from secrets import token_urlsafe from flask import Flask, render_template, url_for, redirect, request, make_response, session from authlib.integrations.flask_client import OAuth from requests import post app = Flask(__name__) SECRET_KEY = token_urlsafe(32) app.secret_key = SECRET_KEY cache = OAuthCache() oauth = OAuth(app) gotosocial = oauth.register( name='gotosocial', client_id='', client_secret='', access_token_url='/oauth/token', access_token_params={'response_type':'token', 'grant_type':'authorization_code', 'client_id':'', 'client_secret':''}, authorize_url='/oauth/authorize', authorize_params={'grant_type':'authorization_code'}, api_base_url='/api', client_kwargs={'scope': 'read'}, ) @app.route('/') def index(): return render_template('index.html') @app.route('/set_domain', methods=['POST']) def set_domain(): if(request.method == 'POST'): try: domain_parse = urlparse(request.form["domain"]) if(domain_parse): if(domain_parse.scheme): domain = domain.geturl() else: domain = f'https://{domain_parse.geturl()}' payload = { 'client_name':'gotosocial-fe', 'redirect_uris':url_for('index', _external=True) } response = post(f'{domain}/api/v1/apps', data=payload) client_data = response.json() oauth.gotosocial.client_id = client_data['client_id'] oauth.gotosocial.client_secret = client_data['client_secret'] oauth.gotosocial.access_token_params = { 'response_type':'token', 'grant_type':'authorization_code', 'client_id':client_data['client_id'], 'client_secret':client_data['client_secret'] } oauth.gotosocial.access_token_url = f'{domain}{oauth.gotosocial.access_token_url}' oauth.gotosocial.authorize_url = f'{domain}{oauth.gotosocial.authorize_url}' oauth.gotosocial.api_base_url = f'{domain}{oauth.gotosocial.api_base_url}' return redirect('/login') else: return "Did you even submit anything?" except: return "Are you sure you're putting in a GoToSocial instance url?" else: return "Sorry, but you can't get *GET* /set_domain, hun." @app.route('/login') def login(): redirect_uri = url_for('authorize', _external=True) return oauth.gotosocial.authorize_redirect(redirect_uri) @app.route('/authorize') def authorize(): token = oauth.gotosocial.authorize_access_token() session['oauth_token'] = token response = oauth.gotosocial.get( 'api/v1/accounts/verify_credentials') response.raise_for_status() return redirect(url_for('home', _external=True)) @app.route('/home') def home(): # If we're here, assume that we already authenticated for now. token = session['oauth_token'] # TODO: Long-term shoukd make sure we store the token in localStorage and try to retrieve it there first. response = oauth.gotosocial.get( 'api/v1/timelines/home', token=token) response.raise_for_status() home_timeline = response.json() return home_timeline # render_template('index.html')