Пример #1
0
def main():
    """docstring for main"""
    username_list = {}

    data = file("data/petster-hamster/ent.petster-hamster")
    for item in data.readlines():
        if not item.startswith("%"):
            res = INFO_PATTERN.findall(item)
            info = dict(zip(KEYS, res))
            username_list[info["id"]] = info["username"]
            user = User(info)
            user.add()
    data.close()

    data = file("data/petster-hamster/out.petster-hamster")
    for item in data.readlines():
        # print repr(item)
        # raw_input()
        if not item.startswith("%"):
            uid1, uid2 = item.strip().split(" ")
            # print repr(uid1), repr(uid2)
            # raw_input()
            username1 = username_list[uid1]
            username2 = username_list[uid2]
            user1 = User.get(username1)
            user2 = User.get(username2)
            user1.follow(username2)
            user2.follow(username1)
    data.close()
Пример #2
0
def register():
    if request.method == 'GET':
        return render_template('register.html', page='signup')
    elif request.method == 'POST':
        username = request.form.get('username', None)
        nickname = request.form.get('nickname', None)
        password = request.form.get('password', None)
        password_again = request.form.get('password_again', None)

        if username is None or nickname is None or password is None or password_again is None:
            flash(u'请检查输入是否为空', 'danger')
            return redirect(url_for('register'))
        password, password_again, username, nickname = unicode(
            password), unicode(password_again), unicode(username), unicode(
                nickname)

        # 1. 用户名是否存在
        user = User.query.filter_by(username=username).first()
        if user:
            flash(u'该用户名已被注册', 'danger')
            return redirect(url_for('register'))
        # 2. 密码输入不一致
        if password != password_again:
            flash(u'两次密码输入不一致', 'danger')
            return redirect(url_for('register'))

        proc_password = utils.encrypt_password(password, salt=config.SALT)
        User.add(User(username, proc_password, nickname))
        flash(u'注册成功', 'success')
        return redirect(url_for('login'))
Пример #3
0
def register():
    if request.method == 'GET':
        return render_template('register.html', page='signup')
    elif request.method == 'POST':
        username = request.form.get('username', None)
        nickname = request.form.get('nickname', None)
        password = request.form.get('password', None)
        password_again = request.form.get('password_again', None)

        if username is None or nickname is None or password is None or password_again is None:
            flash(u'请检查输入是否为空', 'danger')
            return redirect(url_for('register'))
        password, password_again, username, nickname = unicode(password), unicode(password_again), unicode(username), unicode(nickname)

        # 1. 用户名是否存在
        user = User.query.filter_by(username=username).first()
        if user:
            flash(u'该用户名已被注册', 'danger')
            return redirect(url_for('register'))
        # 2. 密码输入不一致
        if password != password_again:
            flash(u'两次密码输入不一致', 'danger')
            return redirect(url_for('register'))

        proc_password = utils.encrypt_password(password, salt=config.SALT)
        User.add(User(username, proc_password, nickname))
        flash(u'注册成功', 'success')
        return redirect(url_for('login'))
Пример #4
0
def oauth_authorized(resp):
    """Called after authorization.  After this function finished handling,
    the OAuth information is removed from the session again.  When this
    happened, the tokengetter from above is used to retrieve the oauth
    token and secret.

    Because the remote application could have re-authorized the application
    it is necessary to update the values in the database.

    If the application redirected back after denying, the response passed
    to the function will be `None`.  Otherwise a dictionary with the values
    the application submitted.  Note that Twitter itself does not really
    redirect back unless the user clicks on the application name.
    """
    next_url = request.args.get('next') or url_for('index')
    if resp is None:
        #TODO: show friendly message
        #flash(u'You denied the request to sign in.')
        return redirect(next_url)

    screen_name = resp['screen_name']
    oauth_token = resp['oauth_token']
    oauth_token_secret = resp['oauth_token_secret']

    user = User.select_by_screen_name(screen_name)
    if not user:
        app.logger.debug('User not found on database. Using the Twitter API')
        auth = tweepy.OAuthHandler(config.CONSUMER_KEY, config.CONSUMER_SECRET)
        auth.set_access_token(oauth_token, oauth_token_secret)
        api = tweepy.API(auth)
        twitter_user = api.get_user(screen_name=screen_name)
        user = User()
        user.id = twitter_user.id
        user.screen_name = twitter_user.screen_name
        user.blocked = 'N'
        user.name = twitter_user.name
        user.description = twitter_user.description
        user.created_at = twitter_user.created_at
        user.friends_count = twitter_user.friends_count
        user.followers_count = twitter_user.followers_count
        user.statuses_count = twitter_user.statuses_count
        user.profile_image_url = twitter_user.profile_image_url
        user.lang = twitter_user.lang
        user.location = twitter_user.location
        user.oauth_token = oauth_token
        user.oauth_token_secret = oauth_token_secret
        User.add(user)
    else:
        user.oauth_token = oauth_token
        user.oauth_token_secret = oauth_token_secret

    flask.session['screen_name'] = resp['screen_name']
    flask.session['oauth_token'] = resp['oauth_token']
    flask.session['oauth_token_secret'] = resp['oauth_token_secret']

    commit()

    return flask.redirect(next_url)
Пример #5
0
def oauth_authorized(resp):
    """Called after authorization.  After this function finished handling,
    the OAuth information is removed from the session again.  When this
    happened, the tokengetter from above is used to retrieve the oauth
    token and secret.

    Because the remote application could have re-authorized the application
    it is necessary to update the values in the database.

    If the application redirected back after denying, the response passed
    to the function will be `None`.  Otherwise a dictionary with the values
    the application submitted.  Note that Twitter itself does not really
    redirect back unless the user clicks on the application name.
    """
    next_url = request.args.get('next') or url_for('index')
    if resp is None:
        #TODO: show friendly message
        #flash(u'You denied the request to sign in.')
        return redirect(next_url)

    screen_name = resp['screen_name']
    oauth_token = resp['oauth_token']
    oauth_token_secret = resp['oauth_token_secret']
    
    user = User.select_by_screen_name(screen_name)
    if not user:
        app.logger.debug('User not found on database. Using the Twitter API')
        auth = tweepy.OAuthHandler(config.CONSUMER_KEY, config.CONSUMER_SECRET)
        auth.set_access_token(oauth_token, oauth_token_secret)
        api = tweepy.API(auth)
        twitter_user = api.get_user(screen_name=screen_name)
        user = User()
        user.id = twitter_user.id
        user.screen_name = twitter_user.screen_name
        user.blocked = 'N'
        user.name = twitter_user.name
        user.description = twitter_user.description
        user.created_at = twitter_user.created_at
        user.friends_count = twitter_user.friends_count
        user.followers_count = twitter_user.followers_count
        user.statuses_count = twitter_user.statuses_count
        user.profile_image_url = twitter_user.profile_image_url
        user.lang = twitter_user.lang
        user.location = twitter_user.location
        user.oauth_token = oauth_token
        user.oauth_token_secret = oauth_token_secret
        User.add(user)
    else:
        user.oauth_token = oauth_token
        user.oauth_token_secret = oauth_token_secret

    flask.session['screen_name'] = resp['screen_name']
    flask.session['oauth_token'] = resp['oauth_token']
    flask.session['oauth_token_secret'] = resp['oauth_token_secret']
    
    commit()
    
    return flask.redirect(next_url)
Пример #6
0
def viewAddUser(argList) -> ViewRemoteResult:
    requestId = bytes.fromhex(argList[0])
    request = Request(commands.COMMAND_ADD_USER, requestId)
    result = sendRequest(request)
    response = result.getResponse()
    if response.isOk():
        user = User(response.args[0 : USER_ID_SIZE], 
                    response.args[USER_ID_SIZE : USER_ID_SIZE+NVS_KEY_MAX_SIZE])
        user.add()
    return result
Пример #7
0
def viewInit(argList) -> ViewRemoteResult:
    password = argList[0]
    request = Request.fromStr(commands.COMMAND_INIT, password)
    result = sendRequest(request)
    response = result.getResponse()
    if response.isOk():
        JsonStorage.initJsonFile()
        user = User(response.args[0:USER_ID_SIZE], 
                    response.args[USER_ID_SIZE : USER_ID_SIZE+NVS_KEY_MAX_SIZE])
        user.add()
    return result
Пример #8
0
def register_process():
    """Process registration."""

    # Get form variables
    fullname = request.form.get("fullname")
    email = request.form.get("email")
    phone_number = request.form.get("phone_number")
    password = request.form.get("password")
    # payer_seller = request.form.get("payer_or_receiver")
    password = password_hash(password)
    # check to see if user already exists. If so, update their details.
    if User.fetch_by_email(email) is None:
        current_user = User.add(fullname, email, phone_number, password)

    else:
        current_user = User.fetch_by_email(email)
        current_user.fullname = fullname
        current_user.phone_number = phone_number
        current_user.password = password

    db.session.commit()

    flash("User %s added." % fullname)

    session["user_id"] = current_user.user_id
    # session["payer_seller"] = current_user.payer_seller
    return redirect("/dashboard")
Пример #9
0
def registration_process():
    """Process registration."""

    email = request.form["register-email"]
    password = request.form["password"]

    if User.get_by_email(email):
        flash("That email is already registered.  ")
        flash("Please register with a different email.")

        print "email already taken"
        return redirect("/")

    User.add(email, password)

    flash("Registration successful.  Welcome %s!" % email)
    return render_template("homepage.html")
Пример #10
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        data = form.data
        # 写入用户信息
        u = User(username=data['username'],
                 email=data['email'],
                 password=data['password'])
        tag = u.add()
        if not tag:
            flash(u'注册失败,请重试')
            return redirect(url_for('register'))
        flash(u'注册成功,请登录')
        return redirect(url_for('login'))
    return render_template('register.html', form=form)
Пример #11
0
def index_post():
    """
    Check validation for SignIn or SignUp

    :rtype: login page with form
    """
    action = request.GET.get('action', 'signin')
    username = request.forms.get('username')
    password = request.forms.get('password')
    if action == 'signup':
        password_confirm = request.forms.get('password_confirm')
        invitation = request.forms.get('invitation')
        res, msg = User.add(username, password, password_confirm, invitation)
    else:
        res, msg = User.auth(username, password)
    if res:
        response.set_cookie('username', username, secret=COOKIES_SECRET)
        redirect('/%s/timeline/' % username)
    else:
        return template(action, username=username, msg=msg)
Пример #12
0
def index_post():
    """
    Check validation for SignIn or SignUp

    :rtype: login page with form
    """
    action = request.GET.get('action', 'signin')
    username = request.forms.get('username')
    password = request.forms.get('password')
    if action == 'signup':
        password_confirm = request.forms.get('password_confirm')
        invitation = request.forms.get('invitation')
        res, msg = User.add(username, password, password_confirm, invitation)
    else:
        res, msg = User.auth(username, password)
    if res:
        response.set_cookie('username', username, secret=COOKIES_SECRET)
        redirect('/%s/timeline/' % username)
    else:
        return template(action, username=username, msg=msg)
Пример #13
0
def index_post():
    """
    Check validation for SignIn or SignUp

    :rtype: login page with form
    """
    action = request.GET.get("action", "signin")
    username = request.forms.get("username")
    password = request.forms.get("password")
    if action == "signup":
        password_confirm = request.forms.get("password_confirm")
        invitation = request.forms.get("invitation")
        res, msg = User.add(username, password, password_confirm, invitation)
    else:
        res, msg = User.auth(username, password)
    if res:
        response.set_cookie("username", username, secret=COOKIES_SECRET)
        redirect("/%s/timeline/" % username)
    else:
        return template(action, username=username, msg=msg)
Пример #14
0
def main():
    """docstring for main"""

    data = file('data/petster-hamster/ent.petster-hamster')
    for item in data.readlines():
        item = item.decode('utf8')
        # print repr(item)
        # print type(item)
        # print item
        if not item.startswith('%'):
            res = INFO_PATTERN.findall(item)
            info = dict(zip(KEYS, res))
            print info['username']
            res, user = User.add(
                username=info['username'],
                password='******' % info['username'],
                password_confirm='pyneo4jet%s' % info['username'],
                invitation=INVITATION_CODE,
            )
            user.update(
                name=info['name'],
                gender=info['gender'],
                hometown=info['hometown'],
            )
            for key in KEYS:
                res, msg = Tweet.add(
                    info['username'],
                    'My %s is %s' % (key, info[key]),
                    (datetime.datetime.now() -
                     datetime.timedelta(days=random.randrange(0, 365)) -
                     datetime.timedelta(seconds=random.randrange(0, 86400))
                     ).strftime('%Y-%m-%d %H:%M:%S'),
                )
                if not res:
                    print msg
                    print key
                    print info[key]
                    raw_input()
    data.close()

    data = file('data/petster-hamster/out.petster-hamster')
    for item in data.readlines():
        # print repr(item)
        # raw_input()
        if not item.startswith('%'):
            username1, username2 = item.strip().split(' ')
            print username1, username2
            # raw_input()
            user1 = User.get(username1)
            user2 = User.get(username2)
            if user1 and user2:
                if (int(username1) + int(username2)) % 2 == 0:
                    res, msg = user2.follow(username1)
                else:
                    res, msg = user1.follow(username2)
                if not res:
                    print msg
                    raw_input()
    data.close()

    db.shutdown()
Пример #15
0
def register():
    form = request.form
    user = User(form)
    user.add()
    return redirect(url_for('index'))
Пример #16
0
def main():
    """docstring for main"""

    data = file('data/petster-hamster/ent.petster-hamster')
    for item in data.readlines():
        item = item.decode('utf8')
        # print repr(item)
        # print type(item)
        # print item
        if not item.startswith('%'):
            res = INFO_PATTERN.findall(item)
            info = dict(zip(KEYS, res))
            print info['username']
            res, user = User.add(
                username=info['username'],
                password='******' % info['username'],
                password_confirm='pyneo4jet%s' % info['username'],
                invitation=INVITATION_CODE,
            )
            user.update(
                name=info['name'],
                gender=info['gender'],
                hometown=info['hometown'],
            )
            for key in KEYS:
                res, msg = Tweet.add(info['username'],
                    'My %s is %s' % (key, info[key]),
                    (
                        datetime.datetime.now() -
                        datetime.timedelta(days=random.randrange(0, 365)) -
                        datetime.timedelta(seconds=random.randrange(0, 86400))
                    ).strftime('%Y-%m-%d %H:%M:%S'),
                )
                if not res:
                    print msg
                    print key
                    print info[key]
                    raw_input()
    data.close()

    data = file('data/petster-hamster/out.petster-hamster')
    for item in data.readlines():
        # print repr(item)
        # raw_input()
        if not item.startswith('%'):
            username1, username2 = item.strip().split(' ')
            print username1, username2
            # raw_input()
            user1 = User.get(username1)
            user2 = User.get(username2)
            if user1 and user2:
                if (int(username1) + int(username2)) % 2 == 0:
                    res, msg = user2.follow(username1)
                else:
                    res, msg = user1.follow(username2)
                if not res:
                    print msg
                    raw_input()
    data.close()

    db.shutdown()
Пример #17
0
def process_new_transaction(user_id):
    """Persist a new transaction into the DB"""

    # Get form variables
    seller_email = request.form.get("seller_email")
    seller_fullname = request.form.get("seller_fullname")
    payment_date = request.form.get("payment_date")
    payment_amount = request.form.get("payment_amount")
    product_details = request.form.get("product_details")
    date = datetime.datetime.strptime(payment_date, "%Y-%m-%d")

    # The recipient is added to the database
    # password = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))
    original_password = '******'
    password = password_hash(original_password)
    if User.fetch_by_email(seller_email) is None:
        User.add(
            fullname=seller_fullname,
            email=seller_email,
            phone_number='',
            password=password,
        )
    db.session.commit()

    seller = User.fetch_by_email(seller_email)
    seller_id = seller.user_id
    payer_id = session['user_id']
    payer = User.fetch(payer_id)
    payer_fullname = payer.fullname
    # An email is sent to the seller to log in and view the contract
    html = "<html><h2>Good Cheddar</h2><br><p>Hi " + seller_fullname \
        + ",</p><br>" + payer_fullname + " would like to send you money via Good Cheddar. \
        <br> Please<a href='http://*****:*****@gmail.com",
            "to": seller_email,
            "subject": "You have a payment pending",
            "html": html
        })

    status_history = {"status": ["waiting from approval from seller"]}
    # The new transaction is created in the database
    new_transaction = Transaction.add(
        payer_id=payer_id,
        seller_id=seller_id,
        payment_amount=float(payment_amount),
        payment_currency="USD",
        payment_date=date,
        payment_is_approved=False,
        product_images='',
        product_details=product_details,
        payment_is_made=False,
        is_disputed=False,
        dispute_images='',
        dispute_details='',
        status_history=json.dumps(status_history),
        status="pending approval from recipient",
        is_completed=False,
    )
    date = date.strftime('%Y-%m-%d')

    flash("Approval prompt sent to the recipient")
    # return redirect("/dashboard")

    return jsonify({
        'new_transaction_id': new_transaction.transaction_id,
        'new_recipient': new_transaction.seller.fullname,
        'new_date': date,
        'new_amount': payment_amount,
        'new_status': "pending approval from recipient",
        'new_action': 'No action'
    })