-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.py
executable file
·255 lines (218 loc) · 9.13 KB
/
service.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
247
248
249
250
251
252
253
254
255
#!/usr/bin/env python3
from urllib.parse import parse_qs
from lib.oauth import verification
from lib.database import helper as dbhelper
from lib.region import regiocodehelper
from lib.config import readConfig
import cherrypy, os, importlib, copy
oauthProviders = {}
APIconf = {}
imageurls = {}
class mentor(verification):
def __init__(self, secretserverkey):
self.secretserverkey = secretserverkey
self.dbapi = dbhelper(APIconf)
self.regiocodehelper = regiocodehelper()
@cherrypy.expose
def login(self, loginProvider):
self.__crossOrigin()
if loginProvider in oauthProviders:
if "sessionId" in cherrypy.request.cookie:
self.logout()
plugin = oauthProviders[loginProvider]["plugin"]
config = oauthProviders[loginProvider]["config"]
key = self.oauthLogin(plugin.getOAuthInstance(), config["requestTokenURL"], config["customerKey"], config["customerSecret"])
return config["loginPage"] + "?oauth_token=" + str(key)
@cherrypy.expose
def callback(self, callbackProvider, oauth_token, oauth_verifier=""):
if callbackProvider in oauthProviders:
plugin = oauthProviders[callbackProvider]["plugin"]
config = oauthProviders[callbackProvider]["config"]
oauthSession = self.oauthCallback(plugin.getOAuthInstance(), config["accessTokenURL"], config["customerKey"], config["customerSecret"], oauth_token, oauth_verifier)
#receive user identifier (provider dependent), provider name (provider dependent), generate user token and set it as cookie
userident, imageurl = plugin.getUserIdentifier(oauthSession, config)
userident = str(plugin.providerName()) + "_" + userident
imageurls[userident] = imageurl.replace("http:", "https:", 1)
usertoken = userident + "|" + str("/".join(self.createExpireTime()))
usertoken_hash = self.generateToken(usertoken)
cookie = usertoken + "|" + usertoken_hash
cherrypy.response.headers["Set-Cookie"] = "sessionId=" + cookie + "; Max-Age=" + str(60*60) + "; Path=/; HttpOnly"
self.__redirect("redirectToAfterLogin")
def __removeCookie(self, name):
if name in cherrypy.request.cookie:
cherrypy.response.cookie[name] = cherrypy.request.cookie[name]
cherrypy.response.cookie[name]["expires"] = 0
cherrypy.response.cookie[name]["Max-Age"] = 0
def __redirect(self, name):
if name in APIconf:
cherrypy.response.status = "303"
cherrypy.response.headers["Location"] = APIconf[name]
else:
return "NO REDIRECT SPECIFIED"
def __convertToHttps(self, url):
if url.lower().startswith("http:") and not url.lower().startswith("https:"):
return "https:" + url[5:len(url)]
return url
def __deleteUserEntry(self, user):
if user in imageurls:
del imageurls[user]
def __crossOrigin(self):
if "Origin" in cherrypy.request.headers:
cherrypy.response.headers["Access-Control-Allow-Origin"] = cherrypy.request.headers["Origin"]
elif "Host" in cherrypy.request.headers:
cherrypy.response.headers["Access-Control-Allow-Origin"] = cherrypy.request.headers["Host"]
@cherrypy.expose
def logout(self):
self.__crossOrigin()
if "sessionId" in cherrypy.request.cookie and self.isAuthorized(cherrypy.request.cookie["sessionId"].value):
userid = cherrypy.request.cookie["sessionId"].value.split("|")[0]
self.__deleteUserEntry(userid)
self.__removeCookie("sessionId")
self.__redirect("redirectToAfterLogout")
return "logged out"
else:
return "not logged in"
@cherrypy.expose
def profileExists(self):
self.__crossOrigin()
if "sessionId" in cherrypy.request.cookie and self.isAuthorized(cherrypy.request.cookie["sessionId"].value):
userid = cherrypy.request.cookie["sessionId"].value.split("|")[0]
if self.dbapi.userExists(userid, "profiles") and self.dbapi.userExists(userid, "contact"):
return "true"
return "false"
return "not logged in"
@cherrypy.expose
def createprofile(self):
self.__crossOrigin()
if "sessionId" in cherrypy.request.cookie and self.isAuthorized(cherrypy.request.cookie["sessionId"].value):
userid = cherrypy.request.cookie["sessionId"].value.split("|")[0]
if not self.dbapi.userExists(userid, "profiles"):
self.dbapi.sendToPostgres(APIconf["createprofile"], (userid, imageurls[userid]))
if not self.dbapi.userExists(userid, "contact"):
self.dbapi.sendToPostgres(APIconf["createcontact"], (userid,))
#self.__deleteUserEntry(userid)
return "OK"
return "not logged in"
@cherrypy.expose
def removeprofile(self):
self.__crossOrigin()
if "sessionId" in cherrypy.request.cookie and self.isAuthorized(cherrypy.request.cookie["sessionId"].value):
userid = cherrypy.request.cookie["sessionId"].value.split("|")[0]
if self.dbapi.userExists(userid, "profiles"):
self.dbapi.sendToPostgres(APIconf["removeprofile"], (userid,))
if self.dbapi.userExists(userid, "contact"):
self.dbapi.sendToPostgres(APIconf["removecontact"], (userid,))
return "OK"
return "not logged in"
@cherrypy.expose
@cherrypy.tools.json_in()
def changeprofile(self):
self.__crossOrigin()
if "sessionId" in cherrypy.request.cookie and self.isAuthorized(cherrypy.request.cookie["sessionId"].value):
userid = cherrypy.request.cookie["sessionId"].value.split("|")[0]
args = cherrypy.request.json
query = []
if not self.dbapi.userExists(userid, "profiles"):
return "profile not existing"
if "id" in args:
return "'id' not allowed"
if "location" in args and args["location"].find(",") > -1 and not args["location"] == "":
args["location"], settings = self.regiocodehelper.resolve(args["location"].split(","))
args["location"] = ",".join(args["location"])
if "imageurl" in args:
args["imageurl"] = self.__convertToHttps(args["imageurl"])
for item in args:
name = "update_" + item
query.append(self.dbapi.modifyUser(userid, name, args[item]))
self.dbapi.sendToPostgres("\n".join(query))
return "OK"
return "not logged in"
@cherrypy.expose
@cherrypy.tools.json_out()
def showprofile(self):
self.__crossOrigin()
if "sessionId" in cherrypy.request.cookie and self.isAuthorized(cherrypy.request.cookie["sessionId"].value):
userid = cherrypy.request.cookie["sessionId"].value.split("|")[0]
profile = self.dbapi.sendToPostgres(APIconf["showprofile"], (userid,))
if len(profile) == 0:
profile["imageurl"] = self.__convertToHttps(imageurls[userid])
else:
self.__deleteUserEntry(userid)
return profile
return {"error": "not logged in"}
@cherrypy.expose
def contactmethods(self):
self.__crossOrigin()
return ",".join(self.dbapi.tableSchema("contact"))
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def searchpeople(self):
self.__crossOrigin()
if "sessionId" in cherrypy.request.cookie and self.isAuthorized(cherrypy.request.cookie["sessionId"].value):
output = {}
args = cherrypy.request.json
if not "location" in args:
return {"error": "'location' requirred"}
defaults = {"available": "true"}
params = copy.deepcopy(args)
params["location"], settings = self.regiocodehelper.resolve(args["location"].split(","))
output["region_resolved"] = ",".join(params["location"])
params["location"] = ",".join(params["location"]) + "%"
for item in params:
defaults[item] = params[item]
query = self.dbapi.searchpeople(defaults)
output["resultset"] = self.dbapi.sendToPostgres(query)
output["request_params"] = args
output["resolve_settings"] = settings
return output
else:
return {"error": "not logged in"}
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def autocompleteRegion(self):
self.__crossOrigin()
searchresult = {}
if not "json" in dir(cherrypy.request):
return 0
regiocodes = cherrypy.request.json
for search in regiocodes:
searchresult[search] = self.regiocodehelper.search(regiocodes[search], search)
return searchresult
def _cp_dispatch(self, vpath):
if vpath[0] == "login":
vpath.pop(0)
cherrypy.request.params["loginProvider"] = vpath.pop(0)
return self
if vpath[0] == "callback":
vpath.pop(0)
cherrypy.request.params["callbackProvider"] = vpath.pop(0)
cherrypy.request.params["oauthToken"] = vpath.pop(0)
cherrypy.request.params["oauthVerifier"] = vpath.pop(0)
return self
def main():
global APIconf
print("Generating secret server key just this instance knows...")
secretserverkey = os.urandom(16)
print("Loading oauth provider plugins...")
for content in os.listdir("oauthproviders"):
if os.path.isdir(os.path.join("oauthproviders", content)):
print(" - " + content)
oauthProviders[content] = {}
oauthProviders[content]["plugin"] = importlib.import_module("oauthproviders." + content).provider()
sfile = open(os.path.join("oauthproviders", content, "config.yml"), "r")
filebuffer = sfile.read()
sfile.close()
config = {}
for entry in filebuffer.split("\n"):
if entry.find(":") > -1:
key, value = entry.split(":", 1)
config[key.strip()] = str(value.strip())
oauthProviders[content]["config"] = config
print("Loading mentorAPI configuration...")
APIconf = readConfig(os.path.join(os.getcwd(), "mentorapi.yml")).config
print("Starting cherrypy server...")
cherrypy.quickstart(mentor(secretserverkey), "/", "mentorserver.cfg")
if __name__ == "__main__":
main()