class TASBackend(ModelBackend): logger = logging.getLogger(__name__) def __init__(self): self.tas = TASClient() # Create an authentication method # This is called by the standard Django login procedure def authenticate(self, username=None, password=None, request=None, **kwargs): user = None if username is not None and password is not None: tas_user = None if request is not None: self.logger.info('Attempting login via TAS for user "%s" from IP "%s"' % (username, request.META.get('REMOTE_ADDR'))) else: self.logger.info('Attempting login via TAS for user "%s" from IP "%s"' % (username, 'unknown')) try: # Check if this user is valid on the mail server if self.tas.authenticate(username, password): tas_user = self.tas.get_user(username=username) self.logger.info('Login successful for user "%s"' % username) else: raise ValidationError('Authentication Error', 'Your username or password is incorrect.') except Exception as e: self.logger.warning(e.args) if re.search(r'PendingEmailConfirmation', e.args[1]): raise ValidationError('Please confirm your email address before logging in.') else: raise ValidationError(e.args[1]) if tas_user is not None: UserModel = get_user_model() try: # Check if the user exists in Django's local database user = UserModel.objects.get(username=username) user.first_name = tas_user['firstName'] user.last_name = tas_user['lastName'] user.email = tas_user['email'] user.save() except UserModel.DoesNotExist: # Create a user in Django's local database self.logger.info('Creating local user record for "%s" from TAS Profile' % username) user = UserModel.objects.create_user( username=username, first_name=tas_user['firstName'], last_name=tas_user['lastName'], email=tas_user['email'] ) try: profile = DesignSafeProfile.objects.get(user=user) except DesignSafeProfile.DoesNotExist: profile = DesignSafeProfile(user=user) profile.save() return user
class TASBackend(ModelBackend): def __init__(self): self.tas = TASClient() # Create an authentication method # This is called by the standard Django login procedure def authenticate(self, username=None, password=None, request=None, **kwargs): user = None if username is not None and password is not None: tas_user = None logger = logging.getLogger('tas') if request is not None: logger.info('Attempting login for user "%s" from IP "%s"' % (username, request.META.get('REMOTE_ADDR'))) else: logger.info('Attempting login for user "%s" from IP "%s"' % (username, 'unknown')) try: # Check if this user is valid on the mail server if self.tas.authenticate(username, password): tas_user = self.tas.get_user(username=username) activate_local_user(username) logger.info('Login successful for user "%s"' % username) else: raise ValidationError('Authentication Error', 'Your username or password is incorrect.') except Exception as e: logger.error(e.args) if re.search(r'PendingEmailConfirmation', e.args[1]): raise ValidationError('Please confirm your email address before logging in.') else: raise ValidationError(e.args[1]) if tas_user is not None: UserModel = get_user_model() try: # Check if the user exists in Django's local database user = UserModel.objects.get(username=username) user.first_name = tas_user['firstName'] user.last_name = tas_user['lastName'] user.email = tas_user['email'] user.save() except UserModel.DoesNotExist: # Create a user in Django's local database user = UserModel.objects.create_user( username=username, first_name=tas_user['firstName'], last_name=tas_user['lastName'], email=tas_user['email'] ) return user
def change_password(request): username = str(request.user) body = json.loads(request.body) current_password = body['currentPW'] new_password = body['newPW'] tas = TASClient(baseURL=settings.TAS_URL, credentials={'username': settings.TAS_CLIENT_KEY, 'password': settings.TAS_CLIENT_SECRET}) auth = tas.authenticate(username, current_password) if auth: try: tas.change_password(username, current_password, new_password) return JsonResponse({'completed': True}) except Exception as e: return JsonResponse({'message': e.args[1]}, status=422) else: return JsonResponse({'message': 'Incorrect Password'}, status=401)
def confirm_legacy_credentials(request): error_message = ( 'Your legacy credentials were rejected. Click ' f'<a href="{reverse("federation_migrate_account")}?force=1">here</a> ' 'to skip this step. Some aspects of your old account may not be ' 'migratable without valid legacy credentials.') if request.method == 'POST': form = KSAuthForm(request, data=request.POST) username = request.POST.get('username') password = request.POST.get('password') if request.user.username == username and form.is_valid(): tas = TASClient() if tas.authenticate(username, password): regenerate_tokens(request, password) # Check if we were able to generate a token for the region the # user is trying to log in to if has_valid_token(request, region=request.GET.get('region')): LOG.info(( 'User {} retrieved unscoped token successfully via manual ' 'form.'.format(username))) else: LOG.info(( 'User {} could not retrieve unscoped token via manual ' 'form.'.format(username))) # Keystone failed for some reason messages.error(request, error_message) else: # Invalid password messages.error(request, error_message) else: LOG.error('An error occurred on form validation for user ' + request.user.username) messages.error(request, error_message) return redirect(request.GET.get('next')) form = KSAuthForm(request) return render(request, 'federation/confirm_legacy_credentials.html', {'form': form})
def clean(self): cleaned_data = self.cleaned_data reset_link = reverse('designsafe_accounts:password_reset') tas = TASClient() current_password_correct = tas.authenticate(self._username, cleaned_data['current_password']) if current_password_correct: tas_user = tas.get_user(username=self._username) pw = cleaned_data['new_password'] confirm_pw = cleaned_data['confirm_new_password'] valid, error_message = check_password_policy(tas_user, pw, confirm_pw) if not valid: self.add_error('new_password', error_message) self.add_error('confirm_new_password', error_message) raise forms.ValidationError(error_message) else: err_msg = mark_safe( 'The current password you provided is incorrect. Please try again. ' 'If you do not remember your current password you can ' '<a href="%s" tabindex="-1">reset your password</a> with an email ' 'confirmation.' % reset_link) self.add_error('current_password', err_msg)
def clean(self): cleaned_data = self.cleaned_data reset_link = reverse('designsafe_accounts:password_reset') tas = TASClient() current_password_correct = tas.authenticate(self._username, cleaned_data['current_password']) if current_password_correct: tas_user = tas.get_user(username=self._username) pw = cleaned_data['new_password'] confirm_pw = cleaned_data['confirm_new_password'] valid, error_message = check_password_policy(tas_user, pw, confirm_pw) if not valid: self.add_error('new_password', error_message) self.add_error('confirm_new_password', error_message) raise forms.ValidationError(error_message) else: err_msg = mark_safe( 'The current password you provided is incorrect. Please try again. ' 'If you do not remember your current password you can ' '<a href="%s" tabindex="-1">reset your password</a> with an email ' 'confirmation.' % reset_link) self.add_error('current_password', err_msg)
def authenticate(cls, username, password): api = TASClient() if api.authenticate(username, password): return cls(initial=api.get_user(username=username))