1
# -*- coding utf-8 -*-
2
# classes/views/oauth.py
3
4
from flask import Module, jsonify, request, render_template, redirect,\
5
                    url_for, current_app
6
import requests
7
8
from swtstore.classes import oauth
9
from swtstore.classes.models.um import User
10
from swtstore.classes.models import Client, AuthorizedClients
11
12
13
Oauth = Module(__name__)
14
15
16
@Oauth.route('/authorize', methods=['GET', 'POST'])
17
@oauth.authorize_handler
18
def authorize(*args, **kwargs):
19
    current_user = User.getCurrentUser()
20
    if current_user is None:
21
        return render_template('oauth/login.html')
22
23
    if request.method == 'GET':
24
        client_id = kwargs.get('client_id')
25
        client = Client.query.get(client_id)
26
        current_app.logger.debug('In /authorize: client: %s', client)
27
        kwargs['client'] = client
28
        kwargs['user'] = current_user
29
        current_app.logger.debug('kwargs %s', kwargs)
30
31
        # See if this client is already authorized by user. If not then return
32
        # a HTML to allow access.
33
        authorized_clients = AuthorizedClients.getByUser(current_user)
34
        if client in authorized_clients:
35
            return render_template('oauth/authorized.html', **kwargs)
36
        else:
37
            return render_template('oauth/authorize.html', **kwargs)
38
39
40
    confirm = request.form.get('confirm', 'no')
41
    authorized = request.form.get('authorized', 'no')
42
    current_app.logger.debug('confirm authorize from user: %s', confirm)
43
    client = Client.query.get(request.form.get('client_id'))
44
45
    if authorized == 'yes':
46
        return True
47
    else:
48
        if confirm == 'yes':
49
            authorization = AuthorizedClients(user=current_user, client=client)
50
            authorization.persist()
51
            return True
52
        else:
53
            return False
54
55
56
@Oauth.route('/token', methods=['GET', 'POST'])
57
@oauth.token_handler
58
def access_token():
59
    #print request.form
60
    current_app.logger.debug('access token touched..')
61
    return None
62
63
@Oauth.route('/errors')
64
def error():
65
    return jsonify(error=request.args.get('error'))