-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
232 lines (190 loc) · 7.08 KB
/
app.py
File metadata and controls
232 lines (190 loc) · 7.08 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
from database import conn
from flask import Flask, request, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
import jwt
from datetime import datetime, timedelta
import os
from dotenv import load_dotenv
from bson.objectid import ObjectId
from database import decoder
from sphereEngine.problems import creatProblem , updateProblem , deleteProblem
from sphereEngine.testcase import createTestCase, getAllTestCases , getTestCase , updateTestCase
from sphereEngine.compiler import createSubmission
from middlewares.decodeToken import decode_token
load_dotenv()
db = conn.client['cometlabs']
app = Flask(__name__)
app.json_encoder = decoder.MongoJSONEncoder
app.config['SECRET_KEY'] = os.getenv('MY_SECRET')
@app.before_first_request
def create_collections():
users = db.users
users.create_index('username', unique=True)
users.create_index('email', unique=True)
@app.route('/', methods=['GET'])
def home():
print('Welcome')
return 'Welcome to this server'
@app.route('/signup', methods=['POST'])
def signup():
print("Signup Attempted")
users = db.users
username = request.json['username']
email = request.json['email']
password = request.json['password']
role =request.json['role']
# Check if username or email already exists
if users.find_one({'$or': [{'username': username}, {'email': email}]}):
return jsonify({'error': 'Username or email already exists'})
# Hash the password
hashed_password = generate_password_hash(password, method='sha256')
# Create a new user document
user = {'username': username, 'email': email, 'password': hashed_password , 'role':role}
users.insert_one(user)
return jsonify({'message': 'User created successfully'})
@app.route('/login', methods=['POST'])
def login():
print('login Attempted')
users = db.users
username = request.json['username']
password = request.json['password']
# print(username , password, role)
# Find the user by username
user = users.find_one({'username': username})
# print(user)
# # Check if the user exists and verify the password
if user and check_password_hash(user['password'], password):
# Generate JWT token
token = jwt.encode(
{
'username': user['username'],
'role':user['role'],
'exp': datetime.utcnow() + timedelta(hours=24)
},
app.config['SECRET_KEY'],
algorithm='HS256'
)
return jsonify({'token': token})
return jsonify({'error': 'Invalid username or password'})
@app.route('/protected', methods=['GET'])
def protected():
token = request.headers.get('Authorization')
if not token:
return jsonify({'error': 'Missing token'})
try:
decoded = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
username = decoded['username']
return jsonify({'message': f'Hello, {username}! This is a protected route.'})
except jwt.ExpiredSignatureError:
return jsonify({'error': 'Token has expired'})
except jwt.InvalidTokenError:
return jsonify({'error': 'Invalid token'})
@app.route('/problems' , methods=['GET' , 'POST' , 'PUT' , 'DELETE'])
def Problems():
problems = db.problems
if request.method == 'GET':
if request.args.get('id') is not None:
id = int(request.args.get('id'))
problem = problems.find_one({'id':id})
# return jsonify(problem)
return problem
else:
projection = {"_id": 1, "name": 1}
documents = list(problems.find({}, projection))
return jsonify(documents)
elif request.method == 'POST':
# print(request.json)
token = None
auth_header = request.headers.get('Authorization')
if auth_header and auth_header.startswith('Bearer '):
token = auth_header.split(' ')[1]
print(token)
user = decode_token(token)
print(user)
if user['role'] != 'admin':
return 'Method Not allowed!!'
res = creatProblem(request.json)
return res
# return 'Done'
elif request.method == 'PUT':
problemId = int(request.args.get('id'))
token = None
auth_header = request.headers.get('Authorization')
if auth_header and auth_header.startswith('Bearer '):
token = auth_header.split(' ')[1]
print(token)
user = decode_token(token)
print(user)
if user['role'] != 'admin':
return 'Method Not allowed!!'
res = updateProblem(request.json , problemId)
return res
elif request.method == 'DELETE':
problemId = int(request.args.get('id'))
res = deleteProblem(problemId)
return res
else:
return 'Method Not Defined'
@app.route('/problems/testcases' , methods=['GET' , 'POST' , 'PUT' ])
def testcases():
if request.method == 'GET':
id = request.args.get('id')
number = request.args.get('number')
token = None
auth_header = request.headers.get('Authorization')
if auth_header and auth_header.startswith('Bearer '):
token = auth_header.split(' ')[1]
print(token)
user = decode_token(token)
print(user)
if user['role'] != 'admin':
return 'Method Not allowed!!'
if id is not None and number is not None:
res = getTestCase(int(id) , int(number))
return res
else:
res = getAllTestCases(int(id))
return res
elif request.method == 'POST':
token = None
auth_header = request.headers.get('Authorization')
if auth_header and auth_header.startswith('Bearer '):
token = auth_header.split(' ')[1]
print(token)
user = decode_token(token)
print(user)
if user['role'] != 'admin':
return 'Method Not allowed!!'
id = request.args.get('id')
res = createTestCase(int(id) , request.json)
return res
elif request.method == 'PUT':
id = request.args.get('id')
number = request.args.get('number')
token = None
auth_header = request.headers.get('Authorization')
if auth_header and auth_header.startswith('Bearer '):
token = auth_header.split(' ')[1]
print(token)
user = decode_token(token)
print(user)
if user['role'] != 'admin':
return 'Method Not allowed!!'
res = updateTestCase(int(id) , int(number), request.json)
return res
else:
return 'Method Not Defined'
@app.route('/submissions' , methods=['GET' , 'POST' ])
def submission():
if request.method=='GET':
return 'Done'
elif request.method == 'POST':
id = int(request.args.get('id'))
uploaded_file = request.files['source']
source = uploaded_file.read().decode('utf-8')
res = createSubmission(id , source)
return res
else:
return 'Method not allowed'
if __name__ == '__main__':
app.run(debug=True)