每个客户端在初始握手期间都设置了X-Auth-Token标头。服务器需要进行数据库查找以验证auth-token是否有效。如果无效,则服务器需要拒绝连接并以403状态响应握手。
我做对了吗?
class EchoServerProtocol(WebSocketServerProtocol):
def onConnect(self, request):
authToken = request.headers['x-auth-token']
user = User(authToken, self.factory.protocols)
user.processNewConnection()
return (None, headers)
class User():
def __init__(self, authToken, factoryProtocols):
self.authToken = authToken
self.factoryProtocols = factoryProtocols
def processNewConnection(self):
query = "SELECT name, address, role, access_token FROM dummy_user WHERE access_token = '"+ self.authToken +"'"
return dbpool.runQuery(query).addCallback(self.handleResult).addErrback(self.errorquery)
def errorquery(self,result):
print ("error received", result)
## Please suggest a better way here
return result
def handleResult(self, result):
if result:
## blah blah blah...
else:
## Please suggest a better way here
raise ConnectionDeny(ConnectionDeny.FORBIDDEN, u'Invalidoooo authentication token'.format(u', '.join(self.factoryProtocols)))
return