forked from Kyria/flask-esipy-example
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
246 lines (199 loc) · 7.03 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# -*- encoding: utf-8 -*-
from datetime import datetime
from esipy import EsiApp
from esipy import EsiClient
from esipy import EsiSecurity
from esipy.exceptions import APIException
from flask import Flask
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from flask_login import LoginManager
from flask_login import UserMixin
from flask_login import current_user
from flask_login import login_required
from flask_login import login_user
from flask_login import logout_user
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm.exc import NoResultFound
import config
import hashlib
import hmac
import logging
import random
import time
# logger stuff
logger = logging.getLogger(__name__)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
console.setFormatter(formatter)
logger.addHandler(console)
# init app and load conf
app = Flask(__name__)
app.config.from_object(config)
# init db
db = SQLAlchemy(app)
migrate = Migrate(app, db)
# init flask login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
# -----------------------------------------------------------------------
# Database models
# -----------------------------------------------------------------------
class User(db.Model, UserMixin):
# our ID is the character ID from EVE API
character_id = db.Column(
db.BigInteger,
primary_key=True,
autoincrement=False
)
character_owner_hash = db.Column(db.String(255))
character_name = db.Column(db.String(200))
# SSO Token stuff
access_token = db.Column(db.String(4096))
access_token_expires = db.Column(db.DateTime())
refresh_token = db.Column(db.String(100))
def get_id(self):
""" Required for flask-login """
return self.character_id
def get_sso_data(self):
""" Little "helper" function to get formated data for esipy security
"""
return {
'access_token': self.access_token,
'refresh_token': self.refresh_token,
'expires_in': (
self.access_token_expires - datetime.utcnow()
).total_seconds()
}
def update_token(self, token_response):
""" helper function to update token data from SSO response """
self.access_token = token_response['access_token']
self.access_token_expires = datetime.fromtimestamp(
time.time() + token_response['expires_in'],
)
if 'refresh_token' in token_response:
self.refresh_token = token_response['refresh_token']
# -----------------------------------------------------------------------
# Flask Login requirements
# -----------------------------------------------------------------------
@login_manager.user_loader
def load_user(character_id):
""" Required user loader for Flask-Login """
return User.query.get(character_id)
# -----------------------------------------------------------------------
# ESIPY Init
# -----------------------------------------------------------------------
# create the app
esiapp = EsiApp().get_latest_swagger
# init the security object
esisecurity = EsiSecurity(
redirect_uri=config.ESI_CALLBACK,
client_id=config.ESI_CLIENT_ID,
secret_key=config.ESI_SECRET_KEY,
headers={'User-Agent': config.ESI_USER_AGENT}
)
# init the client
esiclient = EsiClient(
security=esisecurity,
cache=None,
headers={'User-Agent': config.ESI_USER_AGENT}
)
# -----------------------------------------------------------------------
# Login / Logout Routes
# -----------------------------------------------------------------------
def generate_token():
"""Generates a non-guessable OAuth token"""
chars = ('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
rand = random.SystemRandom()
random_string = ''.join(rand.choice(chars) for _ in range(40))
return hmac.new(
config.SECRET_KEY.encode('utf-8'),
random_string.encode('utf-8'),
hashlib.sha256
).hexdigest()
@app.route('/sso/login')
def login():
""" this redirects the user to the EVE SSO login """
token = generate_token()
session['token'] = token
return redirect(esisecurity.get_auth_uri(
state=token,
scopes=['esi-wallet.read_character_wallet.v1']
))
@app.route('/sso/logout')
@login_required
def logout():
logout_user()
return redirect(url_for("index"))
@app.route('/sso/callback')
def callback():
""" This is where the user comes after he logged in SSO """
# get the code from the login process
code = request.args.get('code')
token = request.args.get('state')
# compare the state with the saved token for CSRF check
sess_token = session.pop('token', None)
if sess_token is None or token is None or token != sess_token:
return 'Login EVE Online SSO failed: Session Token Mismatch', 403
# now we try to get tokens
try:
auth_response = esisecurity.auth(code)
except APIException as e:
return 'Login EVE Online SSO failed: %s' % e, 403
# we get the character informations
cdata = esisecurity.verify()
# if the user is already authed, we log him out
if current_user.is_authenticated:
logout_user()
# now we check in database, if the user exists
# actually we'd have to also check with character_owner_hash, to be
# sure the owner is still the same, but that's an example only...
try:
user = User.query.filter(
User.character_id == cdata['sub'].split(':')[2],
).one()
except NoResultFound:
user = User()
user.character_id = cdata['sub'].split(':')[2]
user.character_owner_hash = cdata['owner']
user.character_name = cdata['name']
user.update_token(auth_response)
# now the user is ready, so update/create it and log the user
try:
db.session.merge(user)
db.session.commit()
login_user(user)
session.permanent = True
except:
logger.exception("Cannot login the user - uid: %d" % user.character_id)
db.session.rollback()
logout_user()
return redirect(url_for("index"))
# -----------------------------------------------------------------------
# Index Routes
# -----------------------------------------------------------------------
@app.route('/')
def index():
wallet = None
# if the user is authed, get the wallet content !
if current_user.is_authenticated:
# give the token data to esisecurity, it will check alone
# if the access token need some update
esisecurity.update_token(current_user.get_sso_data())
op = esiapp.op['get_characters_character_id_wallet'](
character_id=current_user.character_id
)
wallet = esiclient.request(op)
return render_template('base.html', **{
'wallet': wallet,
})
if __name__ == '__main__':
app.run(port=config.PORT, host=config.HOST)