From 16fc7e987f5d148c3c6d1aa1f7a668cedf25ddda Mon Sep 17 00:00:00 2001 From: Emerson Date: Sat, 9 May 2015 21:40:40 -0300 Subject: [PATCH 1/4] Fixed issues #1, #4, #10 --- webnote.py | 305 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 289 insertions(+), 16 deletions(-) diff --git a/webnote.py b/webnote.py index b217862..ed36408 100644 --- a/webnote.py +++ b/webnote.py @@ -1,13 +1,19 @@ import socket import re import json -import urlparse +from urlparse import parse_qs +import sqlite3 as lite +import httplib +import base64 +#import string s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('0.0.0.0', 8080)) s.listen(1) +loged = 0 +userloged = None while True: data = '' @@ -21,6 +27,10 @@ break data += new_data + print 'DATA ORIGINAL\r\n', data + + print '---------------------------------------' + request_match = \ re.match(r'^([^ ]+) ([^ ]+) ([^ ]+)\r\n(.*)$', data, re.DOTALL) if request_match is not None: @@ -28,10 +38,11 @@ resource = request_match.group(2) protocol = request_match.group(3) data = request_match.group(4) + print data else: raise Exception('Cannot read request') - + request_headers = dict() while True: @@ -43,6 +54,7 @@ field_name = field.group(1) field_body = field.group(2) request_headers[field_name.lower()] = field_body + print request_headers data = field.group(3) else: raise Exception('Cannot read request header') @@ -50,18 +62,222 @@ response = '' response += 'HTTP/1.1 200 OK\r\n' - + try: + #print 'userloged = ', userloged with open('.notes') as note_file: note_dict = json.loads(note_file.read()) except IOError: note_dict = dict() + + note_list = [] + for key in note_dict: + note_list.append(note_dict[key]) + + try: + con = lite.connect('datas.db') + with con: + cur = con.cursor() + cur.execute("CREATE TABLE Notes(Id INTEGER PRIMARY KEY, Key TEXT UNIQUE NOT NULL, Note TEXT NOT NULL)") + except lite.OperationalError: + pass + + + try: + con1 = lite.connect('datas.db') + with con1: + cur1 = con1.cursor() + cur1.execute("CREATE TABLE Users(Id INTEGER PRIMARY KEY, Name TEXT UNIQUE NOT NULL, Password TEXT NOT NULL)") + except lite.OperationalError: + pass + + print loged + print userloged + print resource + + if resource == '/auth': + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + if method == 'GET': + response += """ + + + + + +
+

Insira seu usuario e senha!

+ User: +
+ Password: +
+ +
+ + + """ + elif method == 'POST': + print data + new_dict = parse_qs(data) + username = new_dict['user'][0] + password = new_dict['password'][0] + trying = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') + con = lite.connect('datas.db') + username = str(username) + with con: + cur = con.cursor() + cur.execute('SELECT Password FROM Users WHERE Name=:name',{'name': username}) + row = cur.fetchall() + if row == None: + break + authent = row[0][0] + print authent + if trying == authent: + loged = 1 + userloged = username + print 'USERLOGED = ', userloged + print loged + response = '' + response += 'HTTP/1.1 418 I\'m a teapot\r\n' + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + response += """ + + + + + +

Sucess!

+ + + """ + else: + response = '' + response += 'HTTP/1.1 401 Unauthorized\r\n' + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + response += """ + + + + + +

ERROR 401 - Unauthorized

+ + + """ + + elif resource == '/register': + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + if method == 'GET': + response += """ + + + + + +
+

Insira seu nome e senha para registrar!

+ Name: +
+ Password: +
+ +
+ + + """ + elif method == 'POST': + new_dict = parse_qs(data) + username = new_dict['name'][0] + password = new_dict['password'][0] + auth = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') + listtoinsert = [] + listtoinsert.append(username) + listtoinsert.append(auth) + con = lite.connect('datas.db') + with con: + cur = con.cursor() + cur.execute('INSERT INTO Users(Name,Password) VALUES(?,?)', listtoinsert) + + - if resource == '/notes': + elif resource == '/notes': response += 'Content-Type: text/plain; charset=utf-8\r\n' response += '\r\n' for name in note_dict: response += '%s\n' % name + #for count in range(0,len(note_list)): + # response += str(count + 1) + '\n' + con = lite.connect('datas.db') + with con: + cur = con.cursor() + cur.execute('SELECT Key FROM Notes') + while True: + rows = cur.fetchone() + if rows == None: + break + print rows + for row in rows: + response += row + response += '\r\n' + #print note_dict + #print note_list + #print note_list[1] + + elif resource == '/edit_note': + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + if method == 'GET': + con = lite.connect('datas.db') + with con: + cur = con.cursor() + cur.execute('SELECT * FROM Notes;') + #con.text_factory = str + while True: + row = cur.fetchone() + if row == None: + break + row = list(row) + row = str(row) + print row + print row[0] + #response += row[0], row[1], row[2] + response += row + response +='\r\n' + response += """ + + + + + +
+ Qual linha deseja mudar: +
+ Name: +
+ Content: +
+ +
+ + + """ + elif method == 'POST': + new_dict = urlparse.parse_qs(data) + print new_dict + rins1 = new_dict['name'][0] + rins2 = new_dict['content'][0] + rins3 = new_dict['line'][0] + print rins1 + print rins2 + print rins3 + con = lite.connect('datas.db') + with con: + cur = con.cursor() + cur.execute('UPDATE Notes SET Key=:name, Note=:content Where Id=:line', {'name':rins1, 'content':rins2, 'line':rins3}) + elif resource == '/add_note': response += 'Content-Type: text/html; charset=utf-8\r\n' response += '\r\n' @@ -84,25 +300,83 @@ """ elif method == 'POST': while True: - if len(data) != int (request_headers['content-length']): - data += conn.recv(1024) - else: - break - new_dict = urlparse.parse_qs(data) - note_dict[new_dict['name'][0]] = new_dict['content'][0] - with open('.notes', 'w') as note_file: - json.dump(note_dict, note_file) + if request_headers['content-type'] != 'application/x-www-form-urlencoded': + response = '' + response += 'HTTP/1.1 501 Not Implemeted\r\n' + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + response += """ + + + + + +

ERROR 501

+ + + """ + data = '1' + break + + if len(data) != int (request_headers['content-length']): + data += conn.recv(1024) + else: + break + if data != '1': + new_dict = urlparse.parse_qs(data) + note_dict[new_dict['name'][0]] = new_dict['content'][0] + with open('.notes', 'w') as note_file: + json.dump(note_dict, note_file) + + keyins = new_dict['name'][0] + notains = new_dict['content'][0] + listtoinsert = [] + listtoinsert.append(keyins) + listtoinsert.append(notains) + con = lite.connect('datas.db') + with con: + cur = con.cursor() + try: + cur.execute("INSERT INTO Notes(Key,Note) VALUES (?,?);", listtoinsert) + except lite.IntegrityError: + response = '' + response += 'HTTP/1.1 409 Conflict\r\n' + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + response += """ + + + + + +

ERROR 409

+ + + """ else: response += 'Content-Type: text/plain; charset=utf-8\r\n' response += '\r\n' try: - note_match = re.match('^/notes/([a-z]+)$', resource) + note_match = re.match('^/notes/([a-z0-9]+)$', resource) + #print note_match.group(1) if note_match is not None: - response += note_dict[note_match.group(1)] + if note_match.group(1).isalpha(): + response += note_dict[note_match.group(1)] + else: + print note_list + response += note_list[int(note_match.group(1))] + con = lite.connect('datas.db') + with con: + cur = con.cursor() + cur.execute('SELECT Note from Notes WHERE Id=:id',{'id': (int(note_match.group(1)) + 1)}) + row = cur.fetchone() + print row + response += row[0] + else: response += 'Hello World!!!' - except KeyError: + except (KeyError, IndexError): response = '' response += 'HTTP/1.1 404 Not Found\r\n' response += 'Content-Type: text/html; charset=utf-8\r\n' @@ -117,7 +391,6 @@ """ - conn.sendall(response) conn.close() From a05f51297587c75d8311eb099040703db08c7c49 Mon Sep 17 00:00:00 2001 From: Emerson Date: Sat, 9 May 2015 21:51:44 -0300 Subject: [PATCH 2/4] Fixed Integrity problem while registering and implemented 'Note editing' --- webnote.py | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/webnote.py b/webnote.py index ed36408..9b2b657 100644 --- a/webnote.py +++ b/webnote.py @@ -197,9 +197,25 @@ listtoinsert.append(username) listtoinsert.append(auth) con = lite.connect('datas.db') - with con: - cur = con.cursor() - cur.execute('INSERT INTO Users(Name,Password) VALUES(?,?)', listtoinsert) + try: + with con: + cur = con.cursor() + cur.execute('INSERT INTO Users(Name,Password) VALUES(?,?)', listtoinsert) + except lite.IntegrityError: + response = '' + response += 'HTTP/1.1 409 Conflict\r\n' + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + response += """ + + + + + +

ERROR 409

+ + + """ From f37b055d3f43f727b427209f88131e00103e2a5e Mon Sep 17 00:00:00 2001 From: Emerson Date: Mon, 11 May 2015 18:55:33 -0300 Subject: [PATCH 3/4] Fixed urlparse wrong sentences --- webnote.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webnote.py b/webnote.py index 9b2b657..2c63e5c 100644 --- a/webnote.py +++ b/webnote.py @@ -281,7 +281,7 @@ """ elif method == 'POST': - new_dict = urlparse.parse_qs(data) + new_dict = parse_qs(data) print new_dict rins1 = new_dict['name'][0] rins2 = new_dict['content'][0] @@ -339,7 +339,7 @@ else: break if data != '1': - new_dict = urlparse.parse_qs(data) + new_dict = parse_qs(data) note_dict[new_dict['name'][0]] = new_dict['content'][0] with open('.notes', 'w') as note_file: json.dump(note_dict, note_file) From ecc149d97c6563db77b5387ec8d0db645b9f70ca Mon Sep 17 00:00:00 2001 From: Emerson Date: Sun, 12 Jul 2015 23:06:12 -0300 Subject: [PATCH 4/4] fixed issue #1, #3, #4, #8, #9, #10 --- webnote.py | 408 ++++++++++++++++++++++++++--------------------------- 1 file changed, 199 insertions(+), 209 deletions(-) diff --git a/webnote.py b/webnote.py index 2c63e5c..17857ef 100644 --- a/webnote.py +++ b/webnote.py @@ -5,15 +5,15 @@ import sqlite3 as lite import httplib import base64 -#import string s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('0.0.0.0', 8080)) s.listen(1) -loged = 0 userloged = None +uid = 0 +con = lite.connect('datas.db') while True: data = '' @@ -27,10 +27,6 @@ break data += new_data - print 'DATA ORIGINAL\r\n', data - - print '---------------------------------------' - request_match = \ re.match(r'^([^ ]+) ([^ ]+) ([^ ]+)\r\n(.*)$', data, re.DOTALL) if request_match is not None: @@ -38,7 +34,6 @@ resource = request_match.group(2) protocol = request_match.group(3) data = request_match.group(4) - print data else: raise Exception('Cannot read request') @@ -62,9 +57,10 @@ response = '' response += 'HTTP/1.1 200 OK\r\n' - + + #linhas comentadas para previnir o uso de .notes + """ try: - #print 'userloged = ', userloged with open('.notes') as note_file: note_dict = json.loads(note_file.read()) except IOError: @@ -73,28 +69,16 @@ note_list = [] for key in note_dict: note_list.append(note_dict[key]) - + """ + try: - con = lite.connect('datas.db') with con: cur = con.cursor() - cur.execute("CREATE TABLE Notes(Id INTEGER PRIMARY KEY, Key TEXT UNIQUE NOT NULL, Note TEXT NOT NULL)") + cur.execute("CREATE TABLE Users(Id INTEGER PRIMARY KEY, Name TEXT UNIQUE NOT NULL, Password TEXT NOT NULL)") + cur.execute("CREATE TABLE Notes(Id INTEGER PRIMARY KEY, Key TEXT UNIQUE NOT NULL, Note TEXT NOT NULL, CodeUser INTEGER NOT NULL, FOREIGN KEY(CodeUser)REFERENCES Users(id))") except lite.OperationalError: pass - - - try: - con1 = lite.connect('datas.db') - with con1: - cur1 = con1.cursor() - cur1.execute("CREATE TABLE Users(Id INTEGER PRIMARY KEY, Name TEXT UNIQUE NOT NULL, Password TEXT NOT NULL)") - except lite.OperationalError: - pass - - print loged - print userloged - print resource - + if resource == '/auth': response += 'Content-Type: text/html; charset=utf-8\r\n' response += '\r\n' @@ -117,55 +101,53 @@ """ elif method == 'POST': - print data new_dict = parse_qs(data) username = new_dict['user'][0] password = new_dict['password'][0] - trying = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') - con = lite.connect('datas.db') + encoded = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') username = str(username) with con: - cur = con.cursor() - cur.execute('SELECT Password FROM Users WHERE Name=:name',{'name': username}) - row = cur.fetchall() - if row == None: - break - authent = row[0][0] - print authent - if trying == authent: - loged = 1 - userloged = username - print 'USERLOGED = ', userloged - print loged - response = '' - response += 'HTTP/1.1 418 I\'m a teapot\r\n' - response += 'Content-Type: text/html; charset=utf-8\r\n' - response += '\r\n' - response += """ - - - - - -

Sucess!

- - - """ - else: - response = '' - response += 'HTTP/1.1 401 Unauthorized\r\n' - response += 'Content-Type: text/html; charset=utf-8\r\n' - response += '\r\n' - response += """ - - - - - -

ERROR 401 - Unauthorized

- - - """ + cur = con.cursor() + cur.execute('SELECT Password FROM Users WHERE Name=:name',{'name': username}) + row = cur.fetchall() + if row == None: + break + authent = row[0][0] + if encoded == authent: + userloged = username + cur.execute('SELECT Id from Users WHERE Name=:username',{'username':userloged}) + uid = cur.fetchone(); + #a funcao reduce realiza operacoes cumulativas em uma sequencia, da esquerda pra direita, afim de se obter um unico valor + uid = reduce(lambda rst, d: rst * 10 + d, uid) + response = '' + response += 'HTTP/1.1 418 I\'m a teapot\r\n' + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + response += """ + + + + + +

Sucess!

+ + + """ + else: + response = '' + response += 'HTTP/1.1 401 Unauthorized\r\n' + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + response += """ + + + + + +

ERROR 401 - Unauthorized

+ + + """ elif resource == '/register': response += 'Content-Type: text/html; charset=utf-8\r\n' @@ -191,16 +173,15 @@ elif method == 'POST': new_dict = parse_qs(data) username = new_dict['name'][0] - password = new_dict['password'][0] + password = new_dict['password'][0].replace('\n','').replace(';','') auth = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') - listtoinsert = [] - listtoinsert.append(username) - listtoinsert.append(auth) - con = lite.connect('datas.db') + new_note = [] + new_note.append(username) + new_note.append(auth) try: with con: cur = con.cursor() - cur.execute('INSERT INTO Users(Name,Password) VALUES(?,?)', listtoinsert) + cur.execute('INSERT INTO Users(Name,Password) VALUES(?,?)', new_note) except lite.IntegrityError: response = '' response += 'HTTP/1.1 409 Conflict\r\n' @@ -220,79 +201,91 @@ elif resource == '/notes': - response += 'Content-Type: text/plain; charset=utf-8\r\n' - response += '\r\n' - for name in note_dict: - response += '%s\n' % name - #for count in range(0,len(note_list)): - # response += str(count + 1) + '\n' - con = lite.connect('datas.db') - with con: - cur = con.cursor() - cur.execute('SELECT Key FROM Notes') - while True: - rows = cur.fetchone() - if rows == None: - break - print rows - for row in rows: - response += row - response += '\r\n' - #print note_dict - #print note_list - #print note_list[1] + if (userloged): + response += 'Content-Type: text/plain; charset=utf-8\r\n' + response += '\r\n' + #linhas comentadas para nao mostrar os valores de .notes + #for name in note_dict: + # response += '%s\n' % name + with con: + cur = con.cursor() + cur.execute('SELECT Key FROM Notes where CodeUser=:id',{'id': uid}) + while True: + rows = cur.fetchone() + if rows == None: + break + for row in rows: + response += row + response += '\r\n' - elif resource == '/edit_note': + elif resource == '/edit_note' and userloged: response += 'Content-Type: text/html; charset=utf-8\r\n' response += '\r\n' if method == 'GET': - con = lite.connect('datas.db') with con: cur = con.cursor() - cur.execute('SELECT * FROM Notes;') - #con.text_factory = str + cur.execute('SELECT * FROM Notes WHERE CodeUser =:id',{'id':uid}) while True: - row = cur.fetchone() - if row == None: - break - row = list(row) - row = str(row) - print row - print row[0] - #response += row[0], row[1], row[2] - response += row - response +='\r\n' - response += """ - - - - - -
- Qual linha deseja mudar: -
- Name: -
- Content: -
- -
- - - """ + row = cur.fetchone() + if row == None: + break + row = list(row) + row = str(row) + response += row + response +='\r\n' + response += """ + + + + + +
+ Qual linha deseja mudar: +
+ Name: +
+ Content: +
+ +
+ + + """ elif method == 'POST': - new_dict = parse_qs(data) - print new_dict - rins1 = new_dict['name'][0] - rins2 = new_dict['content'][0] - rins3 = new_dict['line'][0] - print rins1 - print rins2 - print rins3 - con = lite.connect('datas.db') - with con: - cur = con.cursor() - cur.execute('UPDATE Notes SET Key=:name, Note=:content Where Id=:line', {'name':rins1, 'content':rins2, 'line':rins3}) + while True: + #pode haver uma concatenacao de dados e vir dados nao suportados + if request_headers['content-type'] != 'application/x-www-form-urlencoded': + response = '' + response += 'HTTP/1.1 501 Not Implemeted\r\n' + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + response += """ + + + + + +

ERROR 501

+ + + """ + unsuported = True + break + + if len(data) != int (request_headers['content-length']): + data += conn.recv(1024) + else: + break + + if unsuported != True: + new_dict = parse_qs(data) + key_insert = new_dict['name'][0].replace('\n','').replace(';','') + note_insert = new_dict['content'][0].replace('\n','').replace(';','') + id_where = new_dict['line'][0].replace('\n','').replace(';','') + with con: + cur = con.cursor() + #se tentar mudar uma linha que nao corresponda a este usuario, nao acontecera nada + cur.execute('UPDATE Notes SET Key=:name, Note=:content Where Id=:line AND CodeUser=:id', {'name':key_insert, 'content':note_insert, 'line':id_where, 'id':uid}) elif resource == '/add_note': response += 'Content-Type: text/html; charset=utf-8\r\n' @@ -316,83 +309,80 @@ """ elif method == 'POST': while True: - if request_headers['content-type'] != 'application/x-www-form-urlencoded': - response = '' - response += 'HTTP/1.1 501 Not Implemeted\r\n' - response += 'Content-Type: text/html; charset=utf-8\r\n' - response += '\r\n' - response += """ - - - - - -

ERROR 501

- - - """ - data = '1' - break + if request_headers['content-type'] != 'application/x-www-form-urlencoded': + response = '' + response += 'HTTP/1.1 501 Not Implemeted\r\n' + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + response += """ + + + + + +

ERROR 501

+ + + """ + unsuported = True + break + + if len(data) != int (request_headers['content-length']): + data += conn.recv(1024) + else: + break - if len(data) != int (request_headers['content-length']): - data += conn.recv(1024) - else: - break - if data != '1': - new_dict = parse_qs(data) - note_dict[new_dict['name'][0]] = new_dict['content'][0] - with open('.notes', 'w') as note_file: - json.dump(note_dict, note_file) - - keyins = new_dict['name'][0] - notains = new_dict['content'][0] - listtoinsert = [] - listtoinsert.append(keyins) - listtoinsert.append(notains) - con = lite.connect('datas.db') - with con: - cur = con.cursor() - try: - cur.execute("INSERT INTO Notes(Key,Note) VALUES (?,?);", listtoinsert) - except lite.IntegrityError: - response = '' - response += 'HTTP/1.1 409 Conflict\r\n' - response += 'Content-Type: text/html; charset=utf-8\r\n' - response += '\r\n' - response += """ - - - - - -

ERROR 409

- - - """ + if unsuported != True: + new_dict = parse_qs(data) + #linhas comentadas para previnir a escrita em .notes + #note_dict[new_dict['name'][0]] = new_dict['content'][0] + #with open('.notes', 'w') as note_file: + # json.dump(note_dict, note_file) + keyins = new_dict['name'][0] + notains = new_dict['content'][0] + codeuserins = uid + new_note = [] + new_note.append(keyins) + new_note.append(notains) + new_note.append(codeuserins) + with con: + cur = con.cursor() + try: + cur.execute("INSERT INTO Notes(Key,Note,CodeUser) VALUES (?,?,?);", new_note) + except lite.IntegrityError: + response = '' + response += 'HTTP/1.1 409 Conflict\r\n' + response += 'Content-Type: text/html; charset=utf-8\r\n' + response += '\r\n' + response += """ + + + + + +

ERROR 409

+ + + """ else: response += 'Content-Type: text/plain; charset=utf-8\r\n' response += '\r\n' try: note_match = re.match('^/notes/([a-z0-9]+)$', resource) - #print note_match.group(1) if note_match is not None: - if note_match.group(1).isalpha(): - response += note_dict[note_match.group(1)] - else: - print note_list - response += note_list[int(note_match.group(1))] - con = lite.connect('datas.db') - with con: - cur = con.cursor() - cur.execute('SELECT Note from Notes WHERE Id=:id',{'id': (int(note_match.group(1)) + 1)}) - row = cur.fetchone() - print row - response += row[0] + with con: + cur = con.cursor() + if note_match.group(1).isalpha(): + cur.execute('SELECT Note from Notes WHERE Key=:name AND CodeUser=:uid' ,{'name': note_match.group(1), 'uid': uid}) + else: + cur.execute('SELECT Note from Notes WHERE Id=:id AND CodeUser=:uid' ,{'id': (int(note_match.group(1)) + 1), 'uid': uid}) + row = cur.fetchone() + response += row[0] else: - response += 'Hello World!!!' - except (KeyError, IndexError): + response += 'Para uso adequado autenticar em /auth!!!' + except (KeyError, IndexError, TypeError): response = '' response += 'HTTP/1.1 404 Not Found\r\n' response += 'Content-Type: text/html; charset=utf-8\r\n' @@ -408,5 +398,5 @@ """ conn.sendall(response) - + unsuported = False; conn.close()