def login(): """ Logs a user in """ form = LoginForm() print(request.get_json()) # Get the csrf_token from the request cookie and put it into the # form manually to validate_on_submit can be used form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): # Add the user to the session, we are logged in! user = User.query.filter(User.email == form.data['email']).first() login_user(user) # reviews = [] # if not user.nonprofit: # reviews = Review.query.filter(Review.application.node_id == user.id).filter(Review.writer_id != user.id).all() # else: # reviews = Review.query.filter(Review.application.nonprofit_id == user.id).filter(Review.writer_id != user.id).all() # for rev in reviews: # user.score += rev.score # if rev.score > 1: # user.karma += rev.application.karma return user.to_dict() return {'errors': validation_errors_to_error_messages(form.errors)}, 401
def login(): # if user is Logged in already, do not let them access this page if current_user.is_authenticated: flash('You are already logged in!') return redirect(url_for('index')) form = LoginForm() # check if form is submitted, log user in if so if form.validate_on_submit(): # query the database for the user trying to log in user = User.query.filter_by(username=form.username.data).first() # if user doesnt exist, reload page and flash messages if user is None or not user.check_password(form.password.data): flash('Credentials are incorrect.') return redirect(url_for('login')) # if user does exist, and credentials are correct, log them in and send them to their profile page login_user(user, remember=form.remember_me.data) flash('You are now logged in!') return redirect(url_for('index', username=current_user.username)) return render_template('login.html', title='Login:', form=form)
def login(): form = LoginForm() return render_template('login.html', title='Sign In', form=form) #from flask import render_template #from app import app #from app.forms import LoginForm #@app.route('/') #@app.route('/index') #def index(): # user = {'username': '******'} # posts = [ # { # 'author': {'username': '******'}, # 'body': ' Beautiful day in Portland!' # }, # { # 'author': {'username': '******'}, # 'body': ' The Avengers movie was so cool!' # } # ] # return render_template('index.html', title='Home', user=user, posts=posts)
def login(): login_form = LoginForm() context = {'login_form': login_form} if login_form.validate_on_submit(): username = login_form.username.data password = login_form.password.data user_doc = get_user(username) if user_doc.to_dict() is not None: password_from_db = user_doc.to_dict()['password'] if password == password_from_db: user_data = UserData(username, password) user = UserModel(user_data) login_user(user) flash('Bienvenido de nuevo') redirect(url_for('hello')) else: flash('La informacion no coincide') else: flash('El usuario no existe') flash('Nombre de usuario registrado') return redirect(url_for('index')) return render_template('login.html', **context)
def login(): # Get users.json data. with open('users.json', 'r+') as jsonfile: # seperate function (users-r) users_data = json.loads(jsonfile.read()) jsonfile.close() # Create login form for user form = LoginForm() user_data, password = None, None # validate user login info if form.validate_on_submit(): flash("Login requested for {form.username.data}.") for user in users_data: if user["username"] == form.username.data: user_data = user password = user_data["password"] print(password == form.password.data) if password == form.password.data: print("correct password") print("pooping") try: # get jobs from websites runpy.run_path("./pyproject.py") except RuntimeError: print( "Something went wrong pulling jobs. Reload and try again." ) return redirect(f"/jobs/{user_data['ID']}") # if user does not exist redirect to account page if user_data is None: print("create account") flash("User does not exist for {form.username.data}") return redirect("/new_account") return render_template("login.html", title="Login", form=form, user_data=user_data)
def login(): if current_user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): user = User.objects.filter(login=form.login.data).first() if user is None: print('user not found') return redirect(url_for('noup')) if user.passwordhash.encode('utf-8') != bcrypt.hashpw( form.password.data.encode('utf-8'), user.passwordhash.encode('utf-8')): print('Invalid password or hash') return redirect(url_for('noup')) login_user(user, True) print("User authenticated") # flash('Login requested for user {}, remember_me={}'.format(form.username.data, form.remember_me.data)) next_page = request.args.get('next') if not next_page: return redirect(url_for('index')) else: print(next_page) return redirect(next_page) return render_template('login.html', title='Login', form=form)
def test_validate_invalid_email_format(self): """Test that the incorrect email format is not validated""" login_form = LoginForm(email="unknown", password="******") self.assertFalse(login_form.validate())
def login(): form = LoginForm() return render_template('login.html', title='Sign In', form=form)
def inkycal_config(): form = LoginForm() if form.validate_on_submit(): # General epaper settings model = request.form.get('model') update_interval = int(request.form.get('update_interval')) calibration_hour_1 = int(request.form.get('calibration_hour_1')) calibration_hour_2 = int(request.form.get('calibration_hour_2')) calibration_hour_3 = int(request.form.get('calibration_hour_3')) orientation: int(request.form.get('orientation')) language = request.form.get('language') info_section = True if (request.form.get('info_section') == "on") else False info_height = int(request.form.get('info_section_height')) if info_section == True else None # template for basic settings template = { "model": model, "update_interval": update_interval, "orientation": int(request.form.get('orientation')), "info_section": info_section, "info_section_height": info_height, "calibration_hours": [calibration_hour_1, calibration_hour_2, calibration_hour_3], "modules": [], } # common module config (shared by all modules) padding_x = int(request.form.get('padding_x')) padding_y = int(request.form.get('padding_y')) fontsize = int(request.form.get('fontsize')) language = request.form.get('language') common_settings = {"padding_x":padding_x, "padding_y":padding_y, "fontsize":fontsize, "language":language} # loop over the modules, add their config data based on user selection, merge the common_settings into each module's config no_of_modules = int(request.form.get("module_counter")) # display size ---- Since Inkycal works in vertical mode (only), the width and height have to be flipped here display_size = Display.get_display_size(model) # returns width,height but flipping these for vertical mode height, width = int(display_size[0]), int(display_size[1]) # If info section was active, substract the height of the info section from the display height if info_section == True: height = height-info_height # get all module heights, calculate single part module_sizes = [int(request.form.get(f"module{i}_height")) for i in range(1, no_of_modules+1)] if sum(module_sizes) != 0: single_part = height / sum(module_sizes) for i in range(1, no_of_modules+1): conf = {} module = 'selected_module'+str(i) if request.form.get(module) != "None": conf = {"position":i , "name": request.form.get(module), "config":{}} for modules in settings: if modules['name'] == request.form.get(module): module_height = int( request.form.get(f"module{i}_height") ) conf['config']['size'] = (width, int(single_part*module_height) ) # Add required fields to the config of the module in question # True/False choices are converted to string for some reason, leading to incorrect values # Convert "True" to True, "False" to False and empty input to None if 'requires' in modules: for key in modules['requires']: val = request.form.get(f'module{i}_{key}').replace(" ", "") if val == "True": val = True elif val == "False": val = False elif val == "": val = None conf['config'][key] = val # For optional fields, check if user entered/selected something. If not, and a default value was given, # use the default value, else set the value of that optional key as None # True/False choices are converted to string for some reason, leading to incorrect values # Convert "True" to True, "False" to False and empty input to None if 'optional' in modules: for key in modules['optional']: if request.form.get(f'module{i}_{key}'): val = request.form.get(f'module{i}_{key}').replace(" ", "") if val == "True": val = True elif val == "False": val = False elif val == "": val = None conf['config'][key] = val else: if "default" in modules["optional"][key]: conf['config'][key] = modules["optional"][key]["default"] else: conf['config'][key] = None # update the config dictionary conf["config"].update(common_settings) template['modules'].append(conf) # Send the data back to the server side in json dumps and convert the response to a downloadable settings.json file try: user_settings = json.dumps(template, indent=4).encode('utf-8') response = Response(user_settings, mimetype="application/json", direct_passthrough=True) response.headers['Content-Disposition'] = 'attachment; filename=settings.json' return response except Exception as e: flash(str(e)) return render_template('inkycal-config-v2-0-0.html', title='Inkycal-Setup', conf=settings, form=form)
def dashboard(): form = LoginForm() return render_template('dashboard.html', form=form)
def login(): form = LoginForm() if form.validate_on_submit(): flash("You are logged in!") return redirect('/') return render_template('login.html', form=form)
def login(): form = LoginForm() if form.validate_on_submit(): flash(f'Login requested for user {form.username.data}, remember_me={form.remember_me.data}') return redirect(url_for('index')) return render_template('login.html', form=form)
def login(): form = LoginForm() if form.validate_on_submit(): return redirect(url_for('home')) return render_template("login.html", form=form)
def login_get(): form = LoginForm() return render_template('login.html', form=form)
def login(): """ The login view of this application. Return a login page or login a user if authentication is successful. """ # Redirect if the current user is logged in if g.user and g.user.is_authenticated: next = get_local_redirect() return redirect(next or url_for('index')) # Prepare the login form form = LoginForm() # If the form is filled if form.validate_on_submit(): # Part 1 # A terrible way to implement login # The administrator of Great Bank is very confident in his application and has published the # source code on the internet. That is what you are reading right now. You can thus see how # the code is implemented and try to find a vulnerability. # The code below execute a request to the database where it tries to match a username and # the password provided by the user in the form. # Unfortunately, he did not escape the values from the user in any way and you can thus # control the query by inserting the right values. # Try to input some code in the login page and see how the code changes in the console. # Can you bypass the password check? # See below for the answer. query = "SELECT * FROM user WHERE username = '******' AND password = '******'" # Print the current query into the console for you to see print(query) result = list(db.engine.execute(query)) if result: for row in result: login_user(User.get_by_username(row['username']), remember=form.remember_me.data) flash('Logged in!', 'success') return form.redirect('index') else: flash('Wrong username or password.', 'error') # By exploiting the fact that none of the code is escaped properly, we can control the SQL # statement and basically, make it always true. By using for instance: # Example of SQL injection: 1' OR '1'='1 # we can make the database say: "Give me 'admin' where password is '1' OR 1=1" # As 1=1 is always true, the second part of the predicament is always true and we bypass the # authentication entirely. You successfully logged in as an admin! # This is one of the simplest form of SQL injection and it is unfortunately still too # common today. # Part 2 # # The admin is pissed as you managed to login as him and take some money from the bank. He # discovered the flaw and patched it. (Please comment the whole code above and uncomment the # code below.) # You can no longer login using the magic password as he now verifies the user exist first # and then check the password. # See below for the next part. ### Patched version of the login: # print("Username: {username}".format(username=form.username.data)) # print("Password: {password}".format(password=form.password.data)) # # user = User.get_by_username(form.username.data) # if user and user.check_password(form.password.data): # login_user(user, remember=form.remember_me.data) # flash('Logged in!', 'success') # return form.redirect('index') # else: # flash('Wrong username or password.', 'error') return render_template('login.html', form=form)
def login(self, view, request): return view("auth/login.html", form=LoginForm())
def index(): form = LoginForm() return render_template('index.html', form=form)
def login() -> render_template: """ Description ----------- This function routes the user either to the login page or to the root/index page if the user logs in or is logged in Params ------ None Return ------ returns a rendered Jinja2 HTML template to be served over the flask application under the `/login' path """ # flask_login stores the concept of a current user # if the user is logged in, this will redirect to # the home page if current_user.is_authenticated: return redirect(url_for('index')) # If the user is not logged in then the flask # application will begin the login and # authenitcation process form = LoginForm() if form.validate_on_submit(): # This returns the user for the form submission if one exists # Otherwise returns None user = User.query.filter_by(username=form.username.data).first() if user is None or not user.check_password(form.password.data): # Go back to login if no user or wrong password flash("[ Invalid Username Or Passowrd ]") return redirect(url_for('login')) # If login succeeds # (user is non None and password is not invalid) # go back to home page login_user(user, remember=form.remember_me.data) # If the user was directed to the login from another page, # this will either retun them to page that they came from # or will default them back to /index next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') return redirect(next_page) # Otherwise stay here on the login page # and wait for the form submission return render_template( "login.html", title='Login', form=form, footer= "If you don't have a profile click I am new here or if you forgot your password then click that link." )
def login(): loginForm = LoginForm() return render_template('login.html', form=loginForm)
def logout(): logout_user() form = LoginForm(request.form) return redirect("/login.html")
def home(): return render_template('home.html', login=LoginForm(), signup=SignupForm())
def login(): form = LoginForm() if form.validate_on_submit(): flash("Login requested for user {}, remember_me = {}".format(form.username.data, form.remember_me.data)) return redirect(url_for("index")) return render_template("login.html", title = "Sign In", form = form)
def login(): form = LoginForm() if form.validate_on_submit(): flash('Login requested for user{}, remember_me={}'.format(form.username.data, form.remember_me.data)) return redirect(url_for('index')) return render_template('login.html', title='Sign In', form=form)
def login(): global Form Form = LoginForm() if Form.validate_on_submit(): return redirect('/answer') return render_template('find.html', title='Sign In', form=Form)
def login(): utente = Utente.def_utente() form = LoginForm(request.form) return render_template('login.html', utente=utente, titolo='Login',form=form)
def index(): lg_form = LoginForm() return render_template('index.html', lg_form=lg_form, title='首页')
def test_correct_data_validates(self): """Test that correct data is validated""" login_form = LoginForm(email="*****@*****.**", password="******") self.assertTrue(login_form.validate())
def login(): ''' Login view. Returns a view for the local HMI and another for any remote connection. :return: Before validation: login.html - After: index.html or admin dashboard :rtype: HTML / redirect ''' form = LoginForm() hmiForm = HmiLoginForm() if hmiForm.validate_on_submit() and request.remote_addr == "127.0.0.1": db = get_db() username = "******" password = hmiForm.password.data user = db.execute('SELECT * FROM user WHERE username = ?', (username, )).fetchone() if check_password_hash(user['password'], password): session.clear() session['user_id'] = user['id'] ipaddr = db.execute('SELECT * FROM ipaddr WHERE userid = ?', (session['user_id'], )).fetchall() if ipaddr: # The user already has an Ip Adress in the database pass else: # The current Ip adress is not in the database db.execute( 'INSERT INTO ipaddr (userid, ipaddress) VALUES (?, ?)', (session['user_id'], request.remote_addr)) db.commit() session['user_role'] = user['user_role'] return redirect(url_for('views.index')) if form.validate_on_submit(): username = form.username.data password = form.password.data db = get_db() error = None user = db.execute('SELECT * FROM user WHERE username = ?', (username, )).fetchone() if user is None: error = 'Incorrect username.' elif not check_password_hash(user['password'], password): error = 'Incorrect password.' if error is None: session.clear() session['user_id'] = user['id'] ipaddr = db.execute('SELECT * FROM ipaddr WHERE userid = ?', (session['user_id'], )).fetchall() ipnotset = True if ipaddr: # The user already has an Ip Adress in the database for ip in ipaddr: if ip['ipaddress'] == request.remote_addr: ipnotset = False if ipnotset: # The current Ip adress is not in the database db.execute( 'INSERT INTO ipaddr (userid, ipaddress) VALUES (?, ?)', (session['user_id'], request.remote_addr)) db.commit() session['user_role'] = user['user_role'] if user['first_login'] == 1: return redirect(url_for('auths.set_password')) if session['user_role'] == 'admin': return redirect(url_for('admins.dashboard')) return redirect(url_for('views.index')) flash(error) if request.remote_addr == "127.0.0.1": return render_template('loginhmi.html', form=hmiForm) else: return render_template('login.html', form=form)
def login(): form = LoginForm() if form.validate_on_submit(): flash(f'User {form.username.data} has logged in!') return redirect(url_for('/index')) return render_template('login.html', title='Sign In', form=form)
def login(): form = LoginForm() return render_template('auth/login.html', form=form)