コード例 #1
0
ファイル: data.py プロジェクト: timur-glushan/tt
def test_data_delete():
  from models.account import Account
  from models.project import Project
  from models.report import Report
  from models.variable import Variable
  
  roles = {
    'administrator':[], 
    'privileged_manager':[], 
    'manager':[], 
    'privileged_member':[], 
    'member':[], 
  }
  rolesVariable = Variable.query.filter_by(name='roles', scope='permissions').first()
  roles.update(rolesVariable.value or {})
  
  for account in [account for account in Account.all() if account.id.startswith('test.')]:
    for role_id, members in roles.items():
      if account.id in members:
        roles[role_id].remove(account.id)
    Account.delete(account.id)
    flash('account deleted: '+str(account))
  
  rolesVariable.value = roles
  rolesVariable.save()
  
  for project in [project for project in Project.all() if project.id.startswith('TEST/')]:
    Project.delete(project.id)
    flash('project deleted: '+str(project))
  
  return redirect(url_for('test_data_index'))
コード例 #2
0
def __update_suffix(account_id, suffix):
    '''
        @description:
            - updates suffix in accounts table
    '''
    Account.update_suffix(account_id=account_id, suffix=suffix)
    Suffixes.set_suffix(account_id=account_id, suffix=suffix)
コード例 #3
0
ファイル: email_generation.py プロジェクト: vedsofie/SPNv2
    def setUp(self):
        #Turn off for sending emails
        email_sender.send_emails(False)
        self.act = Account(name='The Main Account')
        self.act.save()
        self.field_service_guy = User(Email='*****@*****.**',
                                      FirstName='Field_First_Name',
                                      LastName='Service_Last_Name',
                                      username='******',
                                      password='******',
                                      AccountID=self.act.id)
        self.field_service_guy.save()

        self.inactive_user = User(Email='*****@*****.**',
                                  FirstName='Field_First_Name',
                                  LastName='Service_Last_Name',
                                  username='******',
                                  password='******',
                                  AccountID=self.act.id,
                                  Active=False)

        os.environ['SOFIE_AUTO_FOLLOWING_USERS'] = ','.join(
            [self.field_service_guy.UserID, self.inactive_user.UserID])

        self.customer = User(Email='*****@*****.**',
                             FirstName='Customer_First_Name',
                             LastName='Customer_Last_Name',
                             username='******',
                             password='******',
                             AccountID=self.act.id)
        self.customer.save()

        email_sender.send_emails(False)
コード例 #4
0
ファイル: mimic_production.py プロジェクト: vedsofie/SPNv2
def create_accounts():
    account_ids = {}
    accounts = requests.get('http://www.sofienetwork.com/account/',
                            headers={'Accept': 'json',\
                                     'Authorization': authorization})
    accounts = accounts.json()

    for account in accounts:
        try:
            account_json = account
            account_id = account_json['id']
            del account_json['sequence_count']
            del account_json['id']
            del account_json['PrincipalInvestigatorID']
            del account_json['primary_contact_id']
            account = Account(**account_json)

            res = requests.get('http://www.sofienetwork.com/account/%i/logo/' % account_id, headers={'Authorization': authorization})
            account._image = res.content
            account.save()
            print account.id
            account_ids[account_id] = account.id
        except Exception as e:
            print str(e)
            db.session.rollback()
    return account_ids
コード例 #5
0
def verify_signup_email(code):

    success = False

    verifi = Verification.get(code=code)

    if verifi and verifi.account_id:

        # get associated account
        associated_account = Account.get(account_id=verifi.account_id)

        if associated_account:

            current_datetime = datetime.now()

            if current_datetime > verifi.date_expiry:
                raise VerificationExpired()

            # make sure account is not expired

            Account.set_active(account_id=verifi.account_id)
            # delete verification record
            verifi.destroy()

            success = verifi.account_id

    return success
コード例 #6
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache(
        )  # Prevent data from leaking between tests

        self.account = Account.get_or_insert("123",
                                             email="*****@*****.**",
                                             registered=True)
        self.account.put()

        self.account_banned = Account.get_or_insert(
            "456",
            email="*****@*****.**",
            registered=True,
            shadow_banned=True,
        )
        self.account_banned.put()

        event = Event(id="2016test",
                      name="Test Event",
                      event_short="Test Event",
                      year=2016,
                      event_type_enum=EventType.OFFSEASON)
        event.put()
        self.match = Match(id="2016test_f1m1",
                           event=ndb.Key(Event, "2016test"),
                           year=2016,
                           comp_level="f",
                           set_number=1,
                           match_number=1,
                           alliances_json='')
        self.match.put()
コード例 #7
0
    def user_email_to_id(cls, user_email):
        """
        Returns the user id for a given email address (or None if invalid)
        workaround for this bug: https://code.google.com/p/googleappengine/issues/detail?id=8848
        solution from: http://stackoverflow.com/questions/816372/how-can-i-determine-a-user-id-based-on-an-email-address-in-app-engine
        """
        cache_key = 'PushHelper.user_email_to_id():{}'.format(user_email)
        user_id = memcache.get(cache_key)
        if user_id is None:
            u = users.User(user_email)
            key = MobileUser(user=u).put()
            obj = key.get()
            user_id = obj.user.user_id()
            key.delete()
            memcache.set(cache_key, user_id, 60 * 10)

        if Account.get_by_id(user_id) is None:
            # Create an account for this user
            nickname = user_email.split('@')[0]
            Account(id=user_id,
                    email=user_email,
                    nickname=nickname,
                    display_name=nickname,
                    registered=False).put()

        return user_id
コード例 #8
0
ファイル: testing.py プロジェクト: carylF/Caryl-Ford
  def create_account(cls, name=None):
    if not name:
      name = cls.DEFAULT_COMPANY_NAME

    account = Account(name=name)
    account.put()
    return account
コード例 #9
0
 def load_current_account(self):
     '''Loads current user from the local thread and sets it as self.current_account for easier handler access to it.
 Along with that, also sets if the request came from taskqueue or cron, based on app engine headers.
 '''
     if self.current_account is None and self.autoload_current_account:
         from models.account import Account
         unsecure = self.secure_cookie_get(settings.COOKIE_AUTH_KEY)
         headers = self.request.headers
         if not unsecure:
             unsecure = headers.get('Authorization')
         Account.set_current_account_from_access_token(unsecure)
         current_account = Account.current_account()
         current_account.set_taskqueue(
             headers.get('X-AppEngine-QueueName', None) != None
         )  # https://developers.google.com/appengine/docs/python/taskqueue/overview-push#Python_Task_request_headers
         current_account.set_cron(
             headers.get('X-Appengine-Cron', None) != None
         )  # https://developers.google.com/appengine/docs/python/config/cron#Python_app_yaml_Securing_URLs_for_cron
         current_account.set_location_data({
             '_country':
             headers.get('X-AppEngine-Country'),
             '_city':
             headers.get('X-AppEngine-City'),
             '_region':
             headers.get('X-AppEngine-Region')
         })
         self.current_account = current_account
コード例 #10
0
    def _create_account(self, new_account):
        """
        To create new accounts for a customer, check if the customer already has the selected account type.
        If customer does not already have the selected account type, will create new account with initialized balance

        Args:
            new_account (str): the user id of the customer

        Returns:
             bool:  True if user id exists, will create a new chequing/saving account
                    False if user id does not exists, will print error message
        """
        if User.check_existing_user(new_account['account_holder']):
            user = User(new_account['account_holder'])
            if new_account['account_type'] in user.accounts.keys():
                self.session.output({
                    'error':
                        'user already has an account of this type. Returning to main menu.\n'},
                    '[ INVALID ACCOUNT TYPE ERROR ]')
                self._navigate_mainmenu(1)
                return False
            else:
                new_account_created = Account(userid=user.user_id, account_type=new_account['account_type'],
                                              balance=new_account['initial_balance'])
                self.session.output(new_account_created.get_info(),
                                    '\n[ New account created for user {} ]'.format(new_account['account_holder']))
                return True
        else:
            self.session.output({'invalid_account_holder': 'please enter valid account holder id\n'},
                                '\n[ USER ID ERROR ]')
            return False
コード例 #11
0
    def loginUser(self):
        self.testbed.setup_env(user_email="*****@*****.**",
                               user_id="123",
                               user_is_admin='0',
                               overwrite=True)

        Account.get_or_insert("123", email="*****@*****.**", registered=True)
コード例 #12
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.account = Account.get_or_insert(
            "123",
            email="*****@*****.**",
            registered=True)
        self.account.put()

        self.account_banned = Account.get_or_insert(
            "456",
            email="*****@*****.**",
            registered=True,
            shadow_banned=True,
        )
        self.account_banned.put()

        event = Event(id="2016test", name="Test Event", event_short="Test Event", year=2016, event_type_enum=EventType.OFFSEASON)
        event.put()
        self.match = Match(id="2016test_f1m1", event=ndb.Key(Event, "2016test"), year=2016, comp_level="f", set_number=1, match_number=1, alliances_json='')
        self.match.put()
コード例 #13
0
    def get(self, page_num=0):
        self._require_admin()
        page_num = int(page_num)

        num_users = Account.query().count()
        max_page = num_users / self.PAGE_SIZE

        if page_num <= max_page:
            offset = self.PAGE_SIZE * page_num
        else:
            page_num = 0
            offset = 0
        users = Account.query().order(Account.created).fetch(self.PAGE_SIZE,
                                                             offset=offset)

        self.template_values.update({
            "num_users":
            num_users,
            "users":
            users,
            "page_num":
            page_num,
            "page_labels": [p + 1 for p in xrange(max_page + 1)],
        })

        path = os.path.join(os.path.dirname(__file__),
                            '../../templates/admin/user_list.html')
        self.response.out.write(template.render(path, self.template_values))
コード例 #14
0
ファイル: testing.py プロジェクト: carylF/Perfectly-Timed
    def create_account(cls, name=None):
        if not name:
            name = cls.DEFAULT_COMPANY_NAME

        account = Account(name=name)
        account.put()
        return account
コード例 #15
0
def index():
    if request.cookies.get("session"):
        acc = Account()
        v = acc.getAccountIdBySession(request.cookies.get('session'))
        accid = v['id']
        ro = Role()
        u = ro.getRoleByAccountId(accid)
        return render_template("authen/index.html", v=v, u=u)
    return redirect("/authen/signin")
コード例 #16
0
def role2(id):
    acc = Account()
    x = acc.getAccountsById(id)
    #  Thieu
    ro = Role()
    #  Dictionary
    b = ro.getRolesByAccount(id)
    #  print('--------', b)
    return render_template('account/role2.html', a = x, arr = b)
コード例 #17
0
    def create_account(self, account):
        sql = "INSERT INTO account VALUES(DEFAULT, %s, %s, %s, %s, %s) RETURNING *"
        cursor = connection.cursor()
        cursor.execute(sql,
                       (account.account_type, account.amt_dep, account.amt_withdraw, account.status, account.userid))
        connection.commit()
        record = cursor.fetchone()

        return Account(Account(record[0], record[1], record[2], float(record[3]), record[4]))
コード例 #18
0
ファイル: account.py プロジェクト: timur-glushan/tt
def install_account_data():
  """Create all the required accounts if not defined"""
  from application import db
  from models.account import Account, Group
  
  accountList = [
    {
      'alias': 'timur.glushan',
      'first_name': 'Timur',
      'last_name': 'Glushan',
      'email': '*****@*****.**',
      'info': None,
      'group': Group.query.filter_by(alias='administrator').first()
    }
  ]
  
  for accountItem in accountList:
    account = Account.query.filter_by(alias=accountItem['alias']).first()
    if not account:
      account = Account()
      account.alias = accountItem['alias']
      account.first_name = accountItem['first_name']
      account.last_name = accountItem['last_name']
      account.email = accountItem['email']
      account.info = accountItem['info']
      account.group = accountItem['group']
      account.save()
コード例 #19
0
ファイル: field_service_flow.py プロジェクト: vedsofie/SPNv2
    def setUp(self):
        generate_db.drop_database()
        generate_db.generate_database()
        self.generate_roles()
        #Turn off for sending emails
        email_sender.send_emails(False)
        self.act = Account(name='The Sofie Account')
        self.act.save()
        self.field_service_guy = User(Email='*****@*****.**',
                                 FirstName='Field_First_Name',
                                 LastName='Service_Last_Name',
                                 username='******',
                                 password='******',
                                 AccountID=self.act.id,
                                 RoleID=self.super_admin.RoleID)
        self.field_service_guy.save()


        self.inactive_user = User(Email='*****@*****.**',
                                    FirstName='Field_First_Name',
                                    LastName='Service_Last_Name',
                                    username='******',
                                    password='******',
                                    AccountID=self.act.id)

        self.inactive_user.save()

        os.environ['SOFIE_AUTO_FOLLOWING_USERS'] = ','.join([str(self.field_service_guy.UserID),
                                                             str(self.inactive_user.UserID)])


        #os.environ['SOFIE_AUTO_FOLLOWING_USERS'] = str(self.field_service_guy.UserID)

        self.customer_act = Account(name='The Customer')
        self.customer_act.save()

        self.customer = User(Email='*****@*****.**',
                        FirstName='Customer_First_Name',
                        LastName='Customer_Last_Name',
                        username='******',
                        password='******',
                        AccountID=self.customer_act.id,
                        RoleID=self.chemist.RoleID)
        self.customer.save()

        self.customer_team_member = User(Email='*****@*****.**',
                        FirstName='Customer_First_Name',
                        LastName='Customer_Last_Name',
                        username='******',
                        password='******',
                        AccountID=self.customer_act.id,
                        RoleID=self.chemist.RoleID)
        self.customer_team_member.save()

        del emails_skipped[:]
コード例 #20
0
def doSignup():
    id = randomStr(16)
    usr = request.form.get('usr')
    pwd = request.form.get('pwd') + '!@$*&#' + usr  #tranh crack pw
    eml = request.form.get('eml')
    pwd = md5(pwd.encode())
    acc = Account()
    ret = acc.add((id, usr, pwd.digest(), eml))
    if ret > 0:
        return redirect('/auth/signin')
    return render_template('auth/signup.html', err='Username exists')
コード例 #21
0
def doSignup():
    id = randomString(16)
    usr = request.form.get("usr")
    pwd = request.form.get("pwd") + '#$%^&*$@' + usr
    eml = request.form.get("eml")
    pwd = md5(pwd.encode())
    acc = Account()
    ret = acc.add((id, usr, pwd.digest(), eml))
    if ret > 0:
        return redirect("/authen/signin")
    return render_template("authen/signup.html", err="Username Existed")
    def loginUser(self):
        self.testbed.setup_env(
            user_email="*****@*****.**",
            user_id="123",
            user_is_admin='0',
            overwrite=True)

        Account.get_or_insert(
            "123",
            email="*****@*****.**",
            registered=True)
コード例 #23
0
    def all_account(self):
        sql = "SELECT * FROM account"
        cursor = connection.cursor()
        cursor.execute(sql)
        records = cursor.fetchall()
        account_list = []
        for record in records:
            account = Account(record[0], record[1], float(record[2]), float(record[3]), record[4])
            account_list.append(account.json())

        return account_list
コード例 #24
0
    def test_transfer(self):
        account = Account(account_id=0, balance=500, client_id=0)
        account2 = Account(account_id=1, balance=0, client_id=0)

        amount = 250

        account.balance -= amount
        account2.balance += amount

        assert (account.balance) == 250
        assert (account2.balance) == 250
コード例 #25
0
class TestMatchSuggestionAccepter(unittest2.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache(
        )  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.account = Account(email="*****@*****.**", )
        self.account.put()

        self.suggestion = Suggestion(
            author=self.account.key,
            contents_json="{\"youtube_videos\":[\"123456\"]}",
            target_key="2012ct_qm1",
            target_model="match")
        self.suggestion.put()

        self.event = Event(
            id="2012ct",
            event_short="ct",
            year=2012,
            event_type_enum=EventType.REGIONAL,
        )
        self.event.put()

        self.match = Match(
            id="2012ct_qm1",
            alliances_json=
            """{"blue": {"score": -1, "teams": ["frc3464", "frc20", "frc1073"]}, "red": {"score": -1, "teams": ["frc69", "frc571", "frc176"]}}""",
            comp_level="qm",
            event=self.event.key,
            year=2012,
            set_number=1,
            match_number=1,
            team_key_names=[
                u'frc69', u'frc571', u'frc176', u'frc3464', u'frc20',
                u'frc1073'
            ],
            youtube_videos=["abcdef"])
        self.match.put()

    def tearDown(self):
        self.testbed.deactivate()

    def test_accept_suggestions(self):
        MatchSuggestionAccepter.accept_suggestions([self.suggestion])

        match = Match.get_by_id("2012ct_qm1")
        self.assertTrue("abcdef" in match.youtube_videos)
        self.assertTrue("123456" in match.youtube_videos)
コード例 #26
0
def update_profile(account_id, firstname, lastname, address, company):
    firstname = sanitize_html(firstname)
    lastname = sanitize_html(lastname)
    address = sanitize_html(address)
    company = sanitize_html(company)

    Account.update(account_id=account_id,
                   firstname=firstname,
                   lastname=lastname,
                   address=address,
                   company=company)
コード例 #27
0
 async def put(self, *args, **kwargs):
     account_id = kwargs.get('id')
     account = await Account.objects.get(id=account_id)
     if not account:
         raise ValidationError()
     validated = Account.validate_values(self.data)
     updated = Account.update(account, validated)
     await updated.save()
     self.write_json({
         'result': updated.to_dict()
     })
コード例 #28
0
    def get_all_objects(self):
        sql = "SELECT * FROM accounts"
        cursor = connection.cursor()
        cursor.execute(sql)
        records = cursor.fetchall()

        account_list = []
        for record in records:
            account = Account(record[0], record[1], record[2])
            account_list.append(account.json())

        return account_list
コード例 #29
0
ファイル: controller.py プロジェクト: advaithb97/Final
def create_user():
    # get data from request
    data = request.get_json()
    # TODO: see if account exists
    key = Account.random_api_key()
    new_user = Account(data.get("username"), data.get("password"), key)
    new_user.insert()
    # save new account account.save()
    return jsonify({
        "session_id": new_user.api_key,
        "username": new_user.username
    })
コード例 #30
0
    def get_all_objects_from_client(client_id):
        sql = "SELECT * FROM accounts WHERE client_id=%s"
        cursor = connection.cursor()
        cursor.execute(sql, [client_id])
        records = cursor.fetchall()

        account_list = []
        for record in records:
            account = Account(record[0], record[1], record[2])
            account_list.append(account.json())

        return account_list
class TestMatchSuggestionAccepter(unittest2.TestCase):
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.testbed.init_taskqueue_stub(root_path=".")

        self.account = Account(
            email="*****@*****.**",
        )
        self.account.put()

        self.suggestion = Suggestion(
            author=self.account.key,
            contents_json="{\"youtube_videos\":[\"123456\"]}",
            target_key="2012ct_qm1",
            target_model="match"
        )
        self.suggestion.put()

        self.event = Event(
          id="2012ct",
          event_short="ct",
          year=2012,
          event_type_enum=EventType.REGIONAL,
        )
        self.event.put()

        self.match = Match(
            id="2012ct_qm1",
            alliances_json="""{"blue": {"score": -1, "teams": ["frc3464", "frc20", "frc1073"]}, "red": {"score": -1, "teams": ["frc69", "frc571", "frc176"]}}""",
            comp_level="qm",
            event=self.event.key,
            year=2012,
            set_number=1,
            match_number=1,
            team_key_names=[u'frc69', u'frc571', u'frc176', u'frc3464', u'frc20', u'frc1073'],
            youtube_videos=["abcdef"]
        )
        self.match.put()

    def tearDown(self):
        self.testbed.deactivate()

    def test_accept_suggestions(self):
        MatchSuggestionAccepter.accept_suggestion(self.match, self.suggestion)

        match = Match.get_by_id("2012ct_qm1")
        self.assertTrue("abcdef" in match.youtube_videos)
        self.assertTrue("123456" in match.youtube_videos)
コード例 #32
0
def role(id):
    acc = Account()
    ro = Role()
    air = AccountInRole()
    b = air.getRoleByAccount(id)
    li = []
    for v in b:
        li.append(v[0])
    return render_template('account/role.html',
                           a=acc.getAccountById(id),
                           arr=ro.getRoles(),
                           brr=li)
コード例 #33
0
    def login(self, username, password, login_type):
        phone = username
        imeiid = md5(username)[0:15].upper()
        deviceid = md5(username)[0:16].upper()
        pwd = password

        if login_type == 'Email':
            body = dict(deviceid=deviceid,
                        imeiid=imeiid,
                        mail=phone,
                        pwd=pwd,
                        account_type='5',
                        phone_area='Email')
            sign = GetSign(body)
            body = dict(deviceid=deviceid,
                        imeiid=imeiid,
                        mail=phone,
                        pwd=pwd,
                        account_type='5',
                        phone_area='Email',
                        sign=sign)
        elif login_type == 'Phone':
            body = dict(deviceid=deviceid,
                        imeiid=imeiid,
                        phone=phone,
                        pwd=pwd,
                        account_type='4')
            sign = GetSign(body)
            body = dict(deviceid=deviceid,
                        imeiid=imeiid,
                        phone=phone,
                        pwd=pwd,
                        account_type='4',
                        sign=sign)

        url = 'https://account.onethingpcs.com/user/login?appversion=1.6.2'
        cookies = None
        r = requests.post(url=url,
                          data=body,
                          verify=False,
                          headers=headers,
                          cookies=cookies,
                          timeout=10)
        sessionid = r.cookies.get('sessionid')
        userid = r.cookies.get('userid')
        result = json.loads(r.content.decode('unicode-escape'))

        account = Account()
        if result['iRet'] == 0:
            account.sessionid = sessionid
            account.user_id = userid
        return account
コード例 #34
0
def doSignin():
    usr = request.form.get('usr')
    pwd = request.form.get('pwd') + '!@$*&#' + usr  #phai giong voi signup
    pwd = md5(pwd.encode())
    acc = Account()
    v = acc.getAccount((usr, pwd.digest()))
    if v:
        session[
            'userinfo'] = v  #Session variables remember data from request to request, and specifically for each user. Account info is one type of data stored in a session object.
    else:
        return render_template('auth/signin.html',
                               err='Wrong Username or Password')
    return redirect('/auth')
コード例 #35
0
ファイル: account.py プロジェクト: moluwole/FastPay_API
    def get(self):
        data = Account.parser.parse_args()

        user_id = data['user_id']

        user = AccountModel.find_by_user_id(user_id)
        # print user
        if user:
            return {
                "data": AccountModel.return_json(user.user_id, user.balance)
            }, 200
        else:
            return {"message": "No Account Associated yet"}, 404
コード例 #36
0
def edit_password( account_id, old_password, new_password ):
    '''
    main feature function to change password
    @raise InvalidOldPassword: if old password is not equal to current password
    '''
    
    
    
    # invalid format of old password is considered invalid
    # to save processing
    if len(old_password) < 8 or len(old_password) > 32 :
        raise InvalidOldPassword('invalid old password. too short / too long')
    
    if password_tool.is_valid_password_format( password=old_password ) is not True :
        raise InvalidOldPassword('invalid old password. bad format') 
    
    # beyond this point we assume that the old password is likely in valid format
    #--- ----------------------------------------------------------------
    
    # before encrypting, new password length
    if len(new_password) < 8 or len(new_password) > 32 :
        
        raise password_tool.InvalidPasswordLength('invalid password length') 
    
    
    if password_tool.is_valid_password_format( password=new_password ) is not True :
        raise password_tool.InvalidPasswordFormat
    
    # check "new password" format 
    
    encrypted_old_password = password_tool.encrypt( password=old_password )
    encrypted_new_password = password_tool.encrypt( password=new_password )
    
    
    account_object = Account.get( account_id=account_id )
    
    if not account_object:
        raise Account.AccountNotExist('account does not exist')
        
    is_same = account_object.check_same_old_password( password= encrypted_old_password )
    
    if is_same and old_password == new_password:
        raise SameToOldPassword()
    
    if is_same is not True :
        raise InvalidOldPassword('invalid old password. not match')
    
    # password should be ok at this point
    result = account_object.save_new_password( new_password=encrypted_new_password )
    
    return result
コード例 #37
0
    def get(self):
        self._require_admin()

        self.template_values['memcache_stats'] = memcache.get_stats()

        # Gets the 5 recently created users
        users = Account.query().order(-Account.created).fetch(5)
        self.template_values['users'] = users

        # Retrieves the number of pending suggestions
        video_suggestions = Suggestion.query().filter(Suggestion.review_state == Suggestion.REVIEW_PENDING).count()
        self.template_values['video_suggestions'] = video_suggestions

        # version info
        try:
            fname = os.path.join(os.path.dirname(__file__), '../../version_info.json')

            with open(fname, 'r') as f:
                data = json.loads(f.read().replace('\r\n', '\n'))

            self.template_values['git_branch_name'] = data['git_branch_name']
            self.template_values['build_time'] = data['build_time']

            commit_parts = re.split("[\n]+", data['git_last_commit'])
            self.template_values['commit_hash'] = commit_parts[0].split(" ")
            self.template_values['commit_author'] = commit_parts[1]
            self.template_values['commit_date'] = commit_parts[2]
            self.template_values['commit_msg'] = commit_parts[3]

        except Exception, e:
            logging.warning("version_info.json parsing failed: %s" % e)
            pass
コード例 #38
0
ファイル: jobs.py プロジェクト: objcguy/faxrobot
def list():
    """List faxes"""

    v = request.values.get

    account_id = Account.authorize(v('api_key'))
    if not account_id:
        return jsonify(api_error('API_UNAUTHORIZED')), 401

    try:
        page = int(v('page', 1))
        if page < 1:
            raise
    except:
        return jsonify(api_error('JOBS_BAD_PAGINATION_VALUE')), 400

    if v('filter'):
        jobs = Job.query.filter_by(account_id= account_id, status= v('filter'))
    else:
        jobs = Job.query.filter_by(account_id= account_id)
    jobs = jobs.order_by(Job.create_date.desc()).paginate(page, 20, False)

    return jsonify({
        'page':     jobs.page,
        'pages':    jobs.pages,
        'per_page': jobs.per_page,
        'total':    jobs.total,
        'has_next': jobs.has_next,
        'has_prev': jobs.has_prev,
        'jobs':     [job.public_data() for job in jobs.items]
    })
コード例 #39
0
ファイル: jobs.py プロジェクト: objcguy/faxrobot
def restart(access_key):
    """Restarts a failed job"""

    account_id = Account.authorize(request.values.get('api_key'))

    jobs = Job.query.filter_by(access_key = access_key)
    job = jobs.first()
    
    if job == None or not account_id or not account_id == job.account_id:
        return jsonify(api_error('API_UNAUTHORIZED')), 401

    if not job.failed:
        return jsonify(api_error('JOBS_NOT_RESTARTABLE')), 400

    if job.data_deleted:
        return jsonify(api_error('JOBS_DATA_DELETED')), 400

    ip = fix_ip(request.headers.get('x-forwarded-for', request.remote_addr))

    job.ip_address = ip
    job.failed = 0
    job.fail_code = 0
    job.status = 'queued'
    db.session.commit()
    redis_conn = Redis.from_url(os.environ.get('REDIS_URI'))
    q = Queue(connection=redis_conn)
    q.enqueue_call(func=send_fax, args=(job.id,), timeout=600)

    return jsonify(job.public_data())
コード例 #40
0
 def account(self):
     if self._account is None:
         self._account = Account.get_or_insert(
             self.user.user_id(),
             email = self.user.email(),
             nickname = self.user.nickname())
     return self._account
コード例 #41
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        self.testbed.init_taskqueue_stub(root_path=".")

        self.account = Account(email="*****@*****.**")
        self.account.put()

        self.suggestion = Suggestion(
            author=self.account.key,
            contents_json='{"youtube_videos":["123456"]}',
            target_key="2012ct_qm1",
            target_model="match",
        )
        self.suggestion.put()

        self.event = Event(id="2012ct", event_short="ct", year=2012, event_type_enum=EventType.REGIONAL)
        self.event.put()

        self.match = Match(
            id="2012ct_qm1",
            alliances_json="""{"blue": {"score": -1, "teams": ["frc3464", "frc20", "frc1073"]}, "red": {"score": -1, "teams": ["frc69", "frc571", "frc176"]}}""",
            comp_level="qm",
            event=self.event.key,
            game="frc_2012_rebr",
            set_number=1,
            match_number=1,
            team_key_names=[u"frc69", u"frc571", u"frc176", u"frc3464", u"frc20", u"frc1073"],
            youtube_videos=["abcdef"],
        )
        self.match.put()
コード例 #42
0
ファイル: incoming.py プロジェクト: lyonbros/faxrobot
def list():
    """List faxes"""

    v = request.values.get

    account_id = Account.authorize(v('api_key'))
    if not account_id:
        return jsonify(api_error('API_UNAUTHORIZED')), 401

    try:
        page = int(v('page', 1))
        if page < 1:
            raise
    except:
        return jsonify(api_error('INCOMING_BAD_PAGINATION_VALUE')), 400


    faxes = IncomingFax.query.filter_by(account_id= account_id)
    faxes = faxes.order_by(IncomingFax.create_date.desc()).paginate(page, 20,
            False)

    return jsonify({
        'page':     faxes.page,
        'pages':    faxes.pages,
        'per_page': faxes.per_page,
        'total':    faxes.total,
        'has_next': faxes.has_next,
        'has_prev': faxes.has_prev,
        'faxes':    [fax.public_data() for fax in faxes.items]
    })
コード例 #43
0
ファイル: incoming.py プロジェクト: lyonbros/faxrobot
def delete():
    """Delete an incoming fax"""

    from library.mailer import email_admin
    from boto.s3.connection import S3Connection
    from boto.s3.key import Key

    v = request.values.get

    access_key = v('access_key')
    account_id = Account.authorize(v('api_key'))

    if not account_id:
        return jsonify(api_error('API_UNAUTHORIZED')), 401

    faxes = IncomingFax.query.filter_by(access_key = access_key)
    fax = faxes.first()

    db.session.delete(fax)
    db.session.commit()

    try:
        conn = S3Connection(os.environ.get('AWS_ACCESS_KEY'),
                            os.environ.get('AWS_SECRET_KEY'))
        bucket = conn.get_bucket(os.environ.get('AWS_S3_BUCKET'))
        k = Key(bucket)
        k.key ='incoming/' + access_key + '/fax.pdf'
        k.delete()
    except:
        email_admin("AWS S3 connect fail for fax deletion: %s" % access_key)

    return jsonify({"success": True})
 def givePermission(self):
     account = Account.get_or_insert(
         "123",
         email="*****@*****.**",
         registered=True)
     account.permissions.append(AccountPermissions.MUTATE_DATA)
     account.put()
コード例 #45
0
ファイル: accounts.py プロジェクト: lyonbros/faxrobot
def transactions():
    """List transactions"""

    v = request.values.get

    page = int(v('page', 1))

    account_id = Account.authorize(v('api_key'))
    if not account_id:
        return jsonify(api_error('API_UNAUTHORIZED')), 401

    account = Account.query.get(account_id)

    res = Transaction.query.filter_by(account_id= account_id)
    res = res.order_by(Transaction.create_date.desc()).paginate(page, 15, False)

    return jsonify({
        'page':         res.page,
        'pages':        res.pages,
        'per_page':     res.per_page,
        'total':        res.total,
        'has_next':     res.has_next,
        'has_prev':     res.has_prev,
        'transactions': [trans.public_data() for trans in res.items]
    })
コード例 #46
0
ファイル: accounts.py プロジェクト: lyonbros/faxrobot
def remove_card():
    """Removes stored credit card info from the account"""

    from datetime import datetime
    import json
    import stripe

    stripe.api_key = os.environ.get('STRIPE_SECRET_KEY')

    account_id = Account.authorize(request.values.get('api_key'))
    if not account_id:
        return jsonify(api_error('API_UNAUTHORIZED')), 401

    account = Account.query.get(account_id)

    if account.stripe_token and account.stripe_card:
        try:
            customer = stripe.Customer.retrieve(account.stripe_token)
            customer.sources.retrieve(account.stripe_card).delete()
        except:
            pass # oh well, whatever. f**k it.

    account.stripe_token = None
    account.stripe_card = None
    account.last4 = None
    account.auto_recharge = 0
    account.mod_date = datetime.now()
    db.session.commit()

    return jsonify(account.public_data())
コード例 #47
0
ファイル: report.py プロジェクト: timur-glushan/tt
 def listActiveReports(cls, start_date=None, end_date=None, accounts=None, components=None):
   from models.account import Account
   from models.project import Project, Component
   from models.report import Report
   
   query = Report.query\
     .filter(~Report.status.in_(Report._r(Report.STATUS_DELETED)))\
     .join(Report.account)\
     .filter(~Account.status.in_(Account._r(Account.STATUS_DELETED)))\
     .join(Report.component, aliased=True)\
     .filter(~Component.status.in_(Component._r(Component.STATUS_DELETED)))\
     .join(Report.project, aliased=True)\
     .filter(~Project.status.in_(Project._r(Project.STATUS_DELETED)))
   
   if start_date:
     query = query.filter(Report.due_date>=start_date)
   if end_date:
     query = query.filter(Report.due_date<=end_date)
   if accounts:
     query = query.filter(Report.account_id.in_(accounts))
   if components:
     query = query.filter(Report.component_id.in_(components))
   
   query = query.order_by(Account.first_name, Account.last_name, Account.alias, Report.due_date, Report.created)
   
   return query.all()
コード例 #48
0
ファイル: permissions.py プロジェクト: timur-glushan/tt
def test_permissions_all_accounts_groups():
  from models.account import Account
  
  title = 'Testing | Permissions | Listed per-account-role permissions'
  
  data = '<table class="table" width="100%">'
  employees = [employee for employee in Account.all()]
  roles = g._var(name='roles', scope='permissions', default={}).keys()
  data = data + '<tr>'
  data = data + '<th>&nbsp;</th>'
  for role in roles:
    data = data + '<th>'+role+'</th>'
  data = data + '</tr>'
  
  for employee in employees:
    data = data + '<tr>'
    data = data + '<th>'+employee+'</th>'
    for role in roles:
      is_permitted = app.access('role', account=employee, role_id=role)
      data = data + (is_permitted and '<td class="alert alert-success">yes</td>' or '<td class="alert alert-danger">no</td>')
    data = data + '</tr>'
  
  data = data + '</table>'
  data = Markup(data)
  
  return render_template( 'test/index.html', title=title, data=data )
コード例 #49
0
ファイル: account.py プロジェクト: timur-glushan/tt
 def listActiveAccounts(cls):
   from models.account import Account
   
   return Account.query\
     .filter(~Account.status.in_(Account._r(Account.STATUS_DELETED)))\
     .order_by(Account.first_name, Account.last_name, Account.alias)\
     .all()
コード例 #50
0
 def find_one(cls, collection, field, value):
     if collection == 'customers':
         return Customer.fromjson(cls.db[collection].find_one({field: value}))
     if collection == 'prepaids':
         return Prepaid.fromjson(cls.db[collection].find_one({field: value}))
     if collection == 'postpaids':
         return Postpaid.fromjson(cls.db[collection].find_one({field: value}))
     if collection == 'setups':
         return Setup.fromjson(cls.db[collection].find_one({field: value}))
     if collection == 'how_to_pays':
         return HowToPay.fromjson(cls.db[collection].find_one({field: value}))
     if collection == 'how_to_topups':
         return HowToTopup.fromjson(cls.db[collection].find_one({field: value}))
     if collection == 'accounts':
         account = cls.db[collection].find_one({field: value})
         if account is not None:
             return Account.fromjson(cls.find_by_id('customers', account['customer']), cls.find_by_id('prepaids', account['package']), account)
         else:
             return None
     if collection == 'bills':
         bill = cls.db[collection].find({field: value}).sort('payment_date', -1)[0]
         if bill is not None:
             return Bill.fromjson(bill, cls.find_by_id('customers', bill['customer']), cls.find_by_id('postpaids', bill['package']))
         else:
             return None
コード例 #51
0
    def get(self):
        self._require_admin()

        self.template_values['memcache_stats'] = memcache.get_stats()
        self.template_values['databasequery_stats'] = {
            'hits': sum(filter(None, [memcache.get(key) for key in DatabaseQuery.DATABASE_HITS_MEMCACHE_KEYS])),
            'misses': sum(filter(None, [memcache.get(key) for key in DatabaseQuery.DATABASE_MISSES_MEMCACHE_KEYS]))
        }

        # Gets the 5 recently created users
        users = Account.query().order(-Account.created).fetch(5)
        self.template_values['users'] = users

        self.template_values['suggestions_count'] = Suggestion.query().filter(
            Suggestion.review_state == Suggestion.REVIEW_PENDING).count()

        # version info
        try:
            fname = os.path.join(os.path.dirname(__file__), '../../version_info.json')

            with open(fname, 'r') as f:
                data = json.loads(f.read().replace('\r\n', '\n'))

            self.template_values['git_branch_name'] = data['git_branch_name']
            self.template_values['build_time'] = data['build_time']

            commit_parts = re.split("[\n]+", data['git_last_commit'])
            self.template_values['commit_hash'] = commit_parts[0].split(" ")
            self.template_values['commit_author'] = commit_parts[1]
            self.template_values['commit_date'] = commit_parts[2]
            self.template_values['commit_msg'] = commit_parts[3]

        except Exception, e:
            logging.warning("version_info.json parsing failed: %s" % e)
            pass
コード例 #52
0
ファイル: base.py プロジェクト: alevy/Dunbarify
 def __init__(self):
   super(BaseController, self).__init__()
   self.user = users.get_current_user()
   self.vars["user"] = self.user
   self.account = None
   if self.user:
     self.vars["logout_url"] = users.create_logout_url("/")
     self.vars["account"] = self.account = Account.get_by_user(self.user)
コード例 #53
0
    def post(self, user_id):
        self._require_admin()
        user = Account.get_by_id(user_id)

        user.display_name = self.request.get("display_name")
        user.put()

        self.redirect("/admin/user/" + user_id)
コード例 #54
0
    def get(self, user_id):
        self._require_admin()
        user = Account.get_by_id(user_id)
        self.template_values.update({
            "user": user
        })

        path = os.path.join(os.path.dirname(__file__), '../../templates/admin/user_edit.html')
        self.response.out.write(template.render(path, self.template_values))
コード例 #55
0
 def account(self):
     if self._account is None and self.user:
         self._account = Account.get_or_insert(
             self.user.user_id(),
             email = self.user.email(),
             nickname = self.user.nickname(),
             registered = False,
             display_name = self.user.nickname())
     return self._account
コード例 #56
0
ファイル: accounts.py プロジェクト: lyonbros/faxrobot
def get():
    """Gets the account information, provided a correct api_key is specified."""
    account_id = Account.authorize(request.values.get('api_key'))
    if account_id == None:
        return jsonify(api_error('API_UNAUTHORIZED')), 401

    account = Account.query.get(account_id)

    return jsonify(account.public_data())
コード例 #57
0
    def get(self):
        self._require_admin()
        users = Account.query().order(Account.created).fetch(10000)

        self.template_values.update({
            "users": users,
        })

        path = os.path.join(os.path.dirname(__file__), '../../templates/admin/user_list.html')
        self.response.out.write(template.render(path, self.template_values))
コード例 #58
0
 def post(self):
     self._require_admin()
     user_email = self.request.get('email')
     if not user_email:
         self.abort(404)
     users = Account.query(Account.email == user_email).fetch()
     if not users:
         self.abort(404)
     user = users[0]
     self.redirect('/admin/user/edit/{}'.format(user.key.id()))
コード例 #59
0
 def find_by_id(cls, collection, id):
     if collection == 'customers':
         return Customer.fromjson(cls.db[collection].find_one({'_id': ObjectId(id)}))
     if collection == 'prepaids':
         return Prepaid.fromjson(cls.db[collection].find_one({'_id': ObjectId(id)}))
     if collection == 'postpaids':
         return Postpaid.fromjson(cls.db[collection].find_one({'_id': ObjectId(id)}))
     if collection == 'accounts':
         return Account.fromjson(cls.db[collection].find_one({'_id': ObjectId(id)}))
     if collection == 'bills':
         return Bill.fromjson(cls.db[collection].find_one({'_id': ObjectId(id)}))
コード例 #60
0
    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()
        ndb.get_context().clear_cache()  # Prevent data from leaking between tests

        self.account = Account.get_or_insert(
            "123",
            email="*****@*****.**",
            registered=True)
        self.account.put()

        self.account_banned = Account.get_or_insert(
            "456",
            email="*****@*****.**",
            registered=True,
            shadow_banned=True,
        )
        self.account_banned.put()