Skip to content

Commit

Permalink
feat: add endpoint for retrieving the user detail based on token
Browse files Browse the repository at this point in the history
  • Loading branch information
gregmundy committed Oct 9, 2019
1 parent 0fa23c2 commit d804447
Show file tree
Hide file tree
Showing 13 changed files with 127 additions and 46 deletions.
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ marshmallow-sqlalchemy = "*"
bcrypt = "*"
flask-cors = "*"
webargs = "*"
flask-wtf = "*"

[requires]
python_version = "3.7"
17 changes: 16 additions & 1 deletion Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions authserver/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
from authserver.api.client import client_bp
from authserver.api.oauth2 import oauth2_bp
from authserver.api.role import role_bp
from authserver.api.home import home_bp
37 changes: 37 additions & 0 deletions authserver/api/home.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import json
import requests
from flask import Blueprint, render_template, request, redirect, url_for, session
from wtforms import Form, StringField, PasswordField, validators

from authserver.db import db, User, OAuth2Client

home_bp = Blueprint('home_ep', __name__, static_folder='static', template_folder='templates', url_prefix='/')


class LoginForm(Form):
username = StringField('Username', [validators.DataRequired(), validators.length(min=4, max=40)])
password = PasswordField('Password', [validators.DataRequired()])


@home_bp.route('/', methods=['GET', 'POST'])
def login():
form = LoginForm(request.form)
client_id = request.args.get('client_id')
return_to = request.args.get('return_to')
if request.method == 'GET':
if not client_id or not return_to:
return render_template('login.html', form=form)
else:
return render_template('login.html', client_id=client_id, return_to=return_to, form=form)
if form.validate():
username = form.username.data
password = form.password.data
user = User.query.filter_by(username=username).first()
if user and user.verify_password(password):
session['id'] = user.id
return redirect(return_to)
else:
if not client_id or not return_to:
return redirect(url_for('home_ep.login'))
else:
return redirect(url_for('home_ep.login', client_id=client_id, return_to=return_to))
38 changes: 1 addition & 37 deletions authserver/api/oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,28 +29,12 @@ def current_user():
return None


@oauth2_bp.route('/login', methods=['GET', 'POST'])
def login():
client_id = request.args.get('client_id')
return_to = request.args.get('return_to')
if request.method == 'GET':
return render_template('login.html', client_id=client_id, return_to=return_to)
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter_by(username=username).first()
if user and user.verify_password(password):
session['id'] = user.id
return redirect(return_to)
else:
return redirect(url_for('oauth2_ep.login', client_id=client_id, return_to=return_to))


@oauth2_bp.route('/authorize', methods=['GET', 'POST'])
def authorize():
user = current_user()
if not user:
client_id = request.args.get('client_id')
return redirect(url_for('oauth2_ep.login', client_id=client_id, return_to=request.url))
return redirect(url_for('home_ep.login', client_id=client_id, return_to=request.url))
if request.method == 'GET':
try:
grant = authorization.validate_consent_request(end_user=user)
Expand Down Expand Up @@ -91,26 +75,6 @@ def post(self):
return authorization.create_endpoint_response('revocation')


class RedirectResource(Resource):
"""A User Resource.
This resource defines an Auth Service user who may have zero or more OAuth 2.0 clients
associated with their accounts.
"""

def get(self):
try:
code = request.args.get('code')
except Exception:
code = None
if code:
# foo = requests.get('http://localhost:8000/oauth/token')
# print(foo.status_code)
return {'message': 'ok'}, 200


oauth2_api = Api(oauth2_bp)
oauth2_api.add_resource(CreateOAuth2TokenResource, '/token')
oauth2_api.add_resource(RevokeOAuth2TokenResource, '/revoke')
oauth2_api.add_resource(RedirectResource, '/redirect')
8 changes: 8 additions & 0 deletions authserver/api/static/css/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
body {
background-color:#333333;
font-family: 'Raleway', sans-serif;
}

label {
color: #ffffff;
}
Binary file added authserver/api/static/images/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added authserver/api/static/images/logo_small.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
20 changes: 20 additions & 0 deletions authserver/api/templates/_formhelpers.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{% macro render_field(field) %}
<div class="form-row">
<div class="row">
<div class="col">
<label for="{{ field.name }}">{{ field.label }}</label>
</div>
<div class="col">
{{ field(**kwargs)|safe }}
</div>
</div>
</div>
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</dd>
{% endmacro %}
9 changes: 4 additions & 5 deletions authserver/api/templates/login.html
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
{% extends 'base.html' %}
{% block content %}
<form action="" method="post">
{% from "_formhelpers.html" import render_field %}
<form method="post">
<div>
<label for="username">Username</label>
<input type="text" name="username" id="username">
{{ render_field(form.username) }}
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password">
{{ render_field(form.password) }}
</div>
<br>
<button>Sign In</button>
Expand Down
38 changes: 37 additions & 1 deletion authserver/api/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from webargs import fields, validate
from webargs.flaskparser import use_args, use_kwargs

from authserver.db import DataTrust, DataTrustSchema, User, UserSchema, db, OAuth2Client
from authserver.db import DataTrust, DataTrustSchema, User, UserSchema, db, OAuth2Client, OAuth2Token
from authserver.utilities import ResponseBody, require_oauth

POST_ARGS = {
Expand All @@ -23,6 +23,41 @@
}


class UserDetailResource(Resource):
"""Details of the currently logged in user."""

@require_oauth()
def get(self):
try:
token = request.headers.get('authorization').split(' ')[1]
except Exception:
token = None

if token:
token_details = OAuth2Token.query.filter_by(access_token=token).first()
if token_details:
user_id = token_details.user_id
user = User.query.filter_by(id=user_id).first()
return {
'id': user.id,
'username': user.username,
'firstname': user.firstname,
'lastname': user.lastname,
'organization': user.organization,
'email_address': user.email_address,
'telephone': user.telephone,
'active': user.active,
'data_trust_id': user.data_trust_id,
'date_created': str(user.date_created),
'date_last_updated': str(user.date_last_updated)
}

return {
'firstname': 'Unknown',
'lastname': 'Unknown'
}


class UserResource(Resource):
"""A User Resource.
Expand Down Expand Up @@ -177,3 +212,4 @@ def _db_commit(self):
user_bp = Blueprint('user_ep', __name__)
user_api = Api(user_bp)
user_api.add_resource(UserResource, '/users', '/users/<string:id>')
user_api.add_resource(UserDetailResource, '/user')
3 changes: 2 additions & 1 deletion authserver/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from flask_sqlalchemy import SQLAlchemy

from authserver.api import (client_bp, data_trust_bp, health_api_bp, oauth2_bp,
role_bp, user_bp)
role_bp, user_bp, home_bp)
from authserver.config import ConfigurationFactory
from authserver.db import db
from authserver.utilities import config_oauth
Expand Down Expand Up @@ -41,6 +41,7 @@ def create_app(environment: str = None):
config_oauth(app)
CORS(app)
migrate = Migrate(app, db)
app.register_blueprint(home_bp)
app.register_blueprint(health_api_bp)
app.register_blueprint(data_trust_bp)
app.register_blueprint(user_bp)
Expand Down
1 change: 0 additions & 1 deletion authserver/db/models/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ def password(self, password: str):

def verify_password(self, password: str):
try:
print(self.password_hash.encode())
return bcrypt.checkpw(password.encode('utf-8'), self.password_hash.encode('utf-8'))
except Exception as e:
print(e)
Expand Down

0 comments on commit d804447

Please sign in to comment.