def login(): if request.method == 'POST': errors = [] name = request.form['name'] team = Teams.query.filter_by(name=name).first() if team and bcrypt_sha256.verify(request.form['password'], team.password): try: session.regenerate() # NO SESSION FIXATION FOR YOU except: pass # TODO: Some session objects don't implement regenerate :( session['username'] = team.name session['id'] = team.id session['admin'] = team.admin session['nonce'] = sha512(os.urandom(10)) db.session.close() logger = logging.getLogger('logins') logger.warn("[{0}] {1} logged in".format(time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8'))) if request.args.get('next') and is_safe_url(request.args.get('next')): return redirect(request.args.get('next')) return redirect(url_for('challenges.challenges_view')) else: errors.append("That account doesn't seem to exist") db.session.close() return render_template('login.html', errors=errors) else: db.session.close() return render_template('login.html')
def _commit(response=None): if hasattr(session, 'sid_s'): delete_session(session.sid_s) # Regenerate the session to avoid session fixation vulnerabilities. session.regenerate() current_accounts.datastore.commit() return response
def logout(): if authed(): session.clear() try: session.regenerate() except: pass return redirect('/')
def refresh_session(): if session.has_key('gen_time'): gen_time = session['gen_time'] lifetime = app.config['PERMANENT_SESSION_LIFETIME'].seconds if time.time() > gen_time + lifetime / 2: session.regenerate() session['gen_time'] = time.time() else: session['gen_time'] = time.time()
def login(): logger = logging.getLogger('logins') if request.method == 'POST': errors = [] name = request.form['name'] # Check if the user submitted an email address or a team name if utils.check_email_format(name) is True: team = Teams.query.filter_by(email=name).first() else: team = Teams.query.filter_by(name=name).first() if team: if team and bcrypt_sha256.verify(request.form['password'], team.password): try: session.regenerate() # NO SESSION FIXATION FOR YOU except: pass # TODO: Some session objects don't implement regenerate :( session['username'] = team.name session['id'] = team.id session['admin'] = team.admin session['nonce'] = utils.sha512(os.urandom(10)) db.session.close() logger.warn("[{date}] {ip} - {username} logged in".format( date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip(), username=session['username'].encode('utf-8'))) if request.args.get('next') and utils.is_safe_url( request.args.get('next')): return redirect(request.args.get('next')) return redirect(url_for('challenges.challenges_view')) else: # This user exists but the password is wrong logger.warn( "[{date}] {ip} - submitted invalid password for {username}" .format(date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip(), username=team.name.encode('utf-8'))) errors.append("Your username or password is incorrect") db.session.close() return render_template('login.html', errors=errors) else: # This user just doesn't exist logger.warn( "[{date}] {ip} - submitted invalid account information".format( date=time.strftime("%m/%d/%Y %X"), ip=utils.get_ip())) errors.append("Your username or password is incorrect") db.session.close() return render_template('login.html', errors=errors) else: db.session.close() return render_template('login.html')
def confirm_auth_provider(auth_provider): if auth_provider not in provider_users: return redirect('/') provider_user = provider_users[oauth_provider]() # Resolved lambda if provider_user is not None: session.regenerate() login_user(provider_user) db.session.close() return redirect('/')
def login(): errors = get_errors() if request.method == "POST": name = request.form["name"] # Check if the user submitted an email address or a team name if validators.validate_email(name) is True: user = Users.query.filter_by(email=name).first() else: user = Users.query.filter_by(name=name).first() if user: if user.password is None: errors.append( "Your account was registered with a 3rd party authentication provider. " "Please try logging in with a configured authentication provider." ) return render_template("login.html", errors=errors) if user and verify_password(request.form["password"], user.password): session.regenerate() login_user(user) log("logins", "[{date}] {ip} - {name} logged in", name=user.name) db.session.close() if request.args.get("next") and validators.is_safe_url( request.args.get("next")): return redirect(request.args.get("next")) return redirect(url_for("challenges.listing")) else: # This user exists but the password is wrong log( "logins", "[{date}] {ip} - submitted invalid password for {name}", name=user.name, ) errors.append("用户名或密码错误") db.session.close() return render_template("login.html", errors=errors) else: # This user just doesn't exist log("logins", "[{date}] {ip} - submitted invalid account information") errors.append("用户名或密码错误") db.session.close() return render_template("login.html", errors=errors) else: db.session.close() return render_template("login.html", errors=errors)
def login(): if request.method == 'GET': return render_template('login.html') else: username = request.form.get('username') password = request.form.get('password') session.regenerate() # avoid session fixation session['username'] = username session['logged_in'] = True return redirect(url_for('home'))
def login(): # todo: show a message about login success or fail username = request.form.get('username') password = request.form.get('password') try: user = User.get(name=username) except User.DoesNotExist: return redirect(url_for('index')) if (user.validate_password(password)): session.regenerate() session['username'] = username session['logged_in'] = True return redirect(url_for('index'))
def add_user_session(response): """Regenerate current session and add to the SessionActivity table. .. note:: `flask.session.regenerate()` actually calls Flask-KVSession's `flask_kvsession.KVSession.regenerate`. """ # Regenerate the session to avoid session fixation vulnerabilities. session.regenerate() # Save the session first so that the sid_s gets generated. app.session_interface.save_session(app, session, response) add_session(session) current_accounts.datastore.commit() return response
def local_login(): """ Authenticate a user against the database (ignore password). Allows developers to test functionality as valid users without needing to use a third party service. Returns: HTTP Response (werkzeug.wrappers.Response): Redirects the user to the home page (if successful) or to the login page again (if unsuccessful) """ if not current_app.config["USE_LOCAL_AUTH"]: return redirect(url_for('auth.login')) login_form = BasicLoginForm() if request.method == "POST": email = request.form["email"] user = find_user_by_email(email) if user is not None: login_user(user) session.regenerate() session["user_id"] = current_user.get_id() create_auth_event( auth_event_type=event_type.USER_LOGIN, user_guid=session["user_id"], new_value={ 'success': True, } ) next_url = request.form.get("next") if not is_safe_url(next_url): return abort(400, UNSAFE_NEXT_URL) return redirect(next_url or url_for("main.index")) else: error_message = "User {email} not found. Please contact your agency FOIL Officer to gain access to the system.".format( email=email) flash(error_message, category="warning") return render_template( "auth/local_login_form.html", login_form=login_form ) elif request.method == "GET": return render_template( "auth/local_login_form.html", login_form=login_form, next_url=request.args.get("next", ""), )
def setupSession(username): try: session.regenerate() except: pass #some objects don't have regenerate #get relevant user data userData = getUserData(username) #put username and other data into session session["username"] = username session["ssn"] = userData["ssn"] session["id"] = userData["id"] session["firstname"] = userData["first"] session["lastname"] = userData["last"]
def login(): if request.method == 'GET': csrf_token = generate_csrf_token() session['csrf_token'] = csrf_token return render_template('login.html', csrf=csrf_token) else: csrf_token = request.form.get('t') if not 'csrf_token' in session or csrf_token != session['csrf_token']: abort(400) username = request.form.get('u') password = request.form.get('p') if authenticate(username, password): session.regenerate() session['username'] = username return redirect(url_for('index'))
def setupSession(username): try: session.regenerate() except: pass # some objects don't have regenerate # get relevant user data userData = getUserData(username) # put username and other data into session session["username"] = username session["ssn"] = userData["ssn"] session["id"] = userData["id"] session["firstname"] = userData["first"] session["lastname"] = userData["last"]
def handle_authorize(remote, token, user_info): with app.app_context(): user = get_or_create_user( email=user_info["email"], name=user_info["name"]) if user is not None: session.regenerate() login_user(user) log("logins", "[{date}] {ip} - " + user.name + " logged in") db.session.close() return redirect(url_for("challenges.listing")) return redirect('/')
def get(self): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user and user.check_password(form.password.data): session.regenerate() login_user(user, remember=form.remember_me.data) return redirect(url_for('root')) else: form.password.errors.append('The username or password is incorrect.') return render_template('pages/login.html', form=form)
def login(): errors = get_errors() if request.method == "POST": name = request.form["name"] captcha_response = request.form['g-recaptcha-response'] if not is_human(captcha_response): # This user exists but the password is wrong error_captcha = "The response parameter is missing" return render_template("login.html", error_captcha=error_captcha) # Check if the user submitted an email address or a team name if validators.validate_email(name) is True: user = Users.query.filter_by(email=name).first() else: user = Users.query.filter_by(name=name).first() if user: if user and verify_password(request.form["password"], user.password): session.regenerate() login_user(user) log("logins", "[{date}] {ip} - {name} logged in") db.session.close() if request.args.get("next") and validators.is_safe_url( request.args.get("next")): return redirect(request.args.get("next")) return redirect(url_for("challenges.listing")) else: # This user exists but the password is wrong log("logins", "[{date}] {ip} - submitted invalid password for {name}") errors.append("Your username or password is incorrect") db.session.close() return render_template("login.html", errors=errors) else: # This user just doesn't exist log("logins", "[{date}] {ip} - submitted invalid account information") errors.append("Your username or password is incorrect") db.session.close() return render_template("login.html", errors=errors) else: db.session.close() return render_template("login.html", errors=errors)
def logout(): timed_out = request.args.get('timeout') if current_app.config['USE_LDAP']: return redirect(url_for('auth.ldap_logout', timed_out=timed_out)) elif current_app.config['USE_OAUTH']: if 'token' in session: revoke_and_remove_access_token() if current_user.is_authenticated and timed_out is not None: flash("Your session timed out. Please login again", category='info') logout_user() session.regenerate() return redirect(url_for("main.index")) return abort(404)
def home(): form = SigninForm() if 'uid' in session: return redirect(url_for('profile1')) #form.email.errors=None #form.password.errors=None if request.method == "POST": if form.validate() == False: print 'coming here..post' return render_template('home.html', form=form) else: try: session.regenerate() except: print 'session.regenerate error' session['firstname'] = form.data_firstname() session['lastname'] = form.data_lastname() session['companyname'] = form.data_companyname() session['phone'] = form.data_phone() session['email'] = form.email.data session['uid'] = str(uuid.uuid4()) session['desc_html'] = None session['sandbox'] = SANDBOX session['prebuilt'] = PREBUILT session['session_dir'] = session['sandbox'] + '/' + session['uid'] session['prebuilt_dir'] = session['prebuilt'] createSessionDirectory(session['session_dir']) session['train_filenames'] = [] session['test_filenames'] = [] obj = acs.DataAnalytics(session['uid'], session['session_dir']) session['data_object'] = obj session['prebuilt_dict'] = prebuiltDict() session.modified = True #return render_template('agreement.html') return redirect(url_for('profile1')) elif request.method == 'GET': return render_template('home.html', form=form)
def validate(self): if not Form.validate(self): return False user = Users.query.filter_by(user = self.user.data).first() if user and bcrypt_sha256.verify(self.password.data, user.password): try: session.regenerate() # NO SESSION FIXATION FOR YOU except: pass # TODO: Some session objects don't implement regenerate :( session['username'] = user.user session['id'] = user.id session['nonce'] = sha512(os.urandom(10)) db.session.close() return True else: db.session.close() return False
def verify_2fa(): form = Confirm2faForm() if form.validate_on_submit(): username = Models.Customer.query.filter_by(username=session.get('username')).first() print(username.contact) phone = username.contact if utils.verify_twilio_token(phone,form.token.data): u = Models.Customer.query.get(username.userid) login_user(u) session.regenerate() session['last_login'] = datetime.now() del session['username'] del session['otp_session'] response = make_response(redirect(url_for('home_page'))) if response.headers['Location'] == '/': return response else: flash('Token Invalid. Try again or request new one.')
def get(self): if not self.app.config['REGISTER_ENABLED']: return 'Registration is disabled on this server.', 403 if not current_user.is_anonymous(): return 'You can\'t register a new user as an already register user.', 403 user = User() form = RegisterForm(obj=user) if not self.app.config['RECAPTCHA_PRIVATE_KEY']: delattr(form, 'recaptcha') if form.validate_on_submit(): form.populate_obj(user) DATABASE.session.add(user) try: DATABASE.session.commit() session.regenerate() login_user(user, remember=False) return redirect(url_for('root')) except IntegrityError as ex: DATABASE.session.rollback() m = re.search('column (\w+) is not unique', str(ex.orig)) attribute = m and m.group(1) or None if hasattr(form, attribute): form_attribute = getattr(form, attribute) else: form_attribute = form.username form_attribute.errors.append('Database error: "%s".' % ex.orig) return render_template('pages/register.html', form=form)
def get(self): form = LoginForm() if not self.app.config['RECAPTCHA_PRIVATE_KEY']: delattr(form, 'recaptcha') if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user and user.check_password(form.password.data): session.regenerate() login_user(user, remember=form.remember_me.data) return redirect(url_for('root')) else: form.password.errors.append('The username or password is incorrect.') return render_template('pages/login.html', form=form, register_enabled=self.app.config['REGISTER_ENABLED'])
def login(): errors = get_errors() if request.method == "POST": name = request.form["name"] # Check if the user submitted an email address or a team name if validators.validate_email(name) is True: user = Users.query.filter_by(email=name).first() else: user = Users.query.filter_by(name=name).first() if user: if user and verify_password(request.form["password"], user.password): session.regenerate() login_user(user) log("logins", "[{date}] {ip} - {name} logged in") db.session.close() if request.args.get("next") and validators.is_safe_url( request.args.get("next")): return redirect(request.args.get("next")) return redirect(url_for("challenges.listing")) else: # This user exists but the password is wrong log("logins", "[{date}] {ip} - submitted invalid password for {name}") errors.append("Неверное имя пользователя или пароль") db.session.close() return render_template("login.html", errors=errors) else: # This user just doesn't exist log("logins", "[{date}] {ip} - submitted invalid account information") errors.append("Неверное имя пользователя или пароль") db.session.close() return render_template("login.html", errors=errors) else: db.session.close() return render_template("login.html", errors=errors)
def login(): if request.method == 'POST': errors = [] email = request.form['email'] team = Users.query.filter_by(email=email).first() if team: if team and bcrypt_sha256.verify(request.form['password'], team.password): try: session.regenerate() # NO SESSION FIXATION FOR YOU except: pass # TODO: Some session objects don't implement regenerate :( session['username'] = team.name session['id'] = team.id session['admin'] = team.admin session['nonce'] = sha512(os.urandom(10)) db.session.close() logger = logging.getLogger('logins') logger.warn("[{0}] {1} logged in".format( time.strftime("%m/%d/%Y %X"), session['username'].encode('utf-8'))) if request.args.get('next') and is_safe_url( request.args.get('next')): return redirect(request.args.get('next')) return redirect(url_for('challenges.challenges_view')) else: # This user exists but the password is wrong errors.append("Your email or password is incorrect") db.session.close() return render_template('login.html', errors=errors) else: # This user just doesn't exist errors.append("Your email or password is incorrect") db.session.close() return render_template('login.html', errors=errors) else: db.session.close() if request.args.get('next'): return render_template('login.html', next=urllib.quote(request.args.get('next'))) else: return render_template('login.html')
def process_login(): form = auth_forms.LoginForm(request.form) next_url = request.args.get('next') if form.validate(): result = data_api_client.authenticate_user( form.email_address.data, form.password.data) if not result: current_app.logger.info( "login.fail: failed to sign in {email_hash}", extra={'email_hash': hash_email(form.email_address.data)}) flash("no_account", "error") return render_template_with_csrf( "auth/login.html", status_code=403, form=form, next=next_url) user = User.from_json(result) if '_csrf_token' in session: session.pop('_csrf_token') if 'csrf' in session: session.pop('csrf') if current_app.config['REDIS_SESSIONS']: session.regenerate() login_user(user) current_app.logger.info('login.success: {user}', extra={'user': user_logging_string(user)}) check_terms_acceptance() if current_user.role == 'buyer': user = User.load_user(data_api_client, current_user.id) if not user.is_team_member and user.must_join_team: next_url = '/2/team/join' return redirect_logged_in_user(next_url, result.get('validation_result', None)) else: return render_template_with_csrf( "auth/login.html", status_code=400, form=form, next=next_url)
def login(): errors = get_errors() if request.method == 'POST': name = request.form['name'] # Check if the user submitted an email address or a team name if validators.validate_email(name) is True: user = Users.query.filter_by(email=name).first() else: user = Users.query.filter_by(name=name).first() if user: if user and check_password(request.form['password'], user.password): session.regenerate() login_user(user) log('logins', "[{date}] {ip} - {name} logged in") db.session.close() if request.args.get('next') and validators.is_safe_url( request.args.get('next')): return redirect(request.args.get('next')) return redirect(url_for('challenges.listing')) else: # This user exists but the password is wrong log('logins', "[{date}] {ip} - submitted invalid password for {name}") errors.append("Your username or password is incorrect") db.session.close() return render_template('login.html', errors=errors) else: # This user just doesn't exist log('logins', "[{date}] {ip} - submitted invalid account information") errors.append("Your username or password is incorrect") db.session.close() return render_template('login.html', errors=errors) else: db.session.close() return render_template('login.html', errors=errors)
def login(): # login req = request.json if 'name' not in req or 'password' not in req: return {"success": False, "data": None} name = req['name'] if validators.validate_email(name) is True: user = Users.query.filter_by(email=name).first() else: user = Users.query.filter_by(name=name).first() if user and verify_password(request.json["password"], user.password): session.regenerate() login_user(user) db.session.close() return { "success": True, "data": { "nonce": session["nonce"], }} else: db.session.close() return {"success": False, "data": "Your username or password is incorrect"}
def admin(): if request.method == 'POST': username = request.form.get('name') password = request.form.get('password') admin = Teams.query.filter_by(name=request.form['name'], admin=True).first() if admin and bcrypt_sha256.verify(request.form['password'], admin.password): session.regenerate() # NO SESSION FIXATION FOR YOU session['username'] = admin.name session['id'] = admin.id session['admin'] = True session['nonce'] = sha512(os.urandom(10)) db.session.close() return redirect('/admin/graphs') if is_admin(): return redirect('/admin/graphs') return render_template('admin/login.html')
def login(): if session.get('mail') is not None: return redirect('/bbs') error_msg = [] if request.method == 'POST': #Formに情報が欠落していた場合#{{{ if " " in request.form['mail'] and request.form['password']: error_msg.append(u'空白文字が含まれています') return render_template('login.html', error=error_msg) if request.form['password'] == '': error_msg.append(u'パスワードを入力してください') if request.form['mail'] == '': error_msg.append(u'メールアドレスを入力してください') if valid(request.form['password']): error_msg.append(u'パスワードの文字数が多すぎます') if valid(request.form['mail']): error_msg.append(u'メールの文字数が多すぎます') if len(error_msg) != 0: return render_template('login.html', error=error_msg, info=request.form['mail']) #}}} # パスワードチェック if check_user_password((request.form['mail'], \ hashlib.md5(request.form['password'] + 'solt').hexdigest())): #セッションの再発行 session.regenerate() session['mail'] = request.form['mail'] return redirect(url_for('bbs')) else: # パスワードマッチに失敗したとき return render_template('login.html', \ error = [u'メールアドレスまたはパスワードが違います'], info = request.form['mail']) # 更新時(F5) return render_template('login.html')
def admin_view(): if request.method == 'POST': username = request.form.get('name') password = request.form.get('password') admin_user= Teams.query.filter_by(name=request.form['name'], admin=True).first() if admin_user and bcrypt_sha256.verify(request.form['password'], admin_user.password): try: session.regenerate() # NO SESSION FIXATION FOR YOU except: pass # TODO: Some session objects dont implement regenerate :( session['username'] = admin_user.name session['id'] = admin_user.id session['admin'] = True session['nonce'] = sha512(os.urandom(10)) db.session.close() return redirect('/admin/graphs') if is_admin(): return redirect('/admin/graphs') return render_template('admin/login.html')
def requires_login(return_page=None): if session.get("logged_in", None) is not None: # Already logged in? Back to the index for you! return redirect(url_for('index')) if request.method == "POST": if 'le-username' not in request.form or 'le-password' not in request.form: flash('Something went wrong.', 'error') return redirect(url_for('login')) username = request.form['le-username'] password = request.form['le-password'] records = pysql().where('login', username.lower()).where('password', hash_pass(username, password)).get('users') if len(records) != 1: flash("Sorry, the username or password was incorrect.", 'error') return redirect(url_for('login')) else: # correct-a-mundo! records = records[0] # We want the dictionary! session['username'] = records['username'] session['logged_in'] = True session.regenerate() return redirect(url_for('index')) else: return redirect(url_for('login'))
def post(self): if session.new: return "No session could be found. Have you performed a GET first ?", 403 challenge = session.get('api.challenge') if not challenge: return "No challenge information was found. Have you performed a GET first ?", 403 if (request.json.get('challenge') != challenge): return "Challenges do not match. Unable to continue.", 403 user = User.query.filter_by(username=request.json.get('username')).first() if not user or not user.check_password(request.json.get('password')): return "Invalid username or password.", 403 session.regenerate() login_user(user, remember=False) return jsonify()
def get(self): form = LoginForm() if not self.app.config['RECAPTCHA_PRIVATE_KEY']: delattr(form, 'recaptcha') if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user and user.check_password(form.password.data): session.regenerate() login_user(user, remember=form.remember_me.data) return redirect(url_for('root')) else: form.password.errors.append( 'The username or password is incorrect.') return render_template( 'pages/login.html', form=form, register_enabled=self.app.config['REGISTER_ENABLED'])
def login(): if session.get('mail') is not None: return redirect('/bbs') error_msg = [] if request.method == 'POST': #Formに情報が欠落していた場合#{{{ if " " in request.form['mail'] and request.form['password'] : error_msg.append(u'空白文字が含まれています') return render_template('login.html', error = error_msg) if request.form['password'] == '': error_msg.append(u'パスワードを入力してください') if request.form['mail'] == '': error_msg.append(u'メールアドレスを入力してください') if valid(request.form['password']): error_msg.append(u'パスワードの文字数が多すぎます') if valid(request.form['mail']): error_msg.append(u'メールの文字数が多すぎます') if len(error_msg) != 0: return render_template('login.html', error = error_msg, info = request.form['mail']) #}}} # パスワードチェック if check_user_password((request.form['mail'], \ hashlib.md5(request.form['password'] + 'solt').hexdigest())): #セッションの再発行 session.regenerate() session['mail'] = request.form['mail'] return redirect(url_for('bbs')) else: # パスワードマッチに失敗したとき return render_template('login.html', \ error = [u'メールアドレスまたはパスワードが違います'], info = request.form['mail']) # 更新時(F5) return render_template('login.html')
def admin_view(): if request.method == 'POST': username = request.form.get('name') password = request.form.get('password') admin_user = Teams.query.filter_by(name=request.form['name'], admin=True).first() if admin_user and bcrypt_sha256.verify(request.form['password'], admin_user.password): try: session.regenerate() # NO SESSION FIXATION FOR YOU except: pass # TODO: Some session objects dont implement regenerate :( session['username'] = admin_user.name session['id'] = admin_user.id session['admin'] = True session['nonce'] = sha512(os.urandom(10)) db.session.close() return redirect(url_for('admin.admin_graphs')) if is_admin(): return redirect(url_for('admin.admin_graphs')) return render_template('admin/login.html')
def post(self): if session.new: return "No session could be found. Have you performed a GET first ?", 403 challenge = session.get('api.challenge') if not challenge: return "No challenge information was found. Have you performed a GET first ?", 403 if (request.json.get('challenge') != challenge): return "Challenges do not match. Unable to continue.", 403 user = User.query.filter_by( username=request.json.get('username')).first() if not user or not user.check_password(request.json.get('password')): return "Invalid username or password.", 403 session.regenerate() login_user(user, remember=False) return jsonify()
def ldap_login(): login_form = LDAPLoginForm() if request.method == 'POST': email = request.form['email'] password = request.form['password'] user = find_user_by_email(email) if user is not None: authenticated = ldap_authentication(email, password) if authenticated: login_user(user) session.regenerate() session['user_id'] = current_user.get_id() next_url = request.form.get('next') if not is_safe_url(next_url): return abort(400, UNSAFE_NEXT_URL) return redirect(next_url or url_for('main.index')) flash("Invalid username/password combination.", category="danger") return render_template('auth/ldap_login_form.html', login_form=login_form) else: flash( "User not found. Please contact your agency FOIL Officer to gain access to the system.", category="warning") return render_template('auth/ldap_login_form.html', login_form=login_form) elif request.method == 'GET': return render_template('auth/ldap_login_form.html', login_form=login_form, next_url=request.args.get('next', ''))
def regenerate(): session.regenerate() return 'session regenerated'
def index(): session.regenerate() return 'OK'
def _session_regenerate_persist_token(): token = session['token'] token_expires_at = session['token_expires_at'] session.regenerate() session['token'] = token session['token_expires_at'] = token_expires_at
def logout(self): session.regenerate() return ("", 204)
def get_osm_token(token=None): session.regenerate() return session.get("osm_token")
def login(): errors = get_errors() if request.method == "POST": email = request.form["name"] url = "https://api.hackru.org/dev" content = { "email": email, "password": request.form["password"] } response = requests.post(url + "/authorize", data=json.dumps(content)) if response.json()["statusCode"] == 200: token = (response.json()["body"]["token"]) content = { "email": email, "token": token, "query": { "email": email } } response = requests.post(url + "/read", data=json.dumps(content)) print(response.json()) if (response.json()["body"][0]["registration_status"] not in ["confirmed"]): errors.append("your registration status has not been confirmed. please go to hackru.org and confirm it, if issues continue contact [email protected]") db.session.close() return render_template("login.html", errors=errors) name = response.json()["body"][0].get("first_name", "") + " " + response.json()["body"][0].get("last_name", ""); #get name email_address = email password = request.form["password"] website = None affiliation = response.json()["body"][0].get("school", "") #maybe do school? country = None try: with app.app_context(): user = Users(name=name, email=email_address, password=password) if website: user.website = website if affiliation: user.affiliation = affiliation if country: user.country = country db.session.add(user) db.session.commit() db.session.flush() login_user(user) log("registrations", "[{date}] {ip} - {name} registered with {email}") db.session.close() return redirect(url_for("challenges.listing")) except: print("ALREADY A USER") user = Users.query.filter_by(email=email_address).first() session.regenerate() login_user(user) log("logins", "[{date}] {ip} - {name} logged in") db.session.close() if request.args.get("next") and validators.is_safe_url( request.args.get("next") ): return redirect(request.args.get("next")) return redirect(url_for("challenges.listing")) else: # This user just doesn't exist log("logins", "[{date}] {ip} - submitted invalid account information") errors.append("Your username or password is incorrect") db.session.close() return render_template("login.html", errors=errors) else: db.session.close() return render_template("login.html", errors=errors)
def ldap_login(): """ Login a user using the LDAP protocol Args: next (str): URL to redirect the user to if login is successful. (in request.args) Returns: HTTP Response (werkzeug.wrappers.Response): Redirects the user to the home page (if successful) or to the login page again (if unsuccessful) """ if not current_app.config["USE_LDAP"]: return redirect(url_for("auth.login")) login_form = BasicLoginForm() if request.method == "POST": email = request.form["email"] password = request.form["password"] user = find_user_by_email(email) if user is not None: authenticated = ldap_authentication(email, password) if authenticated: login_user(user) session.regenerate() session["user_id"] = current_user.get_id() create_auth_event( auth_event_type=event_type.USER_LOGIN, user_guid=session["user_id"], new_value={ 'success': True, 'type': current_app.config['AUTH_TYPE'] } ) next_url = request.form.get("next", None) if not is_safe_url(next_url) or next_url is None: return abort(400, UNSAFE_NEXT_URL) return redirect(next_url or url_for("main.index")) error_message = "Invalid username/password combination." create_auth_event( auth_event_type=event_type.USER_FAILED_LOG_IN, user_guid=session["user_id"], new_value={ 'success': False, 'type': current_app.config['AUTH_TYPE'], 'message': error_message } ) flash(error_message, category="danger") return render_template("auth/ldap_login_form.html", login_form=login_form) else: error_message = "User not found. Please contact your agency FOIL Officer to gain access to the system." create_auth_event( auth_event_type=event_type.USER_FAILED_LOG_IN, user_guid=session["user_id"], new_value={ 'success': False, 'type': current_app.config['AUTH_TYPE'], 'message': error_message } ) flash(error_message, category="warning") return render_template("auth/ldap_login_form.html", login_form=login_form) elif request.method == "GET": return render_template( "auth/ldap_login_form.html", login_form=login_form, next_url=request.args.get("next", ""), )
def ldap_logout(timed_out=None): logout_user() session.regenerate() if timed_out is not None: flash("Your session timed out. Please login again", category='info') return redirect(url_for('main.index'))
def needs_setup(): if not is_setup(): #clear and regen session if first setup session.regenerate() session.clear() return redirect('/setup')