def send_courses(self, courses, send_to_editors=False, send_to_contributors=False, send_to_due_participants=False, send_to_all_participants=False): from evap.evaluation.models import UserProfile # pivot course-user relationship user_course_map = {} for course in courses: for user in [user for user in self.recipient_list_for_course(course, send_to_editors, send_to_contributors, send_to_due_participants, send_to_all_participants) if user.email != ""]: if user in user_course_map: user_course_map[user].append(course) else: user_course_map[user] = [course] # send emails on a per user basis for user, courses in user_course_map.iteritems(): cc = [] for course in courses: # if email will be sent to editors, also send to all their delegates in CC if send_to_editors: if course.contributions.filter(can_edit=True, contributor=user).exists(): cc.extend([p.email for p in UserProfile.get_for_user(user).delegates.all() if p.email]) break # send email to all cc users of the current user cc.extend([p.email for p in UserProfile.get_for_user(user).cc_users.all() if p.email]) mail = EmailMessage( subject = self.render_string(self.subject, {'user': user, 'courses': courses}), body = self.render_string(self.body, {'user': user, 'courses': courses}), to = [user.email], cc = cc, bcc = [a[1] for a in settings.MANAGERS], headers = {'Reply-To': settings.REPLY_TO_EMAIL}) mail.send(False)
def user_index(request): users = User.objects.order_by("last_name", "first_name", "username") filter = request.GET.get('filter') if filter == "fsr": users = users.filter(is_staff=True) elif filter == "responsibles": users = [user for user in users if UserProfile.get_for_user(user).is_responsible] elif filter == "delegates": users = [user for user in users if UserProfile.get_for_user(user).is_delegate] return render_to_response("fsr_user_index.html", dict(users=users, filter=filter), context_instance=RequestContext(request))
def clean_email(self): email = self.cleaned_data.get('email') if not UserProfile.email_needs_login_key(email): raise forms.ValidationError(_(u"HPI users cannot request login keys. Please login using your domain credentials.")) try: user = User.objects.get(email__iexact=email) self.user_cache = user self.profile_cache = UserProfile.get_for_user(user) except User.DoesNotExist: raise forms.ValidationError(_(u"No user with this email address was found. Please make sure to enter the email address already known to the university office.")) return email
def validate(self): user = UserProfile() user.username = self.username user.first_name = self.first_name user.last_name = self.last_name user.email = self.email user.password = "******" # clean_fields needs that... user.clean_fields()
def handle(self, *args, **options): try: # Get a username username = read_value('Username: '******'Email address: ', is_valid_email) # Get password if it should be set password = read_value_hidden('Password: '******'Yes', 'yes'] else False # create user user = User.objects.create(username=username, email=email, is_staff=is_fsr, is_superuser=is_fsr) if not password is None: user.set_password(password) user.save() profile = UserProfile.get_for_user(user) profile.save() except KeyboardInterrupt: sys.stderr.write("\nOperation cancelled.\n") sys.exit(1)
def save(self, *args, **kw): # first save the user, so that the profile gets created for sure self.instance.user.first_name = self.cleaned_data.get('first_name') self.instance.user.last_name = self.cleaned_data.get('last_name') self.instance.user.email = self.cleaned_data.get('email') self.instance.user.save() self.instance = UserProfile.get_for_user(self.instance.user) super(UserForm, self).save(*args, **kw)
def user_create(request): form = UserForm(request.POST or None, instance=UserProfile()) if form.is_valid(): form.save() messages.success(request, _("Successfully created user.")) return redirect('staff:user_index') else: return render(request, "staff_user_form.html", dict(form=form))
def get_user_profile_object(self): user = UserProfile() user.username = self.username user.first_name = self.first_name user.last_name = self.last_name user.email = self.email user.password = "******" # clean_fields needs that... return user
def store_in_database(self): user = User(username=self.username, first_name=self.first_name, last_name=self.last_name, email=self.email) user.save() profile = UserProfile.get_for_user(user=user) profile.title = self.title profile.save() return user
def user_edit(request, user_id): user = get_object_or_404(User, id=user_id) form = UserForm(request.POST or None, request.FILES or None, instance=UserProfile.get_for_user(user)) if form.is_valid(): form.save() messages.success(request, _("Successfully updated user.")) return redirect('evap.fsr.views.user_index') else: return render_to_response("fsr_user_form.html", dict(form=form, object=user), context_instance=RequestContext(request))
def user_index(request): users = User.objects.order_by("last_name", "first_name", "username") filter = request.GET.get('filter') if filter == "fsr": users = users.filter(is_staff=True) elif filter == "responsibles": users = [ user for user in users if UserProfile.get_for_user(user).is_responsible ] elif filter == "delegates": users = [ user for user in users if UserProfile.get_for_user(user).is_delegate ] return render_to_response("fsr_user_index.html", dict(users=users, filter=filter), context_instance=RequestContext(request))
def user_delete(request, user_id): user = get_object_or_404(User, id=user_id) if UserProfile.get_for_user(user).can_fsr_delete: if request.method == 'POST': user.delete() return redirect('evap.fsr.views.user_index') else: return render_to_response("fsr_user_delete.html", dict(user=user), context_instance=RequestContext(request)) else: messages.add_message(request, messages.ERROR, _("The user '%s' cannot be deleted, because he lectures courses.") % UserProfile.get_for_user(user).full_name) return redirect('evap.fsr.views.user_index')
def clean_email(self): email = self.cleaned_data.get('email') if not UserProfile.email_needs_login_key(email): raise forms.ValidationError(_("HPI users cannot request login keys. Please login using your domain credentials.")) try: user = UserProfile.objects.get(email__iexact=email) self.user_cache = user except UserProfile.DoesNotExist: raise forms.ValidationError(_("No user with this email address was found. Please make sure to enter the email address already known to the university office.")) return email
def test_login_key(self): environ = self.app.extra_environ self.app.extra_environ = {} self.assertRedirects(self.app.get(reverse("evap.results.views.index"), extra_environ={}), "/?next=/results/") self.app.extra_environ = environ user = User.objects.all()[0] userprofile = UserProfile.get_for_user(user) userprofile.generate_login_key() userprofile.save() url_with_key = reverse("evap.results.views.index") + "?userkey=%s" % userprofile.login_key self.app.get(url_with_key)
def _post_clean(self, *args, **kw): # first save the user, so that the profile gets created for sure self.instance.user.username = self.cleaned_data.get('username') self.instance.user.first_name = self.cleaned_data.get('first_name') self.instance.user.last_name = self.cleaned_data.get('last_name') self.instance.user.email = self.cleaned_data.get('email') self.instance.user.is_staff = self.cleaned_data.get('is_staff') self.instance.user.is_superuser = self.cleaned_data.get('is_superuser') self.instance.user.save() self.instance.user.represented_users = self.cleaned_data.get('represented_users') self.instance = UserProfile.get_for_user(self.instance.user) super(UserForm, self)._post_clean(*args, **kw)
def create_contributor_questionnaires(form_groups_items): contributor_questionnaires = [] errors = [] for contribution, form_group in form_groups_items: if contribution.is_general: continue contributor = contribution.contributor user_profile = UserProfile.get_for_user(contributor) contributor_questionnaires.append((user_profile, form_group.values())); if any(form.errors for form in form_group.values()): errors.append(contributor.id) return contributor_questionnaires, errors
def user_edit(request, user_id): user = get_object_or_404(User, id=user_id) form = UserForm(request.POST or None, request.FILES or None, instance=UserProfile.get_for_user(user)) if form.is_valid(): form.save() messages.add_message(request, messages.INFO, _("Successfully updated user.")) if "filter" in request.GET: return custom_redirect('evap.fsr.views.user_index', filter=request.GET['filter']) else: return redirect('evap.fsr.views.user_index') else: return render_to_response("fsr_user_form.html", dict(form=form, object=user), context_instance=RequestContext(request))
def find_matching_internal_user_for_email(request, email): # for internal users only the part before the @ must be the same to match a user to an email matching_users = [ user for user in UserProfile.objects.filter( email__startswith=email.split('@')[0] + '@').order_by('id') if not user.is_external ] if not matching_users: return None if len(matching_users) > 1: raise UserProfile.MultipleObjectsReturned(matching_users) return matching_users[0]
def update(self, user): profile = UserProfile.get_for_user(user=user) if not user.first_name: user.first_name = self.first_name if not user.last_name: user.last_name = self.last_name if not user.email: user.email = self.email if not profile.title: profile.title = self.title if profile.needs_login_key: profile.refresh_login_key() user.save() profile.save()
def clean_email(self): email = self.cleaned_data.get('email') if not UserProfile.email_needs_login_key(email): raise forms.ValidationError(_("HPI users cannot request login keys. Please login using your domain credentials.")) try: user = UserProfile.objects.get(email__iexact=email) self.user_cache = user except UserProfile.DoesNotExist: raise forms.ValidationError(_("No user with this email address was found. Please make sure to enter the email address used for course or event registration.")) if not user.is_active: raise forms.ValidationError(_("Inactive users cannot request login keys.")) return email
def test_login_key(self): environ = self.app.extra_environ self.app.extra_environ = {} self.assertRedirects( self.app.get(reverse("evap.results.views.index"), extra_environ={}), "/?next=/results/") self.app.extra_environ = environ user = User.objects.all()[0] userprofile = UserProfile.get_for_user(user) userprofile.generate_login_key() userprofile.save() url_with_key = reverse( "evap.results.views.index") + "?userkey=%s" % userprofile.login_key self.app.get(url_with_key)
def user_create(request): profile = UserProfile(user=User()) form = UserForm(request.POST or None, instance=profile) if form.is_valid(): #profile.user.save() form.save() messages.add_message(request, messages.INFO, _("Successfully created user.")) if "filter" in request.GET: return custom_redirect('evap.fsr.views.user_index', filter=request.GET['filter']) else: return redirect('evap.fsr.views.user_index') else: return render_to_response("fsr_user_form.html", dict(form=form), context_instance=RequestContext(request))
def get_contributors_with_questionnaires(self, course): for ccm in self.get('course_category_mapping', course_id=course.id): for ccm_to_staff in self.get('ccm_to_staff', ccm_id=ccm.id): # staff --> User staff = self.get_one('staff', id=ccm_to_staff.staff_id) user = self.user_from_db(staff.loginName) # import name profile = UserProfile.get_for_user(user) name_parts = unicode(staff.name).split() if name_parts[0].startswith("Dr"): user.last_name = " ".join(name_parts[1:]) profile.title = name_parts[0] elif name_parts[0] == "Prof.": user.last_name = " ".join(name_parts[2:]) profile.title = " ".join(name_parts[:2]) elif name_parts[0].startswith("Prof"): user.last_name = " ".join(name_parts[1:]) profile.title = name_parts[0] elif len(name_parts) == 2: user.first_name = name_parts[0] user.last_name = name_parts[1] user.save() profile.save() # TODO: import name? self.staff_cache[int(staff.id)] = user try: topic_template = self.get_one( 'topic_template', course_category_id=ccm.course_category_id, questionnaire_template_id=course.evaluation_id, per_person="1") questionnaire = self.questionnaire_cache[int( topic_template.id)] yield user, questionnaire except NotOneException: logger.warn( "Skipping questionnaire for contributor %r in course %r.", user, course.name)
def clean_email(self): email = self.cleaned_data.get('email') if not UserProfile.email_needs_login_key(email): raise forms.ValidationError( _("HPI users cannot request login keys. Please login using your domain credentials." )) try: user = UserProfile.objects.get(email__iexact=email) self.user_cache = user except UserProfile.DoesNotExist as e: raise forms.ValidationError( _("No user with this email address was found. Please make sure to enter the email address used for registration." )) from e if not user.is_active: raise forms.ValidationError( _("Inactive users cannot request login keys.")) return email
def __init__(self, *args, **kwargs): super(CourseForm, self).__init__(*args, **kwargs) self.fields['vote_start_date'].localize = True self.fields['vote_end_date'].localize = True self.fields['kind'].widget = forms.Select(choices=[(a, a) for a in Course.objects.values_list('kind', flat=True).order_by().distinct()]) self.fields['degree'].widget = forms.Select(choices=[(a, a) for a in Course.objects.values_list('degree', flat=True).order_by().distinct()]) self.fields['participants'].queryset = User.objects.order_by("last_name", "first_name", "username") self.fields['participants'].help_text = "" if self.instance.general_contribution: self.fields['general_questions'].initial = [q.pk for q in self.instance.general_contribution.questionnaires.all()] self.fields['last_modified_time_2'].initial = self.instance.last_modified_time self.fields['last_modified_time_2'].widget.attrs['readonly'] = True if self.instance.last_modified_user: self.fields['last_modified_user_2'].initial = UserProfile.get_for_user(self.instance.last_modified_user).full_name self.fields['last_modified_user_2'].widget.attrs['readonly'] = True if self.instance.state == "inEvaluation": self.fields['vote_start_date'].widget.attrs['readonly'] = True self.fields['vote_end_date'].widget.attrs['readonly'] = True
def get_contributors_with_questionnaires(self, course): for ccm in self.get('course_category_mapping', course_id=course.id): for ccm_to_staff in self.get('ccm_to_staff', ccm_id=ccm.id): # staff --> User staff = self.get_one('staff', id=ccm_to_staff.staff_id) user = self.user_from_db(staff.loginName) # import name profile = UserProfile.get_for_user(user) name_parts = unicode(staff.name).split() if name_parts[0].startswith("Dr"): user.last_name = " ".join(name_parts[1:]) profile.title = name_parts[0] elif name_parts[0] == "Prof.": user.last_name = " ".join(name_parts[2:]) profile.title = " ".join(name_parts[:2]) elif name_parts[0].startswith("Prof"): user.last_name = " ".join(name_parts[1:]) profile.title = name_parts[0] elif len(name_parts) == 2: user.first_name = name_parts[0] user.last_name = name_parts[1] user.save() profile.save() # TODO: import name? self.staff_cache[int(staff.id)] = user try: topic_template = self.get_one('topic_template', course_category_id=ccm.course_category_id, questionnaire_template_id=course.evaluation_id, per_person="1") questionnaire = self.questionnaire_cache[int(topic_template.id)] yield user, questionnaire except NotOneException: logger.warn("Skipping questionnaire for contributor %r in course %r.", user, course.name)
def label_from_instance(self, obj): return UserProfile.get_for_user(obj).full_name
def index(request): """Main entry page into EvaP providing all the login options available. THe username/password login is thought to be used for internal users, e.g. by connecting to a LDAP directory. The login key mechanism is meant to be used to include external participants, e.g. visiting students or visiting contributors. """ # parse the form data into the respective form submit_type = request.POST.get("submit_type", "no_submit") new_key_form = NewKeyForm(request.POST if submit_type == "new_key" else None) login_key_form = LoginKeyForm(request.POST if submit_type == "login_key" else None) login_username_form = LoginUsernameForm( request, request.POST if submit_type == "login_username" else None) # process form data if request.method == 'POST': if new_key_form.is_valid(): # user wants a new login key profile = new_key_form.get_profile() profile.generate_login_key() profile.save() EmailTemplate.get_login_key_template().send_user( new_key_form.get_user()) messages.success(request, _(u"Successfully sent email with new login key.")) elif login_key_form.is_valid(): # user would like to login with a login key and passed key test auth_login(request, login_key_form.get_user()) elif login_username_form.is_valid(): # user would like to login with username and password and passed password test auth_login(request, login_username_form.get_user()) # clean up our test cookie if request.session.test_cookie_worked(): request.session.delete_test_cookie() # if not logged in by now, render form if not request.user.is_active: # set test cookie to verify whether they work in the next step request.session.set_test_cookie() return render_to_response("index.html", dict( new_key_form=new_key_form, login_key_form=login_key_form, login_username_form=login_username_form), context_instance=RequestContext(request)) else: # check for redirect variable next = request.GET.get("next", None) if not next is None: if next.startswith("/fsr/"): if request.user.is_staff: return redirect(next) elif next.startswith("/contributor/"): if UserProfile.get_for_user(request.user).is_contributor: return redirect(next) else: return redirect(next) # redirect user to appropriate start page if request.user.is_staff: return redirect('evap.fsr.views.index') elif UserProfile.get_for_user(request.user).is_editor_or_delegate: return redirect('evap.contributor.views.index') else: return redirect('evap.student.views.index')
def check_user(user): if not user.is_authenticated(): return False return (UserProfile.get_for_user(user=user).enrolled_in_courses)
def check_user(user): from evap.rewards.tools import can_user_use_reward_points if not user.is_authenticated(): return False return can_user_use_reward_points(UserProfile.get_for_user(user=user))
def check_user(user): if not user.is_authenticated(): return False return UserProfile.get_for_user(user=user).is_editor
def index(request): """Main entry page into EvaP providing all the login options available. THe username/password login is thought to be used for internal users, e.g. by connecting to a LDAP directory. The login key mechanism is meant to be used to include external participants, e.g. visiting students or visiting contributors. """ # parse the form data into the respective form submit_type = request.POST.get("submit_type", "no_submit") new_key_form = NewKeyForm(request.POST if submit_type == "new_key" else None) login_key_form = LoginKeyForm(request.POST if submit_type == "login_key" else None) login_username_form = LoginUsernameForm(request, request.POST if submit_type == "login_username" else None) # process form data if request.method == 'POST': if new_key_form.is_valid(): # user wants a new login key profile = new_key_form.get_profile() profile.generate_login_key() profile.save() EmailTemplate.get_login_key_template().send_user(new_key_form.get_user()) messages.success(request, _(u"Successfully sent email with new login key.")) elif login_key_form.is_valid(): # user would like to login with a login key and passed key test auth_login(request, login_key_form.get_user()) elif login_username_form.is_valid(): # user would like to login with username and password and passed password test auth_login(request, login_username_form.get_user()) # clean up our test cookie if request.session.test_cookie_worked(): request.session.delete_test_cookie() # if not logged in by now, render form if not request.user.is_active: # set test cookie to verify whether they work in the next step request.session.set_test_cookie() return render_to_response("index.html", dict(new_key_form=new_key_form, login_key_form=login_key_form, login_username_form=login_username_form), context_instance=RequestContext(request)) else: # check for redirect variable next = request.GET.get("next", None) if not next is None: if next.startswith("/fsr/"): if request.user.is_staff: return redirect(next) elif next.startswith("/contributor/"): if UserProfile.get_for_user(request.user).is_contributor: return redirect(next) else: return redirect(next) # redirect user to appropriate start page if request.user.is_staff: return redirect('evap.fsr.views.index') elif UserProfile.get_for_user(request.user).is_editor_or_delegate: return redirect('evap.contributor.views.index') else: return redirect('evap.student.views.index')
def vote(request, course_id): # retrieve course and make sure that the user is allowed to vote course = get_object_or_404(Course, id=course_id) if not course.can_user_vote(request.user): raise PermissionDenied # build forms form_group = {} contributors_with_questionnaires = questionnaires_and_contributions_by_contributor(course) for contributor in contributors_with_questionnaires: for questionnaire, contribution in contributors_with_questionnaires[contributor]: form = QuestionsForm(request.POST or None, contribution=contribution, questionnaire=questionnaire) if form.contribution.contributor == request.user: continue # users shall not vote about themselves if not contributor in form_group: form_group[contributor] = SortedDict() form_group[contributor][(contribution, questionnaire)] = form for contributor in form_group: for (contribution, questionnaire), form in form_group[contributor].items(): for question in questionnaire.question_set.all(): identifier = make_form_identifier(contribution, questionnaire, question) for contributor in form_group: for form in form_group[contributor].values(): if form.is_valid(): continue course_forms = [] contributor_questionnaires = {} errors = [] for form in form_group[None].values(): course_forms.append(form) for contributor in form_group: if contributor == None: continue user_profile = UserProfile.get_for_user(contributor) contributor_questionnaires[user_profile] = form_group[contributor].values() for form in form_group[contributor].values(): if form.errors: errors.append(contributor.id) return render_to_response( "student_vote.html", dict(course_forms=course_forms, contributor_questionnaires=contributor_questionnaires, errors=errors, course=course), context_instance=RequestContext(request)) # all forms are valid # begin vote operation with transaction.commit_on_success(): for contributor in form_group: for (contribution, questionnaire), form in form_group[contributor].items(): for question in questionnaire.question_set.all(): identifier = make_form_identifier(contribution, questionnaire, question) value = form.cleaned_data.get(identifier) if type(value) in [str, unicode]: value = value.strip() if value == 6: #no answer value = None # store the answer if one was given if value: question.answer_class.objects.create( contribution=contribution, question=question, answer=value) # remember that the user voted already course.voters.add(request.user) messages.add_message(request, messages.INFO, _("Your vote was recorded.")) return redirect('evap.student.views.index')
def image(self): return UserProfile.get_for_user(self.contribution.contributor).picture if self.contribution.contributor else None
def bulk_update_users(request, user_file_content, test_run): # pylint: disable=too-many-branches,too-many-locals # user_file must have one user per line in the format "{username},{email}" imported_emails = { clean_email(line.decode().split(',')[1]) for line in user_file_content.splitlines() } emails_of_users_to_be_created = [] users_to_be_updated = [] skipped_external_emails_counter = 0 for imported_email in imported_emails: if is_external_email(imported_email): skipped_external_emails_counter += 1 continue try: matching_user = find_matching_internal_user_for_email( request, imported_email) except UserProfile.MultipleObjectsReturned as e: messages.error( request, format_html( _('Multiple users match the email {}:{}'), imported_email, create_user_list_html_string_for_message(e.args[0]))) return False if not matching_user: emails_of_users_to_be_created.append(imported_email) elif matching_user.email != imported_email: users_to_be_updated.append((matching_user, imported_email)) emails_of_non_obsolete_users = set(imported_emails) | { user.email for user, _ in users_to_be_updated } deletable_users, users_to_mark_inactive = [], [] for user in UserProfile.objects.exclude( email__in=emails_of_non_obsolete_users): if user.can_be_deleted_by_manager: deletable_users.append(user) elif user.is_active and user.can_be_marked_inactive_by_manager: users_to_mark_inactive.append(user) messages.info( request, _('The uploaded text file contains {} internal and {} external users. The external users will be ignored. ' '{} users are currently in the database. Of those, {} will be updated, {} will be deleted and {} will be ' 'marked inactive. {} new users will be created.').format( len(imported_emails) - skipped_external_emails_counter, skipped_external_emails_counter, UserProfile.objects.count(), len(users_to_be_updated), len(deletable_users), len(users_to_mark_inactive), len(emails_of_users_to_be_created))) if users_to_be_updated: messages.info( request, format_html( _('Users to be updated are:{}'), format_html_join( '', '<br />{} {} ({} > {})', ((user.first_name, user.last_name, user.email, email) for user, email in users_to_be_updated)))) if deletable_users: messages.info( request, format_html( _('Users to be deleted are:{}'), create_user_list_html_string_for_message(deletable_users))) if users_to_mark_inactive: messages.info( request, format_html( _('Users to be marked inactive are:{}'), create_user_list_html_string_for_message( users_to_mark_inactive))) if emails_of_users_to_be_created: messages.info( request, format_html( _('Users to be created are:{}'), format_html_join( '', '<br />{}', ((email, ) for email in emails_of_users_to_be_created)))) with transaction.atomic(): for user in deletable_users + users_to_mark_inactive: for message in remove_user_from_represented_and_ccing_users( user, deletable_users + users_to_mark_inactive, test_run): messages.warning(request, message) if test_run: messages.info(request, _('No data was changed in this test run.')) else: for user in deletable_users: user.delete() for user in users_to_mark_inactive: user.is_active = False user.save() for user, email in users_to_be_updated: user.email = email user.save() userprofiles_to_create = [] for email in emails_of_users_to_be_created: userprofiles_to_create.append(UserProfile(email=email)) UserProfile.objects.bulk_create(userprofiles_to_create) messages.success(request, _('Users have been successfully updated.')) return True
def image(self): return UserProfile.get_for_user( self.contribution.contributor ).picture if self.contribution.contributor else None