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 _send_email(subject, message, receiver_name, receiver_email): """ Send Email method :param subject: Subject of the email :param message: Email Content :param receiver_name: Name of the receiver :param receiver_email: Email of the receiver :return: Nothing """ from utils.mailer import EmailHelper EmailHelper.send_email(message=message, subject=subject, receiver_name=receiver_name, receiver_email=receiver_email)
def recover_pwd(request): """ Method used to ask for a reset password :param request: :return: """ if request.user.is_authenticated: return HttpResponseRedirect(reverse('dashboard:dashboard')) if request.POST: username = request.POST['email'] try: profile = Profile.get_by_email(username) # Check if user is active if not profile.user.is_active: messages.error( request, 'Your user is not yet active, ' 'please complete the activation process before requesting a new password' ) return HttpResponseRedirect(reverse('dashboard:login')) profile.reset_token = Profile.get_new_reset_token() profile.ask_reset_at = dt.datetime.now() profile.save() # send e-mail email_body = authentication_reset_password.format( FIRST_NAME=profile.user.first_name.encode('utf-8'), LAST_NAME=profile.user.last_name.encode('utf-8'), BASE_URL=get_current_site(request), TOKEN=profile.reset_token) email_content = "{0}{1}{2}".format( invitation_base_template_header, email_body, invitation_base_template_footer) EmailHelper.send_email(message=email_content, subject='DSPExplorer - Reset Password', receiver_email=profile.user.email) messages.success( request, 'You will receive an email with a link to reset your password!' ) return HttpResponseRedirect(reverse('dashboard:login')) except Profile.DoesNotExist: messages.error(request, 'User not Found.') return HttpResponseRedirect(reverse('dashboard:login')) return render(request, 'dashboard/recover_pwd.html', {})
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 invite(request): if request.method == 'POST': try: address = request.POST['email'].lower() first_name = request.POST['first_name'].title() last_name = request.POST['last_name'].title() except KeyError: messages.error(request, 'Please all the fields are required!') return HttpResponseRedirect(reverse('dashboard:invite')) try: User.objects.get(email=address) messages.error(request, 'User is already a DSP member!') return HttpResponseRedirect(reverse('dashboard:invite')) except User.DoesNotExist: pass try: Invitation.objects.get(receiver_email=HashHelper.md5_hash(address)) messages.error(request, 'User is been already invited!') return HttpResponseRedirect(reverse('dashboard:invite')) except Invitation.DoesNotExist: pass # email not present, filling invitation model try: 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=address, ) subject = 'You are invited to join the OpenMaker community!' content = "{0}{1}{2}".format( invitation_base_template_header, invitation_email_receiver.format( RECEIVER_FIRST_NAME=first_name.encode('utf-8'), RECEIVER_LAST_NAME=last_name.encode('utf-8'), SENDER_FIRST_NAME=request.user.first_name.encode('utf-8'), SENDER_LAST_NAME=request.user.last_name.encode('utf-8'), ONBOARDING_LINK=request.build_absolute_uri( '/onboarding/')), invitation_base_template_footer) EmailHelper.send_email(message=content, subject=subject, receiver_email=address, receiver_name='') messages.success(request, 'Invitation sent!') except EmailAlreadyUsed: messages.error(request, 'User is already a member!') except UserAlreadyInvited: messages.error(request, 'User has already received an invitation!') except Exception as e: print e.message messages.error(request, 'Please try again!') return render(request, 'dashboard/invite.html', {})
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)
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 == '' or sender_last_name == '' or sender_email == '' or receiver_first_name == '' \ or receiver_last_name == '' or receiver_email == '': return bad_request("Please fill al the fields") if sender_email == receiver_email: return bad_request("Sender and receiver must be different") except KeyError: return bad_request("Please fill al the fields") # sender already a DSP user? try: User.objects.get(email=sender_email) return HttpResponseRedirect('http://openmaker.eu/error_sender/') except User.DoesNotExist: pass # receiver already a DSP user? try: User.objects.get(email=receiver_email) return HttpResponseRedirect('http://openmaker.eu/error_receiver/') except User.DoesNotExist: pass # receiver already invited? try: Invitation.objects.get( receiver_email=HashHelper.md5_hash(receiver_email)) return HttpResponseRedirect('http://openmaker.eu/error_invitation/') except Invitation.DoesNotExist: pass Invitation.create(user=None, 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')) subject = 'OpenMaker Nomination.. almost done!' content = "{}{}{}".format( invitation_base_template_header, invitation_email_confirm.format(SENDER_NAME=sender_first_name, CONFIRMATION_LINK=activation_link), invitation_base_template_footer) EmailHelper.send_email(message=content, subject=subject, receiver_email=sender_email, receiver_name='') return HttpResponseRedirect('http://openmaker.eu/pending_invitation/')
def onboarding(request): if request.user.is_authenticated: return HttpResponseRedirect(reverse('dashboard:dashboard')) if request.method == 'POST': try: email = request.POST['email'].lower() pasw = request.POST['password'] pasw_confirm = request.POST['password_confirm'] first_name = request.POST['first_name'].title() last_name = request.POST['last_name'].title() gender = request.POST['gender'] birthdate_dt = datetime.strptime(request.POST['birthdate'], '%Y/%m/%d') birthdate_dt = pytz.utc.localize(birthdate_dt) city = request.POST['city'] occupation = request.POST['occupation'] tags = request.POST['tags'] place = request.POST.get( 'place', None) if request.POST.get('place', None) != '{}' else None if tags == '' or tags == None or tags == 'undefined': raise KeyError twitter_username = request.POST.get('twitter', '') except ValueError: messages.error( request, 'Incorrect birthdate format: it must be YYYY/MM/DD') return HttpResponseRedirect(reverse('dashboard:onboarding')) except KeyError: messages.error(request, 'Please fill the required fields!') return HttpResponseRedirect(reverse('dashboard:onboarding')) # check password if pasw != pasw_confirm: messages.error(request, 'Password and confirm password must be the same') return HttpResponseRedirect(reverse('dashboard:onboarding')) # check birthdate if birthdate_dt > pytz.utc.localize( datetime(dt.datetime.now().year - 13, *birthdate_dt.timetuple()[1:-2])): messages.error(request, 'You must be older than thirteen') return HttpResponseRedirect(reverse('dashboard:onboarding')) # Check image and get url imagefile = 'images/profile/default_user_icon.png' # Check if user exist try: User.objects.get(email=email) messages.error(request, 'User is already a DSP member!') return HttpResponseRedirect(reverse('dashboard:onboarding')) except User.DoesNotExist: pass # profile create try: profile = Profile.create(email, first_name, last_name, imagefile, pasw, gender, birthdate_dt, city, occupation, twitter_username, place) except Exception as exc: logging.error( '[PROFILE_CREATION_ERROR] Error during local profile creation for user email: {USER} , EXCEPTION {EXC}' .format(USER=email, EXC=exc)) messages.error(request, 'Error creating user') return HttpResponseRedirect(reverse('dashboard:onboarding')) # Add tags to profile # @TODO : handle tag Creation exception for tag in map( lambda x: re.sub( r'\W', '', x.lower().capitalize(), flags=re.UNICODE), tags.split(",")): tagInstance = Tag.objects.filter(name=tag).first() or Tag.create( name=tag) profile.tags.add(tagInstance) profile.save() # Add twitter username to social links social_links = json.loads(profile.socialLinks) social_links[0]['link'] = twitter_username profile.socialLinks = json.dumps(social_links) profile.save() # send e-mail confirmation_link = request.build_absolute_uri( '/onboarding/confirmation/{TOKEN}'.format( TOKEN=profile.reset_token)) subject = 'Onboarding... almost done!' content = "{0}{1}{2}".format( invitation_base_template_header, onboarding_email_template.format( FIRST_NAME=first_name.encode('utf-8'), LAST_NAME=last_name.encode('utf-8'), CONFIRMATION_LINK=confirmation_link, ), invitation_base_template_footer) EmailHelper.send_email(message=content, subject=subject, receiver_email=email) messages.success(request, 'Confirmation mail sent!') return HttpResponseRedirect(reverse('dashboard:dashboard')) return render( request, 'dashboard/onboarding.html', {'tags': json.dumps(map(lambda x: x.name, Tag.objects.all()))})
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: User.objects.get(email=receiver_email) messages.error(request, 'User is already a DSP member!') return HttpResponseRedirect(reverse('dashboard:dashboard')) except User.DoesNotExist: pass try: invitation = Invitation.objects.get( sender_email=HashHelper.md5_hash(sender_email), receiver_email=HashHelper.md5_hash(receiver_email)) if invitation.sender_verified: messages.error(request, 'Invitation already sent!') else: # invitation flow start invitation.sender_verified = True invitation.save() # sending invitation mail subject = 'OpenMaker Nomination done!' content = "{0}{1}{2}".format( invitation_base_template_header, invitation_email_confirmed.format( ONBOARDING_LINK=request.build_absolute_uri( '/onboarding/')), invitation_base_template_footer) EmailHelper.send_email(message=content, subject=subject, receiver_email=sender_email, receiver_name='') subject = 'You are invited to join the OpenMaker community!' content = "{0}{1}{2}".format( invitation_base_template_header, invitation_email_receiver.format( 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/')), invitation_base_template_footer) EmailHelper.send_email(message=content, subject=subject, receiver_email=receiver_email, receiver_name='') messages.success(request, 'Invitation complete!') except Invitation.DoesNotExist: messages.error(request, 'Invitation does not exist') return HttpResponseRedirect('http://openmaker.eu/confirmed/')