def account(): args["title"] = "My Account" args["reset_form"] = PasswordResetForm() if args["reset_form"].validate_on_submit(): username = session["user"] old_pwd = args["reset_form"].old_password.data if UserController.validate_pwd(username, old_pwd): new_pwd = args["reset_form"].new_password.data if UserController.reset_pwd(username, new_pwd): flash( "Your password has been changed Successfully! Please login again to continue.", "success") UserController.end_user_session() return redirect(url_for("login")) new_pwd = None flash( "An error occurred while resetting your password! Please try again.", "danger") return redirect(url_for("account")) old_pwd = None flash( "Your old password does not match our records. Please try again.", "danger") return redirect(url_for("account")) return display_page('account')
def share(self, username): tercerosData = self.receiveShare() if not (UserController.verifyFileExistance( tercerosData['nombreArchivo'], username)): self.connection.send({"operacion": "share", "resultado": "error"}) return fileName = tercerosData['nombreArchivo'] usuarios = tercerosData['usuarios'].split(",") usuariosExistentes = map(UserController.verifyExistance, usuarios) listUsuariosExistentes = list(usuariosExistentes) for i, u in enumerate(usuarios): if listUsuariosExistentes[i]: public_key = UserController.getPublicKey(u) self.connection.send({ "operacion": "envioUsuarios", "usuario": u, "publicKey": str(public_key) }) respuesta = self.receiveShare() if (respuesta['resultado'] == "OK"): claveEncriptada = respuesta['claveEncriptada'] # Username: El que esta logueado # U : Al que le estoy dando permiso # ClaveEncriptada : Clave pública del que le estoy dando permiso print("Permiso agregado con éxito") self.connection.send({"operacion": "finEnvioUsuarios"})
def recover(self): userName = self.receiveUsername() result = UserController.getEmail(userName) if result: codigo = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) MailUtil.sendRecovery(result, codigo) self.connection.send({ "operacion": "RecoveryCode", "resultado": "OK" }) cod = self.connection.receive() if (cod == codigo): self.connection.send({ "operacion": "ChangePassword", "resultado": "OK" }) newPassword = self.connection.receiveLogin() UserController.setNewPassword(userName, newPassword) self.connection.send("Contraseña cambiada con éxito") else: self.connection.send({ "operacion": "ChangePassword", "resultado": "ERROR" }) # Hecho asi , hay una sola oportunidad para poner el codigo correctamente else: self.connection.send({ "operacion": "RecoveryCode", "resultado": "ERROR" })
def main(): while True: Viewer.main_view("MAZE") ch = Viewer.main_select() if ch == '1': UserController.login() elif ch == '2': UserController.register() elif ch == '3': exit(1) elif ch == '4': TestingReport.report() else: print("INVALID INPUT!")
def login(): args["title"] = "Login" args["login_form"] = LoginForm() if args["login_form"].validate_on_submit(): username = args["login_form"].username.data pwd = args["login_form"].password.data if UserController.validate_pwd(username, pwd): pwd = None UserController.start_user_session(username) flash("Successfully logged in as " + username + "!", 'success') return redirect(url_for('home')) flash("Sorry, the login information provided was not correct", 'danger') return display_page("login", False)
def signin(): """ get user name and password from sign in fields send them to Controller to validate and return SignIn page on success or back to Index on Fail. Additionally, show the user data on his personal area.""" error = '' try: if request.method == 'POST': username = str(request.form['user']) password = str(request.form['passw']) userptr = UserController.User_Controller() resp = userptr.signin_handler(username,password) #Check type of user if resp == 404:#User not found error = 'Wrong username/password' return render_template("index.html",signin = error) elif resp == 100: error = 'Wrong UserName/Password format' return render_template("index.html",signin = error) else:#resp = 0 - OK #Insert data to the page Welcome {Name} + Data To the Table data = np.array(resp)#convert to numpy array return render_template("signin.html",signin=data) gc.collect() else: return render_template("index.html") except Exception as e: return render_template("index.html",error = error)
def test_contact_iteration(self): """Test contact iteration""" user_contacts = UserController.contact_iteration(3) self.assertEqual(user_contacts, [(u'4153417706', 5, u'Contact3', u'Test', 3), (u'4153417706', 5, u'Contact4', u'Test', 4)])
def download(self, username): response = self.connection.receive() listaFiles = UserController.verPropios(username) tercerosData = self.connection.send({ "operacion": "download", "listaArchivos": listaFiles }) respuesta = self.connection.receive() if respuesta[ 'operation'] == "download" and respuesta['resultado'] != "end": data = UserController.obtenerArchivoPropio(respuesta['filePath']) self.connection.send({ "operacion": "download", "dataArchivo": str(data) })
def test_contact_iteration(self): """Test contact iteration""" user_contacts = UserController.contact_iteration(3) self.assertEqual( user_contacts, [(u"4153417706", 5, u"Contact3", u"Test", 3), (u"4153417706", 5, u"Contact4", u"Test", 4)] )
def changePassword(self, username): oldPassword = self.connection.receive() if (UserController.login(username, oldPassword['old'])): self.connection.send({ "operacion": "ChangePassword", "resultado": "OK" }) newPassword = self.connection.receive() UserController.setNewPassword(username, newPassword['pw']) self.connection.send({ "operacion": "ChangePassword", "resultado": "OK" }) else: self.connection.send({ "operacion": "ChangePassword", "resultado": "ERROR" })
def downloadFrom(self, username): response = self.connection.receive() listaFiles = UserController.verCompartidos(username) tercerosData = self.connection.send({ "operacion": "downloadFrom", "listaArchivos": listaFiles }) respuesta = self.connection.receive() if respuesta['operation'] == "downloadFrom" and respuesta[ 'resultado'] != "end": data, key = UserController.obtenerArchivoDeTercero( respuesta['filePath'], username) self.connection.send({ "operacion": "downloadFrom", "dataArchivo": str(data), "key": key })
def register(self): registerData = self.receiveRegister() result = UserController.register(registerData['username'], registerData['email'], registerData['password']) if result: self.connection.send({"operacion": "Register", "resultado": "OK"}) public_key = self.connection.receive() bytes_as_bytes = eval(public_key['dataPubKey']) UserController.savePublicKey(public_key['pubKeyName'], bytes_as_bytes) self.connection.send({"operacion": "Pub_key", "resultado": "OK"}) # guardar clave secreta else: self.connection.send({ "operacion": "Register", "resultado": "ERROR" })
def display_page(page_name="home", login_required=True): args["active"] = page_name if login_required: if session.get("user"): return render_template("views/" + page_name + ".html", args=args) flash("You must be logged in to view this page!", 'warning') return redirect(url_for('login')) if UserController.check_session_refresh(): flash( "Your current user sessions has expired, please log in again to confirm your identity.", 'warning') return redirect(url_for('login')) return render_template("views/" + page_name + ".html", args=args)
def register(): args["title"] = "Register" args["registration_form"] = RegistrationForm() if args["registration_form"].validate_on_submit(): username = args["registration_form"].username.data if UserController.create_user("auto_gen", username, args["registration_form"].email.data, args["registration_form"].password.data): flash( "Your account [" + username + "] has been created! Please login to continue.", "success") return redirect(url_for("login")) else: flash("Account Creation Error. Please attempt to register again", "danger") return display_page("register", False)
def getTouzhuForPerson(self,person,name,qishu): sql = "select * from {0} where {1} = {2};".format(DBC.PSTAB,DBC.PSID,person) result = DBM.maka_do_sql(sql) if len(result) == 0: result = UserController.inertPersonWith(person, name, name) print '~~~~~~~~~~~~~~~~~~ 插入用户 ~~~~~~~~~~~~~~~~~~~~~~' else: tuple = result[0] touzhu = self.getRandom() currentTime = long(time.time()) currentTime = DU.time_to_date(currentTime) numbers = touzhu['numbers'] numbers = ','.join(numbers) sql = "insert into {0} ({1},{2},{3},{4},{5},{6},{7}) values ('{8}','{9}','{10}','{11}',{12},{13},{14})" \ .format(DBC.BLTAB,DBC.BLQI,DBC.BLTIME,DBC.BLROAD,DBC.BLNUMBER,DBC.BLMONEY,DBC.BLSTATUS,DBC.BLPERSON, \ qishu,currentTime,str(touzhu['road']),numbers,touzhu['beat'],0,person) DBM.maka_do_sql(sql) print '用户预测完成------------------------------------'
def signup(): """ Get user's input of all his data to sign him up. First of all chechks two inserted passwords and then go to DataAccess Layer to validate and insert DB """ error = '' try: if request.method == 'POST': uname = str(request.form['uname']) email = str(request.form['email']) pswdf = str(request.form['pswdf']) pswds = str(request.form['pswds']) if (pswdf != pswds): error = 'Your passwords are not equal!' return render_template("index.html", signup=error) #return error message else: fname = str(request.form['fname']) lname = str(request.form['lname']) address = "" if request.form['address'] == None else str( request.form['address']) number = str(request.form['number']) city = str(request.form['city']) zipCode = str(request.form['zip']) comments = str(request.form['comment']) userptr = UserController.User_Controller() #return values of errors! resp = userptr.signup_handler(uname, pswdf, email, fname, lname, number, address, city, zipCode, comments) error = "Succesfuly Registered!" return render_template("index.html", signin=error) gc.collect() else: return render_template("index.html") except Exception as e: return render_template("item.html", error=error)
def login(self): loggedIn = False for attempt in range(MAX_ATTEMPTS): self.connection.resetSecreto() loginData = self.receiveLogin() result = UserController.login(loginData['username'], loginData['password']) self.connection.secreto = eval(loginData['secret']) if result: self.connection.send({"Connection": "OK"}) loggedIn = True return loginData['username'] # guardar clave secreta elif attempt < MAX_ATTEMPTS - 1: self.connection.send({"Connection": "ERROR"}) if not loggedIn: # este seria un error distinto # bannear ip print(self.address, 'banned') self.connection.send({"Connection": "BAN"}) return None
def user_detail(user_id): """Show info about user.""" if 'user_id' not in session: return redirect("/") elif session['user_id'] != user_id: return redirect("/users/%s" % session['user_id']) user = User.query.get(user_id) contacts = UserController.contact_iteration(user_id) languages = Language.lang_iteration() existing_message = "" if len(contacts) == 0: flash("The user has no contacts, you need to add one") return redirect("/users/%s/add_contact" % user_id) return render_template("contact_edit.html", user=user, user_id=user_id, contacts=json.dumps(contacts), contact_objects = contacts, languages=json.dumps(languages), existing_message=existing_message, user_img=user.get_user_img())
def google_login(): request_data = request.get_json() if "id_token" in request_data: is_verified = OAuthController.verify_token(request_data["id_token"]) if is_verified: user_details = OAuthController.check_existing_user( is_verified["user_email"], is_verified["user_token"]) if user_details["existing_user"]: UserController.start_user_session(user_details["username"]) # Notifies client of successful User Authentication request_data["found_user"] = True return request_data # Auto creates User account from minimal Google information UserController.create_user(is_verified["user_id"], user_details["username"], is_verified["user_email"], is_verified["user_token"]) UserController.start_user_session(user_details["username"]) request_data["found_user"] = False request_data["username"] = user_details["username"] return request_data return display_page("home", False)
import UserController import mysql.connector as mysql import json import User connect = mysql.connect(host="localhost", user="******", passwd="Hahaha01670", auth_plugin='mysql_native_password', database="inventorymanagement") testUserController = UserController.UserController(connect) print(testUserController.printUserTable())
def logout(): UserController.end_user_session() flash("You have been logged out!", 'info') return redirect(url_for('home'))
def getLoginData(self): data = UserController.getCredentials() self.connection.secreto = os.urandom(31) data['secret'] = str(self.connection.secreto) self.username = data['username'] return data
def validate_username(self, username): if not UserController.get_user(username=username.data): raise ValidationError( "This account does not exists. Please re-enter an existing account username." )
def validate_email(self, email): if UserController.get_user(email=email.data): raise ValidationError( "This email address is already in use. Please login instead.")
def validate_username(self, username): if UserController.get_user(username=username.data): raise ValidationError( "This username is already in use. Please select a new one.")