def support(): searchForm = SearchForm() form = SupportForm() if form.validate_on_submit(): if request.content_type != r'application/x-www-form-urlencoded': log.logger.error('Incorrect request content format at /support route') abort(404) if utils.banned_characters(form.subject.data) or utils.banned_characters(form.message.data,matches='[/\\<>%=]') or utils.banned_characters(form.name.data) or utils.banned_characters(form.email.data): log.logger.critical('Malicious character detected in support route') abort(404) try: if os.environ.get('IS_PROD', None): utils.mailgun_send_messageV2('*****@*****.**', form.subject.data, form.message.data,form.email.data) else: mail = Mail(current_app) msg = Message( subject=form.subject.data, recipients=['*****@*****.**'], body=form.message.data, sender=form.name.data, reply_to=form.email.data ) mail.send(msg) flash('Email has sent to u') resp = make_response(redirect(request.url)) if resp.headers['Location'] == '/support': return resp except Exception as message: print(message) #log.logger.exception(message) return render_template('support.html',searchForm=searchForm,form=form)
def edit(productid): if request.method == 'POST': name = request.form['Name'] description = request.form['Description'] stock = request.form['stock'] price = request.form['price'] Image = request.files['Image'] Image2 = request.files['Image2'] model = request.form['model'] product = AdminModels.Product.query.filter_by(productid=productid).first() if utils.banned_characters(name) or utils.banned_characters(description) or utils.banned_characters(model): flash('Suspcious character detected. Please do not try to do malicious stuff') return redirect('/admin/product/edit') if name == '' or description == '' or model == '': flash('Please fill in everything') return redirect('/admin/product/edit/?id={0}&url=%2Fadmin%2Fproduct%2F'.format(product.productid)) if price == '' or stock == '': flash('Stock or price must be integer') return redirect('/admin/product/edit/?={0}&url=/admin/product/'.format(product.productid)) if Image.filename == '' or Image2.filename == '': flash('No selected file') return redirect(url_for('product.edit_view')) if Image and Image2 and utils.allowed_file(Image.filename) and utils.allowed_file(Image2.filename): if product.model == model: product.Name = name product.Description = description product.stock= stock product.price = price ImageName = secure_filename(Image.filename) ImageName2 = secure_filename(Image2.filename) path = os.path.join(current_app.config['UPLOAD_FOLDER'], ImageName) path2 = os.path.join(current_app.config['UPLOAD_FOLDER'], ImageName2) Image.save(path) Image2.save(path2) product.Image = ImageName product.Image2 = ImageName2 product.model = model AdminModels.database.session.commit() return redirect(url_for('product.index_view')) else: models = AdminModels.Product.query.filter_by(model=model).first() if models is None: product.Name = name product.Description = description product.stock = stock product.price = price ImageName = secure_filename(Image.filename) ImageName2 = secure_filename(Image2.filename) path = os.path.join(current_app.config['UPLOAD_FOLDER'], ImageName) path2 = os.path.join(current_app.config['UPLOAD_FOLDER'], ImageName2) Image.save(path) Image2.save(path2) product.Image = ImageName product.Image2 = ImageName2 product.model = model AdminModels.database.session.commit() return redirect(url_for('product.index_view'))
def current(): searchForm = SearchForm() if current_user.is_authenticated: form = ChangePasswordForm() if form.validate_on_submit(): if request.content_type != r'application/x-www-form-urlencoded': log.logger.error('Incorrect request content format at /current route') abort(404) if utils.banned_characters(form.currentPassword.data): log.logger.critical('Malicious character detected in support route. An attempt to inject is possible') abort(404) user = Models.Customer.query.filter_by(username=current_user.username).first() saved_hash= user.password_hash password_hashed = utils.generate_hash(form.currentPassword.data,user.password_salt) if saved_hash == password_hashed: if utils.banned_characters(form.confirm.data.upper(),matches='({0})'.format(str(escape(current_user.username.upper())))): flash('Password should not contain anything related to your username. Please try again!') resp = make_response(redirect(url_for('current_password'))) if resp.headers['Location'] == '/current': return resp elif utils.read_common_password(form.confirm.data) or utils.banned_characters(form.confirm.data.upper(),matches='(PASSWORD)') or utils.banned_characters(form.confirm.data.upper(), matches='(PASSWORD)') or utils.banned_characters(form.confirm.data.upper(), matches='(ADMIN)'): flash('This password is either too common and subsceptiple to hackers or password contain words like \"username\" or \"password\" or \"admin\"') resp = make_response(redirect(url_for('current_password'))) if resp.headers['Location'] == '/current_password': return resp else: try: user = Models.Customer.query.filter_by(username=current_user.username).first() new_salt = utils.generate_salt() new_hash = utils.generate_hash(form.confirm.data,new_salt) user.password_salt = new_salt user.password_hash = new_hash Models.database.session.commit() logout_user() session.destroy() flash('Password has changed,please try to login with new credential') resp = make_response(redirect(url_for('login'))) if resp.headers['Location'] == '/login': return resp except: Models.database.session.rollback() else: flash('Invalid current password') resp = make_response(redirect(url_for('current_password'))) if resp.headers['Location'] == '/current': return resp else: abort(404)
def login(): searchForm = SearchForm() if current_user.is_authenticated: # print(current_user.username) abort(404) errors = '' form = LoginForm() if form.validate_on_submit(): if utils.banned_characters( form.username.data) or utils.banned_characters( form.password.data): log.logger.critical( 'Malicious characters such as \'\"<>#/ detected') errors = 'Invalid username or password' return redirect(url_for('login')) user = Models.Customer.query.filter_by( username=str(escape(form.username.data))).first() if user != None: saved_password_hash = user.password_hash saved_password_salt = user.password_salt password_hash = utils.generate_hash( str(escape(form.password.data)), saved_password_salt) if password_hash == saved_password_hash: if user.verified == 1: print('verified authen') u = Models.Customer.query.get(user.userid) login_user(u) response = make_response(redirect(url_for('home_page'))) log.logger.info( '{0} successfully logs into his account'.format( u.username)) return redirect(url_for('home_page')) else: u = Models.Customer.query.get(user.userid) login_user(u) log.logger.warning( '{0} successfully logs into his account without activating it' .format(u.username)) return redirect(url_for('users.unconfirmed')) else: errors = 'Invalid username or password' else: errors = 'Invalid username or password' else: print(form.errors) return render_template('login.html', form=form, errors=errors, searchForm=searchForm)
def product_create(): if request.method == 'POST': name = request.form['Name'] description = request.form['Description'] stock = request.form['stock'] price = request.form['price'] Image = request.files['Image'] Image2 = request.files['Image2'] model = request.form['model'] products = AdminModels.Product.query.filter_by(model=model).first() if products is None: if utils.banned_characters(name) or utils.banned_characters(description) or utils.banned_characters(model) : flash('Suspcious character detected. Please do not try to do malicious stuff') return redirect('/admin/product/new') if name == '' or description == '' or model =='': flash('Please fill in everything') return redirect('/admin/product/new') if price == '' or stock == '': flash('Stock or price must be integer') return redirect('/admin/product/new') if Image.filename=='' or Image2.filename == '': flash('No selected file') return redirect('/admin/product/new') if Image and Image2 and utils.allowed_file(Image.filename) and utils.allowed_file(Image2.filename): ImageName = secure_filename(Image.filename) ImageName2 = secure_filename(Image2.filename) path = os.path.join(current_app.config['UPLOAD_FOLDER'], ImageName) path2 = os.path.join(current_app.config['UPLOAD_FOLDER'], ImageName2) Image.save(path) Image2.save(path2) product = AdminModels.Product(name, description, stock, price, ImageName, ImageName2,model) AdminModels.database.session.add(product) AdminModels.database.session.commit() return redirect(url_for('product.index_view')) else: flash('Inappoporiate file type') return redirect('/admin/product/new') else: flash('This model has already exist in our inventory') return redirect('/admin/product/new')
def search(): searchForm = SearchForm() if searchForm.validate_on_submit(): if utils.banned_characters(searchForm.search.data): log.logger.critical('Malicious character detected in search') abort(404) if request.content_type != r'application/x-www-form-urlencoded': print('dd') abort(404) query = searchForm.search.data resp = make_response(redirect(url_for('search_result',query=escape(query)))) return resp
def accountUpdate(username): if current_user.is_authenticated and current_user.username == username: form = AccountForm() searchForm = SearchForm() if form.validate_on_submit(): if utils.banned_characters(form.credit_card.data): log.logger.critical('Malicious Character detected in /profile/{0}/account/update'.format(username)) logout_user() abort(404) if request.content_type != 'application/x-www-form-urlencoded': log.logger.error('Incorrect content type format found in /profile/{0}/account/update'.format(username)) abort(404) key_vault = vault.Vault() # try: # key_vault.key_client.get_key(username) # except: # key_vault.set_key(username,4096,key_vault.key_ops) user = Models.Customer.query.filter_by(username=username).first() user.account.payment_method = form.payment_method.data user.account.credit_card = bytes(form.credit_card.data,'utf-8') #key_vault.encrypt(username,form.credit_card.data) user.account.address = form.address.data log.logger.info(f'{user.username} has changed his account information.') Models.database.session.commit() key_vault.key_client.close() key_vault.secret_client.close() log.logger.info('{0} successfuly updated his/her account'.format(user.username)) resp = make_response(redirect(url_for('account',username=username))) print(resp.headers['Location']) if resp.headers['Location'] == '/profile/'+current_user.username+'/account': return resp else: log.logger.exception(form.errors) print(form.errors) return render_template('accountUpdate.html', form=form,searchForm=searchForm) else: abort(404)
def register(): if current_user.is_authenticated: abort(404) searchForm = SearchForm() form = RegisterForm() if form.validate_on_submit(): print('fkffkfkfk') if request.content_type != r'application/x-www-form-urlencoded': log.logger.error('Incorrect content type format') abort(404) if utils.banned_characters(form.username.data) or utils.banned_characters(form.password.data) or utils.banned_characters(form.fname.data) or utils.banned_characters(form.lname.data) or utils.banned_characters(form.email.data): print('d') log.logger.critical('Malicious characters detected in register form',extra={'custom_dimensions': {'Source': request.remote_addr}}) abort(404) if utils.banned_characters(form.confirm.data.upper(),matches='({0})'.format(str(escape(form.username.data.upper())))): flash('Password should not contain anything related to your username. Please try again!') resp = make_response(redirect(url_for('register'))) if resp.headers['Location'] == '/register': return resp if os.environ.get('IS_PROD',None): if utils.banned_characters(form.confirm.data.upper(),matches='(PASSWORD)') or utils.banned_characters(form.confirm.data.upper(), matches='(PASSWORD)') or utils.banned_characters(form.confirm.data.upper(),matches='(ADMIN)') or utils.banned_characters(form.confirm.data.upper(),matches='(USERNAME)'): flash('This password is either too common and subsceptiple to hackers or password contain words like \"username\" or \"password\" or \"admin\"') resp = make_response(redirect(url_for('register'))) if resp.headers['Location'] == '/register': return resp else: if utils.read_common_password(form.confirm.data) or utils.banned_characters(form.confirm.data.upper(),matches='(PASSWORD)') or utils.banned_characters(form.confirm.data.upper(),matches='(PASSWORD)') or utils.banned_characters(form.confirm.data.upper(),matches='(ADMIN)') or utils.banned_characters(form.confirm.data.upper(),matches='(USERNAME)'): flash('This password is either too common and subsceptiple to hackers or password contain words like \"username\" or \"password\" or \"admin\"') resp = make_response(redirect(url_for('register'))) if resp.headers['Location'] == '/register': return resp # du[;ication check username = Models.Customer.query.filter_by(username=str(escape(form.username.data))).first() email = Models.Customer.query.filter_by(email=str(escape(form.email.data))).first() if email is None and username is None: user = '' eresponse='' presponse='' print('wtf') if not os.environ.get('IS_PROD'): wrap_key = classification.get_wrapped_key("seismic-helper-301408", "global", "ispj", "ISPJ_KEY") #eresponse = classification.deidentify("seismic-helper-301408",form.email.data,"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ~`!@#$%^&*()_-+={[}]|:;'<,>.?/\"",wrap_key,["EMAIL_ADDRESS"],"##") presponse = classification.deidentify("seismic-helper-301408",form.fname.data,"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ~`!@#$%^&*()_-+={[}]|:;'<,>.?/\"",wrap_key,["FIRST_NAME"],"##") print(presponse) print('dog') try: if not os.environ.get('IS_PROD'): user = Models.Customer(str(escape(form.username.data)),presponse.item.value,form.lname.data,form.contact.data,str(escape(form.confirm.data)),0,form.email.data) else: user = Models.Customer(str(escape(form.username.data)),str(escape(form.fname.data)),str(escape(form.lname.data)),form.contact.data,str(escape(form.confirm.data)),0,form.email.data) Models.database.session.add(user) Models.database.session.commit() except Exception as errors: print('test') log.logger.exception(errors) Models.database.session.rollback() token = utils.generate_token(user.email) confirm_url = url_for('users.confirm_email',token=token, _external=True) html = render_template('activate.html',confirm_url=confirm_url) subject = 'Please confirm your account' if os.environ.get('IS_PROD', None): utils.mailgun_send_messageV2(current_user.email, subject, html, '*****@*****.**') else: utils.send_email(form.email.data, subject, html) log.logger.info('A new user has sucessfully registered with username of {0}'.format(form.username.data),extra={'custom_dimensions':{'Source':request.remote_addr}}) resp = make_response(redirect(url_for('login'))) if resp.headers['Location'] == '/login': return resp else: if email is not None and username is not None: flash('Username and email exist') elif email is not None: flash('Email exist') elif username is not None: flash('Username exist') return redirect(url_for('register')) else: print(form.username.data) return render_template('register.html',form=form,searchForm=searchForm)
def login(): searchForm = SearchForm() if current_user.is_authenticated: abort(404) errors = '' form = LoginForm() if form.validate_on_submit(): if utils.banned_characters(form.username.data) or utils.banned_characters(form.password.data): log.logger.critical('Malicious characters such as \'\"<>#/ detected') print('d') errors = 'Invalid username or password' abort(404) print(form.username.data) if request.content_type != r'application/x-www-form-urlencoded': log.logger.error('Incorrect content format') abort(404) user = Models.Customer.query.filter_by(username=str(escape(form.username.data))).first() if user is not None: if user.failed_login_time is not None: if user.failed_attempt >=5: date = user.failed_login_time now = datetime.now() span = now - date # unban after 1 day if span.days > 1: user.failed_attempt = 0 Models.database.session.commit() else: date = user.failed_login_time now =datetime.now() span = now - date # incremental of failed login within 20mins if detected. if span.seconds > 1200: user.failed_attempt = 0 Models.database.session.commit() saved_password_hash = user.password_hash saved_password_salt = user.password_salt password_hash = utils.generate_hash(str(escape(form.password.data)),saved_password_salt) if password_hash == saved_password_hash: if user.verified == 1 and user.failed_attempt < 5: print('verified authen') u = Models.Customer.query.get(user.userid) utils.request_twilio_token(user.contact) # login_user(u) # session.destroy() try: user.failed_attempt = 0 Models.database.session.commit() except Exception as errors: log.logger.exception(errors) Models.database.session.rollback() # session.regenerate() session['username'] = user.username session['otp_session'] = datetime.now() # session['last_login'] = datetime.now() log.logger.info('{0} successfully logs into his account'.format(u.username)) resp = make_response(redirect(url_for('verify_token'))) print(resp.headers['Location']) if resp.headers['Location'] == '/VerifyToken': return resp else: abort(404) elif user.verified == 0 and user.failed_attempt < 5: u = Models.Customer.query.get(user.userid) session['username'] = user.username # to be commented out # login_user(u) try: user.failed_attempt = 0 Models.database.session.commit() except: Models.database.session.rollback() # to be commented out # session['last_login'] = datetime.now() session['otp_session'] = datetime.now() log.logger.warning('{0} successfully logs into his account without activating it'.format(u.username)) resp = make_response(redirect(url_for('users.unconfirmed'))) if resp.headers['Location'] == '/unconfirmed': return resp else: abort(404) elif user.failed_attempt >= 5: flash("This account is locked. Please contact us through support for help.") else: if user.failed_attempt >= 5: flash("This account is locked. Please contact us through support for help.") try: print('irfan') if user.failed_attempt < 5: errors = 'Invalid username or password' user.failed_attempt += 1 log.logger.warning(f"{user.username} login invalid credential of {user.failed_attempt} times") if user.failed_attempt == 5: log.logger.critical('An attempt to sign in with {0} has failed more than 5 times. Please investigate this issue'.format(user.username)) utils.mailgun_send_message(user.email,'test','<p>dwdwd</p>') user.failed_login_time = datetime.now() Models.database.session.commit() elif user.failed_attempt >= 5: abort(404) except Exception as errors: log.logger.exception(errors) Models.database.session.rollback() else: errors = 'Invalid username or password' else: print(form.errors) if_prod = os.environ.get('IS_PROD',None) if session.get('username'): return redirect(url_for('verify_token')) else: try: return render_template('login.html',form=form,errors=errors,searchForm=searchForm,if_prod=if_prod) except: return render_template('login.html',form=form,searchForm=searchForm,if_prod=if_prod)
def register(): if current_user.is_authenticated: abort(404) searchForm = SearchForm() form = RegisterForm() if form.validate_on_submit(): username = Models.Customer.query.filter_by( username=str(escape(form.username.data))).first() email = Models.Customer.query.filter_by( email=str(escape(form.email.data))).first() if email is None and username is None: user = '' try: user = Models.Customer(str(escape(form.username.data)), str(escape(form.fname.data)), str(escape(form.lname.data)), form.contact.data, str(escape(form.confirm.data)), 0, str(escape(form.email.data))) Models.database.session.add(user) Models.database.session.commit() except Exception as errors: print('test') log.logger.exception(errors) Models.database.session.rollback() token = utils.generate_token(user.email) confirm_url = url_for('users.confirm_email', token=token, _external=True) html = render_template('activate.html', confirm_url=confirm_url) subject = 'Please confirm your account' utils.send_email(form.email.data, subject, html) log.logger.info( 'A new user has sucessfully registered with username of {0}'. format(form.username.data), extra={'custom_dimensions': { 'Source': request.remote_addr }}) return redirect(url_for('login')) else: if email is not None and username is not None: flash('Username and email exist') elif email is not None: flash('Email exist') elif username is not None: flash('Username exist') return redirect(url_for('register')) else: print(form.username.data) if utils.banned_characters( form.username.data) or utils.banned_characters( form.password.data) or utils.banned_characters( form.fname.data) or utils.banned_characters( form.lname.data) or utils.banned_characters( form.email.data) or utils.banned_characters( form.confirm.data): print('d') log.logger.critical( 'Malicious characters detected in register form', extra={'custom_dimensions': { 'Source': request.remote_addr }}) # ban ip addr for next step return render_template('register.html', form=form, searchForm=searchForm)