-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathauth.py
More file actions
64 lines (58 loc) · 2.51 KB
/
auth.py
File metadata and controls
64 lines (58 loc) · 2.51 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
import os
import jwt # used for encoding and decoding jwt tokens
from fastapi import HTTPException # used to handle error handling
from passlib.context import CryptContext # used for hashing the password
from datetime import datetime, timedelta # used to handle expiry time for tokens
class Auth():
hasher= CryptContext(schemes=['bcrypt'])
secret = os.getenv("APP_SECRET_STRING")
def encode_password(self, password):
return self.hasher.hash(password)
def verify_password(self, password, encoded_password):
return self.hasher.verify(password, encoded_password)
def encode_token(self, username):
payload = {
'exp' : datetime.utcnow() + timedelta(days=0, minutes=30),
'iat' : datetime.utcnow(),
'scope': 'access_token',
'sub' : username
}
return jwt.encode(
payload,
self.secret,
algorithm='HS256'
)
def decode_token(self, token):
try:
payload = jwt.decode(token, self.secret, algorithms=['HS256'])
if (payload['scope'] == 'access_token'):
return payload['sub']
raise HTTPException(status_code=401, detail='Scope for the token is invalid')
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail='Token expired')
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail='Invalid token')
def encode_refresh_token(self, username):
payload = {
'exp' : datetime.utcnow() + timedelta(days=0, hours=10),
'iat' : datetime.utcnow(),
'scope': 'refresh_token',
'sub' : username
}
return jwt.encode(
payload,
self.secret,
algorithm='HS256'
)
def refresh_token(self, refresh_token):
try:
payload = jwt.decode(refresh_token, self.secret, algorithms=['HS256'])
if (payload['scope'] == 'refresh_token'):
username = payload['sub']
new_token = self.encode_token(username)
return new_token
raise HTTPException(status_code=401, detail='Invalid scope for token')
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail='Refresh token expired')
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail='Invalid refresh token')