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 _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 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 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 edit_profile(request): tas = TASClient( baseURL=settings.TAS_URL, credentials={ 'username': settings.TAS_CLIENT_KEY, 'password': settings.TAS_CLIENT_SECRET } ) user = request.user body = json.loads(request.body) portal_profile = user.profile if body['flag'] == 'Required': portal_profile.ethnicity = body['ethnicity'] portal_profile.gender = body['gender'] tas_user = tas.get_user(username=user) body['piEligibility'] = tas_user['piEligibility'] body['source'] = tas_user['source'] tas.save_user(tas_user['id'], body) elif body['flag'] == 'Optional': portal_profile.website = body['website'] portal_profile.professional_level = body['professional_level'] portal_profile.bio = body['bio'] portal_profile.orcid_id = body['orcid_id'] portal_profile.save() return JsonResponse({'portal': model_to_dict(portal_profile), 'tas': tas.get_user(username=user)})
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 _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 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_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 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 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 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')
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(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(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(Department, self).__init__() if id is not None: api = TASClient() initial = api.get_department(id, id) self.__populate(initial) else: self.__populate(initial)
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 save(self, source='IPT', pi_eligibility=INELIGIBLE): data = self.cleaned_data data['source'] = source data['piEligibility'] = pi_eligibility safe_data = data.copy() safe_data['password'] = safe_data['confirmPassword'] = '******' logger.info('Attempting new user registration: %s' % safe_data) tas_user = TASClient().save_user(None, data) return tas_user
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 save(self, source='DesignSafe', pi_eligibility=INELIGIBLE): data = self.cleaned_data data['source'] = source data['piEligibility'] = pi_eligibility safe_data = data.copy() safe_data['password'] = safe_data['confirmPassword'] = '******' logger.info('Attempting new user registration: %s' % safe_data) tas_user = TASClient().save_user(None, data) # create local user UserModel = get_user_model() try: # the user should not exist user = UserModel.objects.get(username=data['username']) logger.warning('On TAS registration, local user already existed? ' 'user=%s' % user) except UserModel.DoesNotExist: user = UserModel.objects.create_user( username=data['username'], first_name=tas_user['firstName'], last_name=tas_user['lastName'], email=tas_user['email'], agree_to_account_limit=data['agree_to_account_limit']) # extended profile information try: # again, this should not exist ds_profile = DesignSafeProfile.objects.get(user=user) ds_profile.ethnicity = data['ethnicity'] ds_profile.gender = data['gender'] except DesignSafeProfile.DoesNotExist: ds_profile = DesignSafeProfile(user=user, ethnicity=data['ethnicity'], gender=data['gender']) ds_profile.save() # terms of use logger.info( 'Prior to Registration, %s %s <%s> agreed to Terms of Use' % (data['firstName'], data['lastName'], data['email'])) try: terms = TermsAndConditions.get_active() user_terms = UserTermsAndConditions(user=user, terms=terms) user_terms.save() except: logger.exception('Error saving UserTermsAndConditions for user=%s', user) return tas_user
def _process_authors(authors): """Process authors. This function transforms the author's details into an list of first name and last name and a list of unique institutions. This is necessary to create the JSON payload for the Datacite API. .. warning:: Authors should be sorted when passed to this function. :param list[dict] authors: List of dict with author's details. Each dictionary must have at least a ``'name'`` key with the author's username. """ creators_details = [] institutions = [] for author in authors: user_obj = None user_tas = None if not author.get('guest'): try: user_obj = get_user_model().objects.get( username=author['name']) except ObjectDoesNotExist: pass if user_obj: if getattr(settings, 'DESIGNSAFE_ENVIRONMENT', 'dev') == 'default': user_tas = TASClient().get_user(username=user_obj.username) else: user_tas = {'institution': 'dev_staging_placeholder'} if user_obj and user_tas: creators_details.append({ 'nameType': 'Personal', 'givenName': user_obj.first_name, 'familyName': user_obj.last_name, }) institutions.append(user_tas['institution']) elif author.get('fname') and author.get('lname'): creators_details.append({ 'nameType': 'Personal', 'givenName': author['fname'], 'familyName': author['lname'], }) if 'inst' in author: institutions.append(author['inst']) institutions = set(institutions) return creators_details, institutions
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_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 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_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 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'))