auth.py
1.83 KB
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
import sys
from datetime import datetime
import hmac
import hashlib
import base64
from .exc import (
JsonRpcInvalidTime,
JsonRpcInvalidLogin,
)
begin_unix_time = datetime(1970, 1, 1)
def get_seconds():
durasi = datetime.utcnow() - begin_unix_time
return int(durasi.total_seconds())
# Fungsi ini digunakan untuk membuat header dan authentikasi pada rpc client
def get_header(userid, password, time_stamp):
msg = '&'.join([str(userid), str(time_stamp)])
msg = msg.encode('utf-8')
if sys.version_info.major == 2:
if isinstance(password, unicode):
password = str(password)
elif isinstance(password, str):
password = password.encode('utf-8')
signature = hmac.new(password, msg=msg, digestmod=hashlib.sha256)
signature = signature.digest()
if sys.version_info.major == 2:
s = base64.encodestring(signature)
else:
s = base64.encodebytes(signature)
if isinstance(s, bytes):
s = str(s)
s = s.replace('\n', '')
return dict(userid=userid, signature=s, key=time_stamp)
lima_menit = 600
# env = request.env
class Auth:
def __init__(self, env):
self.env = env
self.validate_env()
self.validate_time()
def validate_env(self):
if not ('HTTP_USERID' in self.env and
'HTTP_SIGNATURE' in self.env and
'HTTP_KEY' in self.env):
raise JsonRpcInvalidLogin()
def validate_time(self):
self.time_stamp = int(self.env['HTTP_KEY'])
now = get_seconds()
if abs(now - self.time_stamp) > lima_menit:
raise JsonRpcInvalidTime()
def validate_signature(self, api_key):
header = get_header(self.env['HTTP_USERID'], api_key, self.time_stamp)
if header['signature'] != self.env['HTTP_SIGNATURE']:
raise JsonRpcInvalidLogin()