Esempio n. 1
0
 def __init__(self):
     self.__headers = {
         'User-Agent':
         'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36'
     }
     self.__urlString = Config.get_setting('GLOBAL', 'QRESP_SERVER_URL')
     self.__schemaString = Config.get_setting('GLOBAL', 'SCHEMA_URL')
     self.__httpUrlString = Config.get_setting('GLOBAL', 'HTTP_SERVER_URL')
Esempio n. 2
0
def publish():
    """
    Published the created metadata
    """
    form = PublishForm(request.form)
    serverslist = Servers()
    try:
        form.server.choices = [(qrespserver['qresp_server_url'],
                                qrespserver['qresp_server_url'])
                               for qrespserver in serverslist.getServersList()]
    except Exception as e:
        print(e)
        raise InvalidUsage('Could not fetch serverlist, \n ' + str(e),
                           status_code=410)
    if request.method == 'POST' and form.validate():
        fileServerPath = session.get(CURATOR_FIELD.PROJECT,
                                     {}).get("fileServerPath", "")
        serverpathList = fileServerPath.rsplit("/", 2)
        previewFolder = serverpathList[len(serverpathList) -
                                       2] + "_" + serverpathList[
                                           len(serverpathList) - 1]
        error = []
        try:
            with open("papers/" + previewFolder + "/data.json",
                      "r") as jsonData:
                error = serverslist.validateSchema(json.load(jsonData))
        except:
            error.append(
                "No server found. Place files in a publicly accessible server."
            )
        if len(error) > 0:
            return jsonify(error=error), 200
        else:
            session['publishserver'] = form.server.data
            session['emailAddress'] = form.emailId.data
            for item in serverslist.getServersList():
                if form.server.data in item['qresp_server_url']:
                    session['maintaineraddresses'] = item[
                        'qresp_maintainer_emails']
            googleauth = GoogleAuth(
                Config.get_setting(app.config['env'], 'GOOGLE_CLIENT_ID'),
                Config.get_setting(app.config['env'], 'REDIRECT_URI'),
                Config.get_setting('GOOGLE_API', 'SCOPE'))
            google = googleauth.getGoogleAuth()
            auth_url, state = google.authorization_url(Config.get_setting(
                'GOOGLE_API', 'AUTH_URI'),
                                                       access_type='offline')
            session['oauth_state'] = state
        return jsonify(data=auth_url), 200
    return jsonify(error=form.errors), 400
Esempio n. 3
0
def search():
    """
    This method helps in filtering paper content
    """

    try:
        selected_servers = urllib.parse.unquote(
            request.args.get('servers', type=str, default=''))
        fetchdata = FetchDataFromAPI(
            selected_servers,
            str(request.host_url).strip("/") if Config.get_setting(
                'DEV', 'MONGODB_HOST') else None)
        allpaperslist = fetchdata.fetchOutput('/api/search')
    except Exception as e:
        app.logger.error(e)
        return jsonify({"error": e}), 500

    try:
        collectionlist = fetchdata.fetchOutput('/api/collections')
        authorslist = fetchdata.fetchOutput('/api/authors')
        publicationlist = fetchdata.fetchOutput('/api/publications')
        allPapersSize = len(allpaperslist)
    except Exception as e:
        app.logger.error(e)
        return jsonify({"allpaperslist": allpaperslist, "error": str(e)}), 500
        # return render_template('search.html', allpaperslist=allpaperslist)

    return jsonify({
        "allpaperslist": allpaperslist,
        "collectionlist": collectionlist,
        "authorslist": authorslist,
        "publicationlist": publicationlist,
        "allPapersSize": allPapersSize,
        "error": None
    }), 200
Esempio n. 4
0
def searchWord():
    """
    Filtering paper content
    """
    allpaperslist = []
    try:
        searchWord = ""
        paperTitle = request.args.get('paperTitle', type=str)
        doi = request.args.get('doi', type=str)
        tags = json.loads(request.args.get('tags'))
        collectionList = json.loads(request.args.get('collectionList'))
        authorsList = json.loads(request.args.get('authorsList'))
        publicationList = json.loads(request.args.get('publicationList'))
        selected_servers = urllib.parse.unquote(
            request.args.get('servers', type=str, default=''))
        fetchdata = FetchDataFromAPI(
            selected_servers,
            str(request.host_url).strip("/") if Config.get_setting(
                app.config['env'], 'MONGODB_HOST') else None)
        url = '/api/search'+"?searchWord="+searchWord+"&paperTitle="+paperTitle+"&doi="+doi+"&tags="+",".join(tags)+"&collectionList="+",".join(collectionList) + \
              "&authorsList="+",".join(authorsList) + \
            "&publicationList="+",".join(publicationList)
        allpaperslist = fetchdata.fetchOutput(url)
        return jsonify(allpaperslist=allpaperslist), 200
    except Exception as e:
        print(e, file=sys.stderr)
        return jsonify(allpaperslist=allpaperslist), 400
Esempio n. 5
0
def verifypasscode():
    """
    This method verifies with input passcode of flask connection.
    """
    form = PassCodeForm(request.form)
    confirmpasscode = Config.get_setting(app.config['env'],
                                         'QRESP_DB_SECRET_KEY')
    if request.method == 'POST' and form.validate():
        if confirmpasscode == form.passcode.data:
            return jsonify(msg="success"), 200
    return jsonify(msg="failed"), 400
Esempio n. 6
0
def paperdetails(paperid):
    """
    Fetching papers details content
    """
    paperdetail = []
    workflowdetail = []
    try:
        selected_servers = urllib.parse.unquote(
            request.args.get('servers', type=str, default=''))
        fetchdata = FetchDataFromAPI(
            selected_servers,
            str(request.host_url).strip("/") if Config.get_setting(
                app.config['env'], 'MONGODB_HOST') else None)
        url = '/api/paper/' + paperid
        paperdetail = fetchdata.fetchOutput(url)
        url = '/api/workflow/' + paperid
        workflowdetail = fetchdata.fetchOutput(url)
        return jsonify(paperdetail=paperdetail,
                       workflowdetail=workflowdetail), 200
    except Exception as e:
        print(e, file=sys.stderr)
        return jsonify({'error': True}), 500
Esempio n. 7
0
def chartworkflow():
    """
    Fetching chart workflow content
    """
    chartworkflowdetail = []
    try:
        paperid = request.args.get('paperid', 0, type=str)
        paperid = str(paperid).strip()
        chartid = request.args.get('chartid', 0, type=str)
        chartid = str(chartid).strip()
        selected_servers = urllib.parse.unquote(
            request.args.get('servers', type=str, default=''))
        fetchdata = FetchDataFromAPI(
            selected_servers,
            str(request.host_url).strip("/") if Config.get_setting(
                app.config['env'], 'MONGODB_HOST') else None)
        url = '/api/paper/' + paperid + '/chart/' + chartid
        chartworkflowdetail = fetchdata.fetchOutput(url)
        return jsonify(chartworkflowdetail=chartworkflowdetail), 200
    except Exception as e:
        print(e)
        flash('Error in chartdetails. ' + str(e))
        return jsonify(chartworkflowdetail=chartworkflowdetail), 400
Esempio n. 8
0
from project.config import Config
from flask_mongoengine import MongoEngine
from flask_cors import CORS

Config.initialize()

# Create the application instance
connexionapp = connexion.FlaskApp(__name__)

# Read the swagger.yml file to configure the endpoints
swagger_file = (os.path.join(os.getcwd(), 'project/swagger.yml'))
connexionapp.add_api(swagger_file)
app = connexionapp.app

# Create protection and session variables
app.secret_key = Config.get_setting('SECRETS', 'FLASK_SECRET_KEY')
SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
app.config['env'] = 'DEV'
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
Session(app)
ext = Sitemap(app)
CORS(app)

#initialize db
if Config.get_setting(app.config['env'], 'MONGODB_HOST'):
    db = MongoEngine()
    app.config['MONGODB_HOST'] = Config.get_setting(app.config['env'],
                                                    'MONGODB_HOST')
    app.config['MONGODB_PORT'] = int(
        Config.get_setting(app.config['env'], 'MONGODB_PORT'))
Esempio n. 9
0
def authorized():
    """
    Callback for authorization
    """
    form = PublishForm()
    serverslist = Servers()
    form.server.choices = [(qrespserver['qresp_server_url'],
                            qrespserver['qresp_server_url'])
                           for qrespserver in serverslist.getServersList()]
    if 'error' in request.args:
        if request.args.get('error') == 'access_denied':
            print('denied access.')
        return redirect(url_for('qrespcurator'))
    if 'code' not in request.args and 'state' not in request.args:
        print('denied access.')
        return redirect(url_for('qrespcurator'))
    googleauth = GoogleAuth(
        Config.get_setting(app.config['env'], 'GOOGLE_CLIENT_ID'),
        Config.get_setting(app.config['env'], 'REDIRECT_URI'))
    google = googleauth.getGoogleAuth(state=session.get('oauth_state'))
    try:
        token = google.fetch_token(Config.get_setting('GOOGLE_API',
                                                      'TOKEN_URI'),
                                   client_secret=Config.get_setting(
                                       app.config['env'],
                                       'GOOGLE_CLIENT_SECRET'),
                                   authorization_response=request.url)
    except Exception as e:
        print(e)
        return 'HTTP Error occurred.'
    try:
        google = googleauth.getGoogleAuth(token=token)
        resp = google.get(Config.get_setting('GOOGLE_API', 'USER_INFO'))
        if resp.status_code == 200:
            user_data = resp.json()
            emailAddress = session.get('emailAddress')
            server = session.get("publishserver")
            if user_data['email'] in emailAddress:
                try:
                    fileServerPath = session.get(CURATOR_FIELD.PROJECT,
                                                 {}).get("fileServerPath", "")
                    serverpathList = fileServerPath.rsplit("/", 2)
                    previewFolder = serverpathList[len(serverpathList) -
                                                   2] + "_" + serverpathList[
                                                       len(serverpathList) - 1]
                    with open("papers/" + previewFolder + "/data.json",
                              "r") as jsonData:
                        senddescriptor = SendDescriptor(server)
                        jsondata = json.load(jsonData)
                        response = senddescriptor.sendDescriptorToServer(
                            jsondata)
                        if response.status_code == 400:
                            flash("Paper already exists")
                            return redirect(url_for('qrespcurator'))
                        else:
                            try:
                                paperdata = response.json()
                                maintaineraddresses = session.get(
                                    'maintaineraddresses')
                                body = 'The user ' + str(jsondata['info']['insertedBy']['firstName']) + ' with email address ' + \
                                    emailAddress + ' has inserted paper with paper id ' + \
                                    str(paperdata["paperid"])
                                fromx = Config.get_setting(
                                    'GLOBAL', 'MAIL_ADDR')
                                to = maintaineraddresses
                                msg = MIMEMultipart()
                                msg['Subject'] = 'New paper inserted into Qresp ecosystem'
                                msg['From'] = fromx
                                msg['To'] = ", ".join(to)
                                msg.attach(MIMEText(body, 'plain'))
                                mailserver = smtplib.SMTP(
                                    'smtp.gmail.com', 587)
                                mailserver.starttls()
                                mailserver.login(
                                    Config.get_setting('GLOBAL', 'MAIL_ADDR'),
                                    Config.get_setting('SECRETS', 'MAIL_PWD'))
                                mailserver.sendmail(fromx, to, msg.as_string())
                                mailserver.close()
                                return redirect(server + "/paperdetails/" +
                                                paperdata["paperid"])
                            except Exception as e:
                                print(traceback.format_exc())
                                flash('Could not email your administrator' +
                                      str(e))
                                flash('Published')
                                return redirect(url_for('qrespcurator'))
                except Exception as e:
                    print(e)
                    flash('No paper found')
                    return redirect(url_for('qrespcurator'))
            else:
                flash(
                    'Unauthorized access. Could not verify your email address')
                return redirect(url_for('qrespcurator'))
    except Exception as e:
        print(e)
        flash('Unauthorized access. Could not verify your email address')
        return redirect(url_for('qrespcurator'))
    flash('Published')
    return redirect(url_for('qrespcurator'))