コード例 #1
0
ファイル: app.py プロジェクト: rettka30/CUS1166_StudentSystem
def change_password(type, id):
    if type == "Student":
        user = Student.query.get(id)
        # if user.is_authenticated:
        #     return redirect(url_for('index', type="Student", id=id))
        form = PasswordForm()
        if form.validate_on_submit():
            if user is None or not password_manager.verify_password(
                    form.password.data, user.password):
                flash('Invalid password')
                return redirect(
                    url_for('change_password', type='Student', id=id))
            user.password = password_manager.hash_password(form.np.data)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('index', type='Student', id=id))
        return render_template('student_password.html', form=form)
    elif type == "Professor":
        user = Professor.query.get(id)
        # if user.is_authenticated:
        #     return redirect(url_for('index', type="Student", id=id))
        form = PasswordForm()
        if form.validate_on_submit():
            if user is None or not password_manager.verify_password(
                    form.password.data, user.password):
                flash('Invalid password')
                return redirect(
                    url_for('change_password', type='Professor', id=id))
            user.password = password_manager.hash_password(form.np.data)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('index', type='Professor', id=id))
        return render_template('prof_password.html', form=form)
    elif type == "Administrator":
        user = Administrator.query.get(id)
        # if user.is_authenticated:
        #     return redirect(url_for('index', type="Student", id=id))
        form = PasswordForm()
        if form.validate_on_submit():
            if user is None or not password_manager.verify_password(
                    form.password.data, user.password):
                flash('Invalid password')
                return redirect(
                    url_for('change_password', type='Administrator', id=id))
            user.password = password_manager.hash_password(form.np.data)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('index', type='Administrator', id=id))
        return render_template('admin_password.html', form=form)
    else:
        return render_template('error.html')
コード例 #2
0
ファイル: controllers.py プロジェクト: janol77/flask-app
def activate(key, token):
    """Activate Method."""
    try:
        element = User.objects.filter(deleted=False, id=key,
                                      code=token).first()
    except Exception:
        flash("Usuario no Existe", "error")
        return redirect(url_for("index"))
    if element.state == 'confirmed':
        flash(u"Contraseña Actualizada Anteriormente", "info")
        return redirect(url_for('auth.login'))
    if element.state == "email_reset":
        element.state = "confirmed"
        element.save()
        flash(u"Correo Actualizado", "success")
        return redirect(url_for('auth.login'))
    form = PasswordForm(request.form, element)
    if request.method == 'GET':
        return render_template("auth/password.html", form=form)
    if form.validate_on_submit():
        state = element.state
        password = form.password.data
        element.password = password
        element.generate_password()
        element.state = "confirmed"
        element.save()
        flash(u"Contraseña Actualizada", "success")
        if state == 'confirm':
            flash(u"Cuenta Activada", "info")
        return redirect(url_for('auth.login'))
    return render_template("auth/password.html", form=form)
コード例 #3
0
def changePassword():
    form = PasswordForm()
    if session['type'] == 'Student' or session['type'] == 'Faculty':
        if form.validate_on_submit():
            with sql.connect('courseSystem.db') as db:
                c = db.cursor()
            if session['type'] == 'Student':
                find_users = """SELECT * FROM Student S WHERE S.email = ?"""
            else:
                find_users = """SELECT * FROM Professor P WHERE P.email = ?"""
            c.execute(find_users, (session['user'], ))
            results = c.fetchall()
            if results and checkpw(str.encode(form.password.data), results[0][1]) and\
                    (form.newPassword.data == form.confirm.data):
                if session['type'] == 'Student':
                    changePassword = """UPDATE Student
                                        SET password=?
                                        WHERE email=?"""
                else:
                    changePassword = """UPDATE Professor
                                       SET password=?
                                       WHERE email=?"""
                print(form.newPassword.data)
                c.execute(changePassword,
                          (hashpw(str.encode(form.newPassword.data),
                                  gensalt(4)), session['user']))
                db.commit()
                c.close()
            return redirect(url_for('userhome'))
        return render_template('changePassword.html', form=form)
    elif session['type'] == 'Admin':
        return render_template('changePassword.html')
    else:
        return render_template('home.html')
コード例 #4
0
def change_pass():
    form = PasswordForm()
    if form.validate_on_submit():
        flash(f'Your password was updated successfully.', 'success')
        return redirect(url_for('user.home'))

    return render_template('user-change-pass.html', form=form)
コード例 #5
0
def process_password_reset_token(token):
    try:
        password_reset_serializer = URLSafeTimedSerializer(
            current_app.config['SECRET_KEY'])
        email = password_reset_serializer.loads(token,
                                                salt='password-reset-salt',
                                                max_age=3600)
    except BadSignature as e:
        flash('The password reset link is invalid or has expired.', 'danger')
        return redirect(url_for('users.login'))

    form = PasswordForm()

    if form.validate_on_submit():
        user = User.query.filter_by(email=email).first()

        if user is None:
            flash('Invalid email address!', 'danger')
            return redirect(url_for('users.login'))

        user.set_password(form.password.data)
        database.session.add(user)
        database.session.commit()
        flash('Your password has been updated!', 'success')
        return redirect(url_for('users.login'))

    return render_template('users/reset_password_with_token.html', form=form)
コード例 #6
0
def update_password(itsid):
    password_details = Password.query.get_or_404(itsid)
    if password_details.user != current_user:
        abort(403)

    form = PasswordForm()

    if form.validate_on_submit():
        message = form.password.data  # Users real password
        message = message.encode('latin-1')  # processed
        encrypted_text = CIPHER.encrypt(message)  # Got the value
        encrypted_text = encrypted_text.decode()
        password_details.site = form.site.data
        password_details.password = encrypted_text
        password_details.hint = form.hint.data
        db.session.commit()
        flash("Password Updated Successfully!", 'success')
        return redirect(url_for('passwords'))

    elif request.method == "GET":
        form.site.data = password_details.site
        form.hint.data = password_details.hint
    return render_template("create_passwords.html",
                           title='Update Password',
                           form=form,
                           legend='Update')
コード例 #7
0
ファイル: views.py プロジェクト: meysam81/sana
def login3():
    if 'pno' not in session.keys():
        flash('enter pno first')
        return redirect(url_for('login'))

    for key in ['firstname', 'lastname']:
        if key not in session.keys():
            flash('enter name first')
            return redirect(url_for('login2'))

    form = PasswordForm()
    if form.validate_on_submit():
        password = form.password.data

        pno = session['pno']
        firstname = session['firstname']
        lastname = session['lastname']

        user = User.get_by_pno(pno)
        user.firstname = firstname
        user.lastname = lastname
        user.password = password

        db.session.add(user)
        db.session.commit()

        login_user(user)

        remove_ban(request_obj=request.remote_addr)

        return redirect(url_for('index'))
    return render_template('login.html', form=form)
コード例 #8
0
def change_password(user_id):
    form = PasswordForm()
    cursor = g.db.execute('SELECT * FROM user WHERE id=? ', [user_id])
    res = cursor.fetchone()
    if res is None:
        return render_template('404.html')  # 没有改用户 404
    if int(session.get('user_id')) == int(user_id):
        if request.method == 'POST' and form.validate_on_submit():
            old_password = request.form.get('old_password')
            new_password = request.form.get('new_password')
            new_password_repeat = request.form.get('new_password_repeat')
            if new_password != new_password_repeat:
                flash(
                    message=
                    'Please enter the same password in both new password fields.'
                )
                return render_template('change_password.html', form=form)
            if md5_user_psw(res[1], old_password) == res[2]:  # 密码正确
                g.db.execute('UPDATE user SET pass_hash=? WHERE id=?',
                             [md5_user_psw(res[1], new_password), user_id])
                return redirect(
                    url_for('user_profile', user_id=session['user_id']))
            else:
                flash(message='Password error')
                return render_template('change_password.html', form=form)
        else:
            return render_template('change_password.html', form=form)
コード例 #9
0
ファイル: routing.py プロジェクト: vanesa/where-the-truck
def reset_with_token(token):
    """ Resets a user's password, verifying that their token is correct, and 
	then encrypting their new password and logging them in. """
    try:
        email = ts.loads(token, salt="recover-key", max_age=86400)
    except:
        abort(404)

    #get form data
    form = PasswordForm()
    if form.validate_on_submit():
        user = model.User.query.filter_by(email=email).first_or_404()

        password = form.password.data

        # securely store password
        password_hash = pbkdf2_sha256.encrypt(password,
                                              rounds=200000,
                                              salt_size=16)

        user.password = password_hash

        model.db.session.add(user)
        model.db.session.commit()

        # login user
        login_user(user)

        return redirect("/")
    else:
        return render_template("/reset_with_token.html",
                               form=form,
                               token=token)
コード例 #10
0
ファイル: admin.py プロジェクト: NikkeArp/tiea2080-vt3
def login():
    form = PasswordForm()

    if form.validate_on_submit():
        session.clear()
        session['admin_logged'] = True
        return redirect(url_for('admin.home'))

    return render_template('admin/login.html', form=form)
コード例 #11
0
def makePasswordQRcode():
    form = PasswordForm()
    if form.validate_on_submit():
        s = str(form.password.data)
        QR = pyqrcode.create(s)
        myfile = os.path.join(app.static_folder, "QR.png")
        QR.png(myfile, scale=5)
        return redirect(url_for('QRcodedisplay'))
    return render_template('makePasswordQRcode.html', title='Maker', form=form)
コード例 #12
0
ファイル: views.py プロジェクト: LoyiLY/fbone
def password():
    form = PasswordForm()

    if form.validate_on_submit():
        form.populate_obj(user)
        user.password = form.new_password.data

        db.session.commit()

        flash('Password updated.', 'success')

    return render_template('user/password.html', form=form)
コード例 #13
0
def password():
    form = PasswordForm()

    if form.validate_on_submit():
        form.populate_obj(user)
        user.password = form.new_password.data

        db.session.commit()

        flash('Password updated.', 'success')

    return render_template('user/password.html', form=form)
コード例 #14
0
ファイル: password.py プロジェクト: simpuid/cvbuilder
def password():
    form = PasswordForm()
    if form.validate_on_submit():
        if not current_user.check_password(form.current_password.data):
            flash('Current Password wrong', 'danger')
            return redirect(url_for('password.password'))
        current_user.set_password(form.new_password.data)
        current_user.save()
        commit()
        logout_user()
        flash('Password change successful. Please login again', 'success')
        return redirect(url_for('login.login'))
    return render_template('password.html', form=form)
コード例 #15
0
ファイル: views.py プロジェクト: succor-app/study_buddy
def reset_with_token(token):
    try:
        email = ts.loads(token, salt="recover-key", max_age=86400)
    except:
        abort(404)

    form = PasswordForm()

    if form.validate_on_submit():
        user = mongo_db.users.User.find_one({'email' : email})
        user.password = generate_password_hash(form.password.data)
        user.save()

        return redirect(url_for('login'))
    return render_template('reset_with_token.html', form=form, token=token)
コード例 #16
0
def index():
    form = PasswordForm()

    if form.validate_on_submit():

        print(form.password.data)

        if form.password.data == "password":
            return redirect(url_for("home"))

        else:
            message = "wrong password"
            return render_template("password.html", form=form, message=message)

    return render_template("password.html", form=form)
コード例 #17
0
ファイル: views.py プロジェクト: Anioko/Flask-Intern
def intern_profile():
    """Profile page with ability to change password"""
    form = PasswordForm()
    # Form submitted?
    if form.validate_on_submit():
        # Fetch current user's data
        user_data = User.query.filter_by(id = g.user.id).first()
        # Check if old password was correct
        if check_password_hash(user_data.password, form.password.data):
            # Generate new password
            user_data.password = generate_password_hash(form.newpassword.data)
            # Done, commit to database
            db.session.commit()
            flash('Password changed!')
            return redirect(url_for('intern_profile'))
    return render_template('intern/profile.html', form = form)
コード例 #18
0
def view_password():
    user_name = session.get('user_name')
    if not user_name:
        flash('Unauthorized access!', 'danger')
        return redirect(url_for('view_index'))

    form = PasswordForm()
    if form.validate_on_submit():
        user = User.query.filter_by(name=user_name).first()
        if user.verify_password(form.current_password.data):
            user.set_password(form.new_password.data)
            db.session.commit()
            flash('Password update successful!', 'success')
            return redirect(url_for('view_home'))
        else:
            flash('Incorrect password!', 'warning')
    return render_template('password.html', form=form)
コード例 #19
0
ファイル: views.py プロジェクト: k-nut/countandsmile
def auth(username):
    """ Log in """
    if 'username' in session and session['username'] == username:
        return redirect(url_for('home')+username+'/edit')
    else:
        person = PeopleModel.get_by_key_name(username.lower())
        if person:
            form = PasswordForm()
            if form.validate_on_submit():
                if check_password_hash(person.password, form.password.data):
                    session['username'] = username
                    return redirect(url_for('home')+username+'/edit')
                else:
                    flash(u'Das eingegebene Passwort war leider Falsch. Probier es noch einmal')
                    return redirect(url_for('home')+username+'/auth')
            return render_template('auth.html', name=username, form=form)
        else:
            abort(404)
コード例 #20
0
ファイル: views.py プロジェクト: BishopJustice/MultiPage
def reset_with_token(token):
    try:
        email = security.ts.loads(token, salt="recover-key", max_age=86400)
    except:
        abort(404)

    form = PasswordForm()

    if form.validate_on_submit():
        user = User.query.filter_by(email=email).first_or_404()
        user.pwdhash = form.password.data
        user.set_password(user.pwdhash)
        db.session.add(user)
        db.session.commit()

        return redirect(url_for('signin'))

    return render_template('reset_with_token.html', form=form, token=token)
コード例 #21
0
def reset_with_token(token):
    """
    reset password with email token
    @param token: unique token
    @type token: str
    @return: refreshed page indicating success or failure
    """
    try:
        email = ts.loads(token, salt="recover-key", max_age=86400)
    except:
        abort(404)
    form = PasswordForm()
    if form.validate_on_submit():
        user = User.get(email)
        password = form.password.data
        user.change_password(user.set_password(password))
        login_user(user)
        flash('Password changed successfully!')
        return redirect(url_for('main'))
    return render_template('reset_with_token.html', form=form, token=token)
コード例 #22
0
def cambiar_pass():
    if 'username' in session:
        nombre_usuario=session['username']
        formulario = PasswordForm()
        if formulario.validate_on_submit():
            if formulario.password_new.data == formulario.password_check.data:
                datos=[nombre_usuario,formulario.password_new.data]
                with open('usuarios') as archivo:
                    filereader=csv.reader(archivo.readlines())
                with open('usuarios','r+') as archivo:
                    filewriter=csv.writer(archivo)
                    for fila in filereader:
                        if fila[0]==datos[0]:
                            filewriter.writerow(datos)
                        else:
                            filewriter.writerow(fila)
                flash('La contraseña fue cambiada con éxito')
                return redirect(url_for('ingresar'))
            else:
                flash('Las passwords no matchean')
        return render_template('cambiar_contra.html', formulario=formulario)
コード例 #23
0
ファイル: app.py プロジェクト: erojas4704/Classes
def delete_user(username):
    user = User.query.filter_by(username=username).first()
    if user:
        form = PasswordForm()
        password = form.password.data
        if form.validate_on_submit():
            if User.authenticate(username, password):
                session.pop("user_id")
                db.session.delete(user)
                db.session.commit()
                flash("User has been deleted.")
                return redirect("/")
            else:
                flash("Invalid password, loser.")
                return render_template("delete.html", form=form)
        else:
            return render_template("delete.html", form=form)

    else:
        flash("Thou must be logged in to do that.")
        return redirect("/"), 401
コード例 #24
0
def new_password():
    form = PasswordForm()
    if form.validate_on_submit():
        message = form.password.data  # Users real password

        message = message.encode('latin-1')  # processed

        encrypted_text = CIPHER.encrypt(message)  # Got the value
        encrypted_text = encrypted_text.decode()
        password = Password(site=form.site.data,
                            password=encrypted_text,
                            hint=form.hint.data,
                            user=current_user)
        db.session.add(password)
        db.session.commit()
        flash("Password Added", 'success')
        return redirect(url_for('passwords'))
    return render_template("create_passwords.html",
                           title="New Password",
                           form=form,
                           legend='Add')
コード例 #25
0
def details():

    #Form for changing password
    form = PasswordForm()

    if form.validate_on_submit():
        currentPass = form.currentPass.data
        newPass = form.newPass.data
        newPassAgain = form.newPassAgain.data

        #Getting the current user's password
        db = get_db()
        user_id = g.user
        user = db.execute(
            ''' SELECT * FROM users
                            WHERE user_id = ?;''', (user_id, )).fetchone()

        #Ensuring that a user_id exists
        if currentPass is None:
            form.currentPass.errors.append("Unknown user id")

            #Check if your new password confirmation is correct
        if not newPass == newPassAgain:
            form.newPass.errors.append("Passwords do not match.")

        elif not check_password_hash(user["password"], currentPass):
            form.newPass.errors.append("Your password is incorrect.")

        #SQL UPDATE statement for updating the password in the database
        else:
            db.execute(
                '''UPDATE users
                        SET password = ?
                        WHERE user_id = ?;''',
                ((generate_password_hash(newPass)), user_id))

            db.commit()
            form.newPassAgain.errors.append("Password updated.")

    return render_template("details.html", form=form)
コード例 #26
0
def view(slug):
    paste = Paste.get_or_404(slug)
    password = None
    if paste.password:
        form = PasswordForm()
        if form.validate_on_submit():
            if not paste.verify_password(form.password.data):
                flash('비밀번호가 일치하지 않습니다.', 'error')
                return render_template('password.html', form=form)
            password = form.password.data
        else:
            form.flash_errors()
            return render_template('password.html', form=form)

    viewed = session.setdefault('viewed', [])
    if paste.slug not in viewed:
        viewed.append(paste.slug)
        session.permanent = True
        session.modified = True
        paste.view_count += 1
        db.session.add(paste)
        db.session.commit()

    lexer = get_lexer_by_name(paste.lexer)
    formatter = HtmlFormatter(
        linenos=True,
        linespans='line',
        lineanchors='line',
        anchorlinenos=True,
    )

    return render_template(
        'view.html',
        styles=formatter.get_style_defs(),
        highlighted_source=highlight(paste.source, lexer, formatter),
        lexer=lexer,
        paste=paste,
        password=password,
    )
コード例 #27
0
def index():
    form = PasswordForm()
    if form.validate_on_submit():
        return redirect(url_for('/sent'))
    return render_template('index.html', title='Password Generator', form=form)