Beispiel #1
0
def redirect_to_twitter(twitter_handle):
    """Redirect GET requests for /@TwitterHandle/ to respective the OSF user
    account if it associated with an active account

    :param uid: uid for requested User
    :return: Redirect to User's Twitter account page
    """
    try:
        user = User.find_one(Q('social.twitter', 'iexact', twitter_handle))
    except NoResultsFound:
        raise HTTPError(http.NOT_FOUND, data={
            'message_short': 'User Not Found',
            'message_long': 'There is no active user associated with the Twitter handle: {0}.'.format(twitter_handle)
        })
    except MultipleResultsFound:
        users = User.find(Q('social.twitter', 'iexact', twitter_handle))
        message_long = 'There are multiple OSF accounts associated with the ' \
                       'Twitter handle: <strong>{0}</strong>. <br /> Please ' \
                       'select from the accounts below. <br /><ul>'.format(markupsafe.escape(twitter_handle))
        for user in users:
            message_long += '<li><a href="{0}">{1}</a></li>'.format(user.url, markupsafe.escape(user.fullname))
        message_long += '</ul>'
        raise HTTPError(http.MULTIPLE_CHOICES, data={
            'message_short': 'Multiple Users Found',
            'message_long': message_long
        })

    return redirect(user.url)
Beispiel #2
0
def redirect_to_twitter(twitter_handle):
    """Redirect GET requests for /@TwitterHandle/ to respective the OSF user
    account if it associated with an active account

    :param uid: uid for requested User
    :return: Redirect to User's Twitter account page
    """
    try:
        user = OSFUser.find_one(Q('social.twitter', 'iexact', twitter_handle))
    except NoResultsFound:
        raise HTTPError(
            http.NOT_FOUND,
            data={
                'message_short':
                'User Not Found',
                'message_long':
                'There is no active user associated with the Twitter handle: {0}.'
                .format(twitter_handle)
            })
    except MultipleResultsFound:
        users = OSFUser.find(Q('social.twitter', 'iexact', twitter_handle))
        message_long = 'There are multiple OSF accounts associated with the ' \
                       'Twitter handle: <strong>{0}</strong>. <br /> Please ' \
                       'select from the accounts below. <br /><ul>'.format(markupsafe.escape(twitter_handle))
        for user in users:
            message_long += '<li><a href="{0}">{1}</a></li>'.format(
                user.url, markupsafe.escape(user.fullname))
        message_long += '</ul>'
        raise HTTPError(http.MULTIPLE_CHOICES,
                        data={
                            'message_short': 'Multiple Users Found',
                            'message_long': message_long
                        })

    return redirect(user.url)
Beispiel #3
0
def sync_data_from_mailchimp(**kwargs):
    """Endpoint that the mailchimp webhook sends its data to"""
    key = request.args.get('key')

    if key == settings.MAILCHIMP_WEBHOOK_SECRET_KEY:
        r = request
        action = r.values['type']
        list_name = mailchimp_utils.get_list_name_from_id(list_id=r.values['data[list_id]'])
        username = r.values['data[email]']

        try:
            user = User.find_one(Q('username', 'eq', username))
        except NoResultsFound:
            sentry.log_exception()
            sentry.log_message('A user with this username does not exist.')
            raise HTTPError(404, data=dict(message_short='User not found',
                                        message_long='A user with this username does not exist'))
        if action == 'unsubscribe':
            user.mailchimp_mailing_lists[list_name] = False
            user.save()

        elif action == 'subscribe':
            user.mailchimp_mailing_lists[list_name] = True
            user.save()

    else:
        # TODO: get tests to pass with sentry logging
        # sentry.log_exception()
        # sentry.log_message("Unauthorized request to the OSF.")
        raise HTTPError(http.UNAUTHORIZED)
Beispiel #4
0
def add_conference(endpoint,
                   name,
                   active,
                   admins,
                   info_url=None,
                   logo_url=None,
                   public_projects=None):
    try:
        admin_users = [
            OSFUser.find_one(Q('username', 'iexact', admin))
            for admin in admins
        ]
    except ModularOdmException:
        raise RuntimeError(
            "Admin must be a current registered user on the OSF.")

    conf = Conference(endpoint=endpoint,
                      name=name,
                      active=active,
                      info_url=info_url,
                      logo_url=logo_url,
                      admins=admin_users)
    try:
        conf.save()
    except ModularOdmException:
        raise RuntimeError("Conference already exists.")
Beispiel #5
0
def sync_data_from_mailchimp(**kwargs):
    """Endpoint that the mailchimp webhook sends its data to"""
    key = request.args.get('key')

    if key == settings.MAILCHIMP_WEBHOOK_SECRET_KEY:
        r = request
        action = r.values['type']
        list_name = mailchimp_utils.get_list_name_from_id(
            list_id=r.values['data[list_id]'])
        username = r.values['data[email]']

        try:
            user = OSFUser.find_one(Q('username', 'eq', username))
        except NoResultsFound:
            sentry.log_exception()
            sentry.log_message('A user with this username does not exist.')
            raise HTTPError(
                404,
                data=dict(
                    message_short='User not found',
                    message_long='A user with this username does not exist'))
        if action == 'unsubscribe':
            user.mailchimp_mailing_lists[list_name] = False
            user.save()

        elif action == 'subscribe':
            user.mailchimp_mailing_lists[list_name] = True
            user.save()

    else:
        # TODO: get tests to pass with sentry logging
        # sentry.log_exception()
        # sentry.log_message("Unauthorized request to the OSF.")
        raise HTTPError(http.UNAUTHORIZED)
Beispiel #6
0
def auth_email_logout(token, user):
    """
    When a user is adding an email or merging an account, add the email to the user and log them out.
    """

    redirect_url = cas.get_logout_url(service_url=cas.get_login_url(service_url=web_url_for('index', _absolute=True)))
    try:
        unconfirmed_email = user.get_unconfirmed_email_for_token(token)
    except InvalidTokenError:
        raise HTTPError(http.BAD_REQUEST, data={
            'message_short': 'Bad token',
            'message_long': 'The provided token is invalid.'
        })
    except ExpiredTokenError:
        status.push_status_message('The private link you used is expired.')
        raise HTTPError(http.BAD_REQUEST, data={
            'message_short': 'Expired link',
            'message_long': 'The private link you used is expired.'
        })
    try:
        user_merge = User.find_one(Q('emails__address', 'eq', unconfirmed_email))
    except NoResultsFound:
        user_merge = False
    if user_merge:
        remove_sessions_for_user(user_merge)
    user.email_verifications[token]['confirmed'] = True
    user.save()
    remove_sessions_for_user(user)
    resp = redirect(redirect_url)
    resp.delete_cookie(settings.COOKIE_NAME, domain=settings.OSF_COOKIE_DOMAIN)
    return resp
Beispiel #7
0
def populate_conferences(dev=False):
    if dev:
        Conference.remove()
    date_format = '%b %d %Y'
    for meeting, attrs in MEETING_DATA.iteritems():
        meeting = meeting.strip()
        admin_emails = attrs.pop('admins', [])
        admin_objs = []
        if not dev:
            for email in admin_emails:
                try:
                    user = OSFUser.find_one(Q('username', 'iexact', email))
                    admin_objs.append(user)
                except ModularOdmException:
                    raise RuntimeError(
                        'Username {0!r} is not registered.'.format(email))

        # Convert string into datetime object
        try:
            attrs['end_date'] = datetime.strptime(attrs.get('end_date'),
                                                  date_format)
            attrs['start_date'] = datetime.strptime(attrs.get('start_date'),
                                                    date_format)
        except TypeError:
            print '** Meeting {} does not have a start or end date. **'.format(
                meeting)
        custom_fields = attrs.pop('field_names', {})

        conf = Conference(endpoint=meeting, admins=admin_objs, **attrs)
        conf.field_names.update(custom_fields)
        try:
            conf.save()
        except ModularOdmException:
            conf = Conference.find_one(Q('endpoint', 'eq', meeting))
            for key, value in attrs.items():
                if isinstance(value, dict):
                    current = getattr(conf, key)
                    current.update(value)
                    setattr(conf, key, current)
                else:
                    setattr(conf, key, value)
            conf.admins = admin_objs
            changed_fields = conf.save()
            if changed_fields:
                print('Updated {}: {}'.format(meeting, changed_fields))
        else:
            print('Added new Conference: {}'.format(meeting))
Beispiel #8
0
def populate_conferences(dev=False):
    if dev:
        Conference.remove()
    date_format = '%b %d %Y'
    for meeting, attrs in MEETING_DATA.iteritems():
        meeting = meeting.strip()
        admin_emails = attrs.pop('admins', [])
        admin_objs = []
        if not dev:
            for email in admin_emails:
                try:
                    user = User.find_one(Q('username', 'iexact', email))
                    admin_objs.append(user)
                except ModularOdmException:
                    raise RuntimeError('Username {0!r} is not registered.'.format(email))

        # Convert string into datetime object
        try:
            attrs['end_date'] = datetime.strptime(attrs.get('end_date'), date_format)
            attrs['start_date'] = datetime.strptime(attrs.get('start_date'), date_format)
        except TypeError:
            print '** Meeting {} does not have a start or end date. **'.format(meeting)
        custom_fields = attrs.pop('field_names', {})

        conf = Conference(
            endpoint=meeting, admins=admin_objs, **attrs
        )
        conf.field_names.update(custom_fields)
        try:
            conf.save()
        except ModularOdmException:
            conf = Conference.find_one(Q('endpoint', 'eq', meeting))
            for key, value in attrs.items():
                if isinstance(value, dict):
                    current = getattr(conf, key)
                    current.update(value)
                    setattr(conf, key, current)
                else:
                    setattr(conf, key, value)
            conf.admins = admin_objs
            changed_fields = conf.save()
            if changed_fields:
                print('Updated {}: {}'.format(meeting, changed_fields))
        else:
            print('Added new Conference: {}'.format(meeting))
Beispiel #9
0
def add_conference(endpoint, name, active, admins, info_url=None,
                    logo_url=None, public_projects=None):
    try:
        admin_users = [
            User.find_one(Q('username', 'iexact', admin))
            for admin in admins
        ]
    except ModularOdmException:
        raise RuntimeError("Admin must be a current registered user on the OSF.")

    conf = Conference(
        endpoint=endpoint,
        name=name,
        active=active,
        info_url=info_url,
        logo_url=logo_url,
        admins=admin_users
    )
    try:
        conf.save()
    except ModularOdmException:
        raise RuntimeError("Conference already exists.")
Beispiel #10
0
def auth_email_logout(token, user):
    """
    When a user is adding an email or merging an account, add the email to the user and log them out.
    """

    redirect_url = cas.get_logout_url(service_url=cas.get_login_url(
        service_url=web_url_for('index', _absolute=True)))
    try:
        unconfirmed_email = user.get_unconfirmed_email_for_token(token)
    except InvalidTokenError:
        raise HTTPError(http.BAD_REQUEST,
                        data={
                            'message_short': 'Bad token',
                            'message_long': 'The provided token is invalid.'
                        })
    except ExpiredTokenError:
        status.push_status_message('The private link you used is expired.')
        raise HTTPError(http.BAD_REQUEST,
                        data={
                            'message_short': 'Expired link',
                            'message_long':
                            'The private link you used is expired.'
                        })
    try:
        user_merge = OSFUser.find_one(
            Q('emails__address', 'eq', unconfirmed_email))
    except NoResultsFound:
        user_merge = False
    if user_merge:
        remove_sessions_for_user(user_merge)
    user.email_verifications[token]['confirmed'] = True
    user.save()
    remove_sessions_for_user(user)
    resp = redirect(redirect_url)
    resp.delete_cookie(settings.COOKIE_NAME, domain=settings.OSF_COOKIE_DOMAIN)
    return resp
Beispiel #11
0
def find_by_email(email):
    try:
        return OSFUser.find_one(Q('username', 'iexact', email))
    except ModularOdmException:
        return None
Beispiel #12
0
def send_confirm_email(user,
                       email,
                       renew=False,
                       external_id_provider=None,
                       external_id=None,
                       destination=None):
    """
    Sends `user` a confirmation to the given `email`.


    :param user: the user
    :param email: the email
    :param renew: refresh the token
    :param external_id_provider: user's external id provider
    :param external_id: user's external id
    :param destination: the destination page to redirect after confirmation
    :return:
    :raises: KeyError if user does not have a confirmation token for the given email.
    """

    confirmation_url = user.get_confirmation_url(
        email,
        external=True,
        force=True,
        renew=renew,
        external_id_provider=external_id_provider,
        destination=destination)

    try:
        merge_target = OSFUser.find_one(Q('emails__address', 'eq', email))
    except NoResultsFound:
        merge_target = None

    campaign = campaigns.campaign_for_user(user)
    branded_preprints_provider = None

    # Choose the appropriate email template to use and add existing_user flag if a merge or adding an email.
    if external_id_provider and external_id:
        # First time login through external identity provider, link or create an OSF account confirmation
        if user.external_identity[external_id_provider][
                external_id] == 'CREATE':
            mail_template = mails.EXTERNAL_LOGIN_CONFIRM_EMAIL_CREATE
        elif user.external_identity[external_id_provider][
                external_id] == 'LINK':
            mail_template = mails.EXTERNAL_LOGIN_CONFIRM_EMAIL_LINK
    elif merge_target:
        # Merge account confirmation
        mail_template = mails.CONFIRM_MERGE
        confirmation_url = '{}?logout=1'.format(confirmation_url)
    elif user.is_active:
        # Add email confirmation
        mail_template = mails.CONFIRM_EMAIL
        confirmation_url = '{}?logout=1'.format(confirmation_url)
    elif campaign:
        # Account creation confirmation: from campaign
        mail_template = campaigns.email_template_for_campaign(campaign)
        if campaigns.is_proxy_login(
                campaign
        ) and campaigns.get_service_provider(campaign) != 'OSF':
            branded_preprints_provider = campaigns.get_service_provider(
                campaign)
    else:
        # Account creation confirmation: from OSF
        mail_template = mails.INITIAL_CONFIRM_EMAIL

    mails.send_mail(email,
                    mail_template,
                    'plain',
                    user=user,
                    confirmation_url=confirmation_url,
                    email=email,
                    merge_target=merge_target,
                    external_id_provider=external_id_provider,
                    branded_preprints_provider=branded_preprints_provider)
Beispiel #13
0
def find_by_email(email):
    try:
        return User.find_one(Q('username', 'iexact', email))
    except ModularOdmException:
        return None
Beispiel #14
0
def send_confirm_email(user, email, renew=False, external_id_provider=None, external_id=None, destination=None):
    """
    Sends `user` a confirmation to the given `email`.


    :param user: the user
    :param email: the email
    :param renew: refresh the token
    :param external_id_provider: user's external id provider
    :param external_id: user's external id
    :param destination: the destination page to redirect after confirmation
    :return:
    :raises: KeyError if user does not have a confirmation token for the given email.
    """

    confirmation_url = user.get_confirmation_url(
        email,
        external=True,
        force=True,
        renew=renew,
        external_id_provider=external_id_provider,
        destination=destination
    )

    try:
        merge_target = User.find_one(Q('emails__address', 'eq', email))
    except NoResultsFound:
        merge_target = None

    campaign = campaigns.campaign_for_user(user)
    branded_preprints_provider = None

    # Choose the appropriate email template to use and add existing_user flag if a merge or adding an email.
    if external_id_provider and external_id:
        # First time login through external identity provider, link or create an OSF account confirmation
        if user.external_identity[external_id_provider][external_id] == 'CREATE':
            mail_template = mails.EXTERNAL_LOGIN_CONFIRM_EMAIL_CREATE
        elif user.external_identity[external_id_provider][external_id] == 'LINK':
            mail_template = mails.EXTERNAL_LOGIN_CONFIRM_EMAIL_LINK
    elif merge_target:
        # Merge account confirmation
        mail_template = mails.CONFIRM_MERGE
        confirmation_url = '{}?logout=1'.format(confirmation_url)
    elif user.is_active:
        # Add email confirmation
        mail_template = mails.CONFIRM_EMAIL
        confirmation_url = '{}?logout=1'.format(confirmation_url)
    elif campaign:
        # Account creation confirmation: from campaign
        mail_template = campaigns.email_template_for_campaign(campaign)
        if campaigns.is_proxy_login(campaign) and campaigns.get_service_provider(campaign) != 'OSF':
            branded_preprints_provider = campaigns.get_service_provider(campaign)
    else:
        # Account creation confirmation: from OSF
        mail_template = mails.INITIAL_CONFIRM_EMAIL

    mails.send_mail(
        email,
        mail_template,
        'plain',
        user=user,
        confirmation_url=confirmation_url,
        email=email,
        merge_target=merge_target,
        external_id_provider=external_id_provider,
        branded_preprints_provider=branded_preprints_provider
    )