def signup(request): from utils.mailer import EmailHelper email = request.data.get('email', False) password = request.data.get('password', False) password_confirm = request.data.get('password_confirm', False) if len(User.objects.filter(email=email)) > 0: return Response(data={'error': 'User already exist'}, status=401) if not password or password != password_confirm: return Response(data={'error': 'Password and password confirm don\'t match'}, status=401) user = User.create(**request.data) profile = Profile.create(user=user, **request.data) # Send email confirmation_link = request.build_absolute_uri('/onboarding/confirmation/{TOKEN}'.format(TOKEN=profile.reset_token)) EmailHelper.email( template_name='onboarding_email_template', title='OpenMaker Nomination done!', vars={ 'FIRST_NAME': user.first_name.encode('utf-8'), 'LAST_NAME': user.last_name.encode('utf-8'), 'CONFIRMATION_LINK': confirmation_link, }, receiver_email=user.email ) return Response({'success': True}) if profile else Response(data={'error': 'error creating user'}, status=403)
def contact_user_with_email(request, user_id): from django.utils.html import escape, strip_tags if request.user.profile.id == user_id: return Response({'error': 'you cannot send message to yourself'}, status=422) email_message = strip_tags(escape(request.data.get('message', None))) sender = request.user receiver = User.objects.filter(pk=user_id).first() vars = { 'SENDER_FIRST_NAME': sender.first_name, 'SENDER_LAST_NAME': sender.last_name, 'SENDER_PROFILE_PAGE': 'http://explorer.openmaker.eu/profile/' + str(sender.profile.id), 'RECEIVER_FIRST_NAME': receiver.first_name, 'RECEIVER_LAST_NAME': receiver.last_name, 'MESSAGE': email_message } email_title = 'OpenMaker - message from : ' + (sender.first_name + ' ' + sender.last_name).title() EmailHelper.email('user_to_user', receiver.email, email_title, vars) return Response('Message sent')
def send_email(self): p_user = Profile.objects.get(user__id=self.profile.user_id) applier_first_name = p_user.user.first_name applier_last_name = p_user.user.last_name latest_project_name_uploaded_by_current_user = Application.objects.filter(profile_id=self.profile.id).order_by('-id')[0].project_name latest_les_uploaded_by_current_user = Application.objects.filter(profile_id=self.profile.id).order_by('-id')[0].les EmailHelper.email( template_name='pss_upload_confirmation', title='DSPExplorer - Open Maker - Application done!', vars={ 'FIRST_NAME': applier_first_name, 'LAST_NAME': applier_last_name }, receiver_email=p_user.user.email ) admins = settings.EMAIL_ADMIN_LIST for admin in admins: EmailHelper.email( template_name='pss_admin_upload_confirmation', title='New PSS application', vars={ 'APPLIER_FIRST_NAME': applier_first_name, 'APPLIER_LAST_NAME': applier_last_name, 'APPLICATION_NAME': latest_project_name_uploaded_by_current_user, 'LES': self.retrieve_les_label(latest_les_uploaded_by_current_user) }, receiver_email=admin )
def om_confirmation( request, sender_first_name, sender_last_name, sender_email, receiver_first_name, receiver_last_name, receiver_email ): # sender sender_first_name = sender_first_name.decode('base64') sender_last_name = sender_last_name.decode('base64') sender_email = sender_email.decode('base64') # receiver receiver_first_name = receiver_first_name.decode('base64') receiver_last_name = receiver_last_name.decode('base64') receiver_email = receiver_email.decode('base64') try: Invitation.confirm_sender(sender_email=sender_email, receiver_email=receiver_email) except SelfInvitation as e: messages.error(request, 'You cannot invite youself!') return HttpResponseRedirect(reverse('dashboard:dashboard')) except EmailAlreadyUsed as e: messages.error(request, 'User is already a DSP member!') return HttpResponseRedirect(reverse('dashboard:dashboard')) except UserAlreadyInvited as e: messages.error(request, 'You have already invite this user!') return HttpResponseRedirect(reverse('dashboard:dashboard')) # Emails email_vars = { 'RECEIVER_FIRST_NAME': receiver_first_name.encode('utf-8'), 'RECEIVER_LAST_NAME': receiver_last_name.encode('utf-8'), 'SENDER_FIRST_NAME': sender_first_name.encode('utf-8'), 'SENDER_LAST_NAME': sender_last_name.encode('utf-8'), 'ONBOARDING_LINK': request.build_absolute_uri('/onboarding/') } # Send email to receiver only the first time if len(Invitation.get_by_email(receiver_email=receiver_email)) == 1: # Send email for the first time EmailHelper.email( template_name='invitation_email_receiver', title='You are invited to join the OpenMaker community!', vars=email_vars, receiver_email=receiver_email ) # Send mail to sender EmailHelper.email( template_name='invitation_email_confirmed', title='OpenMaker Nomination done!', vars=email_vars, receiver_email=sender_email ) return HttpResponseRedirect('http://openmaker.eu/confirmed/')
def interest_challenge(request, challenge_id): try: challenge = Challenge.objects.get(pk=challenge_id) email_context = { 'USER_NAME': request.user.first_name + ' ' + request.user.last_name, 'USER_EMAIL': request.user.email, 'USER_URL': request.build_absolute_uri( reverse('dashboard:profile', kwargs={'profile_id': request.user.profile.pk})), 'CHALLENGE_TITLE': challenge.title, 'CHALLENGE_URL': request.build_absolute_uri( reverse('dashboard:challenge', kwargs={'challenge_id': challenge.pk})), 'COORDINATOR_EMAIL': challenge.coordinator_email } if request.method == 'POST': # Add interest request.user.profile.add_interest(challenge) # Email Coordinator challenge.notify_admin and EmailHelper.email( template_name='challenge/challenge_coordinator_interest_added', title='Openmaker Explorer - Challenge interest ADDED', vars=email_context, receiver_email=email_context['COORDINATOR_EMAIL']) if request.method == 'DELETE': # Remove interest request.user.profile.delete_interest(Challenge, challenge_id) # Email Coordinator challenge.notify_admin and EmailHelper.email( template_name= 'challenge/challenge_coordinator_interest_removed', title='Openmaker Explorer - Challenge interest REMOVED', vars=email_context, receiver_email=email_context['COORDINATOR_EMAIL']) # Email User challenge.notify_user and EmailHelper.email( template_name='challenge/challenge_user_interest_removed', title='Openmaker Explorer - Challenge interest REMOVED', vars=email_context, receiver_email=email_context['COORDINATOR_EMAIL']) return JsonResponse({'status': 'success'}) except Exception as e: print(e) response = JsonResponse({'status': 'error', 'message': e}) response.status_code = 500 return response
def apiunsubscribe(request): try: first_name = request.user.first_name last_name = request.user.last_name Profile.delete_account(request.user.pk) EmailHelper.email(template_name='account_deletion_confirmation', title='Openmaker Explorer account deletion', vars={ 'FIRST_NAME': first_name, 'LAST_NAME': last_name, }, receiver_email=request.user.email) logout(request) except Exception as e: print('ERROR[dashboard.api14.apiunsubscribe]') print(e) return Response({'error': e}, status=500) return Response()
def test_email_all(self): print '[EMAIL TEST] : all' email_list = ('invitation_email_confirm', 'pss_upload_confirmation', 'invitation_email_receiver', 'onboarding_email_template', 'pss_upload_confirmation', 'pss_admin_upload_confirmation', 'authentication_reset_password') for email_name in email_list: body = EmailHelper.email( template_name=email_name, title='Test Email', vars=self.email_vars, receiver_email='*****@*****.**') self.assertTrue(body, 'Mail error')
def project_invitation(request, status=None): # ToDo add token to avoid actions not allowed from dashboard.serializer import ProjectContributorSerializer if request.method == 'POST': try: body = json.loads(request.body) project_id = body['project_id'] profile_id = body['profile_id'] profile = Profile.objects.get(id=profile_id) project = Project.objects.get(id=project_id, profile=request.user.profile) # can not invite yourself if profile == request.user.profile: return bad_request('you are the owner of the project') contribution = ProjectContributor.objects.filter( project=project, contributor=profile) if len(contribution): if status is not None: # update the status of the invitation / collaboration contribution.update(status=status) serialized = ProjectContributorSerializer( contribution).data return success('ok', 'invitation updated', serialized) else: # ToDo send e-mail email_context = { 'FIRST_NAME': profile.user.first_name, 'LAST_NAME': profile.user.last_name, 'PROJECT_OWNER_FIRST_NAME': request.user.first_name, 'PROJECT_OWNER_LAST_NAME': request.user.last_name, 'PROJECT_NAME': project.name, 'CONFIRMATION_LINK': 'http://{}/profile/{}/invitation/{}/accepted/'. format( get_current_site(request), profile.id, project.id, ), 'DECLINE_LINK': 'http://{}/profile/{}/invitation/{}/declined/'. format( get_current_site(request), profile.id, project.id, ), } if contribution.first().status == 'pending': message = 'invitation re-sent' else: contribution.update(status='pending') message = 'invitation sent' EmailHelper.email( template_name='collaborator_invitation', title='Openmaker Explorer - Project nomination', vars=email_context, receiver_email=profile.user.email) serialized = ProjectContributorSerializer( contribution).data return success('ok', message, serialized) else: 'CREATING NEW INVITATION' # invitation not exist --> create and send e-mail contribution = ProjectContributor(project=project, contributor=profile) contribution.save() email_context = { 'FIRST_NAME': profile.user.first_name, 'LAST_NAME': profile.user.last_name, 'PROJECT_OWNER_FIRST_NAME': request.user.first_name, 'PROJECT_OWNER_LAST_NAME': request.user.last_name, 'PROJECT_NAME': project.name, 'CONFIRMATION_LINK': 'http://{}/profile/{}/invitation/{}/accepted/'.format( get_current_site(request), profile.id, project.id, ), 'DECLINE_LINK': 'http://{}/profile/{}/invitation/{}/declined/'.format( get_current_site(request), profile.id, project.id, ), } EmailHelper.email( template_name='collaborator_invitation', title='Openmaker Explorer - Project nomination', vars=email_context, receiver_email=profile.user.email) serialized = ProjectContributorSerializer( contribution).data return success('ok', 'invitation sent', serialized) except ObjectDoesNotExist as o: print('ERROR ObjectDoesNotExist') print(o) return error() except Exception as e: print('ERROR Exception') print(e) return error() else: bad_request('only post for now')
def post_om_invitation(request): if request.method != 'POST': return not_authorized() try: sender_first_name = request.POST['sender_first_name'].title() sender_last_name = request.POST['sender_last_name'].title() sender_email = request.POST['sender_email'].lower() receiver_first_name = request.POST['receiver_first_name'].title() receiver_last_name = request.POST['receiver_last_name'].title() receiver_email = request.POST['receiver_email'].lower() if sender_first_name.strip() == '' \ or sender_last_name.strip() == '' \ or sender_email.strip() == '' \ or receiver_first_name.strip() == '' \ or receiver_last_name.strip() == '' \ or receiver_email.strip() == '': return bad_request("Please fill al the fields") # Return to dsp error page if sender is already a DSP user? try: User.objects.get(email=sender_email) return HttpResponseRedirect('http://openmaker.eu/error_sender/') except User.DoesNotExist: pass Invitation.create(sender_email=sender_email, sender_first_name=sender_first_name, sender_last_name=sender_last_name, receiver_first_name=receiver_first_name, receiver_last_name=receiver_last_name, receiver_email=receiver_email, sender_verified=False) activation_link = 'http://{}/om_confirmation/{}/{}/{}/{}/{}/{}'.format( get_current_site(request), sender_first_name.encode('utf-8').encode('base64'), sender_last_name.encode('utf-8').encode('base64'), sender_email.encode('base64'), receiver_first_name.encode('utf-8').encode('base64'), receiver_last_name.encode('utf-8').encode('base64'), receiver_email.encode('base64')) EmailHelper.email(template_name='invitation_email_confirm', title='OpenMaker Nomination.. almost done!', vars={ 'SENDER_NAME': sender_first_name, 'CONFIRMATION_LINK': activation_link }, receiver_email=sender_email) except KeyError: return bad_request("Please fill al the fields") except EmailAlreadyUsed: return HttpResponseRedirect('http://openmaker.eu/error_receiver/') except UserAlreadyInvited: return HttpResponseRedirect('http://openmaker.eu/error_invitation/') except SelfInvitation: # @TODO : make appropriate page in openmaker return bad_request("Sender and receiver must be different") except Exception as e: #@TODO : make appropriate page in openmaker return bad_request("Some erro occour please try again") return HttpResponseRedirect('http://openmaker.eu/pending_invitation/')
def invite(request): if request.method == 'POST': try: receiver_email = request.POST['email'].lower() first_name = request.POST['first_name'].title() last_name = request.POST['last_name'].title() if first_name.strip() == '' or last_name.strip( ) == '' or receiver_email.strip() == '': messages.error(request, 'Please fill all the required fields!') return HttpResponseRedirect(reverse('dashboard:invite')) Invitation.create(user=request.user, sender_email=request.user.email, sender_first_name=request.user.first_name, sender_last_name=request.user.last_name, receiver_first_name=first_name, receiver_last_name=last_name, receiver_email=receiver_email) # Emails email_vars = { 'RECEIVER_FIRST_NAME': first_name, 'RECEIVER_LAST_NAME': last_name, 'SENDER_FIRST_NAME': request.user.first_name, 'SENDER_LAST_NAME': request.user.last_name, 'ONBOARDING_LINK': request.build_absolute_uri('/dashboard/') } # Send email to receiver only the first time if len(Invitation.get_by_email( receiver_email=receiver_email)) == 1: EmailHelper.email( template_name='invitation_email_receiver', title='You are invited to join the OpenMaker community!', vars=email_vars, receiver_email=receiver_email) # Send mail to sender EmailHelper.email(template_name='invitation_email_confirmed', title='OpenMaker Nomination done!', vars=email_vars, receiver_email=request.user.email) messages.success(request, 'Invitation sent!') except KeyError: messages.error(request, 'Please fill all the required fields!') return HttpResponseRedirect(reverse('dashboard:invite')) except EmailAlreadyUsed: messages.error(request, 'User is already a member!') return HttpResponseRedirect(reverse('dashboard:invite')) except UserAlreadyInvited: messages.error(request, 'You have already invited this Person!') return HttpResponseRedirect(reverse('dashboard:invite')) except SelfInvitation: messages.error(request, 'You cannot invite youself!') return HttpResponseRedirect(reverse('dashboard:invite')) except Exception as e: print(e.message) messages.error(request, 'Please try again!') return HttpResponseRedirect(reverse('dashboard:invite')) return render(request, 'dashboard/invite.html', {})
def profile(request, profile_id=None, action=None): try: if profile_id: user_profile = Profile.get_by_id(profile_id) else: user_profile = Profile.get_by_email(request.user.email) except Profile.DoesNotExist: return HttpResponseRedirect(reverse('dashboard:dashboard')) # Delete Profile if request.method == 'POST' and action == 'delete': try: first_name = request.user.first_name last_name = request.user.last_name Profile.delete_account(request.user.pk) messages.success(request, 'Account deleted') EmailHelper.email(template_name='account_deletion_confirmation', title='Openmaker Explorer account deletion', vars={ 'FIRST_NAME': first_name, 'LAST_NAME': last_name, }, receiver_email=request.user.email) logout(request) except Exception as e: print('error removing user') print(e) messages.warning( request, 'An error occour deleting your profile, please try again.') return HttpResponseRedirect(reverse('dashboard:profile')) return HttpResponseRedirect(reverse('dashboard:dashboard')) # Update Profile if request.method == 'POST' and request.POST.get('action') != 'delete': new_profile = {} new_user = {} try: new_user['first_name'] = request.POST['first_name'].title() new_user['last_name'] = request.POST['last_name'].title() new_profile['gender'] = request.POST['gender'] new_profile['birthdate'] = datetime.strptime( request.POST['birthdate'], '%Y/%m/%d') new_profile['birthdate'] = pytz.utc.localize( new_profile['birthdate']) new_profile['city'] = request.POST['city'] new_profile['occupation'] = request.POST['occupation'] new_profile['statement'] = request.POST.get('statement', None) # @TODO : check duplicate role assignment new_profile['role'] = request.POST.get('role', None) new_profile['role'] = request.POST.get('role', '') new_profile['organization'] = request.POST.get( 'organization', None) new_profile['sector'] = request.POST.get('sector', None) new_profile['size'] = request.POST.get('size', None) new_profile['technical_expertise'] = request.POST.get( 'technical_expertise', None) new_profile['technical_expertise_other'] = request.POST.get( 'technical_expertise_other', None) new_profile['role_other'] = request.POST.get('role_other', None) new_profile['sector_other'] = request.POST.get( 'sector_other', None) # Multiple choice fields new_profile['types_of_innovation'] = request.POST.get( 'types_of_innovation', None) new_profile['socialLinks'] = request.POST.get('socialLinks', None) # Many to many fields source_of_inspiration = request.POST.get('source_of_inspiration', None) tags = request.POST['tags'] if tags == '' or tags == None or tags == 'undefined': raise KeyError except ValueError: messages.error( request, 'Incorrect birthdate format: it must be YYYY/MM/DD') return HttpResponseRedirect( reverse('dashboard:profile', kwargs={ 'profile_id': user_profile.id, 'action': action })) except KeyError: print(KeyError) messages.error(request, 'Please fill the required fields!') return HttpResponseRedirect( reverse('dashboard:profile', kwargs={ 'profile_id': user_profile.id, 'action': action })) # check birthdate if new_profile['birthdate'] > pytz.utc.localize( datetime(dt.datetime.now().year - 13, * new_profile['birthdate'].timetuple()[1:-2])): messages.error(request, 'You must be older than thirteen') return HttpResponseRedirect( reverse('dashboard:profile', kwargs={ 'profile_id': user_profile.id, 'action': action })) # Update image try: imagefile = request.FILES['profile_img'] filename, file_extension = os.path.splitext(imagefile.name) allowed_extensions = ['.jpg', '.jpeg', '.png'] if not (file_extension in allowed_extensions): raise ValueError('nonvalid') # limit to 1MB if imagefile.size > 1048576: raise ValueError('sizelimit') imagefile.name = str(datetime.now().microsecond) + '_' + str( imagefile._size) + file_extension except ValueError as exc: if str(exc) == 'sizelimit': messages.error(request, 'Image size must be less than 1MB') if str(exc) == 'nonvalid': messages.error(request, 'Profile Image is not an image file') return HttpResponseRedirect(reverse('dashboard:profile')) except KeyError as exc: imagefile = request.user.profile.picture except Exception as exc: messages.error(request, 'Error during image upload, please try again') logging.error( '[VALIDATION_ERROR] Error during image upload: {USER} , EXCEPTION {EXC}' .format(USER=request.user.email, EXC=exc)) return HttpResponseRedirect(reverse('dashboard:profile')) new_profile['picture'] = imagefile user = User.objects.filter(email=request.user.email).first() # Update user fields user.__dict__.update(new_user) user.save() # Update profile fields user.profile.__dict__.update(new_profile) user.profile.save() # Update place, location, country user.profile.set_place(request.POST.get('place', None)) # Update tags user.profile.tags.clear() for tagName in [x.lower().capitalize() for x in tags.split(",")]: user.profile.tags.add( Tag.objects.filter(name=tagName).first() or Tag.create(name=tagName)) # Update sourceofinnovation user.profile.source_of_inspiration.through.objects.all().delete() if source_of_inspiration: for tagName in [ x.lower().capitalize() for x in source_of_inspiration.split(",") ]: user.profile.source_of_inspiration.add( SourceOfInspiration.objects.filter(name=tagName).first() or SourceOfInspiration.create(name=tagName)) # update on crm try: party = Party(user) party.create_or_update() except NotFound as e: messages.error( request, 'There was some connection problem, please try again') return HttpResponseRedirect(reverse('dashboard:profile')) except Exception as e: pass messages.success(request, 'Profile updated!') return HttpResponseRedirect(reverse('dashboard:profile')) user_profile.jsonTags = json.dumps( [x.name for x in user_profile.tags.all()]) user_profile.jsonSourceOfInspiration = json.dumps( [x.name for x in user_profile.source_of_inspiration.all()]) user_profile.types_of_innovation = user_profile.types_of_innovation and json.dumps( user_profile.types_of_innovation.split(',')) context = { 'profile': user_profile, 'profile_action': action, 'is_my_profile': request.user.profile.id == user_profile.id, 'tags': json.dumps([x.name for x in Tag.objects.all()]), 'source_of_inspiration': json.dumps([x.name for x in SourceOfInspiration.objects.all()]) } return render(request, 'dashboard/profile.html', context)