def create_organization(request): """ Lets a user create an organization """ if request.method == 'POST': form = OrganizationCreateForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] website_url = form.cleaned_data['website'] contact_email = form.cleaned_data['contact_email'] organization = _create_organization(name, website_url) organization.enabled = False organization.contact_email = contact_email organization.save() ou = OrganizationUser(organization=organization, level=ROLE_CHOICES[0][0], user=request.user) ou.save() try: sec = SendgridEmailClient() sec.send_mail(OrganizationCreateNotification(organization)) except Exception as e: rbe_logger.exception(e) return render(request, 'organizations/create.html', {'form': None, 'status': 'created'}) # if a GET (or any other method) we'll create a blank form else: form = OrganizationCreateForm() return render(request, 'organizations/create.html', {'form': form})
def associated_service_info(request): if not request.method == 'POST': return JsonResponse({'success': False, 'reason': 'Not a post request'}) assoc_sid = request.POST.get('assoc_sid') if not assoc_sid: return JsonResponse({'success': False, 'reason': 'Requires valid assoc_sid'}) try: assoc_service = AssociatedService.objects.get(id=assoc_sid) if not assoc_service.enabled: return JsonResponse({'success': False, 'reason': 'Requires valid assoc_sid'}) except AssociatedService.DoesNotExist: return JsonResponse({'success': False, 'reason': 'AssociatedService does not exists'}) try: response = requests.get("{}/meta".format(assoc_service.client.website_url), verify=False) if response.status_code != 200: rbe_logger.error("Could not retrieve status from service content={}".format(response.content)) return JsonResponse({'success': False, 'reason': 'Could not retrieve service information'}) else: parameters = response.json() users = parameters.get('users', None) assert re.match(r'[0-9]+', str(users)) return JsonResponse({'success': True, 'users': users}) except Exception as e: rbe_logger.exception(e) return JsonResponse({'success': False, 'reason': 'Could not retrieve service information'})
def invite(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = InviteForm(request.POST) # check whether it's valid: if form.is_valid(): #TODO - restrict double invites across the whole network registration_key = form.save(commit=False) registration_key.user = request.user registration_key.key = str(uuid.uuid4()).replace('-', '') registration_key.save() try: ie = InvitationEmail() ie.send(recipient_list=[registration_key.email], username=request.user.username, key=registration_key.key) return render(request, 'invite.html', {}) except Exception as e: rbe_logger.error("Could not send invite email to {}".format( registration_key.email)) rbe_logger.exception(e) form.add_error( None, 'Could not send invite email. Technical Error.') else: form = InviteForm() return render(request, 'invite.html', {'form': form})
def register(request, registration_key): if request.method == 'POST': # create a form instance and populate it with data from the request: form = RegistrationForm(request.POST) # check whether it's valid: if form.is_valid(): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = create_user(username, email, password) try: sg = SendgridEmailClient() wcm = WelcomeMail(user, user.emailverification) sg.send_mail(wcm) rbe_logger.info("Send welcome message to {}".format(email)) except Exception as e: rbe_logger.exception(e) djauth.login(request, user) return HttpResponseRedirect(reverse('welcome')) # if a GET (or any other method) we'll create a blank form else: form = RegistrationForm(initial={'registration_key': registration_key}) return render(request, 'auth/register.html', {'form': form})
def reset(request): if request.POST: email = request.POST.get('email') form = PasswordResetRequest(request.POST) if not form.is_valid(): return render(request, 'auth/reset_password.html', {'form': form}) u = User.objects.filter(email=email) # Check if a user with this email exists and if so send an email # If not show also the suggest page so emails cannot be guessed if u.exists(): prk = PasswordResetKey.objects.filter(valid_until__lte=datetime.datetime.now()) prk.delete() reset_key = str(uuid.uuid4()).replace('-', '') valid_until = datetime.datetime.now() + datetime.timedelta(hours=2) pwrk = PasswordResetKey(user=u.first(), key=reset_key, valid_until=valid_until) pwrk.save() try: sg = SendgridEmailClient() prm = PasswordResetMail(u.first(), reset_key, valid_until) sg.send_mail(prm) except Exception as e: rbe_logger.error("Could not send the password forgot email to {}".format(email)) rbe_logger.exception(e) return render(request, 'auth/reset_password_email_send.html', {'email': email}) else: return render(request, 'auth/reset_password.html', {'form': PasswordResetRequest()})
def discover(request): try: rc = RequestContext(request) rc['all_objects'] = SlugPhrase.objects.all().annotate(object_count=Count('userskill')).order_by('-object_count')[:50] return render_to_response('discover.html', rc) except Exception as e: rbe_logger.exception(e) return HttpResponseRedirect(reverse('error_page'))
def discover(request): try: rc = RequestContext(request) rc['all_objects'] = sorted( SlugPhrase.objects.all().annotate(object_count=Count('userslugs')), key=lambda x: -x.object_count) return render_to_response('discover.html', rc) except Exception as e: rbe_logger.exception(e) return HttpResponseRedirect(reverse('error_page'))
def delete_skill(request): skill_id = request.POST.get('skill_id') try: sp = UserSkill.objects.get(slug__id=skill_id, user=request.user) sp.delete() return JsonResponse({'success': True}) except UserSkill.DoesNotExist: return JsonResponse({'success': True}) except Exception as e: rbe_logger.exception(e) return JsonResponse({'success': False, 'reason': "Some error occurred!"})
def down_skill_level(request): skill_id = request.POST.get('skill_id') try: sp = UserSkill.objects.get(slug__id=skill_id, user=request.user) sp.level = max(1, sp.level - 1) sp.latest_change = datetime.datetime.now() sp.save() return JsonResponse({'success': True, 'new_level': sp.level}) except UserSkill.DoesNotExist: return JsonResponse({'success': False, 'reason': "Could not find user skill!"}) except Exception as e: rbe_logger.exception(e) return JsonResponse({'success': False, 'reason': "Some error occurred!"})
def register(request, registration_key): if settings.CLOSED_NETWORK: rc = RequestContext(request) return render_to_response('auth/register_info.html', rc) if request.method == 'POST': # create a form instance and populate it with data from the request: form = RegistrationForm(request.POST) # check whether it's valid: if form.is_valid(): username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') registration_key = form.cleaned_data.get('registration_key') u = User.objects.create_user(username=username, email=email, password=password) user = djauth.authenticate(username=username, password=password) if settings.CLOSED_NETWORK: rk = InvitationKey.objects.get(key=registration_key) p = UserProfile(user=u, invited_by=rk.user) p.save() rk.delete() else: p = UserProfile(user=u, invited_by=None) p.save() try: wcm = WelcomeMail() wcm.send(username=user.username, recipient_list=[email]) rbe_logger.info("Send welcome message to {}".format(email)) except Exception as e: rbe_logger.exception(e) djauth.login(request, user) return HttpResponseRedirect( reverse('profile', kwargs={'user_id': request.user.id})) # if a GET (or any other method) we'll create a blank form else: form = RegistrationForm(initial={'registration_key': registration_key}) return render(request, 'auth/register.html', { 'form': form, 'closed_network': settings.CLOSED_NETWORK })
def language_remove(request): """ Removes a language that the suer has registered """ lang = request.POST.get('lang') if not lang or lang not in dict(LANGUAGES): return JsonResponse({'success': False, 'reason': "Language code not known!"}) try: ls = LanguageSpoken.objects.get(user=request.user, language=lang) ls.delete() return JsonResponse({'success': True}) except LanguageSpoken.DoesNotExist: # Language doesn't exists for some reason so we assume we deleted it return JsonResponse({'success': True}) except Exception as e: rbe_logger.exception(e) return JsonResponse({'success': False, 'reason': "Could not remove language"})
def reset(request): if request.POST: email = request.POST.get('email') form = PasswordResetRequest(request.POST) if not form.is_valid(): return render(request, 'auth/reset_password.html', {'form': form}) u = User.objects.filter(email=email) # Check if a user with this email exists and if so send an email # If not show also the suggest page so emails cannot be guessed if u.exists(): prk = PasswordResetKey.objects.filter( valid_until__lte=datetime.datetime.now()) prk.delete() reset_key = str(uuid.uuid4()).replace('-', '') valid_until = datetime.datetime.now() + datetime.timedelta(hours=2) pwrk = PasswordResetKey(user=u.first(), key=reset_key, valid_until=valid_until) pwrk.save() try: prm = PasswordResetMail() prm.send(recipient_list=[email], username=u.first().username, reset_key=reset_key, valid_until=valid_until.isoformat()) except Exception as e: rbe_logger.error( "Could not send the password forgot email to {}".format( email)) rbe_logger.exception(e) return render_to_response('auth/reset_password_email_send.html', {'email': email}) else: return render(request, 'auth/reset_password.html', {'form': PasswordResetRequest()})
def send(request): recipient_id = request.POST.get('recipient_id') message_text = request.POST.get('message_text') error_message = '' try: if not message_text: error_message = 'Empty message cannot be sent!' elif len(message_text) > 1200: error_message = 'A message cannot be longer than 1200 characters!' else: recipient = User.objects.get(id=recipient_id) Message.create_message(request.user, recipient, message_text) return redirect(reverse('conversation', kwargs={'user_id': recipient.id})) except User.DoesNotExist as e: rbe_logger.warning("Had problems") error_message = "User to write to doesn't exists" except Exception as e: error_message = "Unknown error occurred - please try again later" rbe_logger.exception(e) return conversation(request, recipient_id, error_message)
def language_remove(request): """ Removes a language that the suer has registered """ lang = request.POST.get('lang') if not lang or lang not in dict(LANGUAGES): return JsonResponse({ 'success': False, 'reason': "Language code not known!" }) try: ls = LanguageSpoken.objects.get(user=request.user, language=lang) ls.delete() return JsonResponse({'success': True}) except LanguageSpoken.DoesNotExist: # Language doesn't exists for some reason so we assume we deleted it return JsonResponse({'success': True}) except Exception as e: rbe_logger.exception(e) return JsonResponse({ 'success': False, 'reason': "Could not remove language" })