Exemplo n.º 1
0
def change_password(request):
    """
    This function changes the user's password using user inputs of username, current password, and new password with confirmation.
    """
    class ChangePasswordForm(forms.Form):
        username = forms.CharField(label='Enter your username:'******'^[a-zA-Z0-9]*$', message='Invalid username', code='invalid_username')])
        old_passwd  = forms.CharField(label='Current Password:'******'New Password:'******'Confirm Password:'******'GET':
        form = ChangePasswordForm()
    elif request.method == 'POST':
        form = ChangePasswordForm(request.POST)
        if form.is_valid():

            try:
                username = form.cleaned_data.get('username')
                old = form.cleaned_data.get('old_passwd')
                new = form.cleaned_data.get('passwd')
                utils.change_password(ldap_host, ldap_dn, ldap_admin, ldap_cred, username, ldap_user_group, old, new)
                return render(request, 'ss/password_change_success.html')

            except Exception as e:
                log.error(e)
                err = 'Failed to reset password for %s.  The caught exception was %s' % (username, e.message)
                log.error(err)
                info=''
                desc=''
                msg='Unable to change your password.'

                if (isinstance(e, ldap.CONSTRAINT_VIOLATION)):
                    info = e.message['info']
                    desc = e.message['desc']
                    msg =  '''Unable to change your password, %s (%s).''' % (info, desc)

                if (isinstance(e, ldap.INVALID_CREDENTIALS)):
                    desc = e.message['desc']
                    msg =  '''Unable to change your password, %s.''' %  (desc)

                return render(request, 'ss/error.html', {'content': msg})

    return render(request, 'ss/change_password.html', {'form': form})
Exemplo n.º 2
0
def change_password(request):
"""
This function changes the user's password using user inputs of username, current password, and new password with confirmation.
"""
    class ChangePasswordForm(forms.Form):
        username = forms.CharField(label='Enter your username:'******'^[a-zA-Z0-9]*$', message='Invalid username', code='invalid_username')])
        old_passwd  = forms.CharField(label='Current Password:'******'New Password:'******'Confirm Password:'******'GET':
        form = ChangePasswordForm()
    elif request.method == 'POST':
        form = ChangePasswordForm(request.POST)
        if form.is_valid():

            try:
                username = form.cleaned_data.get('username')
                old = form.cleaned_data.get('old_passwd')
                new = form.cleaned_data.get('passwd')
                #userdn = utils.get_userdn(ldap_host, ldap_dn, username)
                log.debug('User, %s, found. Ready to change password from %s to %s.' % (username, old, new))
                utils.change_password(ldap_host, ldap_dn, username, old, new)
                return render(request, 'ss/password_change_success.html')

            except Exception as e:
                log.error(e)
                err = 'Failed to reset password for %s.  The caught exception was %s' % (username, e)
                log.error(err)
                info=''
                desc=''
                msg=''

                if isinstance(e, ldap.CONSTRAINT_VIOLATION):
		    info = e.message['info']
		    desc = e.message['desc']
                    msg =  '''Unable to reset your password, %s (%s).''' % (info, desc)

                return render(request, 'ss/error.html', {'content': msg})

    return render(request, 'ss/change_password.html', {'form': form})
Exemplo n.º 3
0
 def put(self, request):
     """
     ### Change Password
     * While changing password for user registered with email, PUT request
     requires two fields and their values:
         * current_password - String
         * new_password - String
     * Possible HTTP status codes and JSON response:
         * `HTTP_200_OK` - If password change was successful:
                 {
                  "user_id": integer,
                  "message": "Password updated successfully"
                 }
         * `HTTP_401_UNAUTHORIZED` - If user provided incorrect value for
         current_password:
                 {
                  "message": "Current password is incorrect."
                 }
         * `HTTP_400_BAD_REQUEST` - If new_password is same as current_password:
                 {
                  "message": "New password cannot be same as current password"
                 }
         * `HTTP_500_INTERNAL_SERVER_ERROR` - Internal server error
         :param pk:
         :param request:
     """
     # try:
     #     user = validations_utils.user_validation(pk)  # Validates if user exists or not.
     #     validations_utils.user_token_validation(
     #         request.auth.user_id, pk)  # Validates user's Token authentication.
     # except ValidationException as e:  # Generic exception
     #     return Response(e.errors, status=e.status)
     try:
         request.data['current_password']
     except KeyError:
         return Response(messages.REQUIRED_CURRENT_PASSWORD,
                         status=status.HTTP_400_BAD_REQUEST)
     try:
         new_password = request.data['new_password']
         if new_password is None or not re.match(r'[A-Za-z0-9@#$%^&+=]+',
                                                 new_password):
             return Response(messages.PASSWORD_NECESSITY,
                             status=status.HTTP_406_NOT_ACCEPTABLE)
         else:
             pass
     except KeyError:
         return Response(messages.REQUIRED_NEW_PASSWORD,
                         status=status.HTTP_400_BAD_REQUEST)
     data_keys = request.data.keys()
     # Change Password will only require current_password and new_password.
     if 'current_password' in data_keys and 'new_password' in data_keys:
         current_password = request.data['current_password']
         new_password = request.data['new_password']
         try:
             password = utils.change_password(
                 current_password, new_password,
                 request.user)  # Changes password.
             return Response(password, status=status.HTTP_200_OK)
         except ValidationException as e:
             return Response(e.errors, status=e.status)
Exemplo n.º 4
0
def change_password():
    if request.method == 'POST':
        old_password = request.values.get('old_password')
        password = request.values.get('password')
        repassword = request.values.get('repassword')

        if old_password != None and password != None and repassword != None:
            user = User.query.filter(User.login == session['login']).first()
            result = utils.change_password(bcrypt, user, old_password,
                                           password, repassword)

            if result:
                flash(
                    Markup(
                        '<div class="alert alert-success text-center" role="alert">Password changed</div>'
                    ))
            else:
                flash(
                    Markup(
                        '<div class="alert alert-danger text-center" role="alert">Error</div>'
                    ))

        return render_template(
            'change_password.html',
            is_logged_in=session.get('login'),
            is_admin=session.get('is_admin'),
        )
    elif request.method == 'GET':
        return render_template(
            'change_password.html',
            is_logged_in=session.get('login'),
            is_admin=session.get('is_admin'),
        )
Exemplo n.º 5
0
def changepassword_submit():
   form = ChangePasswordForm(request.form)
   if form.validate():
      if utils.validate_user(session['uid'], form.oldpassword.data):
         # Change their password. 
         if utils.change_password(session['uid'], form.oldpassword.data, form.newpassword.data):
            flash("Password changed!")
         else:
            session.clear()
            flash("No LDAP client object?")
      else:
         flash("Old password incorrect.")
      return redirect("/")
   else:
      flash("Password change failed. Please fill in all fields and make sure you type the new password correctly both times.")
      return redirect("/changepassword/")
Exemplo n.º 6
0
def change_user_password(user_id):
    data = request.get_json()

    # if dict has password and repassword keys
    if not all(key in data
               for key in ['old_password', 'password', 'repassword']):
        return jsonify(message='error'), 400

    old_password = data['old_password']
    password = data['password']
    repassword = data['repassword']

    user = User.query.filter(User.id == user_id).first()
    result = utils.change_password(bcrypt, user, old_password, password,
                                   repassword)

    return (jsonify(message='ok'),
            200) if result else (jsonify(message='error'), 400)
Exemplo n.º 7
0
 def save(self):
     change_password(self.user, self.cleaned_data["password1"])
Exemplo n.º 8
0
 def save(self):
     change_password(self.user, self.cleaned_data["password1"])