haldis/app/zeus.py

71 lines
1.9 KiB
Python
Raw Normal View History

2015-03-26 22:17:50 +01:00
from flask import redirect, url_for, session, jsonify, flash, request
from flask.ext.login import login_user
2015-03-26 21:49:14 +01:00
from flask_oauthlib.client import OAuth, OAuthException
import json
import requests
from app import app, db
2015-03-26 22:17:50 +01:00
from models import User
2015-03-26 21:49:14 +01:00
oauth = OAuth(app)
zeus = oauth.remote_app(
'zeus',
consumer_key=app.config['ZEUS_KEY'],
consumer_secret=app.config['ZEUS_SECRET'],
request_token_params={},
base_url='http://kelder.zeus.ugent.be/oauth/api/',
access_token_method='POST',
access_token_url='https://kelder.zeus.ugent.be/oauth/oauth2/token/',
authorize_url='https://kelder.zeus.ugent.be/oauth/oauth2/authorize/'
)
def zeus_login():
2015-03-29 11:46:08 +02:00
return zeus.authorize(callback=url_for('authorized', _external=True))
2015-03-26 21:49:14 +01:00
@app.route('/login/zeus/authorized')
2015-03-26 21:49:14 +01:00
def authorized():
resp = zeus.authorized_response()
if resp is None:
return 'Access denied: reason=%s error=%s' % (
request.args['error'],
request.args['error_description']
)
if isinstance(resp, OAuthException):
return 'Access denied: %s' % resp.message + '<br>' + str(resp.data)
session['zeus_token'] = (resp['access_token'], '')
me = zeus.get('current_user/')
username = me.data.get('username', '').lower()
user = User.query.filter_by(username=username).first()
if len(username) > 0 and user:
return login_and_redirect_user(user)
elif len(username) > 0:
user = create_user(username)
return login_and_redirect_user(user)
flash("You're not allowed to enter, please contact a system administrator")
2015-03-29 11:46:08 +02:00
return redirect(url_for("home"))
2015-03-26 21:49:14 +01:00
@zeus.tokengetter
def get_zeus_oauth_token():
return session.get('zeus_token')
def login_and_redirect_user(user):
login_user(user)
2015-03-27 18:25:09 +01:00
return redirect(url_for("home"))
2015-03-26 21:49:14 +01:00
def create_user(username):
user = User()
2015-03-27 14:03:28 +01:00
user.configure(username, False, 1)
2015-03-26 21:49:14 +01:00
db.session.add(user)
db.session.commit()
return user