Esempio n. 1
0
def contact_profile(request, id):
    """
    Sends a request to the Contact Profile page and retrieves Contact information for the profile.

    Arguments:
        id (string): The id of the contact.

    Returns:
        A rendered page of the Contact Profile.
    """
    user_id = request.session['user_id'] if 'user_id' in request.session else None
    account_type = request.session['account_type'] if 'account_type' in request.session else None

    logger.info('Request made for profile of contact={0} by user={1}'.format(id, user_id))

    user_dao = ctx.get_object('UserDAO')

    try:
        user = user_dao.find(id=id)
    except:
        logger.error('Exception encountered on user lookup for user={0}'.format(id))
        return not_found(request)

    if user and not user_id:
        logger.warn('Unauthorized request made for user={0}'.format(user.id))
        return unauthorized(request)

    contact_dao = ctx.get_object('ContactDAO')

    try:
        contact = contact_dao.find(id=id)
    except:
        logger.error('Exception encountered on contact lookup for contact={0}'.format(id))
        return not_found(request)

    if contact:
        results = contact.__dict__['_data']
    elif user:
        results = user.__dict__['_data']

    org_dao = ctx.get_object('OrganizationDAO')
    try:
        if results['organization']:
            org = org_dao.find(id=results['organization'].id)
            results['organization'] = org.__dict__['_data']
    except:
        logger.error('Exception encountered on organization lookup for organization={0}'
                     .format(results['organization'].id))
        return not_found(request)

    can_edit = contact and account_type == AccountType.CONTRIBUTOR

    return render(request, 'contact/contact_profile.html', {
        'contact': results,
        'can_edit': can_edit,
    })
Esempio n. 2
0
def logout(request):
    """Logs the user out. Sends the user to the index page."""
    if 'user_id' not in request.session:
        logger.error('Bad request made for logout without login')
        return unauthorized(request)

    user_id = request.session['user_id']
    logger.info('Logging out user={0}'.format(user_id))
    request.session.flush()

    return HttpResponseRedirect('/')
Esempio n. 3
0
def request_organization(request):
    """
    Sends a request to the Request Organization page if the user is logged in.

    Returns:
        A rendered page containing the Request Organization form.
    """
    if 'user_id' not in request.session:
        logger.error('Bad request made for organization seed without login')
        return unauthorized(request)
    else:
        user_id = request.session['user_id']

    form = RequestOrgForm(request.POST or None)
    error = ''
    success = ''

    if request.method == 'POST':
        if form.is_valid():
            url = form.cleaned_data['url']
            dao = ctx.get_object('URLMetadataDAO')

            try:
                metadata = URLMetadata(url=url,
                                       domain=UrlUtility.get_domain(url))
            except ValueError:
                error = "Oops! We don't recognize that domain. Please try another."

            if not error:
                try:
                    dto = DTOConverter.to_dto(URLMetadataDTO, metadata)
                    dao.create_update(dto)
                    logger.info(
                        'Org seed with url={0} requested by user={1}'.format(
                            url, user_id))
                    success = 'Your request has been sent successfully!'
                except:
                    error = 'Something went wrong with your request. Please try again later.'

    return render(request, 'organization/request_organization.html', {
        'form': form,
        'success': success,
        'error': error
    })
Esempio n. 4
0
def request_organization(request):
    """
    Sends a request to the Request Organization page if the user is logged in.

    Returns:
        A rendered page containing the Request Organization form.
    """
    if 'user_id' not in request.session:
        logger.error('Bad request made for organization seed without login')
        return unauthorized(request)
    else:
        user_id = request.session['user_id']

    form = RequestOrgForm(request.POST or None)
    error = ''
    success = ''

    if request.method == 'POST':
        if form.is_valid():
            url = form.cleaned_data['url']
            dao = ctx.get_object('URLMetadataDAO')

            try:
                metadata = URLMetadata(url=url, domain=UrlUtility.get_domain(url))
            except ValueError:
                error = "Oops! We don't recognize that domain. Please try another."

            if not error:
                try:
                    dto = DTOConverter.to_dto(URLMetadataDTO, metadata)
                    dao.create_update(dto)
                    logger.info('Org seed with url={0} requested by user={1}'.format(url, user_id))
                    success = 'Your request has been sent successfully!'
                except:
                    error = 'Something went wrong with your request. Please try again later.'

    return render(request, 'organization/request_organization.html', {'form': form, 'success': success, 'error': error})
Esempio n. 5
0
def edit_contact(request, contact_id):
    """
    Sends a request to the Edit Contact page if the user is logged in and has a contributor account type.

    Arguments:
        contact_id (string): The id of the contact that is being edited.

    Returns:
        A rendered page containing the Edit Contact form.
    """
    if 'user_id' not in request.session:
        logger.error('Request to edit contact={0} without login'.format(contact_id))
        return unauthorized(request)
    else:
        user_id = request.session['user_id']
        if 'account_type' not in request.session or request.session['account_type'] != AccountType.CONTRIBUTOR:
            logger.error('Request to edit contact={0} without credentials by user={1}'.format(contact_id, user_id))
            return unauthorized(request)

    contact_dao = ctx.get_object('ContactDAO')

    error = ''
    success = ''

    try:
        contact = contact_dao.find(id=contact_id)
    except:
        logger.error('Exception encountered on contact lookup for contact={0} by user={1}'.format(contact_id, user_id))
        return not_found(request)

    phones = contact.phones if contact.phones else []

    form = EditContactForm(request.POST or None,
                           initial=_create_contact_dict(contact),
                           phones=phones)

    if request.method == 'POST':
        if form.is_valid():
            data = form.cleaned_data
            new_phones = []

            if 'invalid' in data:
                contact.valid = not data['invalid']

            try:
                for key, value in data.items():
                    if key.startswith('phone'):
                        new_phones.append(value.strip())
                    else:
                        setattr(contact, key, value.strip()) if value else setattr(contact, key, None)
            except:
                error = 'Oops! Something went wrong processing your request. Please try again later.'
                logger.error('Error occurred while updating fields for contact={0} by user={1}'.format(contact_id, user_id))

            if not error:
                if new_phones:
                    contact.phones = [p for p in new_phones if p]

                try:
                    contact_dao.create_update(contact)
                    success = 'The contact has been updated successfully!'
                    logger.info('Contact={0} updated by user={1}'.format(contact_id, user_id))
                except:
                    error = 'Oops! There was an error updating the contact. Please try again soon.'

    return render(request, 'contact/edit_contact.html', {'form': form, 'contact_id': contact_id,
                                                         'success': success, 'error': error})
Esempio n. 6
0
def edit_organization(request, org_id):
    """
    Sends a request to the Edit Organization page if the user is logged in and a contributor account type.

    Arguments:
        org_id (string): The id of the organization that is being edited.

    Returns:
        A rendered page containing the Edit Organization form.
    """
    if 'user_id' not in request.session:
        logger.error(
            'Request to edit organization={0} without login'.format(org_id))
        return unauthorized(request)
    else:
        user_id = request.session['user_id']
        if 'account_type' not in request.session or request.session[
                'account_type'] != AccountType.CONTRIBUTOR:
            logger.error(
                'Request to edit organization={0} without credentials by user={1}'
                .format(org_id, user_id))
            return unauthorized(request)

    try:
        dao = ctx.get_object('OrganizationDAO')
        org = dao.find(id=org_id)
    except:
        logger.error(
            'Exception encountered on organization lookup for org={0} by user={1}'
            .format(org_id, user_id))
        return not_found()

    emails = org.emails if org.emails else []
    phone_numbers = org.phone_numbers if org.phone_numbers else []
    types = org.types if org.types else []

    form = EditOrganizationForm(
        request.POST or None,
        initial=_create_org_dict(org),
        emails=emails,
        phone_numbers=phone_numbers,
        types=types,
    )
    error = ''
    success = ''

    if request.method == 'POST':
        if form.is_valid():
            data = form.cleaned_data
            new_emails = []
            new_phone_nums = []
            new_types = []

            try:
                for key, value in data.items():
                    if key.startswith('email'):
                        new_emails.append(value.strip())
                    elif key.startswith('phone'):
                        new_phone_nums.append(value.strip())
                    elif key.startswith('type'):
                        new_types.append(value.strip())
                    else:
                        setattr(org, key, value.strip()) if value else setattr(
                            org, key, None)
            except:
                error = 'Oops! Something went wrong processing your request. Please try again later.'
                logger.error(
                    'Error occurred while updating fields for org={0} by user={1}'
                    .format(org_id, user_id))

            if not error:
                if new_emails:
                    org.emails = [e for e in new_emails if e]
                    if org.emails:
                        org.email_key = org.emails[0]
                if new_phone_nums:
                    org.phone_numbers = [p for p in new_phone_nums if p]
                if new_types:
                    org.types = [t for t in new_types if t]

                try:
                    dao.create_update(org)
                    success = 'The organization has been updated successfully!'
                    logger.info('Org={0} updated by user={1}'.format(
                        org_id, user_id))
                except:
                    error = 'Oops! There was an error updating the organization. Please try again later.'
                    logger.error(
                        'Error occurred saving org={0} by user={1}'.format(
                            org_id, user_id))

    return render(
        request, "organization/edit_organization.html", {
            'form': form,
            'type_choices': ORG_TYPE_CHOICES,
            'org_id': org_id,
            'success': success,
            'error': error
        })
Esempio n. 7
0
def edit_contact(request, contact_id):
    """
    Sends a request to the Edit Contact page if the user is logged in and has a contributor account type.

    Arguments:
        contact_id (string): The id of the contact that is being edited.

    Returns:
        A rendered page containing the Edit Contact form.
    """
    if 'user_id' not in request.session:
        logger.error(
            'Request to edit contact={0} without login'.format(contact_id))
        return unauthorized(request)
    else:
        user_id = request.session['user_id']
        if 'account_type' not in request.session or request.session[
                'account_type'] != AccountType.CONTRIBUTOR:
            logger.error(
                'Request to edit contact={0} without credentials by user={1}'.
                format(contact_id, user_id))
            return unauthorized(request)

    contact_dao = ctx.get_object('ContactDAO')

    error = ''
    success = ''

    try:
        contact = contact_dao.find(id=contact_id)
    except:
        logger.error(
            'Exception encountered on contact lookup for contact={0} by user={1}'
            .format(contact_id, user_id))
        return not_found(request)

    phones = contact.phones if contact.phones else []

    form = EditContactForm(request.POST or None,
                           initial=_create_contact_dict(contact),
                           phones=phones)

    if request.method == 'POST':
        if form.is_valid():
            data = form.cleaned_data
            new_phones = []

            if 'invalid' in data:
                contact.valid = not data['invalid']

            try:
                for key, value in data.items():
                    if key.startswith('phone'):
                        new_phones.append(value.strip())
                    else:
                        setattr(contact, key,
                                value.strip()) if value else setattr(
                                    contact, key, None)
            except:
                error = 'Oops! Something went wrong processing your request. Please try again later.'
                logger.error(
                    'Error occurred while updating fields for contact={0} by user={1}'
                    .format(contact_id, user_id))

            if not error:
                if new_phones:
                    contact.phones = [p for p in new_phones if p]

                try:
                    contact_dao.create_update(contact)
                    success = 'The contact has been updated successfully!'
                    logger.info('Contact={0} updated by user={1}'.format(
                        contact_id, user_id))
                except:
                    error = 'Oops! There was an error updating the contact. Please try again soon.'

    return render(request, 'contact/edit_contact.html', {
        'form': form,
        'contact_id': contact_id,
        'success': success,
        'error': error
    })
Esempio n. 8
0
def contact_profile(request, id):
    """
    Sends a request to the Contact Profile page and retrieves Contact information for the profile.

    Arguments:
        id (string): The id of the contact.

    Returns:
        A rendered page of the Contact Profile.
    """
    user_id = request.session[
        'user_id'] if 'user_id' in request.session else None
    account_type = request.session[
        'account_type'] if 'account_type' in request.session else None

    logger.info('Request made for profile of contact={0} by user={1}'.format(
        id, user_id))

    user_dao = ctx.get_object('UserDAO')

    try:
        user = user_dao.find(id=id)
    except:
        logger.error(
            'Exception encountered on user lookup for user={0}'.format(id))
        return not_found(request)

    if user and not user_id:
        logger.warn('Unauthorized request made for user={0}'.format(user.id))
        return unauthorized(request)

    contact_dao = ctx.get_object('ContactDAO')

    try:
        contact = contact_dao.find(id=id)
    except:
        logger.error(
            'Exception encountered on contact lookup for contact={0}'.format(
                id))
        return not_found(request)

    if contact:
        results = contact.__dict__['_data']
    elif user:
        results = user.__dict__['_data']

    org_dao = ctx.get_object('OrganizationDAO')
    try:
        if results['organization']:
            org = org_dao.find(id=results['organization'].id)
            results['organization'] = org.__dict__['_data']
    except:
        logger.error(
            'Exception encountered on organization lookup for organization={0}'
            .format(results['organization'].id))
        return not_found(request)

    can_edit = contact and account_type == AccountType.CONTRIBUTOR

    return render(request, 'contact/contact_profile.html', {
        'contact': results,
        'can_edit': can_edit,
    })
Esempio n. 9
0
def edit_organization(request, org_id):
    """
    Sends a request to the Edit Organization page if the user is logged in and a contributor account type.

    Arguments:
        org_id (string): The id of the organization that is being edited.

    Returns:
        A rendered page containing the Edit Organization form.
    """
    if 'user_id' not in request.session:
        logger.error('Request to edit organization={0} without login'.format(org_id))
        return unauthorized(request)
    else:
        user_id = request.session['user_id']
        if 'account_type' not in request.session or request.session['account_type'] != AccountType.CONTRIBUTOR:
            logger.error('Request to edit organization={0} without credentials by user={1}'.format(org_id, user_id))
            return unauthorized(request)

    try:
        dao = ctx.get_object('OrganizationDAO')
        org = dao.find(id=org_id)
    except:
        logger.error('Exception encountered on organization lookup for org={0} by user={1}'.format(org_id, user_id))
        return not_found()

    emails = org.emails if org.emails else []
    phone_numbers = org.phone_numbers if org.phone_numbers else []
    types = org.types if org.types else []

    form = EditOrganizationForm(request.POST or None,
                                initial=_create_org_dict(org),
                                emails=emails,
                                phone_numbers=phone_numbers,
                                types=types, )
    error = ''
    success = ''

    if request.method == 'POST':
        if form.is_valid():
            data = form.cleaned_data
            new_emails = []
            new_phone_nums = []
            new_types = []

            try:
                for key, value in data.items():
                    if key.startswith('email'):
                        new_emails.append(value.strip())
                    elif key.startswith('phone'):
                        new_phone_nums.append(value.strip())
                    elif key.startswith('type'):
                        new_types.append(value.strip())
                    else:
                        setattr(org, key, value.strip()) if value else setattr(org, key, None)
            except:
                error = 'Oops! Something went wrong processing your request. Please try again later.'
                logger.error('Error occurred while updating fields for org={0} by user={1}'.format(org_id, user_id))

            if not error:
                if new_emails:
                    org.emails = [e for e in new_emails if e]
                    if org.emails:
                        org.email_key = org.emails[0]
                if new_phone_nums:
                    org.phone_numbers = [p for p in new_phone_nums if p]
                if new_types:
                    org.types = [t for t in new_types if t]

                try:
                    dao.create_update(org)
                    success = 'The organization has been updated successfully!'
                    logger.info('Org={0} updated by user={1}'.format(org_id, user_id))
                except:
                    error = 'Oops! There was an error updating the organization. Please try again later.'
                    logger.error('Error occurred saving org={0} by user={1}'.format(org_id, user_id))

    return render(request, "organization/edit_organization.html", {'form': form,
                                                                   'type_choices': ORG_TYPE_CHOICES,
                                                                   'org_id': org_id,
                                                                   'success': success,
                                                                   'error': error})
Esempio n. 10
0
def send_invite(request):
    """
    Sends a request to the Send Invite page.

    Returns:
        A rendered page with the Send Invite form if the user is logged in.
    """
    if 'user_id' not in request.session:
        logger.error('Request made for send_invite without login')
        return unauthorized(request)
    else:
        user_id = request.session['user_id']

    form = InviteForm(request.POST or None)
    error = ''
    success = ''

    if request.method == 'POST':
        if form.is_valid():
            to = form.cleaned_data['email']
            name = "{0} {1}".format(request.session['first_name'],
                                    request.session['last_name'])

            logger.info('Request made to invite email={0} by user={1}'.format(
                to, user_id))

            if 'message' in form.cleaned_data:
                message = form.cleaned_data['message']

            invitation = "Hello!<br><br>{0} has invited you to be a part of the Anti-Trafficking Atlas (ATA), a " \
                         "website that aggregates anti-trafficking information, such as organizations, people, news, " \
                         "and publications by programmatically pulling data from the web. This site allows " \
                         "researchers, advocates, and volunteers to search for places to help and people with which " \
                         "to collaborate. If you sign up for an account, you can also aid in making sure the website " \
                         "has complete and correct information. Help us make the anti-trafficking efforts of the " \
                         "world easy to find. Go to <a href=\"unlaht.cloudapp.net\">unlaht.cloudapp.net</a> to sign " \
                         "up!<br><br>" \
                         .format(name)

            if message:
                invitation += "{0} says: \"{1}\"<br><br>".format(name, message)

            invitation += "Thank you,<br><br>The ATA Team"

            mail = MIMEText(invitation, 'html')
            mail['Subject'] = 'Come join the Anti-Trafficking Atlas!'
            mail['From'] = 'ATA'
            mail['To'] = to

            username = get_config_value("MAIL", "username")
            password = get_config_value("MAIL", "password")
            server = get_config_value("MAIL", "server")
            port = get_config_value("MAIL", "port")

            try:
                if not (username and password):
                    raise Exception

                s = smtplib.SMTP_SSL('{0}:{1}'.format(server, port))
                s.login(username, password)
                s.sendmail('*****@*****.**', [to], mail.as_string())
                s.quit()
                success = 'Your invite has been sent successfully!'
                logger.info('Invite sent to email={0} by user={1}'.format(
                    to, user_id))
            except:
                logger.error(
                    'Invite request by user={0} to email={1} failed.'.format(
                        user_id, to))
                error = 'Oops! It looks like something went wrong. Please try again later.'
    return render(request, 'user/send_invite.html', {
        'form': form,
        'error': error,
        'success': success
    })