Example #1
0
def signup(request):
    username = request.POST.get("username")
    password = request.POST.get("password")
    if config.InviteOnlySignUp:
        invitecode = request.POST.get("invitecode")

    username, msg = util.check_string(username, 2, 20, config.UsernameChars)
    if not username:
        result = {"status": "error", "error": "username " + msg}
        return util.json_response(result)

    password, msg = util.check_string(password, config.PasswordMinLength)
    if not password:
        result = {"status": "error", "error": "password " + msg}
        return util.json_response(result)

    r = g.redis

    if config.InviteOnlySignUp:
        # race condition here.
        if not r.sismember("invite.code", invitecode):
            result = {"status": "error", "error": "invalid invitation code"}
            return util.json_response(result)

        # mark as used
        r.smove("invite.code", "invite.code.used", invitecode)

    # XXX proxied requests have the same REMOTE_ADDR
    auth, msg = create_user(username, password, request.environ["REMOTE_ADDR"])
    if not auth:
        result = {"status": "error", "error": msg}
    else:
        result = {"status": "ok", "auth": auth}
    return util.json_response(result)
Example #2
0
def vote_news(request):
    auth_user(request.cookies.get('auth'))
    if not g.user:
        result = {'status': 'error',
                  'error': 'Not authenticated.'
                  }
        return util.json_response(result)

    if request.POST.get('apisecret') != g.user["apisecret"]:
        result = {'status': 'error',
                  'error': 'Wrong form secret'
                  }
        return util.json_response(result)

    news_id = util.force_int(request.POST.get('news_id'))
    vote_type = request.POST.get('vote_type')
    if not news_id or (vote_type != 'up' and vote_type != 'down'):
        result = {'status': 'error',
                  'error': 'Missing news ID or invalid vote type.'
                  }
        return util.json_response(result)

    # Vote the news
    karma, error = do_vote_news(news_id, vote_type)
    if karma:
        return util.json_response({"status": "ok" })
    else:
        return util.json_response({"status": "error" })
Example #3
0
def delete_news(request):
    auth_user(request.cookies.get('auth'))
    if not g.user:
        result = {'status': 'error',
                  'error': 'Not authenticated.'
                  }
        return util.json_response(result)

    if request.POST.get('apisecret') != g.user["apisecret"]:
        result = {'status': 'error',
                  'error': 'Wrong form secret'
                  }
        return util.json_response(result)

    news_id = util.force_int(request.POST.get('news_id'))
    if not news_id:
        result = {'status': 'error',
                  'error': 'bad news_id'
                  }
        return util.json_response(result)

    if del_news(news_id, g.user['id']):
        result = {'status': 'ok',
                  'news_id': -1
                  }
        return util.json_response(result)

    result = {'status': 'err',
              'error': 'News too old or wrong ID/owner.'
              }

    return util.json_response(result)
Example #4
0
def user_new():
    # Check if account already exists
    exists = mongo.db.users.find_one({'email': request.json['email']})
    if exists:
        return json_response({'message': 'email already exists'}, status_code=409)
    new_user_data = request.json
    oid = mongo.db.users.insert(new_user_data)
    user = mongo.db.users.find_one({'_id': ObjectId(oid)})
    return json_response(user)
Example #5
0
def user_update(user_id):
    # Authorization
    user = mongo.db.users.find_one({'_id': user_id})
    if not user['email'] == session['email']:
        return json_response({'message': 'unauthorized'}, status_code=401)

    # PUT
    oid = mongo.db.users.save(json_oid(request.json))
    user = mongo.db.users.find_one({'_id': ObjectId(oid)})
    return json_response(user)
Example #6
0
def logout(request):
    auth_user(request.cookies.get("auth"))
    if g.user:
        apisecret = request.POST.get("apisecret")
        if apisecret == g.user["apisecret"]:
            update_auth_token(g.user)
            return util.json_response({"status": "ok"})

    result = {"status": "error", "error": "Wrong auth credentials or API secret."}
    return util.json_response(result)
Example #7
0
def logout(request):
    auth_user(request.cookies.get('auth'))
    if g.user:
        apisecret = request.POST.get('apisecret')
        if apisecret == g.user["apisecret"]:
            update_auth_token(g.user)
            return util.json_response({'status': 'ok'})

    result = {'status': 'error',
              'error': 'Wrong auth credentials or API secret.'
              }
    return util.json_response(result)
Example #8
0
def signup(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    if config.InviteOnlySignUp:
        invitecode = request.POST.get('invitecode')

    username, msg = util.check_string(username, 2, 20, config.UsernameChars)
    if not username:
        result = {
            'status': 'error',
            'error': 'username ' + msg
            }
        return util.json_response(result)

    password, msg = util.check_string(password, config.PasswordMinLength)
    if not password:
        result = {
            'status': 'error',
            'error': 'password ' + msg
            }
        return util.json_response(result)

    r = g.redis

    if config.InviteOnlySignUp:
        #race condition here.
        if not r.sismember('invite.code', invitecode):
            result = {
            'status': 'error',
            'error': 'invalid invitation code',
            }
            return util.json_response(result)

        #mark as used
        r.smove('invite.code', 'invite.code.used', invitecode)

    #XXX proxied requests have the same REMOTE_ADDR
    auth, msg = create_user(username, password, request.environ['REMOTE_ADDR'])
    if not auth:
        result = {
            'status': 'error',
            'error': msg,
            }
    else:
        result = {
            'status': 'ok',
            'auth': auth,
            }
    return util.json_response(result)
def gconnect():
    if request.args.get('state') != login_session['state']:
        return json_response('Invalid state parameter', 400)

    authorization_code = request.data

    try:
        credentials = upgrade_to_credentials(authorization_code)
    except FlowExchangeError:
        return json_response('Failed to upgrade the authorization code.', 401)

    access_token_info = token_info(credentials.access_token)
    if access_token_info.get('error') is not None:
        error = access_token_info.get('error')
        return json_response(error, 500)

    gplus_id = credentials.id_token['sub']
    if access_token_info['user_id'] != gplus_id:
        return json_response("Token's user ID doesn't match given user ID.", 401)

    if access_token_info['issued_to'] != CLIENT_ID:
        return json_response("Token's client ID does not match this app.", 401)

    if is_already_logged_in(login_session):
        return json_response("Current user is already connected.", 401)

    user_info = get_user_info(credentials.access_token)
    update_login_session(login_session, credentials, gplus_id, user_info)
    db_update_user(session, login_session)

    flash("You are now logged in as %s" % login_session['username'])
    return '<html></html>'
Example #10
0
def delete_news(request):
    auth_user(request.cookies.get("auth"))
    if not g.user:
        result = {"status": "error", "error": "Not authenticated."}
        return util.json_response(result)

    if request.POST.get("apisecret") != g.user["apisecret"]:
        result = {"status": "error", "error": "Wrong form secret"}
        return util.json_response(result)

    news_id = util.force_int(request.POST.get("news_id"))
    if not news_id:
        result = {"status": "error", "error": "bad news_id"}
        return util.json_response(result)

    if del_news(news_id, g.user["id"]):
        result = {"status": "ok", "news_id": -1}
        return util.json_response(result)

    result = {"status": "err", "error": "News too old or wrong ID/owner."}

    return util.json_response(result)
Example #11
0
def vote_news(request):
    auth_user(request.cookies.get("auth"))
    if not g.user:
        result = {"status": "error", "error": "Not authenticated."}
        return util.json_response(result)

    if request.POST.get("apisecret") != g.user["apisecret"]:
        result = {"status": "error", "error": "Wrong form secret"}
        return util.json_response(result)

    news_id = util.force_int(request.POST.get("news_id"))
    vote_type = request.POST.get("vote_type")
    if not news_id or (vote_type != "up" and vote_type != "down"):
        result = {"status": "error", "error": "Missing news ID or invalid vote type."}
        return util.json_response(result)

    # Vote the news
    karma, error = do_vote_news(news_id, vote_type)
    if karma:
        return util.json_response({"status": "ok"})
    else:
        return util.json_response({"status": "error"})
Example #12
0
    def as_response(self):
        '''
        return a bundle as a response
        '''
        bundle_dict = self._make_bundle()

        if self.data_format == 'json':
            response = json_response()
            response.data = json.dumps(bundle_dict)
        else:
            response = xml_bundle_response()
            response.data = render_template('bundle.xml', **bundle_dict)

        return response
Example #13
0
def login(request):
    username = request.GET.get("username")
    password = request.GET.get("password")

    username, msg = util.check_string(username, 2, 20)
    if not username:
        result = {"status": "error", "error": "username " + msg}
        return util.json_response(result)

    password, msg = util.check_string(password)
    if not password:
        result = {"status": "error", "error": "password " + msg}
        return util.json_response(result)

    auth, apisecret = check_user_credentials(username, password)

    if auth:
        result = {"status": "ok", "auth": auth, "apisecret": apisecret}

    else:
        result = {"status": "error", "error": "bad username/password"}

    return util.json_response(result)
Example #14
0
def new_channel(globs, request):
    client_id = request.headers.get('X-KeyExchange-Id')

    #if not _valid_client_id(client_id):
    #    # The X-KeyExchange-Id is valid
    #    try:
    #        log = 'Invalid X-KeyExchange-Id'
    #        log_cef(log, 5, request.environ, config,
    #                msg=_cid2str(client_id))
    #    finally:
    #        raise HTTPBadRequest()
    cid = _get_new_cid(client_id)
    headers = [('X-KeyExchange-Channel', cid),
                ('Content-Type', 'application/json')]
    return json_response(cid, headerlist=headers)
Example #15
0
def login(request):
    username = request.GET.get('username')
    password = request.GET.get('password')

    username, msg = util.check_string(username, 2, 20)
    if not username:
        result = {
            'status': 'error',
            'error': 'username ' + msg
            }
        return util.json_response(result)

    password, msg = util.check_string(password)
    if not password:
        result = {
            'status': 'error',
            'error': 'password ' + msg
            }
        return util.json_response(result)

    auth, apisecret = check_user_credentials(username, password)

    if auth:
        result = {
            'status': 'ok',
            'auth': auth,
            'apisecret': apisecret
            }

    else:
        result = {
            'status': 'error',
            'error': 'bad username/password',
            }

    return util.json_response(result)
Example #16
0
def update_profile(request):
    auth_user(request.cookies.get('auth'))
    if not g.user:
        result = {'status': 'error',
                  'error': 'Not authenticated.'
                  }
        return util.json_response(result)

    if request.POST.get('apisecret') != g.user["apisecret"]:
        result = {'status': 'error',
                  'error': 'Wrong form secret'
                  }
        return util.json_response(result)


    password = request.POST.get('password')    #optinal
    email = request.POST.get('email')
    about = request.POST.get('about')

    email, msg = util.check_string(email, maxlen=128)
    if email is None:
        result = {
            'status': 'error',
            'error': 'email ' + msg
            }
        return util.json_response(result)

    about, msg = util.check_string(about, maxlen=256)
    if about is None:
        result = {
            'status': 'error',
            'error': 'about ' + msg
            }
        return util.json_response(result)

    r = g.redis

    if password:
        password, msg = util.check_string(password, config.PasswordMinLength)
        if not password:
            result = {
                'status': 'error',
                'error': 'password ' + msg
                }
            return util.json_response(result)

        r.hset("user:"******"password",
               util.hash_password(password, g.user['salt']))

    r.hmset("user:"******"about": about.rstrip(),
            "email": email
            })
    return util.json_response({'status': "ok"})
Example #17
0
def new_error(status_code):
    '''
    Create a new OperationOutcome resource from HTTP status_code
    '''
    msg, severity = CODES[status_code]
    outcome_content = {
        'resourceType': 'OperationOutcome',
        'issue': {
            'severity': severity,
            'details': msg
        }
    }
    is_xml = (request.args.get('_format', 'xml') == 'xml')
    response= (json_response(json.dumps(outcome_content))
            if not is_xml
            else xml_response(json_to_xml(outcome_content)))
    response.status = status_code
    return response
Example #18
0
    def as_response(self, request, created=False):
        '''
        return the resource as a HTTP response
        '''
        status = '201' if created else '200'

        if request.format == 'json':
            response = json_response(status=status)
            response.data = self.data
        else:
            response = xml_response(status=status)
            response.data = json_to_xml(json.loads(self.data))

        loc_header = 'Location' if created else 'Content-Location'
        response.headers[loc_header] = urljoin(request.api_base, '%s/%s/_history/%s' % (
            self.resource_type,
            self.resource_id,
            self.version))
        return response
Example #19
0
def update_profile(request):
    auth_user(request.cookies.get("auth"))
    if not g.user:
        result = {"status": "error", "error": "Not authenticated."}
        return util.json_response(result)

    if request.POST.get("apisecret") != g.user["apisecret"]:
        result = {"status": "error", "error": "Wrong form secret"}
        return util.json_response(result)

    password = request.POST.get("password")  # optinal
    email = request.POST.get("email")
    about = request.POST.get("about")

    email, msg = util.check_string(email, maxlen=128)
    if email is None:
        result = {"status": "error", "error": "email " + msg}
        return util.json_response(result)

    about, msg = util.check_string(about, maxlen=256)
    if about is None:
        result = {"status": "error", "error": "about " + msg}
        return util.json_response(result)

    r = g.redis

    if password:
        password, msg = util.check_string(password, config.PasswordMinLength)
        if not password:
            result = {"status": "error", "error": "password " + msg}
            return util.json_response(result)

        salt = g.user.get("salt", util.get_rand())
        r.hmset("user:"******"id"], {"password": util.hash_password(password, salt), "salt": salt})

    r.hmset("user:"******"id"], {"about": about.rstrip(), "email": email})
    return util.json_response({"status": "ok"})
Example #20
0
def user_get():
    # Authorization
    user = mongo.db.users.find_one({'_id': ObjectId(session['userId'])})
    if not user:
        return json_response({'message': 'cannot find user'}, status_code=500)
    return json_response(user)
Example #21
0
def submit(request):
    auth_user(request.cookies.get("auth"))
    if not g.user:
        result = {"status": "error", "error": "Not authenticated."}
        return util.json_response(result)

    if request.POST.get("apisecret") != g.user["apisecret"]:
        result = {"status": "error", "error": "Wrong form secret"}
        return util.json_response(result)

    title = request.POST.get("title")
    url = request.POST.get("url")
    text = request.POST.get("text")
    news_id = util.force_int(request.POST.get("news_id"))

    if text:
        text = text.lstrip("\r\n").rstrip()

    if not title or (not url and not text):
        result = {"status": "error", "error": "title and (url or text) required"}
        return util.json_response(result)

    # Make sure the URL is about an acceptable protocol, that is
    # http:// or https:// for now.
    if url and not url.startswith("http://") and not url.startswith("https://"):
        result = {"status": "error", "error": "we only accept http:// and https:// news"}
        return util.json_response(result)

    if len(title) > config.MaxTitleLen or len(url) > config.MaxUrlLen:
        result = {"status": "error", "error": "title or url too long"}
        return util.json_response(result)

    if not url and len(text) > config.CommentMaxLength:
        result = {"status": "error", "error": "text too long"}
        return util.json_response(result)

    if news_id is None:
        result = {"status": "error", "error": "bad news_id"}
        return util.json_response(result)

    if news_id == -1:
        if limit.submitted_recently():
            result = {
                "status": "error",
                "error": "You have submitted a story too recently, "
                + "please wait %s seconds." % limit.allowed_to_post_in_seconds(),
            }
            return util.json_response(result)

        news_id = insert_news(title, url, text, g.user["id"])

    else:
        news_id = edit_news(news_id, title, url, text, g.user["id"])
        if not news_id:
            result = {
                "status": "error",
                "error": "Invalid parameters, news too old to be modified" + "or url recently posted.",
            }
            return util.json_response(result)

    result = {"status": "ok", "news_id": int(news_id)}

    return util.json_response(result)
Example #22
0
def getGmailMessages(email):
    
    #~~~PUT MESSAGE ID BELOW~~~
    messages = ListMessagesMatchingQuery(build_service(get_credentials()), "me", query='from:'+email)

    convos = []

    i = 0
    while (i<len(messages)):
        msg_id = messages[i]["threadId"]
        msg_info = GetMimeMessage(build_service(get_credentials()), "me", msg_id)
        #print msg_info
        #TODO: Find a better way to get the message string, ex: by newlines
        index1 = str(msg_info).index("Content-Type: text/plain; charset=UTF-8")
        index1 += len("Content-Type: text/plain; charset=UTF-8")
        index2 = str(msg_info).index("Content-Type: text/html; charset=UTF-8")
        index2 -= len("--001a113d38862b78c0052be7b244")
        msg_content = str(msg_info)[index1:index2]
        convos.append(msg_content)
        i+=1

    #print convos



    tone_analyzer = ToneAnalyzer(username='******',
                             password='******',
                             version='2016-02-11')

    analyzed_text = []

    for c in convos:
        analyzed_text.append(json.dumps(tone_analyzer.tone(text=c), indent=2))

    tones = {}

    tones["emotion"]=ast.literal_eval(analyzed_text[0])["document_tone"]["tone_categories"][0]["tones"]

    tones["language"]=ast.literal_eval(analyzed_text[0])["document_tone"]["tone_categories"][1]["tones"]
    
    tones["social"]=ast.literal_eval(analyzed_text[0])["document_tone"]["tone_categories"][2]["tones"]

    values = []
    scores = []

    for el in tones["emotion"]:
        values.append(el["tone_name"])
    for el in tones["language"]:
        values.append(el["tone_name"])
    for el in tones["social"]:
        values.append(el["tone_name"])

    print values


    for el in tones["emotion"]:
        scores.append(el["score"])
    for el in tones["language"]:
        scores.append(el["score"])
    for el in tones["social"]:
        scores.append(el["score"])
    print scores

    #print values
    #print scores

    ret={}
    
    ret["values"] = values
    ret["scores"] = scores

    f = open('out.json', 'w+')
    f.write(str(ret))

    return util.json_response(ret);
Example #23
0
def submit(request):
    auth_user(request.cookies.get('auth'))
    if not g.user:
        result = {'status': 'error',
                  'error': 'Not authenticated.'
                  }
        return util.json_response(result)

    if request.POST.get('apisecret') != g.user["apisecret"]:
        result = {'status': 'error',
                  'error': 'Wrong form secret'
                  }
        return util.json_response(result)

    title = request.POST.get('title')
    url = request.POST.get('url')
    text = request.POST.get('text')
    news_id = util.force_int(request.POST.get('news_id'))

    if text:
        text = text.lstrip('\r\n').rstrip()

    if not title or (not url and not text):
        result = {'status': 'error',
                  'error': 'title and (url or text) required'
                  }
        return util.json_response(result)

    # Make sure the URL is about an acceptable protocol, that is
    # http:// or https:// for now.
    if url and not url.startswith('http://') and not url.startswith('https://'):
        result = {'status': 'error',
                  'error': 'we only accept http:// and https:// news'
                  }
        return util.json_response(result)

    if len(title) > config.MaxTitleLen or len(url) > config.MaxUrlLen:
        result = {'status': 'error',
                  'error': 'title or url too long'
                  }
        return util.json_response(result)

    if not url and len(text) > config.CommentMaxLength:
        result = {'status': 'error',
                  'error': 'text too long'
                  }
        return util.json_response(result)

    if news_id is None:
        result = {'status': 'error',
                  'error': 'bad news_id'
                  }
        return util.json_response(result)

    if news_id == -1:
        if limit.submitted_recently():
            result = {'status': 'error',
                      'error': "You have submitted a story too recently, " +
                      "please wait %s seconds." % limit.allowed_to_post_in_seconds()
                      }
            return util.json_response(result)

        news_id = insert_news(title, url, text, g.user['id'])

    else:
        news_id = edit_news(news_id, title, url, text, g.user['id'])
        if not news_id:
            result = {'status': 'error',
                      'error': 'Invalid parameters, news too old to be modified' +
                      'or url recently posted.'
                      }
            return util.json_response(result)

    result = {'status': 'ok',
              'news_id': int(news_id)
              }

    return util.json_response(result)