-
Notifications
You must be signed in to change notification settings - Fork 10
/
command.py
53 lines (48 loc) · 1.57 KB
/
command.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
# -*- coding: utf-8 -*-
import json
import hashlib
class Command(object):
""" The base class for commands the clients can run.
TBD (to be documented)
"""
required = []
def __init__(self, sock, data):
self.sock = sock
try:
self.data = json.loads(data)
pre_hashed = 'x-pre-hashed' in self.data
if 'pwd' in self.data and not pre_hashed:
self.data['pwd'] = hashlib.sha256(self.data['pwd']).hexdigest()
except ValueError, KeyError:
self.error("Unable to decode request JSON")
self._handle = False
return
missing = []
for k in self.required:
if k in self.data:
continue
missing.append(k)
if missing:
self.error("Missing keys: {0}".format(', '.join(missing)))
self._handle = False
return
# This is so we don't call handle() unless we should
self._handle = True
def handle(self, *args, **kwargs):
self.error("This command has not been implemented correctly")
def success(self, payload, message=None, close=True):
self.sock.send(json.dumps({
"success": True,
"message": message,
"payload": payload
}))
if close:
self.sock.close()
def error(self, message, payload=None, close=True):
self.sock.send(json.dumps({
"success": False,
"message": message,
"payload": payload
}))
if close:
self.sock.close()