0% found this document useful (0 votes)
9 views

21bai1012 Json

Uploaded by

gokul krishna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

21bai1012 Json

Uploaded by

gokul krishna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

LAB-11

Gokul Krishna k
21BAI1012

JSON WEB TOKKEN


Code
from flask import Flask, request, jsonify, render_template
import jwt
import datetime
from flask_cors import CORS

app = Flask(__name__)
CORS(app) # Enable CORS
app.config['SECRET_KEY'] = '21BRS1711'

# Dummy student data


students = {
'student1': {
'id': 1,
'name': 'Anish',
'major': 'Computer Science',
'reg_number': '21BRS1711',
'dob': '2000-01-01'
},
'student2': {
'id': 2,
'name': 'Jane Smith',
'major': 'Mathematics',
'reg_number': '21BRS1712',
'dob': '1999-02-02'
}
}

@app.route('/')
def home():
return render_template('index1.html') # Serve the login page

@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
reg_number = data.get('reg_number')
dob = data.get('dob')

# Find the student by registration number


student = next((s for s in students.values() if s['reg_number'] == reg_number), None)

if not student or student['dob'] != dob:


return jsonify({'message': 'Invalid credentials'}), 401

# Create a token
token = jwt.encode({
'reg_number': reg_number,
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
}, app.config['SECRET_KEY'], algorithm='HS256')

return jsonify({'token': token})

@app.route('/student_details', methods=['GET'])
def student_details():
token = request.headers.get('Authorization')

if not token:
return jsonify({'message': 'Token is missing!'}), 401

try:
decoded = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
student = next((s for s in students.values() if s['reg_number'] == decoded['reg_number']), None)

if student:
return jsonify(student)
else:
return jsonify({'message': 'Student not found!'}), 404

except jwt.ExpiredSignatureError:
return jsonify({'message': 'Token has expired!'}), 403
except jwt.InvalidTokenError:
return jsonify({'message': 'Invalid token!'}), 403

@app.route('/student_details_page')
def student_details_page():
return render_template('student_details1.html') # Serve the student details page

if __name__ == '__main__':
app.run(debug=True)

You might also like