def register(request): if request.user is not None and request.user.is_authenticated(): return HttpResponseRedirect(reverse('tas:profile')) if request.method == 'POST': register_form = UserRegistrationForm(request.POST) if register_form.is_valid(): data = register_form.cleaned_data if request.POST.get('request_pi_eligibility'): data['piEligibility'] = 'Requested' else: data['piEligibility'] = 'Ineligible' data['source'] = 'Chameleon' logger.info('Attempting new user registration: %s' % _clean_registration_data(data)) try: tas = TASClient() created_user = tas.save_user(None, data) if data['piEligibility'] == 'Requested': _create_ticket_for_pi_request(created_user) messages.success(request, 'Congratulations! Your account request has been received. Please check your email for account verification.') return HttpResponseRedirect('/') except Exception as e: logger.exception('Error saving user') if len(e.args) > 1: if re.search('DuplicateLoginException', e.args[1]): message = 'The username you chose has already been taken. Please choose another. If you already have an account with TACC, please log in using those credentials.' errors = register_form._errors.setdefault('username', ErrorList()) errors.append(message) messages.error(request, message) elif re.search('DuplicateEmailException', e.args[1]): message = 'This email is already registered. If you already have an account with TACC, please log in using those credentials.' messages.error(request, message + ' <a href="{0}">Did you forget your password?</a>'.format(reverse('tas:password_reset'))) errors = register_form._errors.setdefault('email', ErrorList()) errors.append(message) elif re.search('PasswordInvalidException', e.args[1]): message = 'The password you provided did not meet the complexity requirements.' messages.error(request, message) errors = register_form._errors.setdefault('password', ErrorList()) errors.append(message) else: messages.error(request, 'An unexpected error occurred. If this problem persists please create a help ticket.') else: messages.error(request, 'An unexpected error occurred. If this problem persists please create a help ticket.') # return HttpResponseRedirect(reverse('tas:profile')) else: register_form = UserRegistrationForm() context = { 'register_form': register_form, } if request.method == 'POST': context['request_pi_eligibility'] = request.POST.get('request_pi_eligibility') return render(request, 'tas/register.html', context)
def _transform_authors(entity, publication): """Transform authors. :param dict entity: Entity dictionary. :param dict publication: Publication dictionary. """ entity['value']['authors'] = [] for author in publication['authors']: if author.get('guest', False): continue user = None try: user = get_user_model().objects.get(username=author.get('name')) except ObjectDoesNotExist: LOG.exception("Error retrieving user: %(user)s", {"user": author.get('name')}) if not user: continue entity['value']['authors'].append(author.get('name')) author['lname'] = user.last_name author['fname'] = user.first_name author['email'] = user.email user_tas = TASClient().get_user(username=user.username) author['inst'] = user_tas.get('institution') entity['authors'] = publication['authors']
def profile_edit(request): tas = TASClient() tas_user = tas.get_user(username=request.user) if tas_user['source'] != 'Chameleon': return HttpResponseRedirect(reverse('tas:profile')) if request.method == 'POST': form = UserProfileForm(request.POST, initial=tas_user) if form.is_valid(): data = form.cleaned_data if request.POST.get('request_pi_eligibility'): data['piEligibility'] = 'Requested' _create_ticket_for_pi_request(tas_user) else: data['piEligibility'] = tas_user['piEligibility'] data['source'] = 'Chameleon' tas.save_user(tas_user['id'], data) messages.success(request, 'Your profile has been updated!') return HttpResponseRedirect(reverse('tas:profile')) else: form = UserProfileForm(initial=tas_user) context = { 'form': form, 'user': tas_user, } return render(request, 'tas/profile_edit.html', context)
def _process_password_reset_confirm(request, form): if form.is_valid(): data = form.cleaned_data try: tas = TASClient() return tas.confirm_password_reset(data['username'], data['code'], data['password'], source='DesignSafe') except Exception as e: if len(e.args) > 1: if re.search('account does not match', e.args[1]): form.add_error('username', e.args[1]) elif re.search('No password reset request matches', e.args[1]): form.add_error('code', e.args[1]) elif re.search('complexity requirements', e.args[1]): form.add_error('password', e.args[1]) elif re.search('expired', e.args[1]): form.add_error('code', e.args[1]) else: logger.exception('Password reset failed') form.add_error('__all__', 'An unexpected error occurred. ' 'Please try again') else: form.add_error('__all__', 'An unexpected error occurred. ' 'Please try again') return False
def _process_password_reset_request(request, form): if form.is_valid(): # always show success to prevent data leaks messages.success( request, 'Your request has been received. If an account ' 'matching the username you provided is found, you will ' 'receive an email with further instructions to ' 'complete the password reset process.') username = form.cleaned_data['username'] logger.info('Attempting password reset request for username: "******"', username) try: tas = TASClient() user = tas.get_user(username=username) logger.info('Processing password reset request for username: "******"', username) resp = tas.request_password_reset(user['username'], source='DesignSafe') logger.debug(resp) except Exception as e: logger.exception('Failed password reset request') return True else: return False
def get_profile_data(request): """ JSON profile data """ django_user = request.user tas = TASClient( baseURL=settings.TAS_URL, credentials={ 'username': settings.TAS_CLIENT_KEY, 'password': settings.TAS_CLIENT_SECRET } ) user_profile = tas.get_user(username=request.user.username) history = get_user_history(request.user.username) try: demographics = model_to_dict(django_user.profile) except ObjectDoesNotExist as e: demographics = {} logger.info('exception e:{} {}'.format(type(e), e)) demographics.update(user_profile) context = { 'demographics': demographics, 'history': history, 'licenses': manage_licenses(request), 'integrations': manage_integrations(request), } return JsonResponse(context)
def email_confirmation(request): context = {} if request.method == 'POST': form = EmailConfirmationForm(request.POST) if form.is_valid(): code = request.POST['code'] username = request.POST['username'] try: tas = TASClient() user = tas.get_user(username=username) tas.verify_user(user['id'], code) activate_local_user(username) messages.success( request, 'Congratulations, your email has been verified! Please log in now.' ) return HttpResponseRedirect(reverse('tas:profile')) except Exception as e: logger.exception('Email verification failed') if e[0] == 'User not found': form.add_error('username', e[1]) else: form.add_error( 'code', 'Email verification failed. Please check your verification code and username and try again.' ) else: form = EmailConfirmationForm( initial={'code': request.GET.get('code', '')}) context['form'] = form return render(request, 'tas/email_confirmation.html', context)
def user_projects( request, username ): logger.info( 'User projects requested by admin: %s for user %s', request.user, username ) resp = { 'status': 'error', 'msg': '', 'result': [] } if username: tas = TASClient() try: userData = tas.get_user(username=username) try: userProjects = tas.projects_for_user( username=username ) chameleonProjects = tas.projects_for_group('Chameleon'); if (chameleonProjects and userProjects): for project in userProjects: if project in chameleonProjects: resp['status'] = 'success' resp['result'].append(project) logger.info( 'Total chameleon projects for user %s: %s', username, len( resp ) ) except Exception as e: logger.debug('Error loading projects for user: %s', username) resp['msg'] = 'Error loading projects for user: %s' %username except Exception as e: logger.debug('User not found with username: %s', username) resp['msg'] = 'User not found.' return HttpResponse(json.dumps(resp), content_type="application/json")
def email_confirmation(request): context = {} if request.method == 'POST': form = EmailConfirmationForm(request.POST) if form.is_valid(): code = request.POST['code'] username = request.POST['username'] try: tas = TASClient() user = tas.get_user(username=username) tas.verify_user(user['id'], code) activate_local_user(username) messages.success(request, 'Congratulations, your email has been verified! Please log in now.') return HttpResponseRedirect(reverse('tas:profile')) except Exception as e: logger.exception('Email verification failed') if e[0] == 'User not found': form.add_error('username', e[1]) else: form.add_error('code', 'Email verification failed. Please check your verification code and username and try again.') else: form = EmailConfirmationForm(initial={'code': request.GET.get('code', '')}) context['form'] = form return render(request, 'tas/email_confirmation.html', context)
def confirm_password_reset(self, code, new_password, source=None): if self.username: api = TASClient() return api.confirm_password_reset(self.username, code, new_password, source) else: raise Exception('Cannot reset password: username is not set')
def get_or_craete_authors(publication): authors = publication.get('authors', []) if authors: return authors if publication['project']['value']['projectType'] == 'experimental': authors = publication['experimentsList'][-1].get('authors') elif publication['project']['value']['projectType'] == 'simulation': authors = publication['simulations'][-1].get('authors') elif publication['project']['value']['projectType'] == 'hybrid_simulation': authors = publication['hybrid_simulations'][-1].get('authors') elif publication['project']['value']['projectType'] == 'field_recon': authors = publication['missions'][-1].get('authors') for author in authors: if not author.get('lname'): try: user = get_user_model().objects.get( username=author.get('name')) author['lname'] = user.last_name author['fname'] = user.first_name author['email'] = user.email user_tas = TASClient().get_user(username=user.username) author['inst'] = user_tas.get('institution') except ObjectDoesNotExist: logger.error('User does not exists: %s', author.get('name')) publication['authors'] = authors return publication['authors']
def make_user_pi(self, request, selected_users, form_url=''): # The user has already confirmed the action. # Make the users PI Eligible if request.POST.get('post'): tas = TASClient() for user in selected_users: try: tas_user = tas.get_user(username=user.username) if tas_user['piEligibility'] == 'Eligible': self.message_user(request, _('User %s already PI Eligible') % user.username, level=messages.WARNING) else: tas_user['piEligibility'] = 'Eligible' tas.save_user(tas_user['id'], tas_user) self.message_user(request, _('Granted PI Eligible to %s') % user.username) except: logger.exception('Unable to Grant PI Eligible to %s' % user.username) self.message_user(request, _('Unable to Grant PI Eligible to %s') % user.username, level=messages.ERROR) return None context = { 'title': _('Grant PI eligibility'), 'opts': self.model._meta, 'selected_users': selected_users, 'form_url': form_url, 'action_checkbox_name':helpers.ACTION_CHECKBOX_NAME } context.update(admin.site.each_context()) return TemplateResponse(request, 'admin/tas/make_user_pi.html', context, current_app=self.admin_site.name)
def reset_user_password(self, request, selected_users, form_url=''): # The user has already confirmed the action. # Trigger password reset notifications if request.POST.get('post'): tas = TASClient() for user in selected_users: try: resp = tas.request_password_reset(user.username, source='Chameleon') self.message_user(request, _('Password Reset notification sent to: %s') % user.username) except: logger.exception( 'Failed password reset request' ) self.message_user(request, _('Unable to reset password for: %s') % user.username, level=messages.ERROR) return None context = { 'title': _('Send Password Reset Notification'), 'opts': self.model._meta, 'selected_users': selected_users, 'form_url': form_url, 'action_checkbox_name':helpers.ACTION_CHECKBOX_NAME } context.update(admin.site.each_context()) return TemplateResponse(request, 'admin/tas/reset_user_password.html', context, current_app=self.admin_site.name)
def get_departments_json(request): institutionId = request.GET.get('institutionId') if institutionId: tas = TASClient() departments = tas.get_departments(institutionId) else: departments = {} return HttpResponse(json.dumps(departments), content_type='application/json')
def departments(self): depts = [] if self.id: api = TASClient() data = api.get_departments(self.id) for dept in data: depts.append(Department(initial=dept)) return depts
def __init__(self, username=None, id=None, initial={}): super(User, self).__init__() if username is not None or id is not None: api = TASClient() remote_data = api.get_user(id=id, username=username) self.__populate(remote_data) else: self.__populate(initial)
def __init__(self, id=None, initial={}): super(Institution, self).__init__() if id is not None: api = TASClient() initial = api.get_institution(id) self.__populate(initial) else: self.__populate(initial)
def __init__(self, id=None, initial={}): super(Project, self).__init__() if id is not None: api = TASClient() remote_data = api.project(id) self.__populate(remote_data) else: self.__populate(initial)
def __init__(self, id=None, initial={}): super(Department, self).__init__() if id is not None: api = TASClient() initial = api.get_department(id, id) self.__populate(initial) else: self.__populate(initial)
def projects(self): _projects = [] if self.username: api = TASClient() project_data = api.projects_for_user(username=self.username) for d in project_data: _projects.append(Project(initial=d)) return _projects
def departments_json(request): institution_id = request.GET.get('institutionId') if institution_id: tas = TASClient() departments = tas.get_departments(institution_id) else: departments = {} return HttpResponse(json.dumps(departments), content_type='application/json')
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
def _get_tas_dir(user): # Get $WORK directory tas_client = TASClient(baseURL=settings.TAS_URL, credentials={ 'username': settings.TAS_CLIENT_KEY, 'password': settings.TAS_CLIENT_SECRET }) tas_user = tas_client.get_user(username=user.username) return tas_user['homeDirectory']
def profile_edit(request): tas = TASClient() user = request.user tas_user = tas.get_user(username=user.username) user = request.user ds_profile = DesignSafeProfile.objects.get(user_id=user.id) pro_form = forms.ProfessionalProfileForm(request.POST or None, instance=ds_profile) if request.method == 'POST': form = forms.UserProfileForm(request.POST, initial=tas_user) if form.is_valid() and pro_form.is_valid(): pro_form.save() data = form.cleaned_data # punt on PI Eligibility for now data['piEligibility'] = tas_user['piEligibility'] # retain original account source data['source'] = tas_user['source'] tas.save_user(tas_user['id'], data) messages.success(request, 'Your profile has been updated!') try: ds_profile = user.profile ds_profile.ethnicity = data['ethnicity'] ds_profile.gender = data['gender'] except ObjectDoesNotExist as e: logger.info('exception e: {} {}'.format(type(e), e )) ds_profile = DesignSafeProfile( user=user, ethnicity=data['ethnicity'], gender=data['gender'] ) ds_profile.update_required = False ds_profile.save() return HttpResponseRedirect(reverse('designsafe_accounts:manage_profile')) else: try: tas_user['ethnicity'] = user.profile.ethnicity tas_user['gender'] = user.profile.gender except ObjectDoesNotExist: pass form = forms.UserProfileForm(initial=tas_user) context = { 'title': 'Account Profile', 'form': form, 'pro_form': pro_form } return render(request, 'designsafe/apps/accounts/profile_edit.html', context)
def departments_json(request): institution_id = request.GET.get('institutionId') if institution_id: tas = TASClient(baseURL=settings.TAS_URL, credentials={'username': settings.TAS_CLIENT_KEY, 'password': settings.TAS_CLIENT_SECRET}) departments = tas.get_departments(institution_id) else: departments = {} return HttpResponse( json.dumps(departments), content_type='application/json' )
def view( request ): resp = '' try: tas = TASClient() resp = tas.projects_for_group('Chameleon') logger.debug( 'Total projects: %s', len(resp) ) except Exception as e: logger.exception('Error loading chameleon projects') messages.error( request, e[0] ) raise Exception('Error loading chameleon projects') return HttpResponse(json.dumps(resp), content_type="application/json")
def profile(request): context = {} try: tas = TASClient() resp = tas.get_user(username=request.user) context['profile'] = resp except: context['profile'] = False # raise Exception('error loading profile') return render(request, 'tas/profile.html', context)
def user_projects(request): context = {} tas = TASClient() user = tas.get_user(username=request.user) context['is_pi_eligible'] = user['piEligibility'] == 'Eligible' projects = Project.list(username=request.user) projects = list(p for p in projects if p.source == 'Chameleon') context['projects'] = projects return render(request, 'projects/user_projects.html', context)
def get_fields_choices(): choices = (('', 'Choose One'),) tas = TASClient() fields = tas.fields() for f in fields: choices = choices + ((f['id'], f['name']),) if f['children']: for c in f['children']: choices = choices + ((c['id'], '--- ' + c['name']),) if c['children']: for g in c['children']: choices = choices + ((g['id'], '--- --- ' + g['name']),) return choices
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 get_fields_choices(): choices = (('', 'Choose One'), ) tas = TASClient() fields = tas.fields() for f in fields: choices = choices + ((f['id'], f['name']), ) if f['children']: for c in f['children']: choices = choices + ((c['id'], '--- ' + c['name']), ) if c['children']: for g in c['children']: choices = choices + ( (g['id'], '--- --- ' + g['name']), ) return choices
def get_project_users_json( request, project_id=None ): logger.info( 'Projects users requested.') resp = [] try: tas = TASClient() if project_id is not None: resp = tas.get_project_users( project_id=project_id ) logger.info( 'Total users for project %s: %s', project_id, len( resp ) ) else: raise Exception('Project id is required.') except Exception as e: traceback.print_exc() raise Exception('Error loading projects users.') return HttpResponse(json.dumps(resp), content_type="application/json")
def get_user_data(username): """Returns user contact information : returns: user_data : rtype: dict """ tas_client = TASClient( baseURL=settings.TAS_URL, credentials={ 'username': settings.TAS_CLIENT_KEY, 'password': settings.TAS_CLIENT_SECRET } ) user_data = tas_client.get_user(username=username) return user_data
def profile_edit(request): tas = TASClient() user = request.user tas_user = tas.get_user(username=user.username) if request.method == 'POST': form = forms.UserProfileForm(request.POST, initial=tas_user) if form.is_valid(): data = form.cleaned_data # punt on PI Eligibility for now data['piEligibility'] = tas_user['piEligibility'] # retain original account source data['source'] = tas_user['source'] tas.save_user(tas_user['id'], data) messages.success(request, 'Your profile has been updated!') try: ds_profile = user.profile ds_profile.ethnicity = data['ethnicity'] ds_profile.gender = data['gender'] ds_profile.save() except ObjectDoesNotExist as e: logger.info('exception e: {} {}'.format(type(e), e )) ds_profile = DesignSafeProfile( user=user, ethnicity=data['ethnicity'], gender=data['gender'] ) ds_profile.save() return HttpResponseRedirect(reverse('designsafe_accounts:manage_profile')) else: try: tas_user['ethnicity'] = user.profile.ethnicity tas_user['gender'] = user.profile.gender except ObjectDoesNotExist: pass form = forms.UserProfileForm(initial=tas_user) context = { 'title': 'Manage Profile', 'form': form, } return render(request, 'designsafe/apps/accounts/profile_edit.html', context)
def get_project_users_json(request, project_id=None): logger.info('Projects users requested.') resp = [] try: tas = TASClient() if project_id is not None: resp = tas.get_project_users(project_id=project_id) logger.info('Total users for project %s: %s', project_id, len(resp)) else: raise Exception('Project id is required.') except Exception as e: traceback.print_exc() raise Exception('Error loading projects users.') return HttpResponse(json.dumps(resp), content_type="application/json")
def main(argv=None): if argv is None: argv = sys.argv parser = argparse.ArgumentParser( description='Sync project from TAS to portal') parser.add_argument('--config', type=str, help='Config file path name', required=True) parser.add_argument('--portal-db', type=str, help='Portal database name', default='chameleon_dev') args = parser.parse_args(argv[1:]) conf = configparser.SafeConfigParser(os.environ) conf.read(args.config) db = mysql.connector.connect(host=conf.get('portal', 'host'), user=conf.get('portal', 'username'), passwd=conf.get('portal', 'password'), database=args.portal_db) tas = TASClient(baseURL=conf.get('tas', 'url'), credentials={ 'username': conf.get('tas', 'client_key'), 'password': conf.get('tas', 'client_secret') }) sync_fields_from_tas(tas, db) sync(db, get_projects_from_tas(tas, db), get_projects_from_portal(db))
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 get_tas_client(self): tas_client = TASClient(baseURL=settings.TAS_URL, credentials={ 'username': settings.TAS_CLIENT_KEY, 'password': settings.TAS_CLIENT_SECRET }) return tas_client
def handle(self, *args, **options): users = [] tas = TASClient() if options['username']: u = options['username'] try: djangoUser = User.objects.get(username=u) users.append(djangoUser) except ObjectDoesNotExist: self.stdout.write( self.style.ERROR('No user with username %s' % u)) else: users = User.objects.all() usersToUpdate = [] for u in users: tas_user = tas.get_user(username=u.username) if u.email != tas_user['email']: self.stdout.write( self.style.ERROR('For User %s: %s (Chameleon), %s (TAS)' % (u.username, u.email, tas_user['email']))) u.email = tas_user['email'] usersToUpdate.append(u) if len(usersToUpdate) > 0: if options['skip_confirm']: self._run_update(usersToUpdate) else: self.stdout.write( self.style.NOTICE( '%s users will have their emails synced with TAS. Continue?' % len(usersToUpdate))) confirm = raw_input('Y/N: ') if confirm == 'Y' or confirm == 'y': self.stdout.write( self.style.NOTICE('Updating user emails')) self._run_update(usersToUpdate) else: self.stdout.write( self.style.NOTICE('Cancelling user email sync')) else: self.stdout.write( self.style.NOTICE('There are no user emails to update'))
def list(cls, username=None, group=None): """ Returns a list for projects for the given username or group. An argument for username or group is required and only one may be provided. """ if username is None and group is None: raise TypeError('Argument username or group is required') if username is not None and group is not None: raise TypeError('One one of username or group can be passed') api = TASClient() if username: data = api.projects_for_user(username) elif group: data = api.projects_for_group(group) return list(cls(initial=d) for d in data)
def view( request ): #resp = '' try: tas = TASClient() resp = tas.projects_for_group('Chameleon') for p in resp: tempAlloc = [] for a in p['allocations']: if a['resource'] == 'Chameleon': tempAlloc.append(a) p['allocations'] = tempAlloc logger.debug( 'Total projects: %s', len(resp) ) except Exception as e: logger.exception('Error loading chameleon projects') messages.error( request, e[0] ) raise Exception('Error loading chameleon projects') return HttpResponse(json.dumps(resp), content_type="application/json")
def profile(request): context = {} try: tas = TASClient() resp = tas.get_user(username=request.user) context['profile'] = resp except: context['profile'] = False # raise Exception('error loading profile') if context['profile']['source'] != 'Chameleon': messages.info(request, 'Your account was created outside of the Chameleon Portal. ' \ 'Please visit the <a target="_blank" href="https://portal.tacc.utexas.edu">'\ 'TACC User Portal</a> to edit your profile.') return render(request, 'tas/profile.html', context)
def _process_password_reset_request(request, form): if form.is_valid(): # always show success to prevent data leaks messages.success(request, 'Your request has been received. If an account matching the username you provided is found, you will receive an email with further instructions to complete the password reset process.') username = form.cleaned_data['username'] logger.info('Password reset request for username: "******"', username) try: tas = TASClient() user = tas.get_user(username=username) resp = tas.request_password_reset(user['username'], source='Chameleon') logger.debug(resp) except: logger.exception('Failed password reset request') return True else: return False
def email_confirmation(request, code=None): context = {} if request.method == 'POST': form = forms.EmailConfirmationForm(request.POST) if form.is_valid(): data = form.cleaned_data code = data['code'] username = data['username'] password = data['password'] try: tas = TASClient() user = tas.get_user(username=username) if tas.verify_user(user['id'], code, password=password): logger.info('TAS Account activation succeeded.') check_or_create_agave_home_dir.apply( args=(user["username"], )) return HttpResponseRedirect( reverse('designsafe_accounts:manage_profile')) else: messages.error( request, 'We were unable to activate your account. Please try ' 'again. If this problem persists, please ' '<a href="/help">open a support ticket</a>.') form = forms.EmailConfirmationForm(initial={ 'code': code, 'username': username }) except: logger.exception('TAS Account activation failed') form.add_error( '__all__', 'Account activation failed. Please confirm your ' 'activation code, username and password and try ' 'again.') else: if code is None: code = request.GET.get('code', '') form = forms.EmailConfirmationForm(initial={'code': code}) context['form'] = form return render(request, 'designsafe/apps/accounts/email_confirmation.html', context)
def clean(self): cleaned_data = self.cleaned_data username = cleaned_data.get('username') try: tas = TASClient() user = tas.get_user(username=username) except: self.add_error('username', 'The username provided does not match an existing user.') raise forms.ValidationError('The username provided does not match an existing user.') password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') valid, error_message = check_password_policy(user, password, confirm_password) if not valid: self.add_error('password', error_message) self.add_error('confirm_password', '') raise forms.ValidationError(error_message)
def user_projects(request): context = {} tas = TASClient() user = tas.get_user(username=request.user) context['is_pi_eligible'] = user['piEligibility'] == 'Eligible' projects = Project.list(username=request.user) projects = list(p for p in projects if p.source == 'Chameleon') for proj in projects: try: extras = ProjectExtras.objects.get(tas_project_id=proj.id) proj.__dict__['nickname'] = extras.nickname except ProjectExtras.DoesNotExist: project_nickname = None context['projects'] = projects return render(request, 'projects/user_projects.html', context)
def get_projects_json( request, username=None ): logger.info( 'Projects requested.') resp = [] try: tas = TASClient() chameleonProjects = tas.projects_for_group('Chameleon') if username is not None: userProjects = tas.projects_for_user( username=username ) if (chameleonProjects and userProjects): for project in userProjects: if project in chameleonProjects: resp.append(project) logger.info( 'Total chameleon projects for user %s: %s', username, len( resp ) ) else: logger.info( 'Total chameleon projects: %s', username, len( chameleonProjects ) ) resp = chameleonProjects except Exception as e: traceback.print_exc() raise Exception('Error loading projects.') return HttpResponse(json.dumps(resp), content_type="application/json")
def user_projects( request, username ): logger.info( 'User projects requested by admin: %s for user %s', request.user, username ) resp = { 'status': 'error', 'msg': '', 'result': [] } if username: tas = TASClient() try: userData = tas.get_user(username=username) try: userProjects = tas.projects_for_user( username=username ) #logger.debug(userProjects) temp = {} # run through and make sure all the allocations are associated with one project for p in userProjects: if p['source'] == 'Chameleon': if p['chargeCode'] not in temp: logger.debug('Project ' + p['chargeCode'] + ' is not in the temp yet, adding') temp[p['chargeCode']] = p else: logger.debug('Project ' + p['chargeCode'] + ' is in temp...appending allocations') tempProj = temp[p['chargeCode']] for a in p['allocations']: if a['resource'] == 'Chameleon': tempProj['allocations'].extend(a) temp[p['chargeCode']] = tempProj for code, proj in temp.items(): resp['status'] = 'success' resp['result'].append(proj) logger.info('Total chameleon projects for user %s: %s', username, len(resp)) except Exception as e: logger.debug('Error loading projects for user: %s with error %s', username, e) resp['msg'] = 'Error loading projects for user: %s' %username except Exception as e: logger.debug('User not found with username: %s', username) resp['msg'] = 'User not found.' return HttpResponse(json.dumps(resp), content_type="application/json")
def handle(self, *args, **options): users = [] tas = TASClient() if options['username']: u = options['username'] try: djangoUser = User.objects.get(username=u) users.append(djangoUser) except ObjectDoesNotExist: self.stdout.write(self.style.ERROR('No user with username %s' % u)) else: users = User.objects.all() usersToUpdate = [] for u in users: tas_user = tas.get_user(username=u.username) if u.email != tas_user['email']: self.stdout.write(self.style.ERROR('For User %s: %s (Chameleon), %s (TAS)' % (u.username, u.email, tas_user['email']))) u.email = tas_user['email'] usersToUpdate.append(u) if len(usersToUpdate) > 0: if options['skip_confirm']: self._run_update(usersToUpdate) else: self.stdout.write(self.style.NOTICE('%s users will have their emails synced with TAS. Continue?' % len(usersToUpdate))) confirm = raw_input('Y/N: ') if confirm == 'Y' or confirm == 'y': self.stdout.write(self.style.NOTICE('Updating user emails')) self._run_update(usersToUpdate) else: self.stdout.write(self.style.NOTICE('Cancelling user email sync')) else: self.stdout.write(self.style.NOTICE('There are no user emails to update'))
def email_confirmation(request, code=None): context = {} if request.method == 'POST': form = forms.EmailConfirmationForm(request.POST) if form.is_valid(): data = form.cleaned_data code = data['code'] username = data['username'] password = data['password'] try: tas = TASClient() user = tas.get_user(username=username) if tas.verify_user(user['id'], code, password=password): messages.success(request, 'Congratulations, your account has been activated! ' 'You can now log in to DesignSafe.') return HttpResponseRedirect( reverse('designsafe_accounts:manage_profile')) else: messages.error(request, 'We were unable to activate your account. Please try ' 'again. If this problem persists, please ' '<a href="/help">open a support ticket</a>.') form = forms.EmailConfirmationForm( initial={'code': code, 'username': username}) except: logger.exception('TAS Account activation failed') form.add_error('__all__', 'Account activation failed. Please confirm your ' 'activation code, username and password and try ' 'again.') else: if code is None: code = request.GET.get('code', '') form = forms.EmailConfirmationForm(initial={'code': code}) context['form'] = form return render(request, 'designsafe/apps/accounts/email_confirmation.html', context)
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 get_user_info(request, username): #username = request.GET.get('username') resp = {} resp['result'] = None resp['status'] = 'error' if username is None: resp['message'] = 'Username is required' try: tas = TASClient() resp['status'] = 'success' users = tas.get_user(username=username) projects = tas.projects_for_user(username) resp['result'] = users resp['result']['projects'] = projects except Exception as e: traceback.print_exc() raise Exception('Error fetching user.') return HttpResponse(json.dumps(resp), content_type="application/json")
def approval( request ): resp = {} errors = {} status = '' if request.POST: tas = TASClient() userData = tas.get_user( username=request.user ) data = json.loads(request.body) data['reviewer'] = userData['username'] data['reviewerId'] = userData['id'] logger.info( 'Allocation approval requested by admin: %s', request.user ) logger.info( 'Allocation approval request data: %s', json.dumps( data ) ) validate_datestring = validators.RegexValidator( '^\d{4}-\d{2}-\d{2}$' ) validate_datetimestring = validators.RegexValidator( '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$' ) if not data['decisionSummary']: errors['decisionSummary'] = 'Decision Summary is required.' if not data['status']: errors['status'] = 'Status is required. ' elif not data['status'] in ['Pending', 'pending', 'Approved', 'approved', 'Rejected', 'rejected']: errors['status'] = 'Status must be "Pending", "pending", "Approved", "approved", "Rejected", "rejected"' else: if data['start']: try: validate_datestring( data['start'] ) except ValidationError: errors['start'] = 'Start date must be a valid date string e.g. "2015-05-20" .' elif data['status'].lower() == 'approved': errors['start'] = 'Start date is required.' if data['end']: try: validate_datestring( data['end'] ) except ValidationError: errors['end'] = 'Start date must be a valid date string e.g. "2015-05-20" .' elif data['status'].lower() == 'approved': errors['end'] = 'Start date is required.' if data['computeAllocated']: try: data['computeAllocated'] = int( data['computeAllocated'] ) except ValueError: errors['computeAllocated'] = 'Compute Allocated must be a number.' if data['computeRequested']: try: data['computeRequested'] = int( data['computeRequested'] ) except ValueError: errors['computeRequested'] = 'Compute Requested must be a number.' if data['storageAllocated']: try: data['storageAllocated'] = int( data['storageAllocated'] ) except ValueError: errors['storageAllocated'] = 'Storage Allocated must be a number.' if data['storageRequested']: try: data['storageRequested'] = int( data['storageRequested'] ) except ValueError: errors['storageRequested'] = 'Storage Requested must be a number.' if data['memoryAllocated']: try: data['memoryAllocated'] = int( data['memoryAllocated'] ) except ValueError: errors['memoryAllocated'] = 'Memory Allocated must be a number.' if data['memoryRequested']: try: data['memoryRequested'] = int( data['memoryRequested'] ) except ValueError: errors['memoryRequested'] = 'Memory Requested must be a number.' if data['projectId']: try: data['projectId'] = int( data['projectId'] ) except ValueError: errors['projectId'] = 'Project id must be number.' else: errors['projectId'] = 'Project id is required.' if not data['project']: errors['project'] = 'Project charge code is required.' if data['reviewerId']: try: data['reviewerId'] = int( data['reviewerId'] ) except ValueError: errors['reviewerId'] = 'Reviewer id must be number.' else: errors['reviewerId'] = 'Reviewer id is required.' if not data['reviewer']: errors['reviewer'] = 'Reviewer username is required.' if data['dateRequested']: try: validate_datetimestring(data['dateRequested']) except ValidationError: errors['dateRequested'] = 'Requested date must be a valid date string e.g. "2015-05-20T05:00:00Z" .' #else: # errors['dateRequested'] = 'Requested date is required.' if data['dateReviewed']: try: validate_datestring( data['dateReviewed'] ) except ValidationError: errors['dateReviewed'] = 'Reviewed date must be a valid date string e.g. "2015-05-20" .' else: errors['dateReviewed'] = 'Reviewed date is required.' if len( errors ) == 0: # source data['source'] = 'Chameleon' # log the request logger.info( 'Request data passed validation. Calling TAS ...') try: resp['result'] = tas.allocation_approval( data['id'], data ) logger.info('Allocation approval TAS response: data=%s', json.dumps(resp['result'])) status = 'success' except Exception as e: logger.exception('Error processing allocation approval.') status = 'error' errors['message'] = 'An unexpected error occurred. If this problem persists please create a help ticket.' else: logger.info( 'Request data failed validation. %s', errors.values()) status = 'error' else: status = 'error' errors['message'] = 'Only POST method allowed.' resp['status'] = status resp['errors'] = errors return HttpResponse(json.dumps(resp), content_type="application/json")
def create_allocation(request, project_id, allocation_id=-1): tas = TASClient() user = tas.get_user(username=request.user) if user['piEligibility'] != 'Eligible': messages.error(request, 'Only PI Eligible users can request allocations. If you would ' 'like to request PI Eligibility, please ' '<a href="/user/profile/edit/">submit a PI Eligibility ' 'request</a>.') return HttpResponseRedirect(reverse('projects:user_projects')) project = Project(project_id) allocation = None if allocation_id > 0: for a in project.allocations: if a.id == int(allocation_id): allocation = a # goofiness that we should clean up later; requires data cleansing abstract = project.description if '--- Supplemental details ---' in abstract: additional = abstract.split('\n\n--- Supplemental details ---\n\n') abstract = additional[0] additional = additional[1].split('\n\n--- Funding source(s) ---\n\n') justification = additional[0] if len(additional) > 1: funding_source = additional[1] else: funding_source = '' elif allocation: justification = allocation.justification if '--- Funding source(s) ---' in justification: parts = justification.split('\n\n--- Funding source(s) ---\n\n') justification = parts[0] funding_source = parts[1] else: funding_source = '' else: justification = '' funding_source = '' if request.POST: form = AllocationCreateForm(request.POST, initial={'description': abstract, 'supplemental_details': justification, 'funding_source': funding_source}) if form.is_valid(): allocation = form.cleaned_data.copy() allocation['computeRequested'] = 20000 # Also update the project project.description = allocation.pop('description', None) supplemental_details = allocation.pop('supplemental_details', None) logger.error(supplemental_details) funding_source = allocation.pop('funding_source', None) #if supplemental_details == None: # raise forms.ValidationError("Justifcation is required") # This is required if not supplemental_details: supplemental_details = '(none)' logger.error(supplemental_details) if funding_source: allocation['justification'] = '%s\n\n--- Funding source(s) ---\n\n%s' % ( supplemental_details, funding_source) else: allocation['justification'] = supplemental_details allocation['projectId'] = project_id allocation['requestorId'] = tas.get_user(username=request.user)['id'] allocation['resourceId'] = '39' if allocation_id > 0: allocation['id'] = allocation_id try: logger.info('Submitting allocation request for project %s: %s' % (project.id, allocation)) updated_project = tas.edit_project(project.as_dict()) tas.create_allocation(allocation) messages.success(request, 'Your allocation request has been submitted!') return HttpResponseRedirect( reverse('projects:view_project', args=[updated_project['id']])) except: logger.exception('Error creating allocation') form.add_error('__all__', 'An unexpected error occurred. Please try again') else: form.add_error('__all__', 'There were errors processing your request. ' 'Please see below for details.') else: form = AllocationCreateForm(initial={'description': abstract, 'supplemental_details': justification, 'funding_source': funding_source}) context = { 'form': form, 'project': project, 'alloc_id': allocation_id, 'alloc': allocation } return render(request, 'projects/create_allocation.html', context)
def __init__(self): self.tas = TASClient()
def create_project(request): tas = TASClient() user = tas.get_user(username=request.user) if user['piEligibility'] != 'Eligible': messages.error(request, 'Only PI Eligible users can create new projects. ' 'If you would like to request PI Eligibility, please ' '<a href="/user/profile/edit/">submit a PI Eligibility ' 'request</a>.') return HttpResponseRedirect(reverse('projects:user_projects')) if request.POST: form = ProjectCreateForm(request.POST) if form.is_valid(): # title, description, typeId, fieldId project = form.cleaned_data.copy() project.pop('accept_project_terms', None) # pi pi_user = tas.get_user(username=request.user) project['piId'] = pi_user['id'] # allocations allocation = { 'resourceId': 39, 'requestorId': pi_user['id'], 'computeRequested': 20000, } supplemental_details = project.pop('supplemental_details', None) funding_source = project.pop('funding_source', None) #if supplemental_details == None: # raise forms.ValidationError("Justifcation is required") if not supplemental_details: supplemental_details = '(none)' if funding_source: allocation['justification'] = '%s\n\n--- Funding source(s) ---\n\n%s' % ( supplemental_details, funding_source) else: allocation['justification'] = supplemental_details project['allocations'] = [allocation] # startup project['typeId'] = 2 # source project['source'] = 'Chameleon' try: created_project = tas.create_project(project) messages.success(request, 'Your project has been created!') return HttpResponseRedirect( reverse('projects:view_project', args=[created_project['id']])) except: logger.exception('Error creating project') form.add_error('__all__', 'An unexpected error occurred. Please try again') else: form.add_error('__all__', 'There were errors processing your request. ' 'Please see below for details.') else: form = ProjectCreateForm() return render(request, 'projects/create_project.html', {'form': form})