def login(): """Login page for users """ form = LoginForm() if form.validate_on_submit(): username = form.username.data password = form.password.data try: user = authenticate(username, password) except UserNotFound: flash(gettext(u"Nutzer nicht gefunden!"), "error") except PasswordInvalid: flash(gettext(u"Passwort war inkorrekt!"), "error") else: if isinstance(user, User): login_user(user) elif form.is_submitted(): flash_formerrors(form) if current_user.is_authenticated(): return redirect(url_for('usersuite.usersuite')) return render_template('login.html', form=form)
def signin(): form = LoginForm() if form.validate_on_submit(): user = form.get_user() login_user(user) return redirect(request.args.get("next") or url_for('admin.list_users')) return render_template('login.html', form=form)
def login(): if current_user.is_authenticated(): return redirect(request.args.get('next') or '/') if not settings.PASSWORD_LOGIN_ENABLED: if settings.SAML_LOGIN_ENABLED: return redirect(url_for("saml_auth.sp_initiated", next=request.args.get('next'))) else: return redirect(url_for("google_oauth.authorize", next=request.args.get('next'))) if request.method == 'POST': user = models.User.select().where(models.User.email == request.form['username']).first() if user and user.verify_password(request.form['password']): remember = ('remember' in request.form) login_user(user, remember=remember) return redirect(request.args.get('next') or '/') return render_template("login.html", name=settings.NAME, analytics=settings.ANALYTICS, next=request.args.get('next'), username=request.form.get('username', ''), show_google_openid=settings.GOOGLE_OAUTH_ENABLED, show_saml_login=settings.SAML_LOGIN_ENABLED)
def login(): ''' Let users log in. ''' if request.method == 'GET': return render_template('index.html', next=request.args.get('next')) else: username = request.form['wyr_username'] password = request.form['wyr_password'] remember = request.form.getlist('remember') next = request.form['next'] #first see if username exists if User.query.filter_by(username=username).count() == 1: #get their encrypted pass and check it user = User.query.filter_by(username=username).first() myctx = CryptContext(schemes=['pbkdf2_sha256']) if myctx.verify(password, user.password) == True: if remember: login_user(user, remember=True) else: login_user(user) flash('Welcome back, {}.'.format(username)) else: flash('Sorry, the password is incorrect.') else: flash('Username does not exist.') if next: return redirect('https://www.whatyouveread.com' + next) return redirect(url_for('main.index'))
def post(self): from app import db args = signupParser.parse_args() username = args.username password = args.password.encode('utf-8') hashedpw = bcrypt.hashpw(password, bcrypt.gensalt()).decode() email = args.email print username, hashedpw, email registration_result, valid_registration = validate_registration(username, hashedpw) if valid_registration: user = register_user(username, email, hashedpw) login_user(user) response = jsonify({ 'status': 'success', 'user': user.username }) response.set_cookie('username', user.username, expires=datetime.utcnow() + COOKIE_DURATION, domain=None) response.set_cookie('email', user.email, expires=datetime.utcnow() + COOKIE_DURATION, domain=None) response.set_cookie('user_id', str(user.id), expires=datetime.utcnow() + COOKIE_DURATION, domain=None) return response else: return { 'status': 'error', 'message': registration_result }
def from_profile(cls, user, profile): if user and not user.is_anonymous(): user = None if not user or user.is_anonymous(): email = profile.data.get('email') provider = profile.data.get('provider') first_name = profile.data.get('first_name') last_name = profile.data.get('last_name') if provider not in ('Twitter', 'Douban') and not email: msg = 'Cannot create new user, authentication provider need provide email' # noqa raise Exception(_(msg)) if email is None: conflict = User.objects(first_name=first_name, last_name=last_name).first() else: conflict = User.objects(email=email).first() if conflict: msg = 'Cannot create new user, email {} is already used. Login and then connect external profile.' # noqa msg = _(msg).format(email) raise Exception(msg) now = datetime.now() user = User( email=email, first_name=first_name, last_name=last_name, confirmed_at=now, active=True, ) user.save() login_user(user) connection = cls(user=user, **profile.data) connection.save() return connection
def login(): form = LoginForm() if form.validate_on_submit(): # login and valide the user... login_user(form.user, remember=form.remember.data) return redirect(request.args.get('next') or url_for('web.index')) return render_template('login.html', form=form)
def post(self): from app import db args = loginParser.parse_args() username = args.get('username') password = args.get('password').encode('utf-8') user, auth_status = check_user_auth(password, username=username) print 'success', user, auth_status if(auth_status): login_user(user) response = jsonify({ 'status': 'success' }) response.set_cookie('username', user.username, expires=datetime.utcnow() + COOKIE_DURATION, domain=None) response.set_cookie('user_id', str(user.id), expires=datetime.utcnow() + COOKIE_DURATION, domain=None) return response else: #username and password do not match return jsonify({ 'status': 'error' }, status=401)
def login(): #---------------------------------------------------------------------- # define form form = LoginForm() # Validate form input #if flask.request.method == "POST" and form.validate_on_submit(): if form.validate_on_submit(): try: # Retrieve the user from the datastore user = racedb.find_user(form.email.data) # flag user doesn't exist or incorrect password if not (user and user.check_password(form.password.data)): return flask.render_template('login.html', form=form, error='username or password invalid') # we're good # Keep the user info in the session using Flask-Login login_user(user) flask.session['logged_in'] = True flask.session['user_name'] = user.name flask.session.permanent = True # Tell Flask-Principal the identity changed identity_changed.send( flask.current_app._get_current_object(), identity = Identity(user.id)) userclubs = getuserclubs(user) # zero clubs is an internal error in the databse if not(userclubs): db.session.rollback() raise dbConsistencyError,'no clubs found in database' # give user access to the first club in the list if no club already chosen # club_choices set in nav module. If this club.id is not in club_choices, # need to reset to first available if 'club_id' not in flask.session or flask.session['club_id'] not in [c[0] for c in userclubs]: club = Club.query.filter_by(id=userclubs[0][0]).first() flask.session['club_id'] = club.id flask.session['club_name'] = club.name # set default year to be current year today = timeu.epoch2dt(time.time()) flask.session['year'] = today.year # log login app.logger.debug("logged in user '{}'".format(flask.session['user_name'])) # commit database updates and close transaction db.session.commit() return flask.redirect(flask.request.args.get('next') or flask.url_for('index')) except: # roll back database updates and close transaction db.session.rollback() raise return flask.render_template('login.html', form=form)
def login(username, blogger): this_user = TestUser(username) login_user(this_user) if blogger: identity_changed.send(current_app._get_current_object(), identity=Identity(username)) return redirect("/")
def login(): print(get_locale()) print(request.user_agent.platform) print(request.user_agent.language) print(request.user_agent.browser) print(request.user_agent.version) print(request.headers.get('User-Agent')) print(request.accept_languages.best_match(['en', 'fr'])) print("============") fform = LoginForm(request.form) if request.method == 'POST' and fform.validate(): with app.db.session_scope(): if app.db.authenticate(request.form["user"], request.form["passwd"]): user = app.db.get_user_account_by_login(request.form["user"]) if user.is_admin: login_user(user) flash(gettext("Login successfull"), "success") return redirect('/') else: flash(gettext("This user is not an admin"), "warning") else: flash(gettext("Combination of username and password wrong"), "warning") return render_template('login.html', form=fform, nonav = True)
def show(page): if page == 'index': return render_template('index.html') elif page == 'map': return render_template('map.html') elif page == 'login': form = forms.LoginForm() if form.validate_on_submit(): user = models.User.get_by_username(form.username.data) if user is not None and user.check_password(form.password.data): login_user(user, form.remember_me.data) flash('Login Successful.') return redirect (request.args.get('next') or url_for('user.userPage', username=user.username)) flash('Incorrect username or password.') return redirect(url_for('main.show', page='login')) return render_template('login.html', form=form) elif page == 'signup': form = forms.SignupForm() if form.validate_on_submit(): user = models.User(username=form.username.data, email=form.email.data, password=form.password.data) db.session.add(user) db.session.commit() flash('Thanks for signing up. Please log in.') return redirect(url_for('main.show', page='login')) return render_template('signup.html', form=form) elif page == 'signout': logout_user() return redirect(url_for('main.show', page='index')) else: abort(404)
def login(): """ Login function --- consumes: - application/json tags: - users parameters: - name: email in: body required: true schema: id: user_login properties: email: type: string password: type: string required: [email, password] example: email: "" password: "" responses: 401: description: Authentication failed """ credentials = request.get_json() user = User.query.filter_by(email=credentials['email']).first() if user and bcrypt.check_password_hash(user.password, credentials['password']): login_user(user) return user_schema_secure.jsonify(user) return jsonify({}), 401
def registerUser(): form = UserRegisterForm(request.form) if form.validate_on_submit(): user = User( name = form.name.data, surname = form.surname.data, email = form.email.data, password = utils.encrypt_password(form.password.data), birth_date = form.birth_date.data, #country = form.country.data, il_id = form.il.data if form.il.data > 0 else None, ilce_id = form.ilce.data if form.ilce.data > 0 else None, semt_id = form.semt.data if form.semt.data > 0 else None, confirmed = False, active = True ) for i in form.interests.data: #dao.addObject(interests_users(interest_id=i, user_id=user.id)) user.interests.append(dao.getObject(i, InterestArea)) dao.addObject(user) dao.commit() login_user(user) flash(u'Kayıt oldunuz', 'info') return redirect(url_for('index')) return render_template('register_user.html', form=form)
def login(): print current_user if current_user.is_authenticated(): return redirect('/') if len(request.data): # 表示这是前端通过ajax发送的post请求 json_data = json.loads(request.data) user = UserEntity.query.filter_by(username=json_data['username']).first() if user is not None and user.password == hashlib.md5(json_data['password']).hexdigest(): # 登录成功 login_user(user) result = ResultModel(ResultModel.SUCCESS_CODE, ResultModel.SUCCESS_MSG, None) elif user is not None and user.password != json_data['password']: # 密码错误 result = ResultModel(ResultModel.FAILED_CODE, '密码错误', None) else: # 用户不存在 result = ResultModel(ResultModel.FAILED_CODE, '用户不存在', None) return jsonify(vars(result)) else: # 表明这是通过get方式发送的请求,因此跳转到登录页面让用户进行登录 return render_template('login.html')
def process_login(): form = LoginForm() next_url = request.args.get('next') template_data = main.config['BASE_TEMPLATE_DATA'] if form.validate_on_submit(): user_json = data_api_client.authenticate_user( form.email_address.data, form.password.data) if not user_has_role(user_json, 'supplier'): message = "login.fail: " \ "Failed to log in: %s" current_app.logger.info(message, form.email_address.data) flash("no_account", "error") return render_template( "auth/login.html", form=form, next=next_url, **template_data), 403 user = User.from_json(user_json) login_user(user) if next_url and next_url.startswith('/suppliers'): return redirect(next_url) return redirect(url_for('.dashboard')) else: return render_template( "auth/login.html", form=form, next=next_url, **template_data), 400
def login(): """ Attempt to log into the LDAP server with the authentication provided by a form. """ try: if current_user.is_authenticated(): if opt['VERBOSE']: print(current_user) return redirect(url_for('edit_data', lang='en')), 302 form = request.form username = form['user'] password = form['pass'] if opt['VERBOSE']: print(username) User.try_login(username, password) user = User.get_by_uname(username) if not user: user = User(username) user.add_to_db() session['uid'] = user.id login_user(user) return redirect(url_for('edit_data', lang='en')), 302 except Exception, ex: if opt['VERBOSE']: print(ex) return render_template('login_fail.html'), 401
def register(): form = RegistrationForm(request.form) if request.method == 'POST' and form.validate(): salt = app.config.get("PW_SALT") user = User( form.email.data, form.password.data ) db.session.add(user) db.session.commit() person = Person( user.id, form.first_name.data, form.last_name.data ) db.session.add(person) db.session.commit() login_user(user) return redirect(url_for('index.index')) return common_render('register.jinja', form=form)
def register(): """ register a new user using invite code, note that a newly registered user is not administrator, you need to use an admin user to promote it :return: response """ content = request.get_data(True, as_text=True) register_data = json.loads(content) if ('name' in register_data) and ('password' in register_data) and ('password_repeat' in register_data) and ('invite_code' in register_data) and ('email' in register_data): name = register_data['name'] password = register_data['password'] password_repeat = register_data['password_repeat'] email = register_data['email'] invite_code = register_data['invite_code'] if password != password_repeat: raise ClientError(ClientError.PASSWORD_MISMATCH) if UserCredential.register_user(name=name, password=password, email=email, invite_code=invite_code): # login automatically credential = UserCredential.login_user(name, password) login_user(credential, remember=False) # send email credential.send_confirm_email() return json_resp({'message': 'ok'}, 201) else: raise ClientError(ClientError.INVALID_REQUEST)
def _do_login_user(user, next, remember_me=False): # User must have been authenticated if not user: return unauthenticated() # Check if user account has been disabled if not _call_or_get(user.is_active): flash(_('Your account has not been enabled.'), 'error') return redirect(url_for('user.login')) # Check if user has a confirmed email address user_manager = current_app.user_manager if user_manager.enable_email and user_manager.enable_confirm_email \ and not current_app.user_manager.enable_login_without_confirm_email \ and not user.has_confirmed_email(): url = url_for('user.resend_confirm_email') flash(_('Your email address has not yet been confirmed. Check your email Inbox and Spam folders for the confirmation email or <a href="%(url)s">Re-send confirmation email</a>.', url=url), 'error') return redirect(url_for('user.login')) # Use Flask-Login to sign in user #print('login_user: remember_me=', remember_me) login_user(user, remember=remember_me) # Send user_logged_in signal signals.user_logged_in.send(current_app._get_current_object(), user=user) # Prepare one-time system message flash(_('You have signed in successfully.'), 'success') # Redirect to 'next' URL return redirect(next)
def signup(): if current_user.is_authenticated: return make_success_resp("You're already signed up") form = SignupForm() if form.validate_on_submit(): # check if user_name or email is taken if User.is_user_name_taken(form.user_name.data): return Response.make_error_resp(msg="This username is already taken!", code=409) if User.is_email_taken(form.email.data): return Response.make_error_resp(msg="This email is already taken!", code=409) try: # create new user user = User() form.populate_obj(user) db.session.add(user) db.session.commit() except Exception as e: return Response.make_exception_resp(exception=e) # log the user in login_user(user) return Response.make_success_resp(msg="You successfully signed up! Please check your email for further verification.") return Response.make_form_error_resp(form=form)
def login(): from models.models import User, db, datetime context = { 'password': request.form.get('password'), 'email': request.form.get('email'), 'msg': 'Sorry, but your login or password is incorrect', } if request.method == 'POST': query = User.query.filter_by(email=context.get('email').lower(), password=User.hash_password(context.get('password'))).first() if query: user = User(query=query) query.online = True query.active = datetime.now() db.session.commit() login_user(user, remember=True) else: return render_template('base.html', context=context) return redirect(url_for('main.index_page'))
def signup_noncommercial(): """Sign up endpoint for non-commercial users.""" mb_username = session.fetch_data(SESSION_KEY_MB_USERNAME) if not mb_username: session.persist_data(**{ SESSION_KEY_ACCOUNT_TYPE: ACCOUNT_TYPE_NONCOMMERCIAL, }) return redirect(url_for(".signup")) mb_email = session.fetch_data(SESSION_KEY_MB_EMAIL) form = NonCommercialSignUpForm(default_email=mb_email) if form.validate_on_submit(): new_user = User.add( is_commercial=False, musicbrainz_id=mb_username, contact_name=form.contact_name.data, contact_email=form.contact_email.data, data_usage_desc=form.usage_desc.data, ) login_user(new_user) flash.success("Thanks for signing up!") send_mail( subject="[MetaBrainz] Sign up confirmation", text='Dear %s,\n\nThank you for signing up!\n\nYou can now generate ' 'an access token for the MetaBrainz API on your profile page.' % new_user.contact_name, recipients=[new_user.contact_email], ) return redirect(url_for('.profile')) return render_template("users/signup-non-commercial.html", form=form)
def render_token_login_page(template, org_slug, token): try: user_id = validate_token(token) org = current_org._get_current_object() user = models.User.get_by_id_and_org(user_id, org) except NoResultFound: logger.exception("Bad user id in token. Token= , User id= %s, Org=%s", user_id, token, org_slug) return render_template("error.html", error_message="Invalid invite link. Please ask for a new one."), 400 except (SignatureExpired, BadSignature): logger.exception("Failed to verify invite token: %s, org=%s", token, org_slug) return render_template("error.html", error_message="Your invite link has expired. Please ask for a new one."), 400 status_code = 200 if request.method == 'POST': if 'password' not in request.form: flash('Bad Request') status_code = 400 elif not request.form['password']: flash('Cannot use empty password.') status_code = 400 elif len(request.form['password']) < 6: flash('Password length is too short (<6).') status_code = 400 else: # TODO: set active flag user.hash_password(request.form['password']) models.db.session.add(user) login_user(user) models.db.session.commit() return redirect(url_for('redash.index', org_slug=org_slug)) if settings.GOOGLE_OAUTH_ENABLED: google_auth_url = get_google_auth_url(url_for('redash.index', org_slug=org_slug)) else: google_auth_url = '' return render_template(template, google_auth_url=google_auth_url, user=user), status_code
def login(): if request.method == 'POST': next_page = request.args.get('next') username = request.form['username'] password = request.form['password'] user = biobot.credentials.find_one({'username': username}) if user and check_password(user['password'], password): if user['active']: # Inactived users should not be able to log in login_user(User(username)) biobot.credentials.update_one(user, {'$set': {'last_login' : time.time()}}) # If an admin logs in and there is at least one inactived user, show it if user['admin'] and biobot.credentials.find_one({'active': False}): flash('At least one user account has to be activated', 'info') return redirect(url_for('manage_users')) return redirect(next_page or url_for('home')) else: flash('Account not yet activated by an administrator', 'warning') else: flash('Invalid credentials', 'danger') return render_template('login.html') else: return render_template('login.html')
def login(self, request, session=None): if current_user.is_authenticated(): flash("You are already logged in") return redirect(url_for('admin.index')) username = None password = None form = LoginForm(request.form) if request.method == 'POST' and form.validate(): username = request.form.get("username") password = request.form.get("password") try: user = authenticate(session, username, password) flask_login.login_user(user) return redirect(request.args.get("next") or url_for("admin.index")) except AuthenticationError: flash("Incorrect login details") return self.render('airflow/login.html', title="Airflow - Login", form=form) finally: session.commit() session.close()
def login(): if current_user is not None and current_user.is_authenticated: return redirect(url_for('home')) form = LoginForm() if request.method == "POST" and form.validate_on_submit(): # change this to actually validate the entire form submission # and not just one field username = form.username.data password = form.password.data user = UserProfile.query.filter_by(username=username,password=password).first() # Get the username and password values from the form. # using your model, query database for a user based on the username # and password submitted # store the result of that query to a `user` variable so it can be # passed to the login_user() method. # get user id, load into session if user is not None: login_user(user) # remember to flash a message to the user flash ('Logged in successfully.', 'success') return redirect(url_for("securepage")) # they should be redirected to a secure-page route instead else: flash ('Username or Password incorrect','danger') flash_errors(form) return render_template("login.html", form=form)
def authenticate(cls, username, password): admin = Admin.query.filter_by(username=username).first() if admin is not None and pwd_context.verify(password, admin.password): login_user(admin) return True else: return False
def oauth_callback(provider): if not current_user.is_anonymous(): return redirect(url_for('simple_page.index')) oauth = OAuthSignIn.get_provider(provider) social_id, username, email = oauth.callback() if social_id is None: flash(getttext(u'Authentication failed'), 'danger') return redirect(url_for('simple_page.index')) # check if user exists and if no creates new user = User.query.filter_by(social_id=social_id).first() if user is None: user = User( username=username, password='', email=email, social_id=social_id ) db.session.add(user) db.session.commit() login_user(user, remember=True) user.update_login_info() return redirect(url_for('simple_page.index'))
def activate_account(token=None): """Handles the account activation process.""" if current_user.is_active or not flaskbb_config["ACTIVATE_ACCOUNT"]: flash(_("This account is already activated."), "info") return redirect(url_for('forum.index')) form = None if token is not None: expired, invalid, user = get_token_status(token, "activate_account") else: form = AccountActivationForm() if form.validate_on_submit(): expired, invalid, user = get_token_status(form.token.data, "activate_account") if invalid: flash(_("Your account activation token is invalid."), "danger") return redirect(url_for("auth.request_email_confirmation")) if expired: flash(_("Your account activation token is expired."), "danger") return redirect(url_for("auth.request_activation_token")) if user: user.activated = True user.save() if current_user != user: logout_user() login_user(user) flash(_("Your account has been activated."), "success") return redirect(url_for("forum.index")) return render_template("auth/account_activation.html", form=form)
def login(): sitename = "Einloggen" if current_user.is_authenticated: return redirect(url_for("index")) form = LoginForm() # If csrf-token error: # form = LoginForm(meta={'csrf': True}) if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): login_user(user, remember=form.remember.data) next_page = request.args.get("next") return redirect(next_page) if next_page else redirect( url_for("account")) else: flash( "Login nicht erfolgreich. Bitte überprüfe die E-Mail und das Passwort.", "danger") return render_template("login.html", form=form, title=sitename, sitename=sitename)
def authorized(): if request.args.get('state') != session.get("state"): return redirect(url_for("home")) # No-OP. Goes back to Index page if "error" in request.args: # Authentication/Authorization failure app.logger.info('Failed attempt: login failed using Sign in with Microsoft') return render_template("auth_error.html", result=request.args) if request.args.get('code'): cache = _load_cache() # TODO: Acquire a token from a built msal app, along with the appropriate redirect URI result = _build_msal_app(cache=cache).acquire_token_by_authorization_code( request.args['code'], scopes=Config.SCOPE, redirect_uri=url_for('authorized', _external=True, _scheme='https')) if "error" in result: return render_template("auth_error.html", result=result) session["user"] = result.get("id_token_claims") # Note: In a real app, we'd use the 'name' property from session["user"] below # Here, we'll use the admin username for anyone who is authenticated by MS user = User.query.filter_by(username="******").first() login_user(user) app.logger.info('Login Success: Successfully logged in with "Sign-in with Microsoft"!') _save_cache(cache) return redirect(url_for('home'))
def register_user(): payload = request.get_json() payload['email'] = payload['email'].lower() try: models.User.get(models.User.email == payload['email'] and models.User.username == payload['username']) return jsonify(data={}, message="User with email or username already exists", status=401),401 except models.DoesNotExist: created_user = models.User.create( username= payload['username'], email=payload['email'], password=generate_password_hash(payload['password']), age= payload['age'], school= payload['school'], ) login_user(created_user) user_dict = model_to_dict(created_user) user_dict.pop('password') return jsonify( data= user_dict, message='created an account', status=201),201
def index(): """Login or Register Page""" # If user logged in, redirect to dashboard if current_user.is_authenticated: return redirect(url_for('dashboard')) show_form = 'login' if request.args.get( 'show_form') == 'login' else 'register' registration_form = RegistrationForm() login_form = LoginForm() if registration_form.validate_on_submit(): flash('Thanks for registering') user = User.query.filter( (User.username == registration_form.username.data) | (User.email == registration_form.email.data)).first() if not user: hashed_password = generate_password_hash( registration_form.password.data) new_user = User(username=registration_form.username.data, fullname=registration_form.fullname.data, email=registration_form.email.data, password=hashed_password) db.session.add(new_user) db.session.commit() return redirect(url_for('index', show_form='login')) return '<h1>Username or Email has been used!</h1>' if login_form.validate_on_submit(): user = User.query.filter_by(email=login_form.email.data).first() if user: if check_password_hash(user.password, login_form.password.data): login_user(user, remember=login_form.remember.data) return redirect(url_for('dashboard')) return '<h1>Invalid username or password!</h1>' return render_template('index.html', registration_form=registration_form, login_form=login_form, show_form=show_form)
def signup(): form = SignupForm() if request.method == 'GET': return render_template('signup.html', form=form) elif request.method == 'POST': if form.validate(): if User.query.filter_by(email=form.email.data).first(): return "Email address already exists" if User.query.filter_by(username=form.username.data).first(): return "username already exists" else: newuser = User(email=form.email.data, password=form.password.data, username=form.username.data, name=form.name.data, lastname=form.lastname.data) db.session.add(newuser) db.session.commit() login_user(newuser) subject = "Confirm your email" token = ts.dumps(form.email.data, salt='email-confirm-key') confirm_url = url_for('confirm_email', token=token, _external=True) html = render_template('activate.html', confirm_url=confirm_url) send_email(newuser.email, subject=subject, contents=html) return "User created!!! check {}".format(newuser.email) else: return "Form didn't validate"
def register(): if not request.is_json: abort(400, "Not JSON") data = request.json user = User() password = data.get("password") email = data.get("email") if not (password and email): abort(400, "Password and email not given") if User.query.filter(User.email == email).count() > 0: abort(400, "email already registered") if len(password) < 6: abort(400, "password too short") token = generate_random_string(64) firebase_user = auth.create_user(email=email, email_verified=False, password=password, disabled=False) user.password = password user.email = email user.token = token user.firebase_uid = firebase_user.uid db.session.add(user) db.session.commit() login_user(user) return jsonify(token=token), 200
def login(): form = request.form if request.method == "POST": # change this to actually validate the entire form submission # and not just one field # Get the username and password values from the form. username = form["username"].lower() password = form["password"] # could use request.form['password'] # using your model, query database for a user based on the username # and password submitted. Remember you need to compare the password hash. # You will need to import the appropriate function to do so. # Then store the result of that query to a `user` variable so it can be # passed to the login_user() method below. user = User.query.filter_by(username=username).first() if user is not None and check_password_hash(user.password, password): login_user(user) token = jwt.encode( { "public_id": user.id, "exp": datetime.utcnow() + timedelta(minutes=30), }, app.config["SECRET_KEY"], ) return make_response( jsonify({ "token": token, "user": user.to_json() }), 201) return make_response( "Could not verify", 403, {"WWW-Authenticate": 'Basic realm ="Wrong Password !!"'}, )
def login(): body = request.json received_user_email = body['email'] if not (isinstance(body['email'], str) and isinstance(body['password'], str)): abort(400) session = get_session() try: user = session.query(User).filter( User.email == str(received_user_email)).one() received_password = crypt(body['password'], user.password) if received_password == user.password: login_user(user) response = make_response( json.dumps({ 'error': False, 'message': 'authorized' }), 200) else: response = make_response( json.dumps({ 'error': 401, 'message': 'unauthorized' }), 401) except (MultipleResultsFound, NoResultFound): response = make_response( json.dumps({ 'error': 401, 'message': 'unauthorized' }), 401) session.close() return response
def login(): if current_user.is_authenticated: #检查用户是否已经登录 return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): #form.validate_on_submit()实例方法会执行form校验的工作。 # 当浏览器发起GET请求的时候,它返回False #当用户在浏览器点击提交按钮后,浏览器会发送POST请求。 # form.validate_on_submit()就会获取到所有的数据,运行字段各自的验证器, # 全部通过之后就会返回True,这表示数据有效 # flash('Login requested for user {}, remember_me={}'.format( # form.username.data, form.remember_me.data)) # return redirect(url_for('index')) user = User.query.filter_by(username=form.username.data).first() #filter_by()的结果是一个只包含具有匹配用户名的对象的查询结果集,当你只需要一个结果时, #通常使用first()方法 if user is None or not user.check_password(form.password.data): flash(_('Invalid username or password')) return redirect(url_for('login')) login_user(user, remember=form.remember_me.data) #将用户登录状态注册为已登录,这意味着用户导航到任何未来的页面时, #应用都会将用户实例赋值给current_user变量。 next_page = request.args.get('next') #实现登录成功之后自定重定向回到用户之前想要访问的页面 #当一个没有登录的用户访问被@login_required装饰器保护的视图函数时, #装饰器将重定向到登录页面,不过,它将在这个重定向中包含一些额外的信息以便登录后的回转 if not next_page or url_parse(next_page).netloc != '': #攻击者可以在next参数中插入一个指向恶意站点的URL,因此应用仅在重定向URL是相对路径时 #才执行重定向,这可确保重定向与应用保持在同一站点中。 为了确定URL是相对的还是绝对的, #我使用Werkzeug的url_parse()函数解析,然后检查netloc属性是否被设置。 next_page = url_for('index') return redirect(next_page) return render_template('login.html', title=_('Sign In'), form=form)
def login(): form = LoginForm() if flask.request.method == "POST": if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user is None: return render_template( "login_form.html", title="Login", form=form, form_title="Login", login_failure=True, ) if not check_password_hash(user.password, form.password.data): abort(403) user.create_session() user = user.save() login_user(user) user_activity = UserActivity(activity_name="login", user=user) user_activity.save() return redirect(url_for("spell_check")) else: return render_template( "login_form.html", title="Login", form=form, form_title="Login", login_failure=True, ) # default is a GET request return render_template( "login_form.html", title="Login", form=form, form_title="Login" )
def login(): if isinstance(current_user._get_current_object(), Manager): logout_user() if current_user.is_authenticated: if isinstance(current_user._get_current_object(), Student): return redirect(url_for('student_index')) elif isinstance(current_user._get_current_object(), Teacher): return redirect(url_for('teacher_index')) if request.method == 'POST': username = request.form['username'] password = request.form['password'] remember = request.form.get('remember') remember = [True if remember=='on' else False][0] error = None is_student = 1 user = Student.query.filter_by(StudentNum=username).first() # 判断是否为学生 if not user: # 若不是,则选取老师 is_student = 0 user = Teacher.query.filter_by(TeacherNum=username).first() if not user: error = '学号不存在!' elif not user.check_password(password): error = '密码错误!' if error is None: login_user(user, remember=remember) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('index') if is_student: return redirect(url_for('student_index')) else: return redirect(url_for('teacher_index')) flash(error) return render_template('login.html')
def facebook_authorized(): resp = facebook.authorized_response() if resp is None: flash("Failed to log in with facebook.", category="error") return 'Access denied: reason=%s error=%s' % ( request.args['error_reason'], request.args['error_description']) session['facebook_token'] = (resp['access_token'], '') user_facebook = facebook.get('/me?fields=name,email,id').data # Check if user already exists, else update user = User.query.filter_by(email=user_facebook["email"]).first() if user: login_user(user, True) flash('You are now logged in. Welcome back!', 'success') return redirect(request.args.get('next') or url_for('main.index')) else: # Create a new local user account for this user max_id = db.session.query(db.func.max(User.id)).scalar() user = User(id=max_id + 1, email=user_facebook["email"], social_id=user_facebook["id"], social_provider="facebook", first_name=user_facebook["name"], confirmed=True) # Save and commit our database models db.session.add(user) db.session.commit() session['user_id'] = user.id login_user(user, True) flash('You are now logged in. Welcome!', 'success') return redirect(request.args.get('next') or url_for('main.index')) return False
def login_view(self): if current_user.is_authenticated: return redirect(url_for('home_bp.index')) if request.method == 'POST': email = request.form['email'] password = request.form['password'] user = self.datastore.get_user_by_email(email) if not user: current_app.logger.info('%s does not exist', email) return jsonify({ 'status': 401, 'redirect': False, 'address': None, 'message': 'Incorrect Email or Password', 'model': None }) if user.check_password(password): login_user(user) user.authenticated = True self.datastore.update_user_by_model(user) return jsonify({ 'status': 200, 'redirect': True, 'address': '/', 'message': 'Successully logged in', 'model': None }) else: current_app.logger.info('%s failed to log in', email) return jsonify({ 'status': 401, 'redirect': False, 'address': None, 'message': 'Incorrect Email or Password', 'model': None }) return render_template(self.FLASK_SECURITY_LOGIN_TEMPLATE)
def signup(): # don't go to signup page if the user is already logged in if not current_user.is_anonymous and current_user.is_authenticated: return redirect(url_for("search")) error = None if request.method == "POST": username = request.form["username"] password = request.form["password"] password_duplicate = request.form["password_duplicate"] # The checks that the username has only allowed characters, that the # password is at least pw_min_len characters long, and that the 2 # passwords match is all done on the front end. # capitalisation is preserved for a given user, # but duplicate username check is case insensitive # Check that the username is not already in use if load_user(username) != None: error = "Username already in use." # No error, add the user to the database and sign in if error == None: create_account(username, password) user = load_user(username) login_success = user.check_password(password) assert(login_success) # this must succeed login_user(user) return redirect(url_for("search")) template = LOOKUP.get_template("signup.html") return template.render( username = get_username(), error=error, pw_min_len=pw_min_len )
def login(): form = LoginForm() if form.validate_on_submit(): name = form.username.data pwd = form.password.data user = User.query.filter_by(name=name).first() if user == None: if name in admins: user = User(name=name, password=pwd, registered=1, enable=1, date=get_date(), authkey=generate_key()) db.session.add(user) db.session.commit() else: log_info('账号未注册,请联系管理员') else: if user.registered == 0: return redirect(url_for('register')) if user.enable == 0: log_info('登陆失败, 请联系管理员') else: if (str(user.password) == pwd): session.permanent = True app.permanent_session_lifetime = timedelta(hours=1) # if user and user.check_password_hash(pwd): login_user(user) if user.name in admins: return redirect(url_for('home')) else: return redirect(url_for('details', name=user.name)) else: log_info("密码错误") return render_template('login.html', title='用户登录', form=form)
def login(): if current_user.is_authenticated: return redirect(url_for('index')) login_form = LoginForm(prefix='log') if login_form.submit.data and login_form.validate_on_submit(): # flash('Login requested for user {}, remember_me={}'.format(form.usermail.data, form.remember_me.data)) customer = CustomersDB.get(login_form.usermail.data) if not customer or not customer.check_pass(login_form.password.data): flash('Invalid username or password') return redirect(url_for('login')) login_user(customer, remember=login_form.remember_me.data) return redirect(url_for('index')) signup_form = SignupForm(prefix='sign') if signup_form.submit.data and signup_form.validate_on_submit(): if CustomersDB.get(signup_form.email.data): flash('Given e-mail already registered') return redirect(url_for('login')) new_user = Customer( name=signup_form.name.data, surname=signup_form.surname.data, password=signup_form.password.data, street=signup_form.street.data, email=signup_form.email.data, phone=signup_form.phone.data, postal_code=signup_form.postal_code.data, city=signup_form.city.data, country=signup_form.country.data ) success = CustomersDB.add(new_user) if success: flash('You are registered, plaease Log in!') else: flash('Something gone wrong, try again') return redirect(url_for('login')) return render_template('login.html', global_title=NAME, position='../', after_title=' | Log In', login_form=login_form, signup_form=signup_form)
def wrapper(*args, **kwargs): logout_user() StrUtil.print_debug('adm_login_required. func=[{}]'.format( str(func.__name__))) session_id = app.lib.cms_lib.session.get_session_id( StrUtil.get_safe_config(current_app, 'CMS_SYS_COOKIE')) if session_id: StrUtil.print_debug( 'login_required. session_cookie_name:{0} session_id:{1}'. format('ADMIN_SESSION_COOKIE', session_id)) cst = CmsSessionTable.get_adm_session_info(session_id) if cst is None: flash('invalid user_id or password') return redirect(url_for('adm_login')) # 取得したユーザIDでユーザ情報を取得する user = User.query.filter_by(tuid=cst.user_id).first() if user is None: flash('invalid user_id or password') return redirect(url_for('adm_login')) # 管理者権限チェック pkgCmsSecurity = PkgCmsSecurity() if not pkgCmsSecurity.isAdminUser(user.tuid): flash('利用権限がありません') return redirect( UserAuth._get_redirect_url(url_for('adm_login'))) login_user(user, False) else: StrUtil.print_debug('login_required. no session id got.') return redirect( UserAuth._get_redirect_url(url_for('adm_login'))) return func(*args, **kwargs)
def callback(): """Exchange the 'code' for Cognito tokens""" #http://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html csrf_state = request.args.get('state') code = request.args.get('code') request_parameters = { 'grant_type': 'authorization_code', 'client_id': config.COGNITO_CLIENT_ID, 'code': code, "redirect_uri": config.BASE_URL + "/callback" } response = requests.post("https://%s/oauth2/token" % config.COGNITO_DOMAIN, data=request_parameters, auth=HTTPBasicAuth(config.COGNITO_CLIENT_ID, config.COGNITO_CLIENT_SECRET)) # the response: # http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html if response.status_code == requests.codes.ok and csrf_state == session[ 'csrf_state']: verify(response.json()["access_token"]) id_token = verify(response.json()["id_token"], response.json()["access_token"]) user = User() user.id = id_token["cognito:username"] session['nickname'] = id_token["nickname"] session['expires'] = id_token["exp"] session['refresh_token'] = response.json()["refresh_token"] flask_login.login_user(user, remember=True) return redirect(url_for("home")) return render_template_string(""" {% extends "main.html" %} {% block content %} <p>Something went wrong</p> {% endblock %}""")
def login(): loginform = LoginForm() if loginform.validate_on_submit() and request.method == "POST": username = loginform.username.data password = loginform.password.data user = Users.query.filter_by(username=username).first() if user is not None and check_password_hash(user.password, password): login_user(user) payload = { "username": user.username, "user": user.name, 'iat': datetime.datetime.now(datetime.timezone.utc), 'exp': datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(minutes=30) } encoded_jwt = jwt.encode(payload, app.config['SECRET_KEY'], algorithm='HS256') message = { "message": "Login Successful", "token": encoded_jwt, "id": user.id } return jsonify(message=message) else: errors = {"errors": ["Username or Password is incorrect."]} return jsonify(errors=errors) else: errors = {"errors": form_errors(loginform)} return jsonify(errors=errors)
def test_has_upload_permissions(app): # Test uploader permissions with app.app_context(): # Create a record recid = '12345' get_or_create_hepsubmission(recid, 1) # Check admin user has upload permissions to new record admin_user = user = User.query.first() assert has_upload_permissions(recid, admin_user) # Create a user who is not admin and not associated with a record user = User(email='*****@*****.**', password='******', active=True) db.session.add(user) db.session.commit() login_user(user) assert not has_upload_permissions(recid, user) # Add the user as an uploader but not primary - should not be allowed submission_participant = SubmissionParticipant(user_account=user.id, publication_recid=recid, email=user.email, role='uploader') db.session.add(submission_participant) db.session.commit() assert not has_upload_permissions(recid, user) # Make the participant primary uploader - should now work submission_participant.status = 'primary' db.session.add(submission_participant) db.session.commit() assert has_upload_permissions(recid, user)
def oauth2callback(): # Specify the state when creating the flow in the callback so that it can # verified in the authorization server response. state = session['state'] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES, state=state) flow.redirect_uri = url_for('auth.oauth2callback', _external=True) # Use the authorization server's response to fetch the OAuth 2.0 tokens. authorization_response = request.url flow.fetch_token(authorization_response=authorization_response) # Store credentials in the session. # ACTION ITEM: In a production app, you likely want to save these # credentials in a persistent database instead. credentials = flow.credentials session['credentials'] = credentials_to_dict(credentials) youtube = build(API_SERVICE_NAME, API_VERSION, credentials=credentials) response = youtube.channels().list(part='id,snippet', mine=True).execute() if 'items' in response: channel = response['items'] unique_id = channel[0]['id'] profile_pic = channel[0]['snippet']['thumbnails']['default']['url'] # If the user doesn't exist, add it to the database if not User.get(unique_id): User.create(unique_id, profile_pic) # Either way, collect the user from the database user = User.get(unique_id) login_user(user) return redirect(url_for('index')) else: return redirect(url_for('auth.error'))
def google_auth(): token = google.authorize_access_token() resp = google.get('oauth2/v3/userinfo') resp.raise_for_status() profile = resp.json() user = User.query.filter_by(email=profile['email']).first() if user: user.name = profile['name'] user.picture = profile['picture'] else: user = User( username=profile['login'], name=profile['name'], email=profile['email'], picture=profile['picture'], type='google' ) db.session.add(user) oauth_token = OAuth2Token.query.filter_by(user=user, name='google').first() if oauth_token: oauth_token.access_token = token['access_token'] oauth_token.token_type = token['token_type'] oauth_token.expires_at = token['expires_at'] else: oauth_token = OAuth2Token( user=user, name='google', access_token=token['access_token'], token_type=token['token_type'], expires_at=token['expires_at'] ) db.session.add(oauth_token) db.session.commit() login_user(user) next_url = session.pop('oauth_origin', None) return redirect(next_url or url_for('home'))
def phone(): """ 手机登录认证 """ if current_user and current_user.is_authenticated: return redirect(url_for('index')) if not SWITCH_LOGIN_PHONE: flash(u'手机登录功能关闭,暂不支持手机登录', 'warning') return redirect(url_for('index')) form = LoginPhoneForm() if request.method == 'POST': if form.validate_on_submit(): # 手机号码国际化 area_id = form.area_id.data area_code = area_code_map.get(area_id, '86') mobile_iso = '%s%s' % (area_code, form.phone.data) # 获取认证信息 condition = { 'type_auth': TYPE_AUTH_PHONE, 'auth_key': mobile_iso, 'auth_secret': md5(form.password.data) } user_auth_info = get_user_auth_row(**condition) if not user_auth_info: flash(u'%s, 登录失败,请检查内容后重新登录' % form.phone.data, 'warning') return render_template('auth/phone.html', title='login', form=form) if user_auth_info.status_verified == 0: flash(u'%s, 登录手机尚未验证,请先验证手机' % form.phone.data, 'warning') return render_template('auth/phone.html', title='login', form=form) # session['logged_in'] = True # 用 login_user 函数来登入他们 login_user(get_user_row_by_id(user_auth_info.user_id), remember=form.remember.data) flash(u'%s, 恭喜,您已成功登录' % form.phone.data, 'success') return redirect(request.args.get('next') or url_for('index')) # flash(form.errors, 'warning') # 调试打开 return render_template('auth/phone.html', title='login', form=form, SWITCH_LOGIN_THREE_PART=SWITCH_LOGIN_THREE_PART)
def register(): payload = request.get_json() print("payload", payload) payload['email'] = payload['email'].lower() payload['username'] = payload['username'].lower() print("payload after l/c", payload) try: models.User.get(models.User.email == payload['email']) return jsonify( data={}, message="A user registered with this email already exists.", status=401), 401 except models.DoesNotExist: try: models.User.get(models.User.username == payload['username']) return jsonify(data={}, message="A user with this username already exists.", status=401), 401 except models.DoesNotExist: pw_hash = generate_password_hash(payload['password']) created_user = models.User.create(username=payload['username'], email=payload['email'], password=pw_hash, city=payload['city'], state=payload['state'], picture=payload['picture']) login_user(created_user) created_user_dict = model_to_dict(created_user) print(created_user_dict) created_user_dict.pop('password') return jsonify(data=created_user_dict, message="registered a new user", status=201), 201
def post(self): keys = ('username', 'password') rjson = request.json if rjson is None: return Response.missing_parameters() if all(elem in rjson for elem in keys): if '' in rjson.values(): return Response.invalid_arguments() user = User.objects(username=rjson['username']).first() if user and bcrypt.check_password_hash(user.password, rjson['password']): login_user(user) return make_response( jsonify({ "status": "success", "message": "successful log in!", "access_token": create_access_token( identity=user.username, expires_delta=timedelta(minutes=60)), "refresh_token": create_refresh_token( identity=user.username, expires_delta=timedelta(minutes=60)) })) else: return Response.wrong_credentials() else: return Response.missing_parameters() return Response.unexpected_error()
def login(): # user = User(username="******", password=generate_password_hash("07161997"), name="Jordan Pizza", id="07161997", admin=1) # db_session.add(user) # db_session.commit() if request.method == 'POST': username = request.form['username'] password = request.form['password'] registered_user = User.query.filter_by(username=username).first() if registered_user is None: return render_template('login.html', error="That user doesn't exist.") if not registered_user.check_password(password): return render_template('login.html', error="That didn't work.") else: login_user(registered_user, remember=True) return redirect(url_for("home")) # session.add(registered_user) # session.commit() # if registered_user.is_authenticated(): # login_user(registered_user, remember=True) # return redirect(url_for("home")) elif request.method == "GET": error = request.args.get('error', default=None, type=str) if not error == None: return render_template('login.html', error=error) # if not current_user.is_anonymous(): # current_user.check_login() if current_user.is_authenticated(): return redirect(url_for("home")) return render_template('login.html')
def login(): login_form = UserLogin() register_form = UserRegistration() if login_form.validate_on_submit(): username = login_form.username.data password = login_form.password.data remember_me = login_form.remember_me.data user = User.query.filter( func.lower(User.username) == func.lower(username)).first() if login_user(user, remember_me): flash("You were logged in.", "success") if user.invitations.count(): markup = f'You have {user.invitations.count()} team invitations' markup += f'- click <a href="{url_for("invitations")}">here</a> to view them.' flash(Markup(markup), "info") return redirect(request.args.get("next") or url_for('index')) # Tell Flask-Principal the identity changed identity_changed.send(current_app._get_current_object(), identity=Identity(user.id)) else: flash("Login failed, user not validated", "error") return redirect(url_for("verify_status", username=username)) elif register_form.validate_on_submit(): username = register_form.username.data.strip() password = register_form.password.data email = register_form.email.data new_user = User(username, password, email) body = render_template("emails/account/verification.txt", recipient=new_user, email_changed=False) mail.send_message( subject=f"Welcome to {app.config['LONG_NAME']}, {username}", recipients=[new_user.email], body=body) db.session.add(new_user) db.session.commit() flash("Your account has been created, confirm your email to verify.", "success") return redirect(url_for('verify_status', username=username)) return render_template('account/login.html', login_form=login_form, register_form=register_form)
def login_usuario(): if current_user.is_authenticated: return redirect(url_for('home')) form = UserLoginForm() if form.validate_on_submit(): usuario = Usuario.query.filter_by(nombre=form.nombre.data).first() if usuario is None or not usuario.check_password(form.password.data): flash('Nombre de usuario o contraseña es incorrecto', 'danger') return redirect(url_for('login_usuario')) login_user(usuario, remember=form.remember_me.data) app.logger.info(f'{datetime.now()}: {usuario} logged in') flash(f'Bienvenido {usuario.nombre}!', 'success') next_page = request.args.get('next') if next_page: try: next_page = my_utils.get_last_dir_url(next_page) return redirect(url_for(next_page)) except BuildError: app.logger.info( f'{datetime.now()}: Wierd redirect: {next_page} from {current_user} - {request.remote_addr}' ) return redirect(url_for('home')) else: return redirect(url_for('home')) return render_template('login.html', barra_busqueda=True, titulo='Login', form=form, debug=app.config['DEBUG'])
def flash_errors(form): for field, errors in form.errors.items(): for error in errors: flash(u"Error in the %s field - %s" % ( getattr(form, field).label.text, error ), 'danger') if form.username.data: # Get the username and password values from the form. # using your model, query database for a user based on the username # and password submitted. Remember you need to compare the password hash. # You will need to import the appropriate function to do so. # Then store the result of that query to a `user` variable so it can be # passed to the login_user() method below. # get user id, load into session login_user(user) # remember to flash a message to the user return redirect(url_for("home")) # they should be redirected to a secure-page route instead return render_template("login.html", form=form)
def register(): """Route for Register Page""" # if user already logged in, redirect to main page if g.user is not None and g.user.is_authenticated: return redirect(url_for('index')) form = RegisterForm() if request.method == 'GET': return render_template('register.html', form=form) # validate form submission if form.validate_on_submit(): email = request.form['email'] apartment = request.form['apartment'] password = request.form['password'] u = User(email, apartment, password, 1, datetime.now()) db.session.add(u) db.session.commit() login_user(u) flash('Thank you for signing up!', 'success') return redirect(url_for('edit')) return render_template('register.html', form=form)