simple auth mechanism via JSON Web Token
This commit is contained in:
parent
133e1cd490
commit
489f6b539a
41
auth_utils.py
Normal file
41
auth_utils.py
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
import jwt
|
||||||
|
from hashlib import md5
|
||||||
|
|
||||||
|
JWT_SECRET_KEY = "my secret key"
|
||||||
|
JWT_ALGORITHM = "HS256"
|
||||||
|
|
||||||
|
JWT_AUTH_HEADER = "HTTP_AUTHORIZATION"
|
||||||
|
|
||||||
|
def password_to_hash(password):
|
||||||
|
return md5(password.encode('utf-8')).hexdigest()
|
||||||
|
|
||||||
|
def verify_password(password, hash):
|
||||||
|
return password_to_hash(password) == hash
|
||||||
|
|
||||||
|
def jwt_encode(user):
|
||||||
|
payload = {
|
||||||
|
"user_id" : user.id
|
||||||
|
}
|
||||||
|
|
||||||
|
token = jwt.encode(payload, JWT_SECRET_KEY, JWT_ALGORITHM)
|
||||||
|
|
||||||
|
if isinstance(token, bytes):
|
||||||
|
return token.decode('utf-8')
|
||||||
|
|
||||||
|
return token
|
||||||
|
|
||||||
|
def jwt_decode(token):
|
||||||
|
try:
|
||||||
|
payload = jwt.decode(token, JWT_SECRET_KEY, algorithms = [JWT_ALGORITHM])
|
||||||
|
except jwt.DecodeError:
|
||||||
|
raise Exception("Error decoding signature")
|
||||||
|
except jwt.InvalidTokenError:
|
||||||
|
raise Exception("Invalid token")
|
||||||
|
|
||||||
|
user_id = payload["user_id"]
|
||||||
|
return user_id
|
||||||
|
|
||||||
|
def authorize(request):
|
||||||
|
token = request.headers.get(JWT_AUTH_HEADER, '')
|
||||||
|
user_id = jwt_decode(token)
|
||||||
|
return user_id
|
Loading…
Reference in New Issue
Block a user