Beispiel #1
0
def invite(site_id):
    user = users.get_current_user()
    site = Site.get_admin_or_404(site_id)
    form = InviteForm(request.form)
    if form.validate():
        invite_hash = sha1()
        invite_hash.update(str(site.key()))
        invite_hash.update(os.urandom(8))
        invite_hash.update(form.email.data)
        invite_hash = b32encode(invite_hash.digest()).lower()
        invite = Invitation(hash=invite_hash,
                            email=form.email.data,
                            site=site,
                            admin=form.admin.data,
                            inviter=user)
        invite.put()
        mail.send_mail(
            sender=settings.invite_sender_email,
            to=invite.email,
            subject='%s invited you to join them on %s' %
            (user.email(), settings.appname),
            body=render_template('invite_email.txt', invite=invite),
            html=render_template('invite_email.html', invite=invite),
        )
        if request.is_xhr:
            return 'OK'
        flash('Invitation Sent!', 'success')
    else:
        errors = sum(form.errors.values(), [])
        if request.is_xhr:
            return ', '.join(errors)
        for error in errors:
            flash(error, 'error')
        flash(form.email.data, 'error')
    return redirect(url_for('edit_siteusers', site_id=site_id))
Beispiel #2
0
def invite():
    """Send invitations for this particular project"""

    form = InviteForm()

    if request.method == "POST":
        if form.validate():
            # send the email

            message_body = render_template("invitation_mail.%s" %
                                           get_locale().language)

            message_title = _(
                "You have been invited to share your "
                "expenses for %(project)s",
                project=g.project.name)
            msg = Message(message_title,
                          body=message_body,
                          recipients=[
                              email.strip()
                              for email in form.emails.data.split(",")
                          ])
            mail.send(msg)
            flash(_("Your invitations have been sent"))
            return redirect(url_for(".list_bills"))

    return render_template("send_invites.html", form=form)
Beispiel #3
0
def invite(request):
    if request.POST:
        form = InviteForm(request.POST)
        if form.is_valid():
            site = Site.objects.get(pk=settings.SITE_ID)
            key = ActivateKey.objects.next()
            key.email = form.cleaned_data['email']
            key.save()
            activate_url = '%s%s' % (
                site.domain,
                reverse('regist', kwargs=dict(activate_key=key.activate_key)))
            t = loader.get_template('event/mail/invite.mail')
            c = RequestContext(request, {
                'domain': site.name,
                'activate_url': activate_url
            })
            mail = EmailMessage(_(u'Invitation from %s') % site.name,
                                t.render(c),
                                to=[form.cleaned_data['email']])
            mail.send()
            #request.user.message_set.create(
            #    message=_('Sent invitation message to %(address)s') % {'address': form.cleaned_data['email']})
            #return HttpResponseRedirect(URL_HOME)
            return HttpResponseRedirect(reverse('invite_email_sent'))
    else:
        form = InviteForm()
    return render_to_response('event/invite.html',
                              context_instance=RequestContext(
                                  request, {'form': form}))
Beispiel #4
0
def api_invite(request, output_format="json"):
    """Create a user, but make it disabled.

    Formats: json

    HTTP Method: GET

    Requires authentication: false

    Parameters:

    * email: E-mail address for the new user. 
    """

    status = 201  # HTTP return status.  We'll be optimistic.
    data = {}  # response data

    try:
        if request.method == "POST":
            form = InviteForm(request.POST)
            if form.is_valid():
                email = form.cleaned_data["email"]

                try:
                    user = User.objects.get(email=email)
                    raise UserEmailExists("It looks like you've already requested an invitation.")
                except User.DoesNotExist:
                    username = email  # Username defaults to e-mail address
                    if len(email) > 30:
                        print email
                        # Django usernames can't be longer than 30 characters
                        # Just take the first 30 characters of the part of
                        # the email address before the '@'
                        email_parts = email.partition("@")
                        username = email_parts[0][:30]

                    user = User.objects.create_user(username=username, email=email)
                    user.is_active = False
                    user.set_unusable_password()
                    user.save()
                    user_profile = UserProfile(user=user)
                    user_profile.save()

            else:
                print form.errors
                status = 400  # Caught in a bad request
                data["error"] = "Invalid e-mail address."

        else:
            raise MethodUnsupported("%s is not supported at this time." % (request.method))

    except MethodUnsupported, e:
        status = 405  # Method not allowed
        data["error"] = "%s" % e
Beispiel #5
0
    def index(self):
        form = InviteForm()
        if request.method == 'GET':
            return self.render('admin/index.html', form=form)
        else:
            if form.validate():
                from app.extensions import mail
                if mail.send_invite(form.email.data):
                    return jsonify({'status': 'ok'})

            return jsonify(form.errors)
Beispiel #6
0
    def index(self):
        form = InviteForm()
        if request.method == 'GET':
            return self.render('admin/index.html', form=form)
        else:
            if form.validate():
                from app.extensions import mail
                if mail.send_invite(form.email.data):
                    return jsonify({'status': 'ok'})

            return jsonify(form.errors)
Beispiel #7
0
def invite():
    url = __check_login(url = get_redirect_target())
    if url: return redirect(url)
    inviteform = InviteForm()
    if inviteform.validate():
        user = get_user(session['email'])
        troika = get_troika(inviteform.troika_id.data)
        if troika is None:
            flash(_(u'Invalid Troika Id'), 'error')
        elif troika.get_phase() == 'complete':
            flash(_(u'Can not invite to a completed Troika'), 'error')
        else:
            msg = Message(_(u"Come join the Troika \"%(title)s\"!", title=troika.title),
                      sender = ("Troika Webmaster", "*****@*****.**"),
                      recipients=[inviteform.email.data])
        
            msg.body = _("%(user)s thought you should join the Troika \"%(title)s\":", user = __get_display_name(user), title=troika.title)
            msg.body += "\n\n" + url_for('troika', troika_id=troika.id, _external=True)
            msg.body += "\n\n"
            
            role_string = None
            if inviteform.role.data == '0':
                if troika.lead is None:
                    role_string = _("the lead")
                else:
                    flash(_(u'Troika already has a lead'), 'error')
            elif inviteform.role.data == '1':
                if troika.first_learner is None:
                    role_string = _("the first learner")
                else:
                    flash(_(u'Troika already has a first learner'), 'error')
            elif inviteform.role.data == '2':
                if troika.second_learner is None:
                    role_string = _("the second learner")
                else:
                    flash(_(u'Troika already has a second learner'), 'error')
            elif inviteform.role.data == '3':
                role_string = _("a participant")
            else:
                flash(_(u'Invalid role: ') + 'inviteform.role', 'error')
            if role_string is not None:  
                msg.body += _("as %(role)s.", role=role_string)
                msg.body += "\n\n" 
                msg.body += _("What do you say?") + "\n\n"
                msg.body += __get_troika_message_signature()
                
                mail.send(msg)
                flash(_(u'Invite sent to %(email)s', email = inviteform.email.data))
    else:
        flash(_(u"Invalid invite form") + ': ' + ', '.join((key + ': ' + value[0]) for key, value in inviteform.errors.items()), 'error')
    return redirect(get_redirect_target())
Beispiel #8
0
def registration():
    if 'username' in session:
        pass
        session.pop('username', 0)
        session.pop('user_id', 0)

    check_form = InviteForm()
    if check_form.validate_on_submit():
        if check_form.invite.data in Invite.query.all():
            reg_form = RegistrationForm()
            if reg_form.validate_on_submit():
                # Check for the existence of the user in db
                user = Admin.query.filter_by(login=reg_form.login.data).first()
                if not user:
                    # Create new user
                    new_user = Admin(login=reg_form.login.data,
                                     name=reg_form.name.data,
                                     surname=reg_form.surname.data,
                                     email=reg_form.email.data,
                                     password=reg_form.password.data)
                    db.session.add(new_user)
                    db.session.commit()
                    session['username'] = new_user.login
                    session['user_id'] = new_user.id
                    return redirect('/index')
                else:
                    return render_template(
                        'error_page.html',
                        title='Ошибка',
                        error='Такой пользователь уже существует',
                        link_dict=link_dict,
                        name='')
            return render_template('registration.html',
                                   title='Регистрация',
                                   form=reg_form,
                                   link_dict=link_dict,
                                   name='')
        else:
            return render_template('error_page.html',
                                   title='Ошибка',
                                   error='Неверный код',
                                   link_dict=link_dict,
                                   name='')
    return render_template('invite_check.html',
                           title='Проверка кода-приглашения',
                           form=check_form,
                           link_dict=link_dict,
                           name='')
Beispiel #9
0
def invite(key):
    """
    Invites a user to the organization.  If the user does not already exist, will create
    a temporary user that can be confirmed by the invitee through an activation link
    :param key:
    :return:
    """
    org = utils.organization.get_organization(key)
    form = InviteForm(request.form)
    return_dict = {}

    return_dict = utils.utils.validate_invite_user(request.form)
    if 'status' in return_dict:
        return Response(response=json.dumps(return_dict),
                        status=200,
                        mimetype="application/json")


    return_dict = utils.organization.invite_member(org,
                                                   form.email.data,
                                                   form.first_name.data,
                                                   form.last_name.data)

    response = Response(response=json.dumps(return_dict),
                        status=200,
                        mimetype="application/json")

    return response
def index(request):
    vars = {}
    if request.method == "POST":
        invite_form = InviteForm(request.POST, request.FILES)
        if invite_form.is_valid():
            invite_form.save(request.user)
            context = {"notice": "Thanks for inviting more people to join!"}
            return HttpResponseRedirect(addToQueryString(reverse("tasks"), context))
        else:
            vars["invite_form"] = invite_form
    else:
        vars["invite_form"] = InviteForm()

    vars["siteurl"] = quote("http://%s" % Site.objects.get_current().domain)
    request.user.seen_invite = True
    request.user.save()
    return render_with_context(request, "invite/invite_page.html", vars)
Beispiel #11
0
 def get(self):
     team_id = current_app.config['SLACK_TEAM_ID']
     team_name = get_team_name()
     form = InviteForm(request.form)
     return render_template('index.html',
                            form=form,
                            team_name=team_name,
                            team_id=team_id)
Beispiel #12
0
def contest_invite(contest_id):
    contest = Contest.query.get(contest_id)
    if g.user.user_id != contest.author_id:
        flash('You do not have proper authorization to do this!', 'danger')
        return redirect('/contest/' + str(contest_id))

    form = InviteForm(obj=contest)
    friendships = Friendship.query.filter_by(user_id=g.user.user_id).all()
    users = [
        User.query.get(friendship.friend_id) for friendship in friendships
    ]
    form.users.choices = [(user.user_id, user.username) for user in users]

    if request.method == 'POST' and form.validate():
        form = InviteForm(request.form)
        if form.users.data == None: form.users.data = []
        else:
            form.users.data = [
                User.query.get(user_id) for user_id in form.users.data
            ]

        form.populate_obj(contest)
        contest.save()
        return redirect(
            url_for('contest_overview', contest_id=contest.contest_id))

    return render_template('invite_form.html', form=form, edit=True)
Beispiel #13
0
def index(request):
    vars = {}

    if request.method == "POST":
        invite_form = InviteForm(request.POST, request.FILES)
        if invite_form.is_valid():
            invite_form.save(request.user)

            return HttpResponseRedirect(addToQueryString(reverse("inviteindex"),
                {'notice': strings.INVITE_NOTICE_SUCCESS}))
        else:
            vars['invite_form'] = invite_form
    else:
        vars['invite_form'] = InviteForm()
        
    vars['siteurl'] = quote("http://%s" % Site.objects.get_current().domain)
    
    return render_with_context(request, "invite/invite_page.html", vars)
Beispiel #14
0
def invite(request, next=None):
    """Handles invite form submission"""
    invite_form = InviteForm(instance=Invitation(user=request.user), data=request.POST)
    if invite_form.is_valid():
        invites = invite_form.save()
        emails = ", ".join([invite.email for invite in invites])
        messages.success(request, 'Invitation sent to %s' % emails)
    else:
        messages.error(request, 'Form values where invalid, please try fill out the form again.')

    if request.is_ajax() and request.method == 'POST':
        message_html = loader.render_to_string('_messages.html', {}, RequestContext(request))
        return HttpResponse(message_html)

    next = request.POST.get("next", next)
    if next:
        return redirect(next)
    return redirect("index")
Beispiel #15
0
def edit_siteusers(site_id):
    site = Site.get_admin_or_404(site_id)
    invite_form = InviteForm()
    if request.is_xhr:
        return render_template('siteusers_editor.html',
                               site=site,
                               invite_form=invite_form)
    return render_template('edit_siteusers.html',
                           site=site,
                           invite_form=invite_form)
def invite():
	form = InviteForm()
	if form.validate_on_submit():
		invite_slack_result = invite_to_slack(form.email.data)
		print(invite_slack_result)
		if invite_slack_result["ok"]:
			flash('Invite send at {}'.format(form.email.data, 'success'))
			return(redirect(url_for('welcome')))
		elif invite_slack_result["ok"] is False and invite_slack_result["error"] == "already_in_team":
			flash('There is already a user in the team with the email {}'.format(form.email.data, 'error'))
			return(redirect(url_for('already_in_team_error')))
		elif invite_slack_result["ok"] is False and invite_slack_result["error"] == "already_invited":
			flash('The invitation has already been sent at {}'.format(form.email.data, 'error'))
			return(redirect(url_for('already_invited_error')))
		elif invite_slack_result["ok"] is False and invite_slack_result["error"] == "already_invited":
			flash('The email {} is invalid'.format(form.email.data, 'error'))
			flash('Note that slack does not recognise some email addresses'.format())
			return(redirect(url_for('invalid_email_error')))

	return render_template('invite.html', title='Invite', form=form)
Beispiel #17
0
def invite():
    """Send invitations for this particular project"""

    form = InviteForm()

    if request.method == "POST":
        if form.validate():
            # send the email

            message_body = render_template("invitation_mail.%s" % get_locale().language)

            message_title = _("You have been invited to share your " "expenses for %(project)s", project=g.project.name)
            msg = Message(
                message_title, body=message_body, recipients=[email.strip() for email in form.emails.data.split(",")]
            )
            mail.send(msg)
            flash(_("Your invitations have been sent"))
            return redirect(url_for(".list_bills"))

    return render_template("send_invites.html", form=form)
Beispiel #18
0
def contest_invite(contest_id):
    contest = Contest.query.get(contest_id)
    if g.user.user_id != contest.author_id:
        flash('You do not have proper authorization to do this!', 'danger')
        return redirect('/contest/' + str(contest_id))

    form = InviteForm(obj=contest)
    friendships = Friendship.query.filter_by(user_id=g.user.user_id).all()
    users = [User.query.get(friendship.friend_id) for friendship in friendships]
    form.users.choices = [(user.user_id, user.username) for user in users]

    if request.method == 'POST' and form.validate():
        form = InviteForm(request.form)
        if form.users.data == None: form.users.data = []
        else: form.users.data = [User.query.get(user_id) for user_id in form.users.data]

        form.populate_obj(contest)
        contest.save()
        return redirect(url_for('contest_overview', contest_id=contest.contest_id))

    return render_template('invite_form.html', form=form, edit=True)
def invite(request, next=None):
    """Handles invite form submission"""
    invite_form = InviteForm(instance=Invitation(user=request.user),
                             data=request.POST)
    if invite_form.is_valid():
        invites = invite_form.save()
        emails = ", ".join([invite.email for invite in invites])
        messages.success(request, 'Invitation sent to %s' % emails)
    else:
        messages.error(
            request,
            'Form values where invalid, please try fill out the form again.')

    if request.is_ajax() and request.method == 'POST':
        message_html = loader.render_to_string('_messages.html', {},
                                               RequestContext(request))
        return HttpResponse(message_html)

    next = request.POST.get("next", next)
    if next:
        return redirect(next)
    return redirect("index")
Beispiel #20
0
def site_invite(request,
                template_name='account/invite_non_member.html',
                **kwargs):
    if request.POST:
        form = InviteForm(request.POST)
        if form.is_valid():
            form.save(request.user)
            return HttpResponseRedirect(reverse('messages_all'))
        else:
            form = InviteForm(request.POST)

    else:
        form = InviteForm()

    return render_to_response(template_name, {
        'form': form,
        'hubs': get_hubs(),
    },
                              context_instance=RequestContext(request))
Beispiel #21
0
def invite_user(request):
    active_users = User.objects.filter(is_active=True)
    not_active_users = User.objects.filter(is_active=False)

    if request.method == 'POST':
        form = InviteForm(request.POST)
        if form.is_valid():
            form.save()
            logger.info("Invited new user with email %s" % \
                form.cleaned_data['email']
                )
            messages.info(request, _("Invite email was send for %s" % \
                form.cleaned_data['email'])
                )
            return HttpResponseRedirect(reverse('invite-user'))
    else:
        form = InviteForm()
    data = {
        'form': form,
        'active_users': active_users,
        'not_active_users': not_active_users
    }
    return render_to_response('people/invite.html', data,
      RequestContext(request))
Beispiel #22
0
def organization(key):
    """
    The home page for an organization. displays relevant positions
    and members information.
    :param key:
    :return:
    """
    org = utils.organization.get_organization(key)
    membership = utils.organization.get_membership(org, g.user)
    return render_template('main/organization.html',
                           organization=org,
                           form=InviteForm(),
                           form1=PositionForm(),
                           shift_form=ShiftForm(),
                           membership=membership)
Beispiel #23
0
def invite(site_id):
    user = users.get_current_user()
    site = Site.get_admin_or_404(site_id)
    form = InviteForm(request.form)
    if form.validate():
        invite_hash = sha1()
        invite_hash.update(str(site.key()))
        invite_hash.update(os.urandom(8))
        invite_hash.update(form.email.data)
        invite_hash = b32encode(invite_hash.digest()).lower()
        invite = Invitation(
            hash=invite_hash,
            email=form.email.data,
            site=site,
            admin=form.admin.data,
            inviter=user
        )
        invite.put()
        mail.send_mail(
            sender = settings.invite_sender_email,
            to = invite.email,
            subject = '%s invited you to join them on %s' % (user.email(), settings.appname),
            body = render_template('invite_email.txt', invite=invite),
            html = render_template('invite_email.html', invite=invite),
        )
        if request.is_xhr:
            return 'OK'
        flash('Invitation Sent!', 'success')
    else:
        errors = sum(form.errors.values(), [])
        if request.is_xhr:
            return ', '.join(errors)
        for error in errors:
            flash(error, 'error')
        flash(form.email.data, 'error')
    return redirect(url_for('edit_siteusers', site_id=site_id))
Beispiel #24
0
def site_invite(request, template_name="account/invite_non_member.html", **kwargs):
    if request.POST:
        form = InviteForm(request.POST)
        if form.is_valid():
            form.save(request.user)
            return HttpResponseRedirect(reverse("messages_all"))
        else:
            form = InviteForm(request.POST)

    else:
        form = InviteForm()

    return render_to_response(
        template_name, {"form": form, "hubs": get_hubs()}, context_instance=RequestContext(request)
    )
Beispiel #25
0
def invite_user(request):
    active_users = User.objects.filter(is_active=True)
    not_active_users = User.objects.filter(is_active=False)

    if request.method == 'POST':
        form = InviteForm(request.POST)
        if form.is_valid():
            form.save()
            logger.info("Invited new user with email %s" % \
                form.cleaned_data['email']
                )
            messages.info(request, _("Invite email was send for %s" % \
                form.cleaned_data['email'])
                )
            return HttpResponseRedirect(reverse('invite-user'))
    else:
        form = InviteForm()
    data = {
        'form': form,
        'active_users': active_users,
        'not_active_users': not_active_users
    }
    return render_to_response('people/invite.html', data,
                              RequestContext(request))
Beispiel #26
0
 def post(self):
     form = InviteForm(request.form)
     email = form.email.data
     return jsonify(invite_user(email))
Beispiel #27
0
def api_invite(request, output_format='json'):
    """Create a user, but make it disabled.

    Formats: json

    HTTP Method: GET

    Requires authentication: false

    Parameters:

    * email: E-mail address for the new user. 
    * interest: User's interest in signing up.  Value can be either "publisher",
                "consumer", or an empty string.  Default is an empty string.

    """

    status = 201 # HTTP return status.  We'll be optimistic.
    data = {} # response data 

    try:
        if request.method == 'POST':
            #print "DEBUG: POST"
            form = InviteForm(request.POST)
            #print "DEBUG: form object created"
            if form.is_valid():
                #print "DEBUG: form validated"
                email = form.cleaned_data['email']
                interest = form.cleaned_data['interest']

                try:
                    user = User.objects.get(email=email)
                    raise UserEmailExists("It looks like you've already requested an invitation.") 
                except User.DoesNotExist:
                    username = email # Username defaults to e-mail address
                    if len(email) > 30:
                        #print email
                        # Django usernames can't be longer than 30 characters
                        # Just take the first 30 characters of the part of
                        # the email address before the '@'
                        email_parts = email.partition('@')
                        username = email_parts[0][:30]

                    user = User.objects.create_user(username=username,
                                                    email=email)
                    user.is_active = False
                    user.set_unusable_password()
                    user.save()
                    #print "DEBUG: saved user"
                    user_profile = UserProfile(user=user, interest=interest)
                    user_profile.save()
                    #print "DEBUG: saved user profile"

            else:
                #print "DEBUG: %s" % (form.errors)
                status = 400 # Caught in a bad request
                data['error'] = "Invalid e-mail address."

        else:
            raise MethodUnsupported("%s is not supported at this time." % \
                                (request.method))

    except MethodUnsupported, e:
        logger.warning("API call to %s with unsupported method %s" % \
                    (request.path, request.method))
        status = 405 # Method not allowed
        data['error'] = "%s" % e