Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
Flask==2.2.2
pytest==7.2.1
PyJWT==2.6.0
63 changes: 32 additions & 31 deletions src/generate_api_token.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,41 @@
import jwt
import json
import random
import string
import sqlite3

# Connect to the database (or create it if it doesn't exist)
conn = sqlite3.connect('Tokens.db', check_same_thread=False)
cursor = conn.cursor()

def generate_api_token( payload, secret):
header = {"alg": "HS256", "typ": "JWT"}
encoded_jwt = jwt.encode(payload, secret, algorithm='HS256', headers=header)
return json.dumps({"token": encoded_jwt})
# Create the table to store the tokens (if it doesn't already exist)
cursor.execute('''
CREATE TABLE IF NOT EXISTS Tokens (
token_text text
)
''')
conn.commit()



def verify_api_token(token, secret):
try:
decoded_jwt = jwt.decode(token, secret, algorithms=["HS256"])
return json.dumps({"payload": decoded_jwt})
except:
return {"error": "Invalid signature:"}

class ApiToken:

def generate_token():
# Generate random alpha-numeric string with length 50
token = ''.join(random.choices(string.ascii_letters+string.digits, k=40))
result = cursor.execute("SELECT * FROM Tokens WHERE token_text=?", (token,)).fetchone()

# Check whether the token already exist or not
while result:
token = ''.join(random.choices(string.ascii_letters+string.digits, k=50))
result = cursor.execute("SELECT * FROM Tokens WHERE token_text=?", (token,)).fetchone()

cursor.execute("INSERT INTO Tokens (token_text) VALUES (?)", (token,))
conn.commit()

return token


def is_valid_token(token_to_check):
cursor.execute("SELECT * FROM Tokens WHERE token_text=?", (token_to_check,))
result = cursor.fetchone()

# example

payload = {"sub": "12364567890", "user": "John Doe"}
secret = "Ravipassword" #securely store secret in production

jwt_json = generate_api_token( payload, secret)
print(jwt_json)

jwt_dict = json.loads(jwt_json)
token = jwt_dict["token"]

decoded_jwt = verify_api_token(token, secret)
print(decoded_jwt)




return True if result else False