def authenticate(username, token):
""" Authenticate user from cache or in ES """
# check for user in cache
authtoken = getCache(username, "user")
if authtoken is not False:
if len(authtoken) == 128:
tokenhash = hashlib.sha512(token.encode('utf-8')).hexdigest()
if authtoken == tokenhash:
return True
elif len(authtoken) == 32:
tokenhash = hashlib.md5(token.encode('utf-8')).hexdigest()
if authtoken == tokenhash:
return True
else:
app.logger.error('authenticate(): Hash "{0}" for user "{1}" is not matching md5 or sha512 length! Needs to be checked in memcache!'.format(authtoken, username))
# query ES
else:
try:
res = es.search(index=app.config['WSUSERINDEX'], body={
"query": {
"term": {
"peerName.keyword": username
}
}
})
if res["hits"]["total"] > 1:
app.logger.error('authenticate(): More than one user "%s" in ES index "users" found!' % username)
elif res["hits"]["total"] < 1:
app.logger.error('authenticate(): No user "%s" in ES index "users" found!' % username)
elif res["hits"]["total"] == 1:
authtoken = res["hits"]["hits"][0]["_source"]["token"]
getOnly = res["hits"]["hits"][0]["_source"]["getOnly"]
community = res["hits"]["hits"][0]["_source"]["community"]
if len(authtoken) == 128:
tokenhash = hashlib.sha512(token.encode('utf-8')).hexdigest()
if authtoken == tokenhash:
# add user and token to cache for 24h
setCache(username, authtoken, (60 * 60 * 24), "user")
return True
elif len(authtoken) == 32:
tokenhash = hashlib.md5(token.encode('utf-8')).hexdigest()
if authtoken == tokenhash:
# add user and token to cache for 24h
setCache(username, authtoken, (60 * 60 * 24),"user")
return True
else:
app.logger.error('authenticate(): Hash "{0}" for user "{1}" is not matching md5 or sha512 length! Needs to be checked in ES index!'.format(authtoken, username))
return False
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
评论列表
文章目录