Skip to content

Commit

Permalink
Fixed authorization for DB admin and templates
Browse files Browse the repository at this point in the history
  • Loading branch information
minimalparts committed Feb 2, 2024
1 parent 9b88be6 commit ea4d2b6
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 20 deletions.
31 changes: 26 additions & 5 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
from decouple import Config, RepositoryEnv

# Import flask and template operators
from flask import Flask, render_template
from flask_admin import Admin
from flask import Flask, render_template, request
from flask_admin import Admin, AdminIndexView

# Import SQLAlchemy
from flask_sqlalchemy import SQLAlchemy
Expand Down Expand Up @@ -78,24 +78,24 @@ def configure_logging():


# Import a module / component using its blueprint handler variable (mod_auth)
from app.auth.controllers import auth as auth_module
from app.indexer.controllers import indexer as indexer_module
from app.api.controllers import api as api_module
from app.search.controllers import search as search_module
from app.pod_finder.controllers import pod_finder as pod_finder_module
from app.orchard.controllers import orchard as orchard_module
from app.pages.controllers import pages as pages_module
from app.settings.controllers import settings as settings_module
from app.auth.controllers import auth as auth_module

# Register blueprint(s)
app.register_blueprint(auth_module)
app.register_blueprint(indexer_module)
app.register_blueprint(api_module)
app.register_blueprint(search_module)
app.register_blueprint(pod_finder_module)
app.register_blueprint(orchard_module)
app.register_blueprint(pages_module)
app.register_blueprint(settings_module)
app.register_blueprint(auth_module)
# ..

# Build the database:
Expand All @@ -112,9 +112,30 @@ def configure_logging():
from flask_admin.contrib.sqla.view import ModelView
from flask_admin.model.template import EndpointLinkRowAction

from app.auth.controllers import login_required
import requests

# Flask and Flask-SQLAlchemy initialization here

admin = Admin(app, name='PeARS DB', template_mode='bootstrap3')
class MyAdminIndexView(AdminIndexView):
def is_accessible(self):
access_token = request.headers.get('Token')
if not access_token:
access_token = request.cookies.get('OMD_SESSION_ID')
if not access_token:
return False
if LOCAL_RUN:
url = 'http://localhost:9191/api' #Local test
else:
url = ' https://demo.onmydisk.net/signin/'
data = {'action': 'getUserInfo', 'session_id': access_token}
resp = requests.post(url, json=data, headers={'accept':'application/json', 'Authorization': 'token:'+access_token})
if resp.status_code == requests.codes.ok:
is_admin = resp.json()['isAdmin']
return is_admin # This does the trick rendering the view only if the user is admin


admin = Admin(app, name='PeARS DB', template_mode='bootstrap3', index_view=MyAdminIndexView())

class UrlsModelView(ModelView):
list_template = 'admin/pears_list.html'
Expand Down
7 changes: 6 additions & 1 deletion app/api/controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from app.utils_db import pod_from_file, delete_url
from app.api.models import Urls, Pods
from app import db

from app.auth.controllers import login_required

# Define the blueprint:
api = Blueprint('api', __name__, url_prefix='/api')
Expand All @@ -21,23 +21,27 @@


@api.route('/pods/')
@login_required
def return_pods():
return jsonify(json_list=[p.serialize for p in Pods.query.all()])


@api.route('/pods/<pod>/')
@login_required
def return_pod(pod):
pod = pod.replace('+', ' ')
p = db.session.query(Pods).filter_by(name=pod).first()
return jsonify(p.serialize)


@api.route('/urls/')
@login_required
def return_urls():
return jsonify(json_list=[i.serialize for i in Urls.query.all()])


@api.route('/urls/delete', methods=["GET","POST"])
@login_required
def return_delete(idx=None):
if idx is None:
path = request.args.get('path')
Expand All @@ -57,6 +61,7 @@ def return_delete(idx=None):


@api.route('/urls/move', methods=["GET","POST"])
@login_required
def return_rename():
src = request.args.get('src')
target = request.args.get('target')
Expand Down
26 changes: 21 additions & 5 deletions app/auth/controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,16 @@

# Import flask dependencies
from flask import Blueprint, request, render_template, send_from_directory, make_response
from flask import current_app
from flask import current_app, session
from flask_cors import cross_origin
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from functools import wraps
from inspect import getfullargspec

# Import the database object from the main app module
from app import app

# Import matrix manipulation modules
import numpy as np
from scipy import sparse

# Import utilities
import re
import requests
Expand Down Expand Up @@ -60,6 +58,7 @@ def login():
print(user_info.cookies)
username = user_info.json()['username']
# Create a new response object
session['logged_in'] = True
resp_frontend = make_response(render_template( 'search/user.html', welcome="Welcome "+username))
# Transfer the cookies from backend response to frontend response
for name, value in user_info.cookies.items():
Expand All @@ -86,6 +85,23 @@ def logout():
else:
print("Logged out")
# Create a new response object
session['logged_in'] = False
resp_frontend = make_response(render_template( 'search/anonymous.html'))
resp_frontend.set_cookie('OMD_SESSION_ID', '', expires=0, samesite='Lax')
return resp_frontend


def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
access_token = request.headers.get('Token')
if not access_token:
access_token = request.cookies.get('OMD_SESSION_ID')
if not access_token:
session['logged_in'] = False
return render_template('search/anonymous.html')
if 'access_token' in getfullargspec(f).args:
kwargs['access_token'] = access_token
return f(*args, **kwargs)
return decorated_function

5 changes: 5 additions & 0 deletions app/indexer/controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from app.utils_db import pod_from_file
from app.indexer.htmlparser import extract_links, extract_html
from app.indexer.posix import posix_doc
from app.auth.controllers import login_required
from os.path import dirname, join, realpath, isfile

dir_path = dirname(dirname(realpath(__file__)))
Expand All @@ -33,6 +34,7 @@

# Set the route and accepted methods
@indexer.route("/", methods=["GET", "POST"])
@login_required
def index():
num_db_entries = len(Urls.query.all())
if request.method == "GET":
Expand All @@ -46,6 +48,7 @@ def index():
'''

@indexer.route("/from_crawl", methods=["GET","POST"])
@login_required
def from_crawl():
keyword = "home" #hard-coded
lang = LANG
Expand All @@ -69,6 +72,7 @@ def process_start_url(u):


@indexer.route("/from_docs", methods=["POST"])
@login_required
def from_docs():
print("DOC FILE:", request.files['file_source'])
if request.files['file_source'].filename[-4:] == ".txt":
Expand All @@ -92,6 +96,7 @@ def from_docs():
'''

@indexer.route("/progress_crawl")
@login_required
def progress_crawl():
print("Running progress crawl")
urls, keywords, langs, errors = readUrls(join(dir_path, "urls_to_index.txt"))
Expand Down
10 changes: 3 additions & 7 deletions app/search/controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from app import app
from app.api.models import Urls
from app.search import score_pages
from app.auth.controllers import login_required

# Import matrix manipulation modules
import numpy as np
Expand All @@ -36,13 +37,8 @@

@search.route('/user', methods=['POST','GET'])
@cross_origin()
def user():
access_token = request.headers.get('Token')
if not access_token:
access_token = request.cookies.get('OMD_SESSION_ID')
LOG.info(access_token)
if not access_token:
return render_template('search/anonymous.html')
@login_required
def user(access_token):
if LOCAL_RUN:
url = 'http://localhost:9191/api' #Local test
else:
Expand Down
2 changes: 2 additions & 0 deletions app/templates/base/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@
<hr class="d-lg-none text-white-50">
</li>
<li class="nav-item"><a class="nav-link" href="{{url_for('search.index')}}">Search</a></li>
{% if session.logged_in %}
<li class="nav-item"><a class="nav-link" href="{{url_for('indexer.index')}}">Indexer</a></li>
<li class="nav-item"><a class="nav-link" href="{{url_for('admin.index')}}">DB admin</a></li>
{% endif %}
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="nav-item"><a class="nav-link" href="{{url_for('settings.index')}}">Settings</a></li>
Expand Down
4 changes: 2 additions & 2 deletions test-auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ def auth():
def api():
def getuserinfo():
print("Running getuserinfo")
info = {'username':'tester', 'displayname':'tester', 'profileimage':'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P48/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', 'email':'[email protected]', 'valid':'true'}
info = {'username':'tester', 'displayname':'tester', 'profileimage':'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P48/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', 'email':'[email protected]', 'valid':True, 'isAdmin':False}
r = app.make_response(jsonify(info))
r.mimetype = "application/json"
return r

def signin():
print("Running signin")
info = {'username':'tester', 'displayname':'tester', 'profileimage':'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P48/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', 'email':'[email protected]', 'valid':'true'}
info = {'username':'tester', 'displayname':'tester', 'profileimage':'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P48/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', 'email':'[email protected]', 'valid':True, 'isAdmin':False}
r = app.make_response(jsonify(info))
return r

Expand Down

0 comments on commit ea4d2b6

Please sign in to comment.