def authenticate_user(self): try: print(self.path, type(self.path)) if self.path in [ '/note/api/createdata', '/api/note/delete', '/api/note/update', 'api/note/read', '/api/profile' ]: token = self.headers['token'] print(token) payload = jwt.decode(token, "secret", algorithms='HS256') print(payload) id_key = payload['id'] print(id_key) redis_obj = RedisService() token = redis_obj.get(id_key) print(token, '------->token') if token is None: raise ValueError("You Need To Login First") return method(self) else: return method(self) except jwt.ExpiredSignatureError: res = response(message="Signature expired. Please log in again.") Response(self).jsonResponse(status=404, data=res) except jwt.DecodeError: res = response(message="DecodeError") Response(self).jsonResponse(status=404, data=res) except jwt.InvalidTokenError: res = response(message="InvalidTokenError") Response(self).jsonResponse(status=404, data=res)
def login(self): """ Here User can login and if The username already exists then it will give response or else it will give response of Login done successfully no return :return: """ global jwt_token form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) response_data = {'success': True, "data": [], "message": ""} form_keys = list(form.keys()) if len(form_keys) < 2: response_data.update({ 'success': False, "data": [], "message": " some values are missing" }) Response(self).jsonResponse(status=404, data=response_data) data = {} data['username'] = form['username'].value data['password'] = form['password'].value success = my_db_obj.username_exists(data) if success: my_db_obj.login_user(data) username = data['username'] payload = { 'username': username, 'exp': datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS) } encoded_token = jwt.encode(payload, 'secret', 'HS256').decode('utf-8') response_data.update({ 'success': True, "data": [], "message": "Login Done Successfully Generated Token", 'token': encoded_token }) # response_data.update({"message": "Login done successfully"}) Response(self).jsonResponse(status=202, data=response_data) return encoded_token else: response_data.update({ "message": "Username already exists", "success": False }) Response(self).jsonResponse(status=202, data=response_data)
def do_POST(self): if self.path == '/register': obj = registration obj.register(self) elif self.path == '/login': obj = registration obj.login(self) elif self.path == '/forgot': obj = registration obj.forgot_password(self) elif '/reset' in self.path: from urllib.parse import urlparse, parse_qs query_components = parse_qs(urlparse(self.path).query) token = query_components["token"][0] token = jwt.decode(token, "secret", algorithms='HS256') key = token["email_id"] print(key) obj = registration obj.store(self, key) elif self.path == '/insert': obj = registration print(self.headers['token']) catch = self.headers['token'] flag = obj.auth(self, catch) if flag: obj = registration obj.insert(self) else: response_data = {'success': False, "data": [], "message": "User Should have to register"} Response(self).jsonResponse(status=404, data=response_data) elif self.path == '/create': obj = registration obj.create(self) elif self.path == '/profile': # self.send_response(200) # self.send_header("Content-type", "image/jpg") # self.send_header("Content-length", 20) # self.end_headers() # print(self.send_header) obj = registration obj.updateProfile(self) else: response_data = {'success': False, "data": [], "message": "URL Invalid"} Response(self).jsonResponse(status=404, data=response_data)
def login_user(self): """ Here User can login and if The username already exists then it will give response or else it will give response of Login done successfully no return :return: """ object = DbManaged() # global jwt_token form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) form_keys = list(form.keys()) if 'email' and 'password' in form_keys: data = {} data['email'] = form['email'].value data['password'] = form['password'].value email = data['email'] id, email = object.read_email(email=email) print(id, '--------->id') if id: payload = { 'id': id, 'exp': datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS) } encoded_token = jwt.encode(payload, 'secret', 'HS256').decode('utf-8') redis_obj = RedisService() # id_key = id[0] redis_obj.set(id, encoded_token) print(redis_obj.get(id), '------------->r.get') res = response(success=True, message="Login Successfully", data=[{ "token": encoded_token }]) Response(self).jsonResponse(status=200, data=res) else: Response(self).jsonResponse( status=400, data=response(message="credentials are missing"))
def do_GET(self): # self._set_headers() if self.path == '/register': with open('templates/register.html', 'r') as f: html_string_register = f.read() self.wfile.write(self._html(html_string_register)) elif self.path == '/login': with open('templates/login.html', 'r') as f: html_string_login = f.read() self.wfile.write(self._html(html_string_login)) elif self.path == '/forgot': with open('templates/forgot.html', 'r') as f: html_string_login = f.read() self.wfile.write(self._html(html_string_login)) elif '/reset' in self.path: from urllib.parse import urlparse, parse_qs query_components = parse_qs(urlparse(self.path).query) token = query_components["token"][0] with open('templates/reset.html', 'r') as f: html_string_register = f.read() output = html_string_register.format(result=token) self.wfile.write(self._html(output)) elif self.path == '/upload': # with open('templates/profileupload.html', 'r') as f: # html_string_register = f.read() Response(self).html_response(status=200, data=self._html()) elif self.path == '/listing': obj = user catch, respon, res = obj.listing_notes(self) response_data = { 'success': True, "data": [], "message": "This is listing Of is_pinned{}{}{}".format( catch, respon, res) } Response(self).jsonResponse(status=404, data=response_data) else: # response_data = {'success': False, "data": [], "message": "URL Invalid"} # Response(self).jsonResponse(status=404, data=response_data) with open('templates/error.html', 'r') as f: html_string_register = f.read()
def register(self): """ Here Registration of the user is done and it will check if the customers email is existing in database or not if present response is sent and if not present registration is done no return type:return: """ form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) response_data = {'success': True, "data": [], "message": ""} form_keys = list(form.keys()) if len(form_keys) < 3: response_data.update({ 'success': False, "data": [], "message": " some values are missing" }) Response(self).jsonResponse(status=404, data=response_data) data = {} data['email'] = form['email'].value data['password'] = form['password'].value data['confirm_password'] = form['confirm_password'].value success = my_db_obj.email_address_exists(data) present = my_db_obj.email_validate(form['email'].value) if not present: response_data.update({ "message": "Email Format is Invalid please Re-enter Email", "success": False }) Response(self).jsonResponse(status=202, data=response_data) else: if success: my_db_obj.registration(data) response_data.update({ "success": True, "data": [], "message": "Registration Done Successfully" }) Response(self).jsonResponse(status=202, data=response_data) else: response_data.update({ "message": "Email Already Exists", "success": False }) Response(self).jsonResponse(status=202, data=response_data)
def register_user(self): """ Here Registration of the user is done and it will check if the customers email is existing in database or not if present response is sent and if not present registration is done no return type:return: """ form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) response_data = {'success': True, "data": [], "message": ""} form_keys = list(form.keys()) if len(form_keys) < 2: response_data.update({ 'success': False, "data": [], "message": " some values are missing" }) Response(self).jsonResponse(status=404, data=response_data) data = {} data['email'] = form['email'].value data['password'] = form['password'].value email = data['email'] password = data['password'] id = object.read_email(email) present = object.email_validate(email) catch_response = obj.register_logic(data, id, present) return catch_response
def insert_note(self): """ Here record is inserted in table and response is shown :return: """ print(self.headers['token'], '---->token') token = self.headers['token'] payload = jwt.decode(token, 'secret', algorithms='HS256') print(payload) id = payload['id'] print(id, '------>id') form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) data = {} data['tittle'] = form['tittle'].value data['description'] = form['description'].value data['color'] = form['color'].value data['is_pinned'] = form['is_pinned'].value data['is_archived'] = form['is_archived'].value data['is_trashed'] = form['is_trashed'].value data['user_id'] = id object.query_insert(data) response_data = { 'success': True, "data": [], "message": "Inserted Successfully" } Response(self).jsonResponse(status=404, data=response_data)
def insert(self): """ Here record is inserted in table and response is shown :return: """ form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) data = {} print("hcduhc") data['tittle'] = form['tittle'].value data['description'] = form['description'].value data['color'] = form['color'].value data['isPinned'] = form['isPinned'].value data['isArchive'] = form['isArchive'].value data['isTrash'] = form['isTrash'].value print(data) my_db_obj.query_insert(data) response_data = { 'success': True, "data": [], "message": "Inserted Successfully" } Response(self).jsonResponse(status=404, data=response_data)
def updateProfile(self): object = DbManaged() print(self.headers['token'], '---->token') token = self.headers['token'] payload = jwt.decode(token, 'secret', algorithms='HS256') print(payload) id = payload['id'] print(id, '------>id') form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) data = {} # pdb.set_trace() data['profile_path'] = form['profile_path'].value data['user_id'] = id key = data['user_id'] # image = base64.b64encode(data['path']) # valid_image = image.decode("utf-8") flag = object.validate_file_extension(data) check = object.validate_file_size(data) # valid_image = image.decode("utf-8") # sql = "INSERT INTO Picture(path) VALUES (%s)" # val = (data['path']) # # obj = db_connection() # my_db_obj.queryExecute(sql, val) object.update_profile(data, key) # print(flag) # print(check) if flag and check: response_data = { 'success': True, "data": [], "message": "Profile Updated Successfully" } Response(self).jsonResponse(status=404, data=response_data) else: response_data = { 'success': True, "data": [], "message": "Unsupported file extension" } Response(self).jsonResponse(status=404, data=response_data)
def do_DELETE(self): """ This function is used for deleting the data from the database. """ note_details = NoteDetails if self.path == '/note/api/delete': response_data=note_details.delete_data(self) Response(self).jsonResponse(status=200, data=response_data)
def do_PUT(self): """ This function is used for updating data in the database. """ note_details = NoteDetails if self.path == '/note/api/update': response_data=note_details.update_data(self) Response(self).jsonResponse(status=200, data=response_data)
def do_GET(self): """ This do_get method is used to request data from server. """ self._set_headers() note_details=NoteDetails if self.path == '/register': with open("templates/registration.html") as file: html_string_register = file.read() self.wfile.write(self._html(html_string_register)) if self.path == '/login': with open("templates/login.html") as file: html_string_login = file.read() self.wfile.write(self._html(html_string_login)) if self.path == '/forgotpassword': with open("templates/forgotpassword.html") as file: html_string_fp = file.read() self.wfile.write(self._html(html_string_fp)) elif 'new' in self.path: from urllib.parse import urlparse, parse_qs query_comp = parse_qs(urlparse(self.path).query) token = query_comp["new"][0] with open('templates/resetpassword.html') as f: html_string_register = f.read() output = html_string_register.format(result=token) self.wfile.write(self._html(output)) if self.path == '/note/api/read': responsee = note_details.read_data(self) Response(self).jsonResponse(status=200, data=responsee) if self.path == '/note/api/trash': responsee=note_details.is_trash(self) Response(self).jsonResponse(status=200, data=responsee) if self.path == '/note/api/pinned': responsee=note_details.is_pinned(self) Response(self).jsonResponse(status=200, data=responsee) if self.path == '/note/api/archive': responsee=note_details.is_archive(self) Response(self).jsonResponse(status=200, data=responsee)
def authenticate_user(self): """ this function is used to decode and check whether the user is authorized user or not :param catch: True:return: """ try: print(self.path, type(self.path)) if self.path in [ '/api/note/insert', '/api/note/delete', '/api/note/update' ]: print("gcsyudch") token = self.headers['token'] payload = jwt.decode(token, "secret", algorithms='HS256') print(payload) id = payload['id'] redis_obj = RedisService() token = redis_obj.get(id) print(token, '------->token') if token is None: raise ValueError("You Need To Login First") return method(self) else: return method(self) except jwt.ExpiredSignatureError: # return 'Signature expired. Please log in again.' # response['message']="Signature expired. Please log in again." res = response(message="Signature expired. Please log in again.") Response(self).jsonResponse(status=404, data=res) except jwt.DecodeError: # return "Wrong Token" res = response(message="DecodeError") Response(self).jsonResponse(status=404, data=res) except jwt.InvalidTokenError: # return 'Invalid token. Please log in again.' res = response(message="InvalidTokenError") Response(self).jsonResponse(status=404, data=res)
def do_DELETE(self): if self.path == '/delete': obj = registration print(self.headers['token']) catch = self.headers['token'] flag = obj.auth(self, catch) if flag: obj = registration obj.delete(self) else: response_data = {'success': False, "data": [], "message": "User Should have to register"} Response(self).jsonResponse(status=404, data=response_data)
def forgot_password(self): """ Here if User Forgot Password so can change password and here If want to reset he have to give email and then link will be sent to email and with that link the password will be reset no return :return: """ global my_db_obj form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) response_data = {'success': True, "data": [], "message": ""} # my_db_obj = DbManaged() data = {} data['email'] = form['email'].value present = my_db_obj.email_address_exists(data) if present: response_data.update({ "success": False, "message": "Wrong Credentials" }) Response(self).jsonResponse(status=202, data=response_data) else: email = data['email'] encoded = jwt.encode({ "email_id": email }, 'secret', algorithm='HS256').decode("utf-8") message = f"http://127.0.0.1:8888/reset/?token={encoded}" my_db_obj.smtp(email, message) response_data.update({ "success": True, "message": "Successfully sent mail" }) Response(self).jsonResponse(status=202, data=response_data)
def updateProfile(self): form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) data = {} # pdb.set_trace() data['path'] = form['path'].value data['id'] = form['id'].value # image = base64.b64encode(data['path']) # valid_image = image.decode("utf-8") flag = my_db_obj.validate_file_extension(data) check = my_db_obj.validate_file_size(data) # valid_image = image.decode("utf-8") # sql = "INSERT INTO Picture(path) VALUES (%s)" # val = (data['path']) # # obj = db_connection() # my_db_obj.queryExecute(sql, val) my_db_obj.update_profile(data) # print(flag) # print(check) if flag and check: response_data = { 'success': True, "data": [], "message": "Profile Updated Successfully" } Response(self).jsonResponse(status=404, data=response_data) else: response_data = { 'success': True, "data": [], "message": "Unsupported file extension" } Response(self).jsonResponse(status=404, data=response_data)
def do_DELETE(self): if self.path == '/api/note/delete': obj = user catch = self.headers['token'] flag = obj.authenticate_user(self, catch) if flag: obj = user obj.delete_note(self) else: response_data = { 'success': False, "data": [], "message": "User Should have to register" } Response(self).jsonResponse(status=404, data=response_data)
def delete(self): """ Here record is Deleted in table and response is shown no return:return: """ form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) data = {} data['id'] = form['id'].value my_db_obj.query_delete(data) response_data = { 'success': True, "data": [], "message": "Deleted Successfully" } Response(self).jsonResponse(status=404, data=response_data)
def create_note(self): """ Here creation of table is done and response is shown no return:return: """ form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': "POST", 'CONTENT_TYPE': self.headers['Content-Type'], }) data = {} data['tablename'] = form['tablename'].value object.query_create(data) response_data = { 'success': True, "data": [], "message": "created table Successfully" } Response(self).jsonResponse(status=404, data=response_data)
def store(self, key): """ here password will be updated and response will be show password updated Successfully no return:return: """ form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) data = {} data['password'] = form['password'].value my_db_obj.update_password(data, key) response_data = { 'success': False, "data": [], "message": "Password Updated Successfully" } Response(self).jsonResponse(status=404, data=response_data)
def read_note(self): """ Here record is Read in table and response is shown no return:return: """ object = DbManaged() form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) data = {} data['tablename'] = form['tablename'].value print(data) object.query_read(data) response_data = { 'success': True, "data": [], "message": "Read Successfully" } Response(self).jsonResponse(status=404, data=response_data)
def do_POST(self): """ This do_post method is used for submitting the data to be processed to server. """ version = self.protocol_version user_details = UserDetails note_details=NoteDetails if self.path == '/register': response_data = user_details.for_registration(self) Response(self).jsonResponse(status=200, data=response_data) if self.path == '/login': response_data=user_details.for_login(self) Response(self).jsonResponse(status=200, data=response_data) if self.path == '/forgotpassword': response_data=user_details.forgot_password(self, version) Response(self).jsonResponse(status=200, data=response_data) elif 'new' in self.path: from urllib.parse import urlparse, parse_qs query_comp = parse_qs(urlparse(self.path).query) token = query_comp["new"][0] tokenn = jwt.decode(token, 'secret', algorithm='HS256') user_details.set_password(self, tokenn['email']) response_data = user_details.set_password(self, version) Response(self).jsonResponse(status=200, data=response_data) if self.path == '/note/api/createdata': responsee=note_details.create_data(self) Response(self).jsonResponse(status=200, data=responsee) if self.path == '/note/api/profilepicture': responsee=user_details.create_picture(self) Response(self).jsonResponse(status=200, data=responsee)
def do_POST(self): if self.path == '/register': obj = user response_data = obj.register_user(self) Response(self).jsonResponse(status=404, data=response_data) elif self.path == '/login': obj = user obj.login_user(self) elif self.path == '/forgot': obj = user obj.forgot_password(self) elif '/reset' in self.path: try: from urllib.parse import urlparse, parse_qs query_components = parse_qs(urlparse(self.path).query) token = query_components["token"][0] print(token) token = jwt.decode(token, "secret", algorithms='HS256') key = token["email_id"] obj = user obj.update_confirmation(self, key) except json.decoder.JSONDecodeError: response_data = { 'success': False, "data": [], "message": "Json decode Error raised" } Response(self).jsonResponse(status=404, data=response_data) except jwt.exceptions.DecodeError: response_data = { 'success': False, "data": [], "message": "JWT decode error raised" } Response(self).jsonResponse(status=404, data=response_data) elif self.path == '/api/note/insert': print('--->here') obj = user obj.insert_note(self) # response_data = {'success': False, "data": [], "message": "User Should have to register"} # Response(self).jsonResponse(status=404, data=response_data) elif self.path == '/api/profile': print(self.headers) token = self.headers['token'] payload = jwt.decode(token, "secret", algorithms='HS256') print(payload) id = payload['id'] ctype, pdict = cgi.parse_header(self.headers.get('content-type')) pdict['boundary'] = bytes(pdict['boundary'], "utf-8") if ctype == 'multipart/form-data': form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) filename = form['upfile'].filename data = form['upfile'].file.read() open("./media/%s" % filename, "wb").write(data) profile_data = { 'profile_path': f'./media/{filename}', 'id': id } from model.dbmanipulate import DbManaged obj = DbManaged() obj.update_profile(profile_data) else: response_data = { 'success': False, "data": [], "message": "URL Invalid" } Response(self).jsonResponse(status=404, data=response_data)