Esempio n. 1
0
def username(username):
    acc = models.Account.pull(username)

    if acc is None:
        abort(404)
    elif ( request.method == 'DELETE' or 
            ( request.method == 'POST' and 
            request.values.get('submit',False) == 'Delete' ) ):
        if current_user.id != acc.id and not current_user.is_super:
            abort(401)
        else:
            acc.delete()
            flash('Account ' + acc.id + ' deleted')
            return redirect(url_for('.index'))
    elif request.method == 'POST':
        if current_user.id != acc.id and not current_user.is_super:
            abort(401)
        newdata = request.json if request.json else request.values
        if newdata.get('id',False):
            if newdata['id'] != username:
                acc = models.Account.pull(newdata['id'])
            else:
                newdata['api_key'] = acc.data['api_key']
        
        # attempt to do password updates first
        if 'password' in newdata and not newdata['password'].startswith('sha1'):
            if "confirm" in newdata and newdata.get("confirm") != newdata.get("password"):
                flash("Passwords do not match")
                return render_template("account/view.html", account=acc)
            acc.set_password(newdata['password'])
        
        # update everything else
        for k, v in newdata.items():
            if k not in ['submit','password','confirm']:
                acc.data[k] = v
        
        # save the record and return the new view
        acc.save()
        flash("Record updated")
        return render_template('account/view.html', account=acc)
    else:
        if util.request_wants_json():
            resp = make_response( 
                json.dumps(acc.data, sort_keys=True, indent=4) )
            resp.mimetype = "application/json"
            return resp
        else:
            return render_template('account/view.html', account=acc)
Esempio n. 2
0
def username(username):
    acc = models.Account.pull(username)

    if acc is None:
        abort(404)
    elif request.method == "DELETE" or (request.method == "POST" and request.values.get("submit", False) == "Delete"):
        if current_user.id != acc.id and not current_user.is_super:
            abort(401)
        else:
            acc.delete()
            flash("Account " + acc.id + " deleted")
            return redirect(url_for(".index"))
    elif request.method == "POST":
        if current_user.id != acc.id and not current_user.is_super:
            abort(401)
        newdata = request.json if request.json else request.values
        if newdata.get("id", False):
            if newdata["id"] != username:
                acc = models.Account.pull(newdata["id"])
            else:
                newdata["api_key"] = acc.data["api_key"]

        # attempt to do password updates first
        if "password" in newdata and not newdata["password"].startswith("sha1"):
            if "confirm" in newdata and newdata.get("confirm") != newdata.get("password"):
                flash("Passwords do not match")
                return render_template("account/view.html", account=acc)
            acc.set_password(newdata["password"])

        # update everything else
        for k, v in newdata.items():
            if k not in ["submit", "password", "confirm"]:
                acc.data[k] = v

        # save the record and return the new view
        acc.save()
        flash("Record updated")
        return render_template("account/view.html", account=acc)
    else:
        if util.request_wants_json():
            resp = make_response(json.dumps(acc.data, sort_keys=True, indent=4))
            resp.mimetype = "application/json"
            return resp
        else:
            return render_template("account/view.html", account=acc)
Esempio n. 3
0
def index():
    if current_user.is_anonymous():
        abort(401)
    users = models.Account.all() #{"sort":{'id':{'order':'asc'}}},size=1000000
    if len(users) > 0:
        accs = [models.Account.pull(i['_source']['id']) for i in users['hits']['hits']]
        # explicitly mapped to ensure no leakage of sensitive data. augment as necessary
        users = []
        for acc in accs:
            user = {'id':acc.id, "email" : acc.email}
            if 'created_date' in acc.data:
                user['created_date'] = acc.data['created_date']
            users.append(user)
    if util.request_wants_json():
        resp = make_response( json.dumps(users, sort_keys=True, indent=4) )
        resp.mimetype = "application/json"
        return resp
    else:
        return render_template('account/users.html', users=users)
Esempio n. 4
0
def api_lookup(path='',ids=[]):
    givejson = util.request_wants_json()
    path = path.replace('.json','')

    idlist = []
    if ids and isinstance(ids,basestring):
        idlist = [ {"id":i} for i in ids.split(',') ]
    elif ids:
        for i in ids:
            if isinstance(i,basestring):
                idlist.append({"id":i})
            else:
                idlist.append(i)
    elif request.json:
        for item in request.json:
            if isinstance(item,dict):
                idlist.append(item)
            else:
                idlist.append({"id":item})
    elif path and len(path) > 0:
        idlist = [ {"id":i} for i in path.split(',') ]

    if len(idlist) > 1000:
        abort(400)

    if idlist:
        results = workflow.lookup(idlist).json()
    else:
        results = json.dumps({})

    if request.method == 'GET' and not givejson:
        if path:
            triggered = idlist
        else:
            triggered = False
        return render_template('index.html', results=results, triggered=triggered)
    else:
        resp = make_response( results )
        resp.mimetype = "application/json"
        return resp
Esempio n. 5
0
def api_lookup(path='',ids=[]):
    givejson = util.request_wants_json()
    path = path.replace('.json','')
    idlimit = config.LOOKUP_LIMIT
    
    # have we been asked to prioritise?
    priority = bool(request.values.get("priority", False))
    if priority:
        idlimit = config.PRIORITY_LOOKUP_LIMIT
    
    idlist = []

    # look for JSON in the incoming request data
    if request.json:
        # the MIME type of the request is set properly - this is how it
        # should be
        request_json = request.json
    else:
        request_json = None

        # check if somebody just POST-ed without bothering to request
        # the right MIME type
        try:
            request_json = json.loads(request.data)
        except ValueError:
            pass

        # now check if the client mislabeled the request really badly,
        # i.e. saying it's HTML form data when it's actually JSON
        try:
            request_json = json.loads(str(request.form))
        except ValueError:
            pass

    if ids and isinstance(ids,basestring):
        idlist = [ {"id":i} for i in ids.split(',') ]
    elif ids:
        for i in ids:
            if isinstance(i,basestring):
                idlist.append({"id":i})
            else:
                idlist.append(i)
    elif request_json:
        for item in request_json:
            if isinstance(item,dict):
                idlist.append(item)
            else:
                idlist.append({"id":item})
    elif path and len(path) > 0:
        idlist = [ {"id":i} for i in path.split(',') ]

    log.debug('LOOKUP: About to do a request size test. Len of idlist: ' + str(len(idlist)))
    if len(idlist) > idlimit:
        abort(400)

    if idlist:
        results = workflow.lookup(idlist, priority).json()
    else:
        results = json.dumps({})

    if request.method == 'GET' and not givejson:
        if path:
            triggered = idlist
        else:
            triggered = False
        return render_template('index.html', results=results, triggered=triggered)
    else:
        resp = make_response( results )
        resp.mimetype = "application/json"
        return resp
Esempio n. 6
0
def issue(path=''):
    givejson = util.request_wants_json()
    path = path.replace('.json','')

    i = False
    
    if path:
        i = models.Issue.pull(path)

    if request.method == 'GET':
        if givejson:
            resp = make_response( i.data )
            resp.mimetype = "application/json"
            return resp
        else:
            return render_template('issue.html', issue=i)

    elif request.method == 'POST':
        if not i:
            i = models.Issue()

        if request.json:
            i.data = request.json
        elif request.values:
            i.data['about'] = request.values['about']
            i.data['issue'] = request.values['issue']
            i.data['email'] = request.values['email']
        else:
            abort(404)

        # only save an issue about an ID we actually have a record for
        if len(i.data['about']) < 9:
            cid = 'pmid:'
        else:
            cid = 'doi:'
        check = models.Record.pull(cid + i.data['about'].replace('/','_'))
        if check is not None:
            i.save()
        elif givejson:
            abort(404)
        else:
            flash("Sorry, your issue is about an identifier for which we do not hold a record.", 'error')
            return render_template('issue.html', issue=i)

        if app.config['CONTACT_EMAIL'] and not app.config['DEBUG']:
            text = 'Hey, an issue has been raised for ' + i.data['about'] + '\n\nView it at http://oag.cottagelabs.com/issue/' + i.id
            util.send_mail([app.config['CONTACT_EMAIL']], app.config['CONTACT_EMAIL'], "issue raised", text)

        if givejson:
            resp = make_response( i.data )
            resp.mimetype = "application/json"
            return resp
        else:
            flash("Thanks, your issue has been raised", 'success')
            return redirect('/issue/' + i.id)

    elif request.method == 'DELETE' and i:
        i.delete()
        return ""
    else:
        abort(404)