Exemple #1
0
 def post(self):
     account_id = self.get_argument('id')
     try:
         Account.delete().where(Account.id == account_id).execute()
     except:
         pass
     self.write('OK')
Exemple #2
0
def _do_service(session):
    threading.Timer(BaseConfig.TICKOVER, _do_service, [session]).start()
    clan = RSClan(BaseConfig.CLAN_NAME)

    for member in clan.clan_members:
        member = RSAccount(member)
        acc_in_db = session.query(Account).filter(Account.username == member.username).first()
        if acc_in_db == None:
            acc = Account()
            acc.username = member.username
            session.add(acc)
            session.commit()
            session.refresh(acc)
            acc_id = acc.id
        else:
            acc_id = acc_in_db.id

        hiscores = member.hiscores
        if hiscores != None:
            most_rec = session.query(SkillTable).filter(SkillTable.account_id == acc_id).filter(
                SkillTable.skill_id == 0).order_by("timestamp").first()
            if most_rec != None:
                if hiscores["Overall"]["XP"] > most_rec.xp:
                    add_hiscore(hiscores, acc_id, session)
            else:
                add_hiscore(hiscores, acc_id, session)
Exemple #3
0
 def post(self):
     account_id = self.get_argument('id')
     try:
         Account.update(is_activated=False).execute()
         Account.update(is_activated=True).where(Account.id == account_id).execute()
     except:
         pass
     self.write('OK')
Exemple #4
0
def upsert_bank(jurisdiction_id, bank_code=None, name=None, fetched=False):
    if bank_code not in swift_banks:
        if is_blank(name):
            name = None
        if not jurisdiction_id:
            jurisdiction_id = jurisdiction_by_code("XX")

        s = Session()
        bank = _get_bank(s, jurisdiction_id, bank_code)
        if not bank:
            bank = Bank(code=bank_code,
                        name=name,
                        country_id=jurisdiction_id,
                        fetched=fetched)
            s.add(bank)
            cash_account = Account(
                code=None, acc_type="CASH", bank=bank, fetched=True
            )  # CASH accounts don't really exist, so all pre-fetched
            s.add(cash_account)
        elif name:
            if not bank.name:
                bank.name = name
            elif bank.name != name:
                print("Bank with different name: old: %s; new: %s"\
                 %(bank.name, name))
                if len(name) > len(bank.name):
                    bank.name = name

        s.commit()
        swift_banks[bank_code] = bank.id
        s.close()

    return swift_banks[bank_code]
Exemple #5
0
def call(program, argv):
    parser = argparse.ArgumentParser(prog=program)

    parser.add_argument("dbid", help="new profile's account DBID", type=int)
    parser.add_argument("name", help="new profile's username")
    parser.add_argument("agent", help="new profile's agent")
    parser.add_argument("-u", "--uuid", help="new profile's UUID", type=UUID)

    args = parser.parse_args(argv)

    input_uuid = args.uuid if args.uuid is not None else uuid4()

    account: Account = Account.get(id=args.dbid)
    if account is None:
        print("No account matches that DBID!")
        exit(1)

    try:
        profile = Profile.create(uuid=input_uuid,
                                 agent=args.agent,
                                 account=account,
                                 name=args.name)
    except ExistsException:
        print("Name not available.")
        exit(1)

    try:
        commit()
    except Exception as e:
        print(str(e))
        exit(1)

    print(profile)
Exemple #6
0
def register():
    form1 = registerForm()
    if form1.validate_on_submit():
        newUser = form1.userName.data
        newPwd = form1.passWord.data
        email = form1.email.data
        """
        #generate confirm url
        token = generate_token(email)
        confirm_url = confirm_token(token)
        # email vertify
        try:
            send_email(email, confirm_url , email.html)
        except:
            flash("email is not exit")
            return redirect(url_for('register'))
        """
        try:
            user = Account(username=newUser,
                           password=md5Pwd(newPwd),
                           email=email)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('index'))
        except:
            flash(" username have been registered ")
            return redirect(url_for('register'))
    else:
        pass
    return render_template('register.html', form=form1)
Exemple #7
0
 async def bind_account(self, account, cookies):
     _account = Account()
     _account.email = account
     _account.cookies = cookies
     try:
         if self.fake:
             self.spider = FakeSpider(account=_account)
         else:
             self.spider = Spider(account=_account)
     except LoginFailedException:
         self.spider = None
         await self.report_login_failed(account)
         self.logger.error('Login Failed')
     else:
         self.account = account
         self.task_consume_tag = await self.channel.basic_consume(
             queue_name='worker_task', callback=self.handle_task, no_wait=True)
         self.logger.info('Bind account successful. {}'.format(account))
Exemple #8
0
    def post(self):
        session = self.get_argument('session')
        homepage = self.get_argument('homepage')
        import logging
        logging.debug('session: '+session)
        logging.debug('homepage: '+homepage)
        
        try:
            name = re.findall(r'^http(?:s?)://www\.douban\.com/people/(.+)/$', homepage).pop(0)
            account = Account.get(Account.name == name)
            account.session = session
            account.is_invalid = False
            account.save()
        except Account.DoesNotExist:
            Account.create(session=session, name=name)
        except IndexError:
            pass

        self.write('OK')
Exemple #9
0
    def get(self):
        workers = self.server.workers
        pedding_tasks = self.server.tasks
        accounts = Account.select().where(Account.is_invalid == False)

        if not accounts.count():
            self.redirect(self.reverse_url('settings.accounts.login'))
            return
        
        self.render('dashboard.html', workers=workers,
                    pedding_tasks=pedding_tasks, accounts=accounts, all_tasks=ALL_TASKS.keys())
Exemple #10
0
def _check_message(reply_token, text, sender):
    userdata = Account.get_or_insert(sender)
    print userdata.flag
    print reply_token

    if text == "@flow_event":
        register.reg0(reply_token, text, userdata)
    elif text == u"予定登録":

        payloads = {
            "replyToken":
            reply_token,
            "messages": [
                {
                    "type":
                    "text",
                    "text":
                    u"追加する予定やお知らせを入力してください。\n(例)2月3日の13時より、経済学の定期試験があります。資料の持ち込みは不可です。皆さん頑張りましょう!"
                },
            ]
        }

        Massage.reply(payloads)
        userdata.flag = "addtask"
        userdata.put()

    elif userdata.flag == "addtask":
        add_task(text)

    elif userdata.flag == None or userdata.flag == "false":

        payloads = {
            "replyToken": reply_token,
            "messages": [
                {
                    "type": "text",
                    "text": u"只今、メンテナンスモード中です。"
                },
            ]
        }

        Massage.reply(payloads)

    elif text == "@flow_event":
        register.reg0(reply_token, text, userdata)

    elif userdata.flag == "reg1":
        register.reg1(reply_token, text, userdata)

    elif userdata.flag == "reg2":
        register.reg2(reply_token, text, userdata)

    elif userdata.flag == "reg3":
        register.reg3(reply_token, text, userdata)
Exemple #11
0
def attempt_login(username: str, password: str):
    """Try to log user in

    :param username: Account username
    :param password: Cleartext account password
    :return: Account if credentials correct, None otherwise.
    :rtype: Account or None
    """
    account = Account.get(lambda a: a.username == username)
    if account is None or not password_compare(password, account.password):
        return None
    return account
def call(program, argv):
    parser = argparse.ArgumentParser(prog=program)

    parser.add_argument("dbid", help="DBID of account", type=int)
    parser.add_argument("password", help="password to test")

    args = parser.parse_args(argv)

    account: Account = Account.get(id=args.dbid)
    if account is None:
        print("No account matches that DBID!")
        exit(1)

    print(password_compare(args.password, account.password))
def call(program, argv):
    parser = argparse.ArgumentParser(prog=program)

    parser.add_argument("dbid", help="account dbid", type=int)

    args = parser.parse_args(argv)

    account = Account.get(id=args.dbid)
    if account is None:
        print("There is no account with this DBID.")
        exit(1)

    for question in account.security_questions:
        print(question)
Exemple #14
0
def call(program, argv):
    parser = argparse.ArgumentParser(prog=program)

    parser.add_argument("-n",
                        "--username",
                        help="username regex",
                        metavar="REGEX")
    parser.add_argument("-u",
                        "--uuid",
                        help="UUID regex no dashes",
                        metavar="REGEX")
    parser.add_argument("-igt",
                        "--id-gt",
                        help="DBID is greater than X",
                        metavar="X",
                        type=int)
    parser.add_argument("-ilt",
                        "--id-lt",
                        help="DBID is less than X",
                        metavar="X",
                        type=int)
    parser.add_argument("-x",
                        "--max",
                        help="maximum entries printed",
                        metavar="X",
                        type=int)

    args = parser.parse_args(argv)

    username_pattern = re.compile(
        args.username if args.username is not None else ".*")
    uuid_pattern = re.compile(args.uuid if args.uuid is not None else ".*")

    accounts = Account.select()

    printed_count = 0
    for account in accounts:
        if username_pattern.fullmatch(account.username) is None:
            continue
        if uuid_pattern.fullmatch(account.uuid.hex) is None:
            continue
        if args.id_gt is not None and not account.id > args.id_gt:
            continue
        if args.id_lt is not None and not account.id < args.id_lt:
            continue
        printed_count += 1
        print(str(account))
        if args.max is not None and printed_count >= args.max:
            break
Exemple #15
0
    def post(self):
        tasks = json.loads(self.get_argument('tasks'))
        task_names = tasks['tasks']
        account_ids = tasks['accounts']

        if isinstance(task_names, list) and isinstance(account_ids, list):
            for task_name in task_names:
                task_type = ALL_TASKS.get(task_name)
                for account_id in account_ids:
                    try:
                        account = Account.get(Account.id == account_id)
                        task = task_type(account)
                        self.server.add_task(task)
                    except Account.DoesNotExist:
                        pass
            self.server.push_task()
        self.write('OK')
Exemple #16
0
def call(program, argv):
    parser = argparse.ArgumentParser(prog=program)

    parser.add_argument("dbid", help="DBID of account", type=int)

    uuids = parser.add_mutually_exclusive_group()
    uuids.add_argument("-u", "--uuid", help="change account UUID", type=UUID)
    uuids.add_argument("-ru",
                       "--random-uuid",
                       help="refresh account UUID",
                       action="store_true")

    parser.add_argument("-n", "--username", help="change account username")
    parser.add_argument("-p", "--password", help="change account password")
    parser.add_argument("--delete",
                        help="delete this account",
                        action="store_true")

    args = parser.parse_args(argv)

    account: Account = Account.get(id=args.dbid)
    if account is None:
        print("No account matches that DBID!")
        exit(1)

    if args.uuid is not None:
        account.uuid = args.uuid
    if args.random_uuid:
        account.uuid = uuid4()
    if args.username is not None:
        account.username = args.username
    if args.password is not None:
        account.password = password_hash(args.password)
    if args.delete:
        account.delete()

    try:
        commit()
    except Exception as e:
        print(e)
        exit(1)

    if not args.delete:
        print(str(account))
def call(program, argv):
    parser = argparse.ArgumentParser(prog=program)

    parser.add_argument("dbid", help="account dbid", type=int)
    parser.add_argument("qid", help="question id", type=int)
    parser.add_argument("answer", help="question answer")

    args = parser.parse_args(argv)

    account = Account.get(id=args.dbid)
    if account is None:
        print("There is no account with this DBID.")
        exit(1)

    if args.qid not in SECURITY_QUESTIONS:
        print("Invalid question id.")
        exit(1)

    question = account.add_answer(question_id=args.qid, answer=args.answer)

    commit()

    print(question)
Exemple #18
0
#send email to vertify
def send_email(email, subject):
    token = generate_token(email)
    confrim_url = url_for('confirm_email', token=token, _external=True)
    html = render_template(email.html, confirm_url=confirm_url)
    msg = Message(subject, recipients=[email])
    msg.html
    mail.send(msg)
"""
#init database
from db import db, Account
db.drop_all()
db.create_all()
user1 = Account(username="******",
                password=md5Pwd("test1"),
                email="*****@*****.**")
user2 = Account(username="******",
                password=md5Pwd("test2"),
                email="*****@*****.**")
db.session.add_all([user1, user2])
db.session.commit()


#view function
@app.route('/', methods=['GET', 'POST'])
def index():
    session['username'] = ''
    session['passWord'] = ''
    loginform = loginForm()
    if loginform.validate_on_submit():
Exemple #19
0
def login_twitter_authenticated():

    # build token from oauth token redirected to us
    # goes with the secret token we recieved in `login_twitter()`
    token = oauth.Token(request.args['oauth_token'],
                        session['twitter_request_token_secret'])

    token.set_verifier(request.args['oauth_verifier'])

    # request an access token
    consumer = oauth.Consumer(app.config['TWITTER_CONSUMER_KEY'],
                              app.config['TWITTER_CONSUMER_SECRET'])
    client = oauth.Client(consumer, token)

    resp, content = client.request(app.config['TWITTER_ACCESS_TOKEN_URL'],
                                   "POST")

    if resp['status'] != '200':
        flash("Failed to login!", 'error')
        return redirect(url_for("questions"))

    # data contains our final token and secret for the account
    data = dict(urlparse.parse_qsl(content))

    oauth_token = data['oauth_token']
    oauth_token_secret = data['oauth_token_secret']

    api = twitter.Api(consumer_key=app.config['TWITTER_CONSUMER_KEY'],
                      consumer_secret=app.config['TWITTER_CONSUMER_SECRET'],
                      access_token_key=oauth_token,
                      access_token_secret=oauth_token_secret)

    try:
        twitter_data = api.VerifyCredentials().AsDict()
    except twitter.TwitterError:
        flash("Cannot validate Twitter credentials.", 'error')
        return redirect(url_for("questions"))

    # print twitter_data

    # either create or update account information
    twaccount = Twitter.query.filter_by(id=twitter_data['id']).first()

    if twaccount is None:
        account = Account()
        db.session.add(account)

        twaccount = Twitter()
        twaccount.id = twitter_data['id']
        twaccount.account = account
    else:
        account = twaccount.account

    twaccount.screen_name = account.username = twitter_data['screen_name']
    account.image_url = twitter_data['profile_image_url']
    twaccount.raw = jsonify(twitter_data)

    twaccount.oauth_token = oauth_token
    twaccount.oauth_token_secret = oauth_token_secret
    db.session.add(twaccount)

    # try to add friends
    try:
        friendIDs = []
        cursor = -1
        while True:
            data = api.GetFriendIDs(cursor=cursor)
            friendIDs += data['ids']
            if 'next_cursor' not in data or \
                    data['next_cursor'] == 0 or \
                    data['next_cursor'] == data['previous_cursor']:
                break

            cursor = data['next_cursor']

        twaccount.follows = [db.TwitterFollow(follower_id=account.id, followee_id=f) for f in friendIDs]
        account.following = [f.account for f in twaccount.following]
        log.debug("following: %s", [a.username for a in account.following])

    except twitter.TwitterError:
        pass

    log.info("commiting twitter login info: account.id=%s", account.id)
    if not commit():
        flash("Error while logging in.", 'error')
        return redirect(url_for("questions"))

    session['account_id'] = twaccount.account_id

    flash("Logged in as {0}.".format(account.username), 'success')
    if 'url_after_login' in session:
        return redirect(session.pop('url_after_login'))

    return redirect(url_for("questions"))
Exemple #20
0
def upsert_account(code, acc_type, bank_id, org_id=None, fetched=False):
    """Atomic operation
	includes commit
	does not include normalisation 
	"""
    # TODO: Cleanup search of accounts
    # Does not solve the entire problem. Remains scenario when local refereces comes before IBAN reference
    if code not in iban_accounts:
        s = Session()

        if acc_type == "CASH":
            if not bank_id:
                print("CASH account without bank: code: %s, org: %s" %
                      (code, org_id))
                bank_id = swift_banks[None]
            if bank_id not in cash_bank_accounts:
                acc = Account(code=None,
                              acc_type="CASH",
                              bank_id=bank_id,
                              owner_id=org_id,
                              fetched=True)
                s.add(acc)
                s.commit()
                cash_bank_accounts[bank_id] = acc.id
                s.close()
                return cash_bank_accounts[bank_id]

        acc = None
        if acc_type == "LOCAL":
            iban_acc = _get_iban_account_by_local_code(s, code)
            if iban_acc:
                acc = iban_acc
                code = iban_acc.code
                acc_type = "IBAN"

        acc = acc if acc else _get_account_by_code(s, code)
        if acc:
            if acc.organisation:

                if org_id and org_id != acc.owner_id:
                    if debug:                        print("Account %s with different owner: old: %s; new: %s"\
               %(code, acc.owner_id, org_id))
                    merge_organisations(acc.owner_id, org_id)
                    org_id = acc.owner_id
            elif org_id:
                acc.owner_id = org_id
        else:
            if not code:
                print("Account without code: bank: %d, org: %d, type: %s" %
                      (bank_id, org_id, acc_type))
            #bank = _get_bank(s, bank_id)
            acc = Account(code=code,
                          acc_type=acc_type,
                          bank_id=bank_id,
                          owner_id=org_id,
                          fetched=fetched)

            s.add(acc)

        s.commit()
        iban_accounts[code] = acc.id
        s.close()

    return iban_accounts[code]
Exemple #21
0
 def get(self):
     self.render('settings/accounts/index.html', rows=Account.select())