Example #1
0
def register_process():
    """
    Handles user registration
    """

    handle = escape(str(request.form['handle'].strip()))
    firstname = escape(str(request.form['fname'].strip()))
    lastname = escape(str(request.form['lname'].strip()))
    email = escape(str(request.form['email'].strip()))
    passwd = escape(str(request.form['passwd'].strip()))

    mysql_inst = DataIOMySQL()
    mysql_inst.connect()

    # TODO - check for duplicates / additional validation
    mysql_inst.insert(
        'User',
        handle=handle,
        email=email,
        firstname=firstname,
        lastname=lastname,
        password=hmac(passwd),
        date_join=int(time.time())
    )

    # TODO - error condition
    return render_template('login.html')
Example #2
0
def get_MW_identity(user):
    """Get identifying information about the user
    :param user:            string, user
    :param handshaker:      Handshakerobject from mwoauth
    :return:                MW identity object
    """
    key = hmac(user)
    handshaker = get_serialized(settings.MWOAUTH_HANDSHAKER_PKL_KEY, key)
    access_token = get_serialized(settings.MWOAUTH_ACCTOKEN_PKL_KEY, key)
    return handshaker.identify(access_token)
Example #3
0
    def process(self, article):
        """
        Freshens the redis entry for `article`
        """

        DataIORedis().connect()

        key = hmac(article)

        # Get wiki
        try:
            wiki = wikipedia.WikipediaPage(article, preload=True)
        except DisambiguationError as e:
            # choose a disambiguation
            return
        except PageError as e:
            # bad page proceed with crawl
            return

        # extract & parse html
        html = parse_strip_elements(wiki.html())
        html = parse_convert_links(html)

        # Get flickr content
        res = flickr.call('photos_search', {'text': article,
                                            'format': 'json',
                                            'sort': 'relevance',
                                         })

        # TODO - detect failed responses
        res_json = json.loads(res[14:-1])

        # Extract data for the first photo returned
        owner = res_json['photos']['photo'][0]['owner']
        photo_id = res_json['photos']['photo'][0]['id']
        farm = res_json['photos']['photo'][0]['farm']
        server = res_json['photos']['photo'][0]['server']
        title = res_json['photos']['photo'][0]['title']
        secret = res_json['photos']['photo'][0]['secret']

        page_content = {
            'content': html,
            'owner': owner,
            'photo_id': photo_id,
            'farm': farm,
            'server': server,
            'title': title,
            'secret': secret
        }
        DataIORedis().write(key, json.dumps(page_content))

        # return the links
        return wiki.links
Example #4
0
    def check_password(self, password):

        if self.pw_hash:
            try:
                password = escape(str(password))
                return self.pw_hash == hmac(password)
            except (TypeError, NameError) as e:
                log.error(__name__ +
                              ' :: Hash check error - ' + e.message)
                return False
        else:
            return False
Example #5
0
def get_MW_access_token(user, response_query_string):
    """Generate Access token from MW auth query string + access token
    :param user:                    string, user
    :param handshaker:              Handshakerobject from mwoauth
    :param response_query_string:   Query string from MW auth
    :return:
    """
    key = hmac(user)

    # unpickle the handshaker
    handshaker = get_serialized(settings.MWOAUTH_HANDSHAKER_PKL_KEY, key)
    req_token = get_serialized(settings.MWOAUTH_REQTOKEN_PKL_KEY, key)

    # Obtain authorized key/secret for "resource owner"
    access_token = handshaker.complete(req_token, response_query_string)

    # Serialize access token in redis - ovewrite request token
    set_serialized(access_token, settings.MWOAUTH_ACCTOKEN_PKL_KEY, key)

    return access_token
Example #6
0
def get_MW_redirect(user):
    """Fetch redirect from mwoauth via consumer token for user
    :param user:    string, user
    :return:        string, redirect url for user
    """
    consumer_token = ConsumerToken(settings.MW_CLIENT_KEY,
                                   settings.MW_CLIENT_SECRET)

    # Construct handshaker with wiki URI and consumer
    handshaker = Handshaker(COMMONS_URL, consumer_token)

    # Step 1: Initialize -- ask MediaWiki for a temporary key/secret for user
    redirect, request_token = handshaker.initiate()

    # Pickle the handshaker & request token
    key = hmac(user)
    set_serialized(handshaker, settings.MWOAUTH_HANDSHAKER_PKL_KEY, key)
    set_serialized(request_token, settings.MWOAUTH_REQTOKEN_PKL_KEY, key)

    # Step 2: Authorize -- send user to MediaWiki to confirm authorization
    return redirect
Example #7
0
def upload_complete():
    """POST, Renders the page for completing upload to mediawiki via api
    :return:    template for view
    """

    success = True

    msg = ''

    #  Attempt api upload
    uid = hmac(User(current_user.get_id()).get_id())

    log.info('Attempting upload to Commons for user: '******'article']
    filename = request.form['filename']
    photourl = request.form['photourl']
    flickr_photo_id = request.form['flickr_photo_id']
    articleurl = settings.SITE_URL + '/mashup?article=' + article

    # Obtain access token if it exists
    acc_token = None
    try:
        acc_token = mw.get_serialized(settings.MWOAUTH_ACCTOKEN_PKL_KEY, uid)

    except IOError:
        msg = 'No mediawiki token for your user. See <a href="%s">MWOauth</a>' % (
            settings.SITE_URL + '/mwoauth')
        log.info('No mediawiki token for "%s"' % str(uid))
        success = False


    # If access token was successfully fetched talk to commons api
    if success:
        response = mw.api_upload_url(request.form['photourl'], acc_token, filename)


        # Validate the response
        if response.status_code != requests.codes.ok:
            success = False
            msg = str(response.status_code)
        elif 'error' in response.json():
            success = False
            msg = response.json()['error']['info']
        else:
            success = True
            msg = 'OK'

        # Determine if the photo has already been uploaded to commons
        with UploadsModel() as um:
            if um.get_upload(flickr_photo_id):
                msg = 'This photo has already been uploaded.'
                success = False

        # Ensure that upload model is updated
        if success:
            with ArticleModel() as am:
                article_data = am.get_article_by_name(article)
            with PhotoModel() as pm:
                photo_data = pm.get_photo(flickr_photo_id, article_data.id)
            with UploadsModel() as um:
                um.insert_upload(photo_data.id, flickr_photo_id, article_data.id, uid)

        log.info('UPLOAD RESPONSE: ' + str(response.json()))

    return render_template('upload_complete.html',
                           success=success,
                           articleurl=articleurl,
                           article=article,
                           photourl=photourl,
                           apierror=msg
                           )