Skip to content

Commit

Permalink
Defensible implementation of Onboarding Activity # TODO: Bug fix and …
Browse files Browse the repository at this point in the history
…Unit Tests
  • Loading branch information
rpaw053 committed Mar 13, 2017
1 parent 17feca3 commit 6117c82
Show file tree
Hide file tree
Showing 6 changed files with 114 additions and 35 deletions.
95 changes: 62 additions & 33 deletions orcidhub-core/authcontroller.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from application import mail
from tokenGeneration import generate_confirmation_token, confirm_token
from application import login_manager
from registrationForm import OrgConfirmationForm


@app.route("/")
Expand All @@ -33,16 +34,18 @@ def login():
session['given_names'] = request.headers['Givenname']
session['email'] = request.headers['Mail']
orcidUser = OrcidUser.query.filter_by(email=session['email']).first()
tuakiri_orgName = request.headers['O']
# import pdb;pdb.set_trace()

registerOptions = {}
if (not (orcidUser is None) and (orcidUser.confirmed)):
login_user(orcidUser)
registerOptions = {}
if current_user.get_urole() == UserRole.ADMIN:
registerOptions['Register Researcher'] = "/Tuakiri/register/researcher"
elif current_user.get_urole() == UserRole.SUPERUSER:
registerOptions['Register Researcher'] = "/Tuakiri/register/researcher"
registerOptions['Register Organisation'] = "/Tuakiri/register/organisation"
else:
registerOptions['View Work'] = "/Tuakiri/redirect"

if token:
# This is a unique id got from Tuakiri SAML used as identity in database
Expand All @@ -51,7 +54,23 @@ def login():
organisationName=request.headers['O'], registerOptions=registerOptions)
else:
return render_template("base.html")
elif (orcidUser is None):
# Check if the organization to which user belong is onboarded, if yes onboard user automatically
organisation = Organisation.query.filter_by(tuakiriname=tuakiri_orgName).first()
if (organisation is not None) and (organisation.confirmed):
orcidUser = OrcidUser(rname=session['given_names'], email=session['email'], urole=UserRole.RESEARCHER,
confirmed=True, orgid=organisation.emailid, auedupersonsharedtoken=token)
db.session.add(orcidUser)
db.session.commit()
login_user(orcidUser)
registerOptions['View Work'] = "/Tuakiri/redirect"
return render_template("base.html", userName=request.headers['Displayname'],
organisationName=request.headers['O'], registerOptions=registerOptions)
else:
flash("Organisation not onboarded", 'warning')
return redirect(url_for("index"))
else:
# return render_template("login.html")
return redirect(url_for("index"))


Expand All @@ -66,20 +85,22 @@ def demo():
authorization_url, state = client.authorization_url(authorization_base_url)
session['oauth_state'] = state
auedupersonsharedtoken = session.get("Auedupersonsharedtoken")
userPresent = False
# userPresent = False
# Check if user details are already in database
if auedupersonsharedtoken:
data = Researcher.query.filter_by(auedupersonsharedtoken=auedupersonsharedtoken).first()
if auedupersonsharedtoken and current_user.is_active():
# data = Researcher.query.filter_by(auedupersonsharedtoken=auedupersonsharedtoken).first()
data = OrcidUser.query.filter_by(auedupersonsharedtoken=auedupersonsharedtoken,
email=current_user.email).first()
if None is not data:
userPresent = True
# If user details are already there in database redirect to profile instead of orcid
if userPresent:
flash("Your account is already linked to ORCiD", 'warning')
return redirect(url_for('profile'))
else:
return redirect(
iri_to_uri(authorization_url) + "&family_names=" + session['family_names'] + "&given_names=" + session[
'given_names'] + "&email=" + session['email'])
# If user details are already there in database redirect to profile instead of orcid
if (data.auth_token is not None) and (data.orcidid is not None):
flash("Your account is already linked to ORCiD", 'warning')
return redirect(url_for('.profile'))
else:
return redirect(
iri_to_uri(authorization_url) + "&family_names=" + session['family_names'] + "&given_names=" +
session[
'given_names'] + "&email=" + session['email'])


# Step 2: User authorization, this happens on the provider.
Expand Down Expand Up @@ -115,22 +136,21 @@ def profile():
orcid = ""
auedupersonsharedtoken = session['Auedupersonsharedtoken']

if auedupersonsharedtoken is not None:
data = Researcher.query.filter_by(auedupersonsharedtoken=auedupersonsharedtoken).first()
if None is not data:
name = data.rname
oauth_token = data.auth_token
orcid = data.orcidid
else:
# if auedupersonsharedtoken is not None:
data = OrcidUser.query.filter_by(email=session['email']).first()
if data is not None:
# data = Researcher.query.filter_by(auedupersonsharedtoken=auedupersonsharedtoken).first()
name = data.rname
oauth_token = data.auth_token
orcid = data.orcidid
if oauth_token is None:
orcid = session['oauth_token']['orcid']
name = session['oauth_token']['name']
researcher = Researcher(rname=session['oauth_token']['name'],
orcidid=session['oauth_token']['orcid'],
auth_token=session['oauth_token']['access_token'],
auedupersonsharedtoken=session['Auedupersonsharedtoken'])
oauth_token = session['oauth_token']['access_token']
db.session.add(researcher)
data.orcidid = orcid
data.auth_token = oauth_token
db.session.commit()
else:
login_manager.unauthorized()
client = OAuth2Session(client_id, token={'access_token': oauth_token})
headers = {'Accept': 'application/json'}
resp = client.get("https://api.sandbox.orcid.org/v1.2/" +
Expand Down Expand Up @@ -182,8 +202,13 @@ def registerResearcher():
@app.route("/Tuakiri/confirm/<token>", methods=["GET", "POST"])
def confirmUser(token):
email = confirm_token(token)
# For now only GET method is implemented
if request.method == 'GET':
form = OrgConfirmationForm()
# For now only GET method is implemented will need post method for organisation
# to enter client secret and client key for orcid
if request.method == 'POST':
if form.validate() is False:
return 'Please fill in all fields <p><a href="/Tuakiri/register/organisation">Try Again!!!</a></p>'

if email is False:
login_manager.unauthorized()
tuakiri_token = request.headers.get("Auedupersonsharedtoken")
Expand All @@ -196,13 +221,13 @@ def confirmUser(token):
# Update Organisation
organisation.tuakiriname = tuakiri_orgName
organisation.confirmed = True
organisation.orcid_client_id = "Test"
organisation.orcid_secret = "Test sec"
organisation.orcid_client_id = form.orgOricdClientId.data
organisation.orcid_secret = form.orgOrcidClientSecret.data

# Update Orcid User
orcidUser.confirmed = True
orcidUser.auedupersonsharedtoken = tuakiri_token
db.commit()
db.session.commit()
with app.app_context():
msg = Message("Welcome to OrcidhHub",
recipients=[email])
Expand All @@ -215,7 +240,11 @@ def confirmUser(token):
else:
login_manager.unauthorized()
elif request.method == 'GET':
return "Form"
if email is False:
login_manager.unauthorized()
form.orgEmailid.data = email
form.orgName.data = request.headers['O']
return render_template('orgconfirmation.html', form=form)


@app.after_request
Expand Down
12 changes: 12 additions & 0 deletions orcidhub-core/initializedb.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
from application import db
from model import Organisation, OrcidUser, UserRole
db.drop_all()
db.create_all()

addOrganisation = Organisation(org_name="The Royal Society of NewZealand", emailid="nzorcidhub@royalsociety.org.nz", tuakiriname="The Royal Society of NewZealand",
orcid_client_id="client-123", orcid_secret="secret-123", confirmed=True)
superUser = OrcidUser(rname="The Royal Society of NewZealand", email="nzorcidhub@royalsociety.org.nz", orcidid="test123", auth_token="test123",
auedupersonsharedtoken="test-123", confirmed=True,
urole=UserRole.SUPERUSER, orgid="nzorcidhub@royalsociety.org.nz")

db.session.add(addOrganisation)
db.session.commit()
db.session.add(superUser)
db.session.commit()
7 changes: 7 additions & 0 deletions orcidhub-core/registrationForm.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,10 @@ class OrgRegistrationForm(FlaskForm):
orgName = StringField('Organisation Name: ', validators=[DataRequired()])
orgEmailid = EmailField('Organisation EmailId: ',
validators=[DataRequired(), Email()])
class OrgConfirmationForm(FlaskForm):
orgName = StringField('Organisation Name: ', validators=[DataRequired()])
orgEmailid = EmailField('Organisation EmailId: ',
validators=[DataRequired(), Email()])
orgOricdClientId = StringField('Organisation Orcid Client Id: ', validators=[DataRequired()])
orgOrcidClientSecret = StringField('Organisation Orcid Client Secret: ',
validators=[DataRequired()])
2 changes: 1 addition & 1 deletion orcidhub-core/templates/confirmation.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{% extends "base.html" %}

{% block content %}
<h1>Sign In</h1>
<h1>Please fill up below Data</h1>
<form action="" method="post" name="login">
{{ form.hidden_tag() }}

Expand Down
15 changes: 15 additions & 0 deletions orcidhub-core/templates/orgconfirmation.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{% extends "base.html" %}

{% block content %}
<h1>Organisation Confirmation Form</h1>
<form action="" method="post" name="confirm">
{{ form.hidden_tag() }}

<p>Organisation Name:{{ form.orgName(size=50) }}</p><br>
<p>Organisation Email:{{ form.orgEmailid(size=50) }}</p><br>
<p>Enter Organisation Orcid Client ID:{{ form.orgOricdClientId(size=50) }}</p><br>
<p>Enter Organisation Orcid Client Secret:{{ form.orgOrcidClientSecret(size=50) }}</p><br>

<p><input type="submit" value="Confirm"></p>
</form>
{% endblock %}
18 changes: 17 additions & 1 deletion orcidhub-core/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from application import app
from config import client_id, client_secret, authorization_base_url, \
token_url, scope, redirect_uri
# from application import db
import unittest

Expand Down Expand Up @@ -31,6 +33,7 @@ def test_index(self):
assert b"Royal Society of New Zealand" in rv.data, \
"'Royal Society of New Zealand' should be present on the index page."

"""
def test_ValidLogin(self):
with self.app.session_transaction() as sess:
sess['Auedupersonsharedtoken'] = "abc"
Expand All @@ -51,7 +54,20 @@ def test_InvalidLogin(self):
assert b"<!DOCTYPE html>" in resp.data
assert b"Home" in resp.data
assert b"Royal Society of New Zealand" in resp.data, \
"'Royal Society of New Zealand' should be present on the index page."
"'Royal Society of New Zealand' should be present on the index page. """

def test_demo(self):
with self.app.session_transaction() as sess:
sess['Auedupersonsharedtoken'] = "abc"
sess['family_names'] = "paw"
sess['given_names'] = "ros"
sess['email'] = "get@orcidhub.org.nz"
sess['client_id'] = client_id
sess['scope'] = scope
sess['redirect_uri'] = redirect_uri
sess['authorization_base_url'] = authorization_base_url
resp = self.app.get('/Tuakiri/redirect')
#assertRedirects(resp,"url")

def test_auth(self):
pass
Expand Down

0 comments on commit 6117c82

Please sign in to comment.