-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
172 lines (140 loc) · 5.49 KB
/
app.py
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
from flask import Flask, redirect, request
import requests
from flask_restful import Api
import json
from urllib.parse import urlparse
import tempfile
import re
import random
from flask_jwt_extended import jwt_required, get_jti
import sqlite3
from flask_restful import Resource, reqparse
from user import resources
import logging as logger
app = Flask(__name__)
api = Api(app)
connection = sqlite3.connect('url.db', check_same_thread=False)
cursor = connection.cursor()
# connection.execute('''CREATE TABLE URLS
# (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
# URL TEXT NOT NULL);''')
parser_linker = reqparse.RequestParser()
parser_linker_post = reqparse.RequestParser()
parser_linker_post.add_argument('link', help='Something went wrong', required=True)
parser_linker_post.add_argument('X-Access-Token', type=str, location='headers', required=True)
# char = lambda x: [char for char in x]
words = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
def base62encode(number):
buf = []
base = len(words)
while number:
number, remainder = divmod(number, base)
buf.append(words[remainder - 1])
buf.reverse()
return ''.join(buf)
def base62decode(hashed):
base = len(words)
number = 0
strlen = len(hashed)
id_x = 0
for x in hashed:
power = (strlen - (id_x + 1))
number += words.index(x) * (base ** power)
id_x += 1
return number
def VerifyJwt(token):
r = requests.post("http://0.0.0.0:3000/token/verify", headers={"Authorization": "Bearer " + token + ""})
response = json.loads((r.content).decode('utf-8'))
response_status = r.status_code
if response_status == 200 and response['code'] == 1:
return True
else:
return False
class urllinker(Resource):
def get(self, id):
try:
redirect_url = connection.execute('SELECT URL FROM URLS WHERE ID = ' + str(base62decode(id)) + ';')
url = ""
for x in redirect_url:
url = x[0]
if url == "":
return {"message": "404. ID not found"}, 404
else:
return redirect(url, code=301)
except Exception as e:
return {}, 404
def put(self, id):
data = parser_linker_post.parse_args()
urlparsed = urlparse(data['link'])
if VerifyJwt(data['X-Access-Token']):
if (urlparsed.scheme == "http" or urlparsed.scheme == "https"):
redirect_url = connection.execute('SELECT URL FROM URLS WHERE ID = ' + str(base62decode(id)) + ';')
url = ""
for x in redirect_url:
url = x[0]
if len(url) != 0:
cursor.execute(
'''UPDATE URLS SET URL="''' + urlparsed.geturl() + '''" WHERE id = ''' + str(base62decode(id)) +
''' ;''')
row_id = cursor.lastrowid
hash = base62encode(row_id)
print(hash)
return {'id': hash, "changes": "ok"}, 201
else:
return "Not found", 404
elif (urlparsed.scheme == "javascript" or urlparsed.scheme == "data"):
return "", 302, {'Location': "https://i.imgflip.com/2w8wup.jpg"}
else:
return "", 400
else:
return {"msg": "The resource is forbidden"}, 403
def delete(self, id):
data = parser_linker_post.parse_args()
if VerifyJwt(data['X-Access-Token']):
connection.execute('DELETE FROM URLS WHERE id = ' + str(base62decode(id)) + ';')
return "", 204
else:
return {"msg": "The resource is forbidden"}, 403
class urllinkerpost(Resource):
def post(self):
data = parser_linker_post.parse_args()
if VerifyJwt(data['X-Access-Token']):
redirect_url = urlparse(data['link'])
print(redirect_url.scheme)
if (redirect_url.scheme == "http" or redirect_url.scheme == "https"):
cursor.execute('''INSERT INTO URLS (URL)
VALUES ( "''' + redirect_url.geturl() + '''" );''')
row_id = cursor.lastrowid
hash = base62encode(row_id)
print(hash)
return {'id': hash}, 201
elif (redirect_url.scheme == "javascript" or redirect_url.scheme == "data"):
return "", 302, {'Location': "https://i.imgflip.com/2w8wup.jpg"}
else:
return "", 400
else:
return {"msg": "The resource is forbidden"}, 403
def delete(self):
data = parser_linker_post.parse_args()
if VerifyJwt(data['X-Access-Token']):
connection.execute('DELETE FROM URLS;')
return "", 204
else:
return {"msg": "The resource is forbidden"}, 403
def get(self):
data = parser_linker_post.parse_args()
if VerifyJwt(data['X-Access-Token']):
try:
redirect_url = connection.execute('SELECT URL FROM URLS;')
url = []
for x in redirect_url:
url.append(x[0])
return {"id": url, "status": 200}, 200
except Exception as e:
return {}, 404
else:
return {"msg": "The resource is forbidden", "status": 403}, 403
api.add_resource(urllinker, '/<string:id>')
api.add_resource(urllinkerpost, '/')
if __name__ == '__main__':
app.run(debug=True)