Ejemplo n.º 1
0
def edit_password():
    if request.method == 'POST':
        old_password = request.form.get('old_password')
        new_password = bcrypt.generate_password_hash(request.form.get('new_password')).decode('utf-8')
        new_password_verify = request.form.get('new_password_verify')

        try:
            username=session['username']
            sprawdzanie_uzytkownika_haslo = User.query.filter_by(username=username).first()

            if not bcrypt.check_password_hash(sprawdzanie_uzytkownika_haslo.password, old_password):
                flash("Podaleś błędne stare hasło!", 'danger')
                return render_template('edit_password.html')

            if not bcrypt.check_password_hash(new_password, new_password_verify):
                flash("Podane hasła się nie zgadzają!", 'danger')
                return render_template('edit_password.html')


            sprawdzanie_uzytkownika_haslo.password = new_password
            db.session.commit()
            flash("Hasło zmienione", 'success')
            return redirect('/login')

        except ServerError as err:
            flash(str(err), 'danger')
            return render_template('edit_password.html')


    return render_template('edit_password.html')
Ejemplo n.º 2
0
 def post(self):
     # get the post data
     post_data = request.get_json()
     try:
         # fetch the user data
         user = User.query.filter_by(email=post_data['email']).first()
         if user and bcrypt.check_password_hash(user.password,
                                                post_data['password']):
             auth_token = user.encode_auth_token(user.id)
             if auth_token:
                 responseObject = {
                     'token': auth_token.decode(),
                     'profile': {
                         'id': user.id,
                         'username': user.fullname,
                         'email': user.email
                     }
                 }
                 return make_response(jsonify(responseObject)), 200
         else:
             responseObject = {
                 'status': 'fail',
                 'message': 'User does not exist.'
             }
             return make_response(jsonify(responseObject)), 404
     except Exception as e:
         print(e)
         responseObject = {'status': 'fail', 'message': 'Try again'}
         return make_response(jsonify(responseObject)), 500
Ejemplo n.º 3
0
 def validate_password(self, password):
     subscriber = Subscriber.query.filter_by(email = self.email.data).first()
     if subscriber:
         check_password = bcrypt.check_password_hash(subscriber.password,
                                                     password.data)
         if not check_password:
             raise ValidationError('Wrong password')
Ejemplo n.º 4
0
    def post(self):
        args = self.parser.parse_args()

        try:
            student = StudentModel.query.get(args['id'])

            if student:
                password = student.password
                correct = bcrypt.check_password_hash(
                    password, args['password'])

                if correct:
                    acess_token = create_access_token(identity=student.id)
                    return {
                        'message': 'Logged successfully',
                        'acess_token': acess_token
                    }

                return {'message': 'Invalid credencials'}

            return {'message': 'Invalid credencials'}

        except Exception as e:
            print(e)
            return {'message': 'Something got wrong'}
Ejemplo n.º 5
0
def login():

    if current_user.is_authenticated:
        flash("Already Logged In.", "success")
        return redirect(url_for("home"))
    form = LoginForm()
    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")
            flash(f"Login Successful. Welcome {user.username}", "success")

            # Stored until user has logged out
            session["username"] = user.username
            session["email"] = user.email

            if form.category.data == "Employer":
                return (redirect(next_page) if next_page else redirect(
                    url_for("employer")))
            elif form.category.data == "Employee":
                return (
                    # redirect(next_page) if next_page else redirect(url_for("employee"))
                    plaid_authenticate())
            else:
                return redirect(next_page) if next_page else redirect(
                    url_for("home"))
        else:
            flash(
                "Login Unsuccessful. Check your email and password and try again!",
                "danger",
            )

    return render_template("login.html", title="Login", form=form)
Ejemplo n.º 6
0
def login():
    if 'username' in session:
        return redirect(url_for('info'))

    if request.method == 'POST':
        username_form = request.form.get('username')
        password_form = request.form.get('password')

        try:
            szukany_uzytkownik = User.query.filter_by(username=username_form).first()
        except ServerError as err:
            flash(str(err), 'danger')
            return render_template('login.html')

        if szukany_uzytkownik is None:
            flash("Zły login lub hasło!", 'danger')
            return render_template('login.html')

        if not bcrypt.check_password_hash(szukany_uzytkownik.password, password_form):
            flash("Zły login lub hasło!", 'danger')
            return render_template('login.html')

        session['username'] = username_form
        session.pop('adminMode', None)
        if (szukany_uzytkownik.is_admin()):
            session['admin'] = True
        login_user(szukany_uzytkownik)
        return redirect(url_for('info'))
    return render_template('login.html')
Ejemplo n.º 7
0
def login():
    if not request.is_json:
        return jsonify({"msg": "Missing JSON in request"}), 400

    username_form = request.json.get('username', None)
    password_form = request.json.get('password', None)

    if not username_form or len(str(username_form).replace(" ", "")) == 0:
        field = {'field': 'username'}
        raise FormMissingParametersException(payload=field, program='login')

    if not password_form or len(str(password_form).replace(" ", "")) == 0:
        field = {'field': 'password'}
        raise FormMissingParametersException(payload=field, program='login')

    user = User.query.filter(User.username == username_form).first()

    if user is None:
        field = {'error': 'Usuario nao cadastrado'}
        raise AuthException(payload=field, program='login')

    if not bcrypt.check_password_hash(user.password, password_form):
        field = {'error': 'Senha incorreta'}
        raise AuthException(payload=field, program='login')

    # Identity can be any data that is json serializable
    access_token = create_access_token(identity=user.username)
    return jsonify(access_token=access_token), 200
Ejemplo n.º 8
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))

    form = login_form()
    # print(request.args.get('next'))
    if form.validate_on_submit():
        print(form.password.data)
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            if bcrypt.check_password_hash(user.password, form.password.data):
                login_user(user)

                next_page = request.args.get('next')
                if next_page:
                    return redirect(next_page)
                else:
                    return redirect(url_for('home'))
            else:
                flash('Incorrect password', 'danger')
        else:
            flash('Email is not yet registered', 'danger')

    return render_template('login.html',
                           title='HOME',
                           mssge='Random Message',
                           form=form,
                           header='Login')
Ejemplo n.º 9
0
def login():
    auth = request.get_json()
    print(auth)
    if not auth or not auth['email'] or not auth['password']:
        return make_response(
            'Could not verify', 401,
            {'WWW-Authenticate': 'Basic realm="Login required!"'})

    user = User.query.filter_by(email=auth['email']).first()

    if not user:
        return make_response(
            'Such user doesn\'t exist', 401,
            {'WWW-Authenticate': 'Basic realm="Login required!"'})

    if bcrypt.check_password_hash(user.password, auth['password']):
        token = jwt.encode(
            {
                'id': user.id,
                'exp':
                datetime.datetime.utcnow() + datetime.timedelta(minutes=30)
            }, app.config['SECRET_KEY'])
        result = user_schema.dump(user)
        return jsonify({
            'token': token.decode('UTF-8'),
            'userId': result['id']
        })

    return make_response('Could not verify', 401,
                         {'WWW-Authenticate': 'Basic realm="Login required!"'})
def auth_login():

    email = request.form.get('email')
    password = request.form.get('password')
    # if current_user.is_authenticated:
    #     return redirect(url_for('home'))
    # form = LoginForm()
    # 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')
    #         expiry = timedelta(days=1)
    #         access_token = create_access_token(identity=str(user.id), expires_delta=expiry)
    #         return redirect(next_page) if next_page else redirect(url_for('home'))
    #     else:
    #         flash('Login Unsuccessful. Please check email and password', 'danger')
    # return render_template('login.html', title='Login', form=form)

    #user_fields = user_schema.load(request.json)

    user = Users.query.filter_by(email=email).first()

    if not user or not bcrypt.check_password_hash(user.password,
                                                  password):  #changed
        return abort(401, description="Incorrect username and password")
    login_user(user)
    print(current_user.email)

    #expiry = timedelta(days=1)
    #access_token = create_access_token(identity=str(user.id), expires_delta=expiry)

    #return jsonify({ "token": access_token })
    return redirect(url_for('post.post_index'))
Ejemplo n.º 11
0
def auth_login():
    username = request.form.get('username')
    #email = request.form.get('email')
    password = request.form.get('password')
    # print(username)
    # print(password)
    # user_fields = user_schema.load(request.json)

    # user = User.query.filter_by(username=user_fields["username"]).first()
    user = User.query.filter_by(username=username).first()

    # don't login if the user doesn't exist
    if not user:
        return abort(401, description="Incorrect username")

    if not bcrypt.check_password_hash(user.password, password):
        return abort(401, description="Incorrect password")

    #print(current_user.username)
    login_user(user)
    #print(current_user.username)

    #expiry = timedelta(days=1)
    #access_token = create_access_token(identity=str(user.id), expires_delta=expiry)
    #return jsonify({"token": access_token})

    return redirect(url_for('settlements.settlement_index'))
Ejemplo n.º 12
0
def login(domain_name):
    tenant = Tenant.query.filter_by(domain_name=domain_name).first_or_404()

    # try except so that failed validation returns 401 reponse rather than 500
    try:
        data = UserSchema(exclude=["is_admin", "name", "expires_in"]).load(flask.request.json)
    except:
        return flask.abort(401)

    user = User.query.filter(
        User.email==data["email"],
        User.tenant_id==tenant.id
    ).first()

    if not user or not bcrypt.check_password_hash(user.password, data["password"]) or datetime.datetime.utcnow() > user.expires_on:
        return flask.abort(401)
    
    token = jwt.create_access_token(
        identity = user.id, 
        expires_delta=datetime.timedelta(days=1), # jwt token is invalidated after one day
        additional_claims={
            "is_admin":user.is_admin,
            "is_owner":user.is_owner
        } 
        # adds is_admin and is_owner claims to jwt token
    )
    return flask.jsonify(token)

    
Ejemplo n.º 13
0
    def check_password(cls, email, password):
        record = UserModel.query.filter_by(email=email).first()

        if record and bcrypt.check_password_hash(record.password, password):
            return True
        else:
            return False
Ejemplo n.º 14
0
def admin_login():
    form = AdminLoginForm()

    if form.validate_on_submit():
        email = form.email.data
        subscriber = Subscriber.query.filter_by(email=email).first()

        if subscriber and bcrypt.check_password_hash(subscriber.password,
                                                     form.password.data):
            login_user(subscriber, remember=form.remember.data)
            print("after check password", subscriber)
            flash('Welcome back, {}'.format(subscriber.first_name), 'success')
            next_page = request.args.get('next')

            if not is_safe_url(next_page):
                print(current_user)
                return abort(400)

            print("From login form", current_user)

            return redirect(next_page or url_for('adm.admin_home'))
        else:
            flash('Invalid Credentials', 'danger')

    return render_template('admin_login.html', form=form)
Ejemplo n.º 15
0
def register():

    if request.method == 'POST':
        new_username = request.form.get('username')
        new_password = bcrypt.generate_password_hash(request.form.get('password')).decode('utf-8')
        new_password_verify = request.form.get('password_verify')
        new_email = request.form.get('email')

        try:
            sprawdzanie_uzytkownika_login = User.query.filter_by(username=new_username).first()
            if sprawdzanie_uzytkownika_login is not None:
                flash("Podany login już istnieje", 'danger')
                return render_template('register.html',username=new_username,email=new_email)

            sprawdzanie_uzytkownika_email = User.query.filter_by(email=new_email).first()
            if sprawdzanie_uzytkownika_email is not None:
                flash("Podany przez Ciebie adres e-mail już istnieje", 'danger')
                return render_template('register.html',username=new_username,email=new_email)

            if not bcrypt.check_password_hash(new_password, new_password_verify):
                flash("Podane hasła się nie zgadzają!", 'danger')
                return render_template('register.html',username=new_username,email=new_email)

            new_user = User(username=new_username, password=new_password, email=new_email)
            db.session.add(new_user)
            db.session.commit()
            return redirect('/login')

        except ServerError as err:
            flash(str(err), 'danger')
            return render_template('register.html')

    return render_template('register.html')
Ejemplo n.º 16
0
    def userpass(cls,email,password):
        print(password)
        record = AuthenticationModel.query.filter_by(email=email).first()

        if record and bcrypt.check_password_hash(record.password,password):
            return True
        else:
            return False
Ejemplo n.º 17
0
 def auth(self):
     user = db.query(User).filter(
         and_(User.username == self.username)).one_or_none()
     if user is None or not bcrypt.check_password_hash(
             user.password, self.password):
         self.error = _(u'Niepoprawne parametry logowania')
         return False
     Application.authorize_user(user)
     return True
Ejemplo n.º 18
0
def auth_login():
    user_fields = user_schema.load(request.json)
    user = User.query.filter_by(email=user_fields["email"]).first()
    if not user or not bcrypt.check_password_hash(user.password, user_fields["password"]):
        return abort(401, description="Incorrect username and password")

    expiry = timedelta(days=1)                                                                         # set the access cookies in the browser that sent the request
    access_token = create_access_token(identity=str(user.id), expires_delta=expiry)                    # set_access_cookies(resp, access_token)

    return jsonify({ "token": access_token })                                                  
Ejemplo n.º 19
0
def index():
    lform = login_form()
    rform = register_form()
    nform = newpost_form()
    if lform.lsubmit.data and lform.validate_on_submit():
        user = User.query.filter_by(email=lform.lemail.data).first()
        if user and bcrypt.check_password_hash(user.password,
                                               lform.lpassword.data):

            login_user(user)
            nextpage = request.args.get("next")
            flash("شما وارد شدید", category="success")
            if nextpage:
                return redirect(nextpage)
            else:
                return redirect(url_for("index"))
        else:
            flash("ایمیل و پسورد را دوباره چک کنید", category="danger")
            return redirect(url_for("index"))
    if rform.rsubmit.data and rform.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(rform.rpassword.data)
        user = User(firstname=rform.firstname.data,
                    lastname=rform.lastname.data,
                    email=rform.remail.data,
                    password=hashed_password)
        db.session.add(user)
        db.session.commit()
        # send_email(user)
        flash("ثبت نام شما با موفقیت انجام شد.", category="success")
        return redirect(url_for("index"))
    if current_user.is_authenticated == True:
        postslen = len(current_user.posts)
        page = request.args.get("page", 1, int)
        posts = Post.query.filter_by(author=current_user).order_by(
            Post.id.desc()).paginate(page=page, per_page=5)
    else:
        postslen = 0
        posts = None
    if nform.nsubmit.data and nform.validate_on_submit():
        post = Post(title=nform.title.data,
                    date=nform.date.data,
                    time=nform.time.data,
                    user_id=current_user.id)
        db.session.add(post)
        db.session.commit()
        flash("پست شما افزوده شد", category="success")
        return redirect(url_for("index"))
    return render_template("index.html",
                           lform=lform,
                           rform=rform,
                           nform=nform,
                           title="صفحه اصلی",
                           posts=posts,
                           postslen=postslen)
Ejemplo n.º 20
0
def login_post():
    
    username=request.form.get("username")
    password=request.form.get('password')
    user = User.query.filter_by(username=username).first()
    
    if not user or not bcrypt.check_password_hash(user.password, password):
        return abort(401, description="Incorrect username or password")
    login_user(user)

    return redirect(url_for("home.home_page"))
Ejemplo n.º 21
0
def user_login():
    user_fields = user_schema.load(request.json)                                              # Getting the fields from the User Schema
    user = User.query.filter_by(email=user_fields["email"]).first()                        # Query the user table with the email and return the first user

    if not user or not bcrypt.check_password_hash(user.password, user_fields["password"]): # If there is no user or the password is wrong
        return abort(401, description="Incorrect username or password")                             # Return the error "Incorrect username or password"

    expiry = timedelta(days=1)                                                                      # Time for the token to expire
    access_token = create_access_token(identity=str(user.id), expires_delta=expiry)              # The access token, with the user id and the expiration date

    return jsonify({ "token": access_token })                                                       # Return the token
Ejemplo n.º 22
0
def user_login():
    user_fields = user_schema.load(request.json)
    user = User.query.filter_by(email=user_fields["email"]).first()

    if not user or not bcrypt.check_password_hash(user.password,
                                                  user_fields["password"]):
        return abort(401, description="Incorrect username or password")

    expiry = timedelta(days=1)
    access_token = create_access_token(identity=str(user.id),
                                       expires_delta=expiry)

    return jsonify({"token": access_token})
Ejemplo n.º 23
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('decks.all_decks'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is None or not bcrypt.check_password_hash(
                user.password, form.password.data):
            flash('Invalid credentials', 'danger')
            return redirect(url_for('users.login'))
        login_user(user)
        return redirect(url_for('decks.all_decks'))
    return render_template('login.html', title='Login', form=form)
Ejemplo n.º 24
0
def auth_login():
    username = request.form.get('username')
    password = request.form.get('password')

    user_username = Users.query.filter_by(username=username).first()

    if not (user_username
            and bcrypt.check_password_hash(user_username.password, password)):
        flash("Incorrect Login", "info")
        return redirect(url_for('auth.login'))

    login_user(user_username)
    return redirect(url_for('users.profile', id=user_username.id))
Ejemplo n.º 25
0
def login():
    form=LoginForm()

    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_me.data)
            flash("Login successfully ","success")
            return redirect(url_for("home"))
        else :
            flash("Username or password is incorrect","danger")

    return render_template("user/login.html",title="Login",form=form)
Ejemplo n.º 26
0
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    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('home'))
    return render_template('login.html', title='Login', form=form)
Ejemplo n.º 27
0
def auth_login():
    username = request.form.get('username')
    password = request.form.get('password')

    user = User.query.filter_by(username=username).first()
    # don't login if the user doesn't exist
    if not user:
        return abort(401, description="Incorrect username")
    if not bcrypt.check_password_hash(user.password, password):
        return abort(401, description="Incorrect password")

    login_user(user)
    return redirect(url_for('bookings.booking_index'))
Ejemplo n.º 28
0
def login():
    if request.method == "GET":
        return render_template('login.html', title="Register")
    else:
        auth = request.authorization
        username = request.form.get("u")
        password = request.form.get("p")

        if (not username or not password):
            flash("Missing at least one input fields", "danger")
            return make_response(
                render_template('login.html', inputError="Login"), 422)

        if (User.query.filter_by(username=username).first() is None):
            flash("User " + username + " not found in DB", "danger")
            return make_response(
                render_template('login.html', inputError="Login"), 404)
        user = User.query.filter_by(username=username).first()
        fname = user.fname
        lname = user.lname
        if (not bcrypt.check_password_hash(
                user.password, password)):  # user.password != password
            flash("Incorrect password", "danger")
            return make_response(
                render_template('login.html', inputError="Login"),
                401)  # unauthorize status code

        # Create token conditions passed #payload
        token = jwt.encode(
            {
                'iss': "http://localhost:9000/authenticate",
                'id': user.id,
                'username': username,
                'status': "success",
                'iat': datetime.datetime.utcnow(),
                'exp':
                datetime.datetime.utcnow() + datetime.timedelta(minutes=1)
            }, app.config["SECRET_KEY"])
        session["token"] = token.decode(
            'UTF-8'
        )  # causes problems {'authentication': {'message': 'Unrecognized Token', 'payload': 'None', 'status': 'fail'}}
        session["username"] = username
        session["fname"] = fname
        session["lname"] = lname

        # return jsonify({'token' : token.decode('UTF-8')})
        return make_response(
            render_template('homepage.html',
                            fname=fname,
                            lname=lname,
                            username=username), 200)
Ejemplo n.º 29
0
def auth_login():
    account_fields = account_schema.load(request.json)

    account = Accounts.query.filter_by(email=account_fields["email"]).first()

    if not account or not bcrypt.check_password_hash(
            account.password, account_fields["password"]):
        return abort(401, description="Incorrect username and password")

    expiry = timedelta(days=1)
    access_token = create_access_token(identity=str(account.id),
                                       expires_delta=expiry)

    return jsonify({"token": access_token})
Ejemplo n.º 30
0
def admin_login():
    admin_fields = admin_schema.load(request.json)

    admin = Admin.query.filter_by(username=admin_fields["username"]).first()

    if not admin or not bcrypt.check_password_hash(admin.password,
                                                   admin_fields["password"]):
        return abort(401, description="Incorrect username and password")

    expiry = timedelta(hours=2)
    access_token = create_access_token(identity=str(admin.admin_id),
                                       expires_delta=expiry)

    return jsonify({"token": access_token})
Ejemplo n.º 31
0
def login():
	if current_user.is_authenticated():
		return redirect(url_for('index'))

	login = Login(request.form)

	if request.method == 'POST' and login.validate():
		user = User.get_by_name(login.name.data)

		if not user or not bcrypt.check_password_hash(user.h, login.password.data):
			login.name.errors.append('Invalid username or password specified.')
			return render_template('login.html', title='Log In', form=login)
		

		login_user(user)
		flash('You are now logged in as ' + user.username + '.')

		return redirect(url_for('index'))

	return render_template('login.html', title='Log In', form=login)