示例#1
0
 def get(self, username=None):
     try:
         checkout_info = payment.get_checkout_data(self.user, GlobalConfig.get_configs())
         if checkout_info == 'free':
             self.redirect('/', abort=True)
     except payment.coupon.InActiveCouponExpcetion as e:
         lr = tt_logging.construct_log(msg_short='Error Processing User\'s Checkout',
                                       msg=e.message,
                                       log_type=tt_logging.PAYMENT, request=self.request, request_user=self.user)
         log.error(lr['dict_msg']['msg'], extra=lr)
         raise HttpErrorException.bad_request('There was an error processing your checkout')
     except Exception as e:
         lr = tt_logging.construct_log(msg_short='Error Processing User\'s Checkout',
                                       msg=e.message,
                                       log_type=tt_logging.PAYMENT, request=self.request, request_user=self.user)
         log.error(lr['dict_msg']['msg'], extra=lr)
         raise
     template_data = {
         'title': 'thinkTank Checkout',
         'nav_bar_title': 'thinkTank',
         'domain': self.request.host_url,
         'merchant': self.user.merchant,
         'payment_plan': checkout_info['items']['pay_plan'],
         'jwt_token': checkout_info['jwt_token'],
         'production': server.PRODUCTION,
     }
     if 'adjusted_plan' in checkout_info['items']:
         template_data['adjusted_plan'] = checkout_info['items']['adjusted_plan']
     template_index = JINJA_ENVIRONMENT.get_template('checkout.html')
     self.response.write(template_index.render(template_data))
示例#2
0
    def get(self):
        gc = GlobalConfig.get_configs()
        if gc.allow_user_registration:
            self.redirect('/', abort=True)

        template_index = JINJA_ENVIRONMENT.get_template('register_disabled.html')
        self.response.write(template_index.render())
示例#3
0
 def login_timeout(self):
     gc = GlobalConfig.get_configs()
     timeout_point = datetime.datetime.now() - datetime.timedelta(
         minutes=gc.failed_login_attemps_timeout)
     for attemp in self.failed_login_attemps:
         if attemp < timeout_point:
             self.failed_login_attemps.remove(attemp)
         else:
             break  # Attemps should be in order
     self.put()
     if len(self.failed_login_attemps) < gc.failed_login_attemps_limit:
         return False
     return True
def run():
    gc = GlobalConfig.get_configs()
    users = User.query()

    for user in users.iter():
        log.info('Check ' + user.username + ' account status')

        if runtime.is_shutting_down():
            break

        if user.account_status == payment.TRIAL or user.account_status == payment.TRIAL_EXPIRED:
            expire_date = user.account_expire_date + timedelta(days=gc.trial_expiring_grace_period)
            days_till_expire = (expire_date - datetime.now()).days
            log.info(user.username + ' account expires in ' + str(days_till_expire))

            if days_till_expire in gc.trial_expiring_email_intervales:
                log.info(user.username + '\'s trial expires in ' + str(days_till_expire) + ' days')
                mail.send_trial_ending_email(days_till_expire, user, gc)
            elif days_till_expire == 0:
                log.info(user.username + '\'s trial has expired')
                user.account_statue = payment.TRIAL_EXPIRED
                user.put()
                mail.send_trial_ended_email(user, gc)
            elif days_till_expire * -1 in gc.trial_expired_email_intervales:
                user.account_statue = payment.TRIAL_EXPIRED
                user.put()
                mail.send_after_trial_ended_email(days_till_expire * -1, user, gc)

        elif user.account_status != payment.ORG and user.account_status != payment.SUB:
            expire_date = user.account_expire_date + timedelta(days=gc.acct_expiring_grace_period)
            days_till_expire = (expire_date - datetime.now()).days
            log.info(user.username + ' account expires in ' + str(days_till_expire))

            if days_till_expire in gc.acct_expiring_email_intervales and user.account_status != payment.SUB:
                log.info(user.username + '\'s account expires in ' + str(days_till_expire) + ' days')
                mail.send_account_expiring_email(days_till_expire, user, gc)
            elif days_till_expire == 0:
                log.info(user.username + '\'s account has expired')
                user.account_statue = payment.EXPIRED
                user.put()
                mail.send_account_expired_email(user, gc)
            elif days_till_expire * -1 in gc.acct_expired_email_intervales:
                user.account_statue = payment.EXPIRED
                user.put()
                mail.send_after_account_expired_email(days_till_expire * -1, user, gc)

        else:
            log.info('Nothing to check')

    if runtime.is_shutting_down():
        log.warning('Had to stop notifing users, backend receaved shut donw request')
示例#5
0
    def put(self, user=None):
        gc = GlobalConfig.get_configs()
        if not gc.allow_user_registration:
            self.redirect('/register/disabled/', abort=True)

        if self.json_request.get('organization'):
            return HttpErrorException.forbidden()

        User.new(self.json_request, request=self.request, worldshare_group=Group.get_worldshare_key())
        creds = GenericCredentials(self.json_request.get('username'), self.json_request.get('password'))
        if not creds.authenticate():
            raise HttpErrorException.bad_request('faild to authinicate')

        session = login(self.request, creds, User)
        self.response.set_cookie('auth_user', base64.b64encode(creds.username))
        self.response.set_cookie('user', creds.username)
        self.response.set_cookie('auth_token', session.token)
示例#6
0
    def get(self, request=None):
        gc = GlobalConfig.get_configs()
        if not gc.allow_user_registration:
            self.redirect('/register/disabled/', abort=True)
            return

        coupon_code = self.request.get('coupon_code')
        coupon_obj = None

        if coupon_code != '':
            try:
                coupon_obj = coupon.Coupon.get_coupon(coupon_code.lower())
                if not coupon_obj.is_active():
                    raise HttpErrorException.bad_request('coupon is not active')
            except coupon.InvalidCouponCodeException:
                raise HttpErrorException.bad_request('invalid coupon code')

        payment_plans = payment_plan.get_payment_plan_list()
        pay_plan = self.request.get('payment_plan')

        if pay_plan != '':
            try:
                pay_plan = payment_plan.get_payment_plan(pay_plan)
            except payment_plan.InvalidPaymentPlanException as e:
                raise HttpErrorException.bad_request(e.message)
        else:
            pay_plan = payment_plans[0]

        template_data = {
            'title': 'thinkTank Registration',
            'nav_bar_title': 'thinkTank',
            'domain': self.request.host_url,
            'payment_plans': payment_plans,
            'active_payment_plan': pay_plan['id'],
        }

        if coupon_obj:
            template_data['coupon'] = coupon_code

        template_index = JINJA_ENVIRONMENT.get_template('register.html')
        self.response.write(template_index.render(template_data))
示例#7
0
 def post(self, username=None):
     mail.send_email_verification(self.user, GlobalConfig.get_configs())
示例#8
0
 def get(self):
     gc = GlobalConfig.get_configs()
     if gc.allow_non_admin_user_login:
         self.redirect('/', abort=True)
     template_index = JINJA_ENVIRONMENT.get_template('login_disabled.html')
     self.response.write(template_index.render())
示例#9
0
 def post(self):
     # TODO: This handler needs broken down into smaller methods. No point cleaning
     # this up until that is complete.
     if self.json_request.get('status') == 'login':
         gc = GlobalConfig.get_configs()
         user = User.get_by_id(self.json_request.get('username'))
         if not user:
             self.request.body = ''  # Make sure we don't record the users credentials in plan text
             lr = tt_logging.construct_log(msg_short='Unknow user attempted to login',
                                           log_type=tt_logging.USER, request=self.request)
             log.info(lr['dict_msg']['msg'], extra=lr)
             raise HttpErrorException.bad_request('invalid username or password given')
         if user.login_timeout():
             raise HttpErrorException.forbidden()
         if not gc.allow_non_admin_user_login and not user.is_admin:
             self.request.body = ''  # Make sure we don't record the users credentials in plan text
             lr = tt_logging.construct_log(msg_short='User attempted to loggin, but login is disabled',
                                           log_type=tt_logging.USER, request=self.request, request_user=user)
             log.info(lr['dict_msg']['msg'], extra=lr)
             raise HttpErrorException.forbidden()
         creds = GenericCredentials.from_request(self.json_request)
         if not creds.authenticate():
             user.failed_login_attemps.append(datetime.datetime.now())
             self.request.body = ''  # Make sure we don't record the users credentials in plan text
             lr = tt_logging.construct_log(msg_short='User provided invalid credentials',
                                           log_type=tt_logging.USER, request=self.request, request_user=user)
             log.info(lr['dict_msg']['msg'], extra=lr)
             raise HttpErrorException.bad_request('invalid username or password given')
         user.failed_login_attemps = []
         user.last_login == datetime.datetime.now()
         user.put()
         session = login(self.request, creds, User)
         self.request.body = ''  # Make sure we don't record the users credentials in plan text
         lr = tt_logging.construct_log(msg_short='User logged in',
                                       msg='User logged in: session: %s, IP Address: %s' %
                                           (session.token, self.request.remote_addr),
                                       log_type=tt_logging.USER, request=self.request, request_user=user)
         log.info(lr['dict_msg']['msg'], extra=lr)
         self.response.set_cookie('auth_user', base64.b64encode(creds.username))
         self.response.set_cookie('user', creds.username)
         self.response.set_cookie('auth_token', session.token)
         self.write_json_response({'status': 'success'})
     elif self.json_request.get('status') == 'logout':
         user = User.get_by_id(self.json_request.get('user'))
         Session.invalidate_cache_for(user)
         session = Session.get_by_id(user.username)
         if session is not None:
             lr = tt_logging.construct_log(msg_short='User logged out',
                                           msg='User logged out: session: %s, IP Address: %s' %
                                               (session.token, self.request.remote_addr),
                                           log_type=tt_logging.USER, request=self.request, request_user=user)
             log.info(lr['dict_msg']['msg'], extra=lr)
             session.key.delete()
         else:
             lr = tt_logging.construct_log(msg_short='User logged out',
                                           msg='User logged out: session: %s, IP Address: %s' %
                                               self.request.remote_addr,
                                           log_type=tt_logging.USER, request=self.request, request_user=user)
             log.info(lr['dict_msg']['msg'], extra=lr)
     elif self.json_request.get('reset_password'):
         user = User.get_by_id(self.json_request.get('username'))
         if not user:
             raise HttpErrorException.bad_request('invalid username')
         lr = tt_logging.construct_log(msg_short='Password Reset Requested',
                                       msg='User has requested password reset',
                                       log_type=tt_logging.USER, request=self.request, request_user=user)
         log.info(lr['dict_msg']['msg'], extra=lr)
         user.send_password_reset()
     else:
         self.write_json_response({'status': 'failed do not know what to do!!!'})
def handle_google_callback(jwt_token):
    from server import GlobalConfig
    gc = GlobalConfig.get_configs()
    if SANDBOX_MODE:
        jwt_token = jwt.decode(jwt_token, SANDBOX_SELLER_SECRET)
    else:
        jwt_token = jwt.decode(jwt_token, gc.google_seller_secret)
    log.info('Google Callback jwt: ' + str(jwt_token))
    order_id = jwt_token['response']['orderId']
    from models.account.user import User
    from models import payment
    if 'request' in jwt_token:
        user_id = jwt_token['request']['sellerData']
        user = User.query(User.user_id == user_id).get()
        if not user:
            raise InvalidSellerDataException(
                'could not find user to match user_id: ' + str(user_id))
        payment.process_payment(
            user=user,
            status='complete',
            discription='Recurrening payment',
            denomination=jwt_token['request']['recurrence']['currencyCode'],
            price=jwt_token['request']['initialPayment']['price']
            if 'initialPayment' in jwt_token['request'] else 0,
            rec_price=jwt_token['request']['recurrence']['price'],
            merchant='Google',
            order_id=order_id,
            merchant_data=jwt_token)
        lr = tt_logging.construct_log(msg_short='[Google Postback] JWT',
                                      msg=str(jwt_token),
                                      log_type=tt_logging.PAYMENT,
                                      user=user)
        log.info(lr['dict_msg']['msg'], extra=lr)

    else:
        if 'statusCode' in jwt_token['response']:
            if jwt_token['response']['statusCode'] == 'SUBSCRIPTION_CANCELED':
                trans = Transaction.query(
                    Transaction.order_id == order_id).get()
                if not trans:
                    raise InvalidOrderIdException(
                        'Could not find transaction for order id')
                user = trans.user.get()
                user.account_expire_data = datetime.datetime.now(
                ) + datetime.timedelta(
                    days=gc.subscription_account_extension_period)
                user.account_status = payment.PAID
                user.put()
                payment.process_payment(
                    user=user,
                    status='complete',
                    discription='Recurrening canceled',
                    denomination='',
                    price=0,
                    rec_price=0,
                    merchant='Google',
                    order_id=order_id,
                    merchant_data=jwt_token,
                    update_status=False,
                )
                lr = tt_logging.construct_log(
                    msg_short='[Google Postback] JWT',
                    msg=str(jwt_token),
                    log_type=tt_logging.PAYMENT,
                    user=user)
                log.info(lr['dict_msg']['msg'], extra=lr)
    return order_id
示例#11
0
 def send_password_reset(self):
     mail.send_password_reset(self, GlobalConfig.get_configs())
示例#12
0
 def send_username_email(self):
     mail.send_username(self, GlobalConfig.get_configs())
示例#13
0
 def setup_billable_account(self, pay_plan):
     return payment.setup_billable_account(self, pay_plan,
                                           GlobalConfig.get_configs())
示例#14
0
 def edit(self, request, request_data, request_user=None):
     if not request_user:
         lr = tt_logging.construct_log(
             msg_short='Unknow User tried altering a User',
             log_type=tt_logging.SECURITY,
             affected_user=self,
             request=request)
         log.warning(lr['dict_msg']['msg'], extra=lr)
         raise HttpErrorException.forbidden()
     if request_user.key != self.key:
         if not request_user.is_admin:
             lr = tt_logging.construct_log(
                 msg_short='Non-Admin User tried altering another User',
                 log_type=tt_logging.SECURITY,
                 affected_user=self,
                 request_user=request_user,
                 request=request)
             log.warning(lr['dict_msg']['msg'], extra=lr)
             raise HttpErrorException.forbidden()
     if request_data.get('add'):
         if request_data.get('add') == 'group':
             if request_data.get('group_id') is None:
                 raise HttpErrorException.bad_request('no group id given')
             if request_data.get(
                     'group_id'
             ) == 'super_admin' and not request_user.is_super_admin:
                 raise HttpErrorException.forbidden()
             group = ndb.Key('Group', request_data.get('group_id')).get()
             if not group:
                 raise HttpErrorException.bad_request('invalid group id')
             if group.key not in self.groups:
                 self.groups.append(group.key)
                 lr = tt_logging.construct_log(
                     msg_short='User Was Added to Group',
                     msg='User was added to group %s' % group.key.id(),
                     log_type=tt_logging.USER,
                     affected_user=self,
                     request_user=request_user,
                     request=request,
                     artifact=group)
                 log.info(lr['dict_msg']['msg'], extra=lr)
             else:
                 raise HttpErrorException.bad_request(
                     'user already in group')
     if request_data.get('remove'):
         if request_data.get('remove') == 'group':
             if request_data.get('group_id') is None:
                 raise HttpErrorException.bad_request('no group id given')
             if request_data.get(
                     'group_id'
             ) == 'super_admin' and not request_user.is_super_admin:
                 raise HttpErrorException.forbidden()
             group = ndb.Key('Group', request_data.get('group_id')).get()
             if not group:
                 raise HttpErrorException.bad_request('invalid group id')
             if group.key in self.groups:
                 self.groups.remove(group.key)
                 lr = tt_logging.construct_log(
                     msg_short='User Was Removed to Group',
                     msg='User was removed from group %s' % group.key.id(),
                     log_type=tt_logging.USER,
                     affected_user=self,
                     request_user=request_user,
                     request=request,
                     artifact=group)
                 log.info(lr['dict_msg']['msg'], extra=lr)
             else:
                 raise HttpErrorException.bad_request('user not in group')
     if request_data.get('groups'):
         old_groups = server.get_ids_from_key_list(self.groups)
         new_groups = request_data.get('groups')
         for group_id in new_groups:
             if group_id not in old_groups:
                 if group_id == 'super_admin' and not request_user.is_super_admin:
                     raise HttpErrorException.forbidden()
                 group = ndb.Key('Group', group_id).get()
                 if not group:
                     raise HttpErrorException.bad_request(
                         'invalid group id')
                 if group.key not in self.groups:
                     self.groups.append(group.key)
                     lr = tt_logging.construct_log(
                         msg_short='User Was Added to Group',
                         msg='User was added to group %s' % group.key.id(),
                         log_type=tt_logging.USER,
                         affected_user=self,
                         request_user=request_user,
                         request=request,
                         artifact=group)
                     log.info(lr['dict_msg']['msg'], extra=lr)
         for group_id in old_groups:
             if group_id not in new_groups:
                 if group_id == 'super_admin' and not request_user.is_super_admin:
                     raise HttpErrorException.forbidden()
                 group = ndb.Key('Group', group_id).get()
                 if not group:
                     raise HttpErrorException.bad_request(
                         'invalid group id')
                 if group.key in self.groups:
                     self.groups.remove(group.key)
                     lr = tt_logging.construct_log(
                         msg_short='User Was Removed to Group',
                         msg='User was removed from group %s' %
                         group.key.id(),
                         log_type=tt_logging.USER,
                         affected_user=self,
                         request_user=request_user,
                         request=request,
                         artifact=group)
                     log.info(lr['dict_msg']['msg'], extra=lr)
     if request_data.get('first_name') and request_data.get(
             'first_name') != self.first_name:
         old_first_name = self.first_name
         self.first_name = request_data.get('first_name')
         lr = tt_logging.construct_log(
             msg_short='User Fist Name Was Change',
             msg='User fist name was change from %s to %s' %
             (old_first_name, self.first_name),
             log_type=tt_logging.USER,
             affected_user=self,
             request_user=request_user,
             request=request)
         log.info(lr['dict_msg']['msg'], extra=lr)
     if request_data.get('last_name') and request_data.get(
             'last_name') != self.last_name:
         old_last_name = self.last_name
         self.last_name = request_data.get('last_name')
         lr = tt_logging.construct_log(
             msg_short='User Last Name Was Change',
             msg='User last name was change from %s to %s' %
             (old_last_name, self.last_name),
             log_type=tt_logging.USER,
             affected_user=self,
             request_user=request_user,
             request=request)
         log.info(lr['dict_msg']['msg'], extra=lr)
     if request_data.get('display_name') and request_data.get(
             'display_name') != self.display_name:
         old_display_name = self.display_name
         self.display_name = request_data.get('display_name')
         lr = tt_logging.construct_log(
             msg_short='User Dislay Name Was Change',
             msg='User display name was change from %s to %s' %
             (old_display_name, self.display_name),
             log_type=tt_logging.USER,
             affected_user=self,
             request_user=request_user,
             request=request)
         log.info(lr['dict_msg']['msg'], extra=lr)
     if request_data.get('password'):
         self.password = Password(request_data.get('password'))
         lr = tt_logging.construct_log(
             msg_short='User Password Was Changed',
             msg='Request not recorded to protect new password',
             log_type=tt_logging.USER,
             affected_user=self,
             request_user=request_user)
         log.info(lr['dict_msg']['msg'], extra=lr)
     if request_data.get(
             'email') and request_data.get('email') != self.email:
         old_email = self.email
         self.email = request_data.get('email')
         lr = tt_logging.construct_log(
             msg_short='User Email Was Change',
             msg='User email was change from %s to %s' %
             (old_email, self.email),
             log_type=tt_logging.USER,
             affected_user=self,
             request_user=request_user,
             request=request)
         log.info(lr['dict_msg']['msg'], extra=lr)
         self.email_verification = EmailVerification.new()
         mail.send_email_verification(self, GlobalConfig.get_configs())
         self.email_verification.lock_act = False
     if request_data.get('phone_type'):
         if not request_data.get('phone_number'):
             raise HttpErrorException.bad_request('no phone number given')
         old_phones = self.phone_numbers
         self.update_or_add_phone(request_data.get('phone_type'),
                                  request_data.get('phone_number'))
         lr = tt_logging.construct_log(
             msg_short='User Updated or Added Phone Number',
             msg='User updated or added phone number: old: %s, new: %s' %
             (str(old_phones), str(self.phone_numbers)),
             log_type=tt_logging.USER,
             affected_user=self,
             request_user=request_user,
             request=request)
         log.info(lr['dict_msg']['msg'], extra=lr)
     if request_data.get('address'):
         old_address = self.address
         address = request_data.get('address')
         self.address = {
             'street1': address['street1'],
             'city': address['city'],
             'state': address['state'],
             'zip_code': address['zip_code']
         }
         if 'street2' in address:
             self.address['street2'] = address['street2']
         lr = tt_logging.construct_log(
             msg_short='User Updated Their Address',
             msg='User updated their address from [%s] to [%s]' %
             (str(old_address), str(self.address)),
             log_type=tt_logging.USER,
             affected_user=self,
             request_user=request_user,
             request=request)
         log.info(lr['dict_msg']['msg'], extra=lr)
     if request_data.get('reset_password'):
         mail.send_password_reset(self, GlobalConfig.get_configs())
     self.put()
示例#15
0
    def new(request_user,
            verify_email=True,
            request=None,
            worldshare_group=None,
            organization=None):
        if not request_user.get('username'):
            raise HttpErrorException.bad_request('no username given')
        if request_user.get('username') == 'anonymous':
            raise HttpErrorException.bad_request('reserved username')
        if len(request_user.get('username')) > 75:
            raise HttpErrorException.bad_request(
                'username to long, max 75 characters')
        if User.get_by_id(request_user.get('username')):
            raise HttpErrorException.bad_request('username not available')
        if not request_user.get('password'):
            raise HttpErrorException.bad_request('no password given')
        if not request_user.get('first_name'):
            raise HttpErrorException.bad_request('no first name given')
        if not request_user.get('last_name'):
            raise HttpErrorException.bad_request('no last name given')
        if not request_user.get('email'):
            raise HttpErrorException.bad_request('no email given')
        if not request_user.get('phone_numbers'):
            raise HttpErrorException.bad_request('no phone number given')
        if not request_user.get('payment_plan') and not organization:
            raise HttpErrorException.bad_request('no payment plan given')
        creds = GenericCredentials.from_request(request_user)
        user = User(id=request_user.get('username'))
        user.user_id = server.create_uuid()
        user.username = request_user.get('username')
        user.display_name = request_user.get(
            'display_name',
            request_user.get('first_name') + ' ' +
            request_user.get('last_name'))
        user.password = Password(creds.password)
        user.first_name = request_user.get('first_name')
        user.last_name = request_user.get('last_name')
        user.email = request_user.get('email')
        user.email_changed = datetime.datetime.now()
        user.groups.append(worldshare_group)
        for num_type in request_user.get('phone_numbers'):
            user.phone_numbers.append(
                {num_type: request_user.get('phone_numbers').get(num_type)})
        if request_user.get('address'):
            address = request_user.get('address')
            user.address = {
                'street1': address['street1'],
                'city': address['city'],
                'state': address['state'],
                'zip_code': address['zip_code']
            }
            if 'street2' in address:
                user.address['street2'] = address['street2']
        if request_user.get('birthday'):
            user.birthday = request_user.get('birthday')
        if organization:
            user.organization = organization.key
            user.groups.append(organization.org_group)
        coup = request_user.get('coupon_code')
        if coup != '' and coup is not None:
            try:
                coup = coupon.Coupon.get_coupon(
                    request_user.get('coupon_code').lower())
                user.coupon = coup.key
            except coupon.InvalidCouponCodeException as e:
                raise HttpErrorException.bad_request(e.message)
        if user.organization:
            user.account_status = payment.ORG
            user.account_type = payment.ORG
            user.account_expire_data = datetime.datetime.max
        else:
            if not request_user.get('merchant'):
                raise HttpErrorException.bad_request('no merchant given')

            payment.init_payment(user, request_user.get('payment_plan'),
                                 request_user.get('merchant'))
        if verify_email:
            user.email_verification = EmailVerification.new()
            import smtplib

            try:
                mail.send_email_verification(user, GlobalConfig.get_configs())
            except smtplib.SMTPException as e:
                log.error('Could not send verification email')
                log.exception(e)
        else:
            user.email_verification = EmailVerification.new(verified=True)
        lr = tt_logging.construct_log(msg_short='New User Registered',
                                      msg='%s %s has registered an account' %
                                      (user.first_name, user.last_name),
                                      log_type=tt_logging.REGISTRATION,
                                      request_user=user,
                                      request=request)
        log.info(lr['dict_msg']['msg'], extra=lr)
        user.put()
        return user
示例#16
0
 def initialize(self, request, response):
     """Initializes the handler instance with Request and Response objects; called
     automatically by WSGIApplication does this after instantiating the handler class."""
     super(AuthorizationRequestHanlder, self).initialize(request, response)
     self.gc = GlobalConfig.get_configs()
示例#17
0
def main(project_id):
    print('Logging into app engine')
    remote_api_stub.ConfigureRemoteApiForOAuth(
        '{}.appspot.com'.format(project_id), '/_ah/remote_api')
    print('Logged in')

    global_conf = GlobalConfig.get_by_id(config.global_config_id)
    if not global_conf:
        GlobalConfig.new()

    from google.appengine.api import memcache
    memcache.flush_all()

    print 'Flushing all memcache'
    memcache.flush_all()

    global_conf = tt_logging.LoggingConfig.get_by_id(config.logging_config_id)
    if not global_conf:
        tt_logging.LoggingConfig.new()

    global_conf = GlobalConfig.get_by_id(config.global_config_id)
    if not global_conf:
        GlobalConfig.new()

    wordshare = Group.query(Group.name == 'world')
    if wordshare.get() is None:
        wordshare = Group(id='world',
                          name='World Share',
                          description='World Share')
        wordshare.active = True
        wordshare.put()

    print 'Checking for super users'
    dragonchain = Organization.get_by_id('DragonChain')
    if dragonchain is None:
        dragonchain = Organization(id='DragonChain',
                                   name='DragonChain',
                                   description='DragonChain',
                                   domain='dragonchain.com',
                                   owner='Joe Roets',
                                   webpage='https://dragonchain.com/',
                                   point_of_contact='Joe Roets',
                                   email='*****@*****.**',
                                   phone='+1 111 111 1111',
                                   account_type='super_account')
        dragonchain.groups.append(wordshare.key)
        dragonchain.put()

    super_admin = Group.get_by_id('super_admin')
    if super_admin is None:
        super_admin = Group(id='super_admin',
                            name='Super Administrator',
                            description='Super Administrator',
                            organization=dragonchain.key)
        super_admin.active = True
        super_admin.put()

    org = Group.query(Group.name == 'DragonChain')
    if org.get() is None:
        org = Group(key=Group.create_key(),
                    name='DragonChain',
                    description='DragonChain organization group',
                    organization=dragonchain.key)
        org.active = True
        org.organization = dragonchain.key
        dragonchain.groups.append(org.key)
        dragonchain.org_group = org.key
        org.put()

    tech = Group.query(Group.name == 'Tech')
    if tech.get() is None:
        tech = Group(key=Group.create_key(),
                     name='Tech',
                     description='Tech',
                     organization=dragonchain.key)
        tech.active = True
        tech.organization = dragonchain.key
        dragonchain.groups.append(tech.key)
        tech.put()

    legal = Group.query(Group.name == 'Legal')
    if legal.get() is None:
        legal = Group(key=Group.create_key(),
                      name='Legal',
                      description='Legal',
                      organization=dragonchain.key)
        legal.active = True
        legal.organization = dragonchain.key
        dragonchain.groups.append(legal.key)
        legal.put()

    finance = Group.query(Group.name == 'Finance')
    if finance.get() is None:
        finance = Group(key=Group.create_key(),
                        name='Finance',
                        description='Finance',
                        organization=dragonchain.key)
        finance.active = True
        finance.organization = dragonchain.key
        dragonchain.hidden_groups.append(finance.key)
        finance.put()

    marketing = Group.query(Group.name == 'Marketing')
    if marketing.get() is None:
        marketing = Group(key=Group.create_key(),
                          name='Marketing',
                          description='Marketing',
                          organization=dragonchain.key)
        marketing.active = True
        marketing.organization = dragonchain.key
        dragonchain.groups.append(marketing.key)
        marketing.put()

    topsec = Group.query(Group.name == 'Top Secret')
    if topsec.get() is None:
        topsec = Group(key=Group.create_key(),
                       name='Top Secret',
                       description='Top Secret',
                       organization=dragonchain.key)
        topsec.active = True
        topsec.organization = dragonchain.key
        dragonchain.hidden_groups.append(topsec.key)
        topsec.put()

    secret = Group.query(Group.name == 'Secret')
    if secret.get() is None:
        secret = Group(key=Group.create_key(),
                       name='Secret',
                       description='Secret',
                       organization=dragonchain.key)
        secret.active = True
        secret.organization = dragonchain.key
        dragonchain.hidden_groups.append(secret.key)
        secret.put()

    confid = Group.query(Group.name == 'Confidential')
    if confid.get() is None:
        confid = Group(key=Group.create_key(),
                       name='Confidential',
                       description='Confidential',
                       organization=dragonchain.key)
        confid.active = True
        tech.organization = dragonchain.key
        dragonchain.groups.append(confid.key)
        confid.put()

    amiller_su = User.get_by_id('amiller_su')
    if amiller_su is None:
        print 'Super user amiller not found, creating him now'
        User.new(
            {
                'username': '******',
                'password': '******',
                'first_name': 'Andrew',
                'last_name': 'Miller',
                'email': '*****@*****.**',
                'phone_numbers': {
                    'main': '304-123-1234'
                }
            },
            verify_email=False,
            organization=dragonchain,
            worldshare_group=Group.get_worldshare_key())
        amiller_su = User.get_by_id('amiller_su')
        amiller_su.organization = dragonchain.key
        amiller_su.require_password_change = True
        amiller_su.groups = [super_admin.key]
        amiller_su.put()
        dragonchain.admins.append(amiller_su.key)

    baxter_su = User.get_by_id('baxter_su')
    if baxter_su is None:
        print 'Super user joe not found, creating him now'
        User.new(
            {
                'username': '******',
                'password': '******',
                'first_name': 'Baxter',
                'last_name': 'Finch',
                'email': '*****@*****.**',
                'phone_numbers': {
                    'main': '304-123-1234'
                }
            },
            verify_email=False,
            organization=dragonchain,
            worldshare_group=Group.get_worldshare_key())
        baxter_su = User.get_by_id('baxter_su')
        baxter_su.groups.append(super_admin.key)
        baxter_su.organization = dragonchain.key
        baxter_su.require_password_change = True
        baxter_su.put()
        dragonchain.admins.append(baxter_su.key)

    joe_su = User.get_by_id('joe_su')
    if joe_su is None:
        print 'Super user joe not found, creating him now'
        User.new(
            {
                'username': '******',
                'password': '******',
                'first_name': 'Joe',
                'last_name': 'Roets',
                'email': '*****@*****.**',
                'phone_numbers': {
                    'main': '304-123-1234'
                }
            },
            verify_email=False,
            organization=dragonchain,
            worldshare_group=Group.get_worldshare_key())
        joe_su = User.get_by_id('joe_su')
        joe_su.groups.append(super_admin.key)
        joe_su.organization = dragonchain.key
        joe_su.require_password_change = True
        joe_su.put()
        dragonchain.admins.append(joe_su.key)

    amiller = User.get_by_id('amiller')
    if amiller is None:
        print 'User amiller not found, creating him now'
        User.new(
            {
                'username': '******',
                'password': '******',
                'first_name': 'Andrew',
                'last_name': 'Miller',
                'email': '*****@*****.**',
                'phone_numbers': {
                    'main': '304-123-1234'
                }
            },
            verify_email=False,
            organization=dragonchain,
            worldshare_group=Group.get_worldshare_key())
        amiller = User.get_by_id('amiller')
        amiller.organization = dragonchain.key
        amiller.require_password_change = True
        amiller.groups.append(tech.key)
        amiller.groups.append(legal.key)
        amiller.put()

    joe = User.get_by_id('joe')
    if joe is None:
        print 'User joe not found, creating him now'
        User.new(
            {
                'username': '******',
                'password': '******',
                'first_name': 'Joe',
                'last_name': 'Roets',
                'email': '*****@*****.**',
                'phone_numbers': {
                    'main': '304-123-1234'
                }
            },
            verify_email=False,
            organization=dragonchain,
            worldshare_group=Group.get_worldshare_key())
        joe = User.get_by_id('joe')
        joe.groups.append(tech.key)
        joe.groups.append(legal.key)
        joe.organization = dragonchain.key
        joe.require_password_change = True
        joe.put()

    baxter = User.get_by_id('baxter')
    if baxter is None:
        print 'User baxter not found, creating him now'
        User.new(
            {
                'username': '******',
                'password': '******',
                'first_name': 'Baxter',
                'last_name': 'Finch',
                'email': '*****@*****.**',
                'phone_numbers': {
                    'main': '304-123-1234'
                }
            },
            verify_email=False,
            organization=dragonchain,
            worldshare_group=Group.get_worldshare_key())
        baxter = User.get_by_id('baxter')
        baxter.groups.append(tech.key)
        baxter.groups.append(legal.key)
        baxter.organization = dragonchain.key
        baxter.require_password_change = True
        baxter.put()

    bob = User.get_by_id('bob')
    if bob is None:
        print 'User bob not found, creating him now'
        User.new(
            {
                'username': '******',
                'password': '******',
                'first_name': 'bob',
                'last_name': 'bob',
                'email': '*****@*****.**',
                'phone_numbers': {
                    'main': '304-123-1234'
                }
            },
            verify_email=False,
            organization=dragonchain,
            worldshare_group=Group.get_worldshare_key())
        bob = User.get_by_id('bob')
        bob.organization = dragonchain.key
        bob.require_password_change = True
        bob.groups.append(tech.key)
        bob.groups.append(legal.key)
        bob.put()

    tom = User.get_by_id('tom')
    if tom is None:
        print 'User tom not found, creating him now'
        User.new(
            {
                'username': '******',
                'password': '******',
                'first_name': 'tom',
                'last_name': 'tom',
                'email': '*****@*****.**',
                'phone_numbers': {
                    'main': '304-123-1234'
                }
            },
            verify_email=False,
            organization=dragonchain,
            worldshare_group=Group.get_worldshare_key())
        tom = User.get_by_id('tom')
        tom.organization = dragonchain.key
        tom.require_password_change = True
        tom.groups.append(tech.key)
        tom.groups.append(legal.key)
        tom.put()

    sam = User.get_by_id('sam')
    if sam is None:
        print 'User sam not found, creating him now'
        User.new(
            {
                'username': '******',
                'password': '******',
                'first_name': 'sam',
                'last_name': 'sam',
                'email': '*****@*****.**',
                'phone_numbers': {
                    'main': '304-123-1234'
                }
            },
            verify_email=False,
            organization=dragonchain,
            worldshare_group=Group.get_worldshare_key())
        sam = User.get_by_id('sam')
        sam.organization = dragonchain.key
        sam.require_password_change = True
        sam.groups.append(tech.key)
        sam.groups.append(secret.key)
        sam.put()

    dragonchain.put()
示例#18
0
    def to_dict(self, user=None, request=None):
        include = [
            'user_id',
            'username',
            'last_login',
            'first_name',
            'last_name',
            'display_name',
            'registration_date',
            'modified_ts',
            'email',
            'email_changed',
            'phone_numbers',
            'address',
            'birthday',
            'groups',
            'organization',
            'password_expiration_date',
            'require_password_change',
            'account_type',
            'account_status',
            'account_expire_data',
            'tour_home_complete',
            'tour_project_complete',
            'ddss',
            'spectra_count',
        ]
        d = super(User, self).to_dict(include=include)

        if d['modified_ts']:
            d['modified_ts'] = str(d['modified_ts'])
        if d['registration_date']:
            d['registration_date'] = time.mktime(
                d['registration_date'].timetuple())
        if d['account_expire_data']:
            d['account_expire_data'] = time.mktime(
                d['account_expire_data'].timetuple())
        if d['last_login'] is not None:
            d['last_login'] = time.mktime(d['last_login'].timetuple())
        else:
            d['last_login'] = '******'
        if d['email_changed']:
            d['email_changed'] = time.mktime(d['email_changed'].timetuple())
        d['id'] = self.key.id()

        gc = GlobalConfig.get_configs()
        if self.ddss is None:
            d['ddss'] = gc.default_ddss
        if self.spectra_count is None:
            d['spectra_count'] = gc.default_spectra_count

        if not self.is_world_user():
            d['full_name'] = self.full_name

        groups = []
        d['groups'] = ndb.get_multi(d['groups'])
        index = 0
        for g in d['groups']:
            if g is None:
                self.groups.remove(self.groups[index])
                lr = tt_logging.construct_log(
                    msg_short='Broken Group Key in User Group List',
                    msg=
                    'Found a broken group key (%s) in the user\'s group list\n'
                    'Key has been removed' % str(self.groups[index]),
                    log_type=tt_logging.USER,
                    request_user=user,
                    affected_user=self,
                    request=request)
                log.error(lr['dict_msg']['msg'], extra=lr)
            groups.append(g.to_dict())
            index += 1
        d['groups'] = groups

        if d['organization'] is not None:
            d['organization'] = d['organization'].id()

        if d['password_expiration_date'] is not None:
            d['password_expiration_date'] = str(d['password_expiration_date'])

        if self.organization:
            if self.is_org_admin:
                d['is_admin'] = True
            else:
                d['is_admin'] = False
            if self.is_super_admin:
                d['is_super_admin'] = True
            else:
                d['is_super_admin'] = False
        return d