blob: 6ca6e9a4488b76a9b17d7d699e894bfbdb917052 [file] [log] [blame]
Akronca9bd982016-12-06 16:59:57 +01001from functools import wraps
2import json
3
4from flask_admin import Admin
5from werkzeug.utils import redirect
6
7import APIFactory
8import messaging
9from models import SigninForm, SignupForm, UserEncoder, ProfileForm, AdminView
10from providers import User
11import providers
12
13
14__author__ = 'hanl'
15
16from flask import Flask, render_template, request, session, url_for, flash, current_app
17
18from flask_babel import Babel, gettext as _
19from flask_login import LoginManager, logout_user, login_user, current_user
20import config
21
22lm = LoginManager()
23babel = Babel()
24admin = Admin()
25
26app = Flask(__name__)
27message_handler = messaging.NotificationHandler()
28providers.load_provider(config.AUTH_PROVIDER, message_handler)
29
30app.config.from_object(config)
31app.json_encoder = UserEncoder
32app.debug = config.DEBUG
33
34admin.init_app(app)
35babel.init_app(app)
36lm.init_app(app)
37
38admin.add_view(AdminView())
39
40# @app.before_request
41@app.route('/lang/<language>')
42def set_locale(lang=None):
43 setattr(session, 'lang', lang)
44 return render_template(url_for('index'), lang_code=lang)
45
46
47@babel.localeselector
48def get_locale():
49 browser_locale = request.accept_languages.best_match(config.LANGUAGES, default="de")
50 lang = session.get('lang', browser_locale)
51 setattr(session, 'lang', lang)
52 return lang
53
54
55def secured(func):
56 '''
57 overriding login_required, but redirects to login, not to unauthorized page
58 :param func:
59 :return:
60 '''
61
62 @wraps(func)
63 def decorated_view(*args, **kwargs):
64 if current_app.login_manager._login_disabled:
65 return func(*args, **kwargs)
66 elif not current_user.is_authenticated():
67 # fixme: how to set next?
68 return redirect(request.args.get('next') or url_for('login'))
69 return func(*args, **kwargs)
70
71 return decorated_view
72
73
74@lm.user_loader
75def load_user(username):
76 # either from session of via rest; cache if possible
77 return providers.provider.get_user(username, session)
78
79
80@app.route('/')
81def index():
82 return render_template('index.html', lang_code=get_locale())
83
84
85@app.route('/profile', methods=['GET', 'POST'])
86@secured
87def profile():
88 user = providers.provider.get_user(session['user_id'], session, True)
89 form = ProfileForm(obj=user)
90 if request.method == 'POST':
91 pass
92 elif request.method == 'GET':
93 return render_template('profile.html', form=form, submit=_('Update'))
94
95
96@app.route('/profile/<user>', methods=['GET'])
97def user_profile(user=None):
98 user = User(username=user)
99 form = ProfileForm(obj=user)
100 if request.method == 'POST':
101 pass
102 elif request.method == 'GET':
103 return render_template('profile.html', form=form, submit=_('Update'))
104
105
106@app.route('/search', methods=['GET'])
107# @secured
108def search():
109 if request.method == "GET":
110 data = request.args
111 print "has query %s" % str(data)
112 if 'q' in data:
113 # auth=APIFactory.Oauth2Auth(session['access_token'])
114 response = APIFactory.get("search", params=data)
115 if response is None:
116 pass
117 elif message_handler.isError(response):
118 message_handler.notifyNext(response.json(), flash)
119 else:
120 raw_json = response.json()
121 return render_template('search.html', lang=config.QUERY_LANGUAGES,
122 q=data['q'], ql=data['ql'], result=raw_json,
123 result_string=json.dumps(raw_json, indent=4))
124 return render_template('search.html', lang=config.QUERY_LANGUAGES,
125 q=None, ql=None,
126 result=None)
127
128
129@app.route('/serialize', methods=['GET', 'POST'])
130@secured
131def serialize():
132 return render_template('search.html')
133
134
135@app.route('/login', methods=['GET', 'POST'])
136def login():
137 form = SigninForm()
138 if request.method == 'POST':
139 if not form.validate():
140 print "unsuccessful validation"
141 return render_template('login.html', form=form)
142 else:
143 user = User(username=form.username.data, password=form.password.data)
144 success = providers.provider.login(session, user)
145 if success:
146 login_user(user)
147 else:
148 return redirect(url_for('login'))
149 print "the data serialized %s" % json.dumps(user, cls=UserEncoder)
150 return redirect(request.args.get('next') or url_for('profile'))
151 elif request.method == 'GET':
152 return render_template('login.html', form=form, submit=_('sign in'))
153
154
155@app.route('/logout')
156@secured
157def logout():
158 if not providers.provider.logout(session):
159 redirect(url_for('login'))
160 logout_user()
161 return redirect(url_for('index'))
162
163
164@app.route('/signup', methods=['GET', 'POST'])
165def signup():
166 form = SignupForm()
167 if request.method == 'POST':
168 if not form.validate():
169 print "unsuccessful validation"
170 return render_template('signup.html', form=form)
171 else:
172 passw = form.password.data
173 newuser = User(firstName=form.firstName.data, lastName=form.lastName.data,
174 email=form.email.data, username=form.username.data,
175 institution=form.institution.data, phone=form.phone.data,
176 address=form.address.data)
177 response = APIFactory.post("user/register")
178
179 elif request.method == 'GET':
180 return render_template('signup.html', form=form, submit=_('sign up'))
181
182
183@app.route('/reset', methods=['POST'])
184def reset():
185 pass
186
187
188@app.errorhandler(404)
189def page_not_found(e):
190 return render_template('404.html'), 404
191
192
193if __name__ == '__main__':
194 app.run()