Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
105 changes: 105 additions & 0 deletions Naman Singla/Assignment 3/demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import os
from flask import Flask, request, jsonify, make_response

app = Flask(__name__)

tokens = []
user_data = {}

help_info = '''
<pre>
This application has following endpoints:
/ --> Returns information about different endpoints
/get_token --> A GET request at this endpoint return a token. Return format:
{
"token" : "<generated token value>"
}
/register --> A POST request at this endpoint saves user data. The request data should be in following format:
{
"username" : "<username of the user being registered>",
"data" : "<data to be saved>",
"token" : "<token value generated earlier>"
}
This endpoint does not return any data on successful completion.
/get_data --> A POST request at this endpoint return user data corresponding to a token. The request format is:
{
"token" : "<token value>"
}
On successful completion, the return data is in following format:
{
"username" : "<username of the registered user>"
"data" : "<data of the user>"
}

On succcessful completion, the response code is set to be 200.
For /register and /get_data endpoints, if there is some error(i.e. response code is not 200) then the format of return data is:
{
"error" : "<error description>"
}
</pre>
'''

def add_header(inp):
resp = make_response(inp)
resp.headers['Access-Control-Allow-Origin'] = "*"
return resp

@app.route("/")
def index():
return add_header(help_info), 200

@app.route("/get_token", methods = ['GET'])
def generate_token():
global tokens
token = os.urandom(8).hex()
tokens.append(token)
return add_header(jsonify(token = token)), 200

@app.route("/register", methods = ['POST', 'OPTIONS'])
def save_data():
global user_data
if request.method == 'OPTIONS':
resp = make_response()
resp.headers['Access-Control-Allow-Origin'] = "*"
resp.headers['Access-Control-Allow-Methods'] = "POST, OPTIONS"
resp.headers['Access-Control-Allow-Headers'] = "*"
return resp, 204

if request.content_type != 'application/json':
return add_header(jsonify(error = "json format required")), 400
json_data = request.json
if "token" not in json_data:
return add_header(jsonify(error = "token value missing")), 400
if "username" not in json_data:
return add_header(jsonify(error = "username field missing")), 400
if "data" not in json_data:
return add_header(jsonify(error = "data field missing")), 400
if not json_data["token"] in tokens:
return add_header(jsonify(error = "invalid token value")), 404
if json_data["token"] in user_data.keys():
return add_header(jsonify(error = "a user already registered for this token value")), 400
user_data[json_data["token"]] = {"username" : json_data["username"], "data" : json_data["data"]}
return add_header("User added successfully"), 200

@app.route("/get_data", methods = ['POST', 'OPTIONS'])
def send_data():
if request.method == 'OPTIONS':
resp = make_response()
resp.headers['Access-Control-Allow-Origin'] = "*"
resp.headers['Access-Control-Allow-Methods'] = "POST, OPTIONS"
resp.headers['Access-Control-Allow-Headers'] = "*"
return resp, 204

if request.content_type != 'application/json':
return add_header(jsonify(error = "json format required")), 400
json_data = request.json
if "token" not in json_data:
return add_header(jsonify(error = "token value missing")), 400
if not json_data["token"] in tokens:
return add_header(jsonify(error = "invalid token")), 404
if not json_data["token"] in user_data.keys():
return add_header(jsonify(error = "no user registered with this token")), 404
return add_header(jsonify(**user_data[json_data["token"]])), 200

if __name__ == "__main__":
app.run(debug = True, port = 12345)
37 changes: 37 additions & 0 deletions Naman Singla/Assignment 3/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<html>
<head>
<title>Server</title>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table style="margin: auto;margin-top: 30vh; transform: scale(2,2);">
<tr>
<th>Register</th>
<th>Login</th>
</tr>
<tr>
<td style="text-align: center;"><input id="get_token" type="button" value="Get Token"></td>
<td style="border: 0px;"><input id="token2" type="text" placeholder="Input Token"></td>
</tr>
<tr>
<td><input id="username" type="text" placeholder="Username"><br>
<input id="data" type="text" placeholder="Data"><br>
<input id="token1" type="text" placeholder="Token">
</td>
<td>
<input type="text" placeholder="Username" id="user2" readonly style="margin-bottom: 10px;"><br>
<input type="text" placeholder="Data" id="dat2" readonly>
</td>
</tr>
<tr>
<td style="text-align: center;"><input id="register" type="button" value="Register"></td>
<td style="text-align: center;"><input id="get_data" type="button" value="Get Data"></td>
</tr>
</table>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
58 changes: 58 additions & 0 deletions Naman Singla/Assignment 3/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
function getToken(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("token1").value=JSON.parse(xhttp.responseText).token;
alert("Your Token is : "+JSON.parse(xhttp.responseText).token);
}
};
xhttp.open("GET","http://localhost:12345/get_token",true);
xhttp.send();
}
function Register(){
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {
//alert(xhttp.responseText);
if (this.readyState == 4) {
if(this.status==200){
alert(xhttp.responseText);
}else{
alert("Sorry, an error occured :\n"+JSON.parse(xhttp.responseText).error);
}
}
};
var obj = new Object();
obj.username=String(document.getElementById("username").value);
obj.data=String(document.getElementById("data").value);
obj.token=String(document.getElementById("token1").value);
xhttp.open("POST","http://localhost:12345/register",true);
xhttp.setRequestHeader("Content-Type","application/json");
xhttp.send(JSON.stringify(obj));
}
function GetData(){
document.getElementById("user2").value="";
document.getElementById("dat2").value="";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
var res = JSON.parse(xhttp.responseText);
if(res.error)alert(res.error);
if(this.status=200){

document.getElementById("user2").value=res.username;
document.getElementById("dat2").value=res.data;
}
}

};
xhttp.open("POST","http://localhost:12345/get_data",true);
xhttp.setRequestHeader("Content-Type","application/json");
var tok=new Object();
tok.token=document.getElementById("token2").value;
xhttp.send(JSON.stringify(tok));

}
document.getElementById("get_token").addEventListener("click", getToken);
document.getElementById("register").addEventListener("click", Register);
document.getElementById("get_data").addEventListener("click", GetData);