def populate_intercom_user(session_key, user_detail=None): """ Creates or updates an intercom user with information from itsyou.online Args: session_key (ndb.Key): key of the Session for this user user_detail (UserDetailsTO): key of the Session for this user """ intercom_plugin = get_plugin('intercom_support') if intercom_plugin: session = session_key.get() if not session: return assert isinstance(session, Session) assert isinstance(intercom_plugin, IntercomSupportPlugin) data = get_user(session.user_id, session.jwt) intercom_user = upsert_intercom_user(data.username, data) tag_intercom_users(IntercomTags.APP_REGISTER, [data.username]) if user_detail: message = """Welcome to the ThreeFold Foundation app. If you have questions you can get in touch with us through this chat. Our team is at your service during these hours: Sunday: 07:00 - 15:00 GMT +1 Monday - Friday: 09:00 - 17:00 GMT +1 Of course you can always ask your questions outside these hours, we will then get back to you the next business day.""" chat_id = start_or_get_chat(get_config(NAMESPACE).rogerthat.api_key, '+default+', user_detail.email, user_detail.app_id, intercom_user, message) deferred.defer(store_chat_id_in_user_data, chat_id, user_detail)
def get_influx_client(): config = get_config(NAMESPACE).influxdb # type: InfluxDBConfig if config is MISSING: return None return influxdb.InfluxDBClient(config.host, config.port, config.username, config.password, config.database, config.ssl, config.ssl)
def get(self): config = get_config(NAMESPACE) assert isinstance(config, TffConfiguration) if config.backup_disabled is True: logging.info('Backup is disabled, doing nothing') return models_to_backup = [] # intercom_support models_to_backup.extend( ['IntercomConversation', 'RogerthatConversation']) # its_tyo_online_auth models_to_backup.extend( ['Profile', 'ProfileAppEmailMapping', 'Session']) # tff_backend models_to_backup.extend([ 'GlobalStats', 'NodeOrder', 'ProfilePointer', 'InvestmentAgreement', 'TffProfile', 'ThreeFoldBlockHeight', 'ThreeFoldWallet', 'ThreeFoldTransaction', 'ThreeFoldPendingTransaction' ]) for model_to_backup in models_to_backup: taskqueue.add(url='/_ah/datastore_admin/backup.create', method='GET', queue_name="data-backup", params={ 'filesystem': 'gs', 'gs_bucket_name': 'tff-backend-backups', 'name': model_to_backup, 'kind': [model_to_backup] })
def user_registered(user_detail, origin, data): logging.info('User %s:%s registered', user_detail.email, user_detail.app_id) data = json.loads(data) required_scopes = get_config(IYO_AUTH_NAMESPACE).required_scopes.split(',') if origin == REGISTRATION_ORIGIN_OAUTH: access_token_data = data.get('result', {}) access_token = access_token_data.get('access_token') jwt = create_jwt(access_token, scope='offline_access') else: return decoded_jwt = decode_jwt_cached(jwt) username = decoded_jwt.get('username', None) if not username: logging.warn('Could not find username in jwt.') return missing_scopes = [ s for s in required_scopes if s and s not in decoded_jwt['scope'] ] if missing_scopes: logging.warn('Access token is missing required scopes %s', missing_scopes) logging.debug('Decoded JWT: %s', decoded_jwt) scopes = decoded_jwt['scope'] # Creation session such that the JWT is automatically up to date _, session = create_session(username, scopes, jwt, secret=username)
def create_odoo_quotation(billing_info, shipping_info, product_id): logging.info( 'Creating quotation: \nbilling_info: %s\nshipping_info: %s\nproduct_id: %s', billing_info, shipping_info, product_id) cfg = get_config(NAMESPACE) erp_client = _get_erp_client(cfg) customer = { 'billing': { 'name': billing_info.name, 'email': billing_info.email, 'phone': billing_info.phone, 'address': billing_info.address }, 'shipping': None } if shipping_info and shipping_info.name and shipping_info.email and shipping_info.phone and shipping_info.address: customer['shipping'] = { 'name': shipping_info.name, 'email': shipping_info.email, 'phone': shipping_info.phone, 'address': shipping_info.address } billing_id, shipping_id = _save_customer(erp_client, customer) return _create_quotation(cfg, erp_client, billing_id, shipping_id, product_id)
def _validate_socket(prop, value): # type: (ndb.StringProperty, object) -> unicode socket_types = get_config(NAMESPACE).odoo.product_ids.keys() if value in socket_types: return value else: raise datastore_errors.BadValueError('Value %r for property %s is not an allowed choice' % (value, prop._name))
def get_nodes_from_odoo(order_id): cfg = get_config(NAMESPACE) erp_client = _get_erp_client(cfg) sale_order_model = erp_client.model('sale.order') stock_picking_model = erp_client.model('stock.picking') stock_move_model = erp_client.model('stock.move') stock_production_lot_model = erp_client.model('stock.production.lot') sale_order = sale_order_model.browse(order_id) nodes = [] for picking_id in sale_order.picking_ids.id: stock_picking = stock_picking_model.browse(picking_id) for move_line in stock_picking.move_lines.id: stock_move = stock_move_model.browse(move_line) for lot in stock_move.lot_ids: serial_number = lot.name stock_production_lot = stock_production_lot_model.browse( lot.id) if stock_production_lot.product_id.id in cfg.odoo.product_ids.values( ) and stock_production_lot.ref: nodes.append({ 'id': stock_production_lot.ref, 'serial_number': serial_number }) return nodes
def get(self): code = self.request.GET.get('code', None) state = self.request.GET.get('state', None) try: if not (code or state): logging.debug('Code or state are missing.\nCode: %s\nState:%s', code, state) raise HttpBadRequestException() login_state = OauthState.create_key(state).get() if not login_state: logging.debug('Login state not found') raise HttpBadRequestException() config = get_config(NAMESPACE) assert isinstance(config, ItsYouOnlineConfiguration) if config.login_with_organization: username, scopes = get_user_scopes_from_access_token(code, login_state) jwt = None else: jwt, username, scopes = get_jwt(code, login_state) except HttpException as e: render_error_page(self.response, e.http_code, e.error) return _, session = login_user(self.response, username, scopes, jwt) self.redirect('/') if config.fetch_information: deferred.defer(set_user_information, Profile.create_key(username), session.key, _queue='iyo-requests')
def put_investment_agreement(agreement_id, agreement, admin_user): admin_app_user = create_app_user_by_email( admin_user.email(), get_config(NAMESPACE).rogerthat.app_id) # type: (long, InvestmentAgreement, users.User) -> InvestmentAgreement agreement_model = InvestmentAgreement.get_by_id( agreement_id) # type: InvestmentAgreement if not agreement_model: raise HttpNotFoundException('investment_agreement_not_found') if agreement_model.status == InvestmentAgreement.STATUS_CANCELED: raise HttpBadRequestException('order_canceled') if agreement.status not in (InvestmentAgreement.STATUS_SIGNED, InvestmentAgreement.STATUS_CANCELED): raise HttpBadRequestException('invalid_status') # Only support updating the status for now agreement_model.status = agreement.status if agreement_model.status == InvestmentAgreement.STATUS_CANCELED: agreement_model.cancel_time = now() elif agreement_model.status == InvestmentAgreement.STATUS_SIGNED: agreement_model.paid_time = now() if agreement.currency == 'BTC': _set_token_count(agreement_model, agreement.token_count_float) deferred.defer(_send_ito_agreement_to_admin, agreement_model.key, admin_app_user) agreement_model.put() return agreement_model
def _inform_support_of_new_node_order(node_order_id): node_order = get_node_order(node_order_id) cfg = get_config(NAMESPACE) iyo_username = get_iyo_username(node_order.app_user) subject = 'New Node Order by %s' % node_order.billing_info.name body = """Hello, We just received a new Node order from %(name)s (IYO username %(iyo_username)s) with id %(node_order_id)s. This order needs to be manually approved since this user has not invested more than %(tokens)s tokens yet via the app. Check the old purchase agreements to verify if this user can sign up as a hoster and if not, contact him. Please visit https://tff-backend.appspot.com/orders/%(node_order_id)s to approve or cancel this order. """ % { 'name': node_order.billing_info.name, 'iyo_username': iyo_username, 'node_order_id': node_order.id, 'tokens': REQUIRED_TOKEN_COUNT_TO_HOST } for email in cfg.investor.support_emails: mail.send_mail(sender='*****@*****.**', to=email, subject=subject, body=body)
def _handle_request(self, kwargs, write_result=False): # first try to create the app on rogerthat backend kwargs['route'] = 'restapi/apps' data = json.loads(self.request.body) app_type = data['app_type'] data['type'] = app_type data['name'] = data['title'] self.request.body = json.dumps(data) status_code, content, headers = ProxyHandlerRogerthat._handle_request(self, kwargs, write_result) if status_code != httplib.OK: self.response.headers = headers self.response.status = status_code self.response.write(content) else: # Create app on app configurator only if it was created successfully on backend kwargs['route'] = '/api/apps' data = json.loads(self.request.body) backend_server = get_backend_server(kwargs['backend_id']) data['app_constants'], data['cloud_constants'] = get_backend_constants(backend_server) self.request.body = json.dumps(data) ProxyHandlerConfigurator._handle_request(self, kwargs) if self.response.status_int in (httplib.OK, httplib.CREATED): config = get_config(IYO_NAMESPACE) organization = '%(root_org)s.backends.%(backend_id)s.apps.%(app_id)s' % { 'root_org': config.root_organization.name, 'backend_id': backend_server.id, 'app_id': data['app_id'] } username = get_current_session().user_id deferred.defer(create_organization_with_roles, organization, PermissionType.APP_PERM, username) if not DEBUG and app_type == 1: # only for cityapps deferred.defer(create_app_group, data['app_id'])
def get_session(self): username = get_config(NAMESPACE).apple.iyo_username session = Session.list_active_user(username).get() if not session: logging.error( 'No session found for %s! Login with this account to resolve the issue', username) return session
def check_auth(self, auth): encoded_auth = auth[1] username_colon_pass = base64.b64decode(encoded_auth) username, password = map(lambda x: x.lower().strip(), username_colon_pass.split(':')) config = get_config(NAMESPACE) assert isinstance(config, TffConfiguration) return username == config.apple.username and password == config.apple.password
def confirm_odoo_quotation(order_id): # type: (long, dict) -> bool cfg = get_config(NAMESPACE) erp_client = _get_erp_client(cfg) result = erp_client.execute('sale.order', 'action_button_confirm', [order_id]) logging.info('action_button_confirm result: %s', result) return result
def send_emails_to_support(subject, body): cfg = get_config(NAMESPACE) sender = 'no-reply@%s.appspotmail.com' % app_identity.get_application_id() logging.debug('Sending email to support: %s\n %s', subject, body) for email in cfg.support_emails: logging.debug('Sending email to %s', email) mail.send_mail(sender=sender, to=email, subject=subject, body=body)
def _orc_call(path): # type: (basestring) -> apiproxy_stub_map.UserRPC cfg = get_config(NAMESPACE) jwt = _refresh_jwt(cfg.orchestator.jwt) headers = {'Authorization': u'Bearer %s' % jwt} rpc = urlfetch.create_rpc(deadline=30) urlfetch.make_fetch_call(rpc, url=u'https://orc.threefoldtoken.com%s' % path, headers=headers) return rpc
def get(self): session = get_current_session() if is_valid_session(session): self.redirect('/') return config = get_config(NAMESPACE) if not config.login_with_organization: self.redirect('/login/continue?%s' % self.request.query) return render_page(self.response, os.path.join('unauthenticated', 'signin.html'), plugin_name=NAMESPACE)
def get_api_client(): if _client: return _client config = get_config(NAMESPACE) assert isinstance(config, TffConfiguration) if DEBUG: assert config.onfido.api_key.startswith('test_') onfido.configuration.api_key['Authorization'] = 'token=%s' % config.onfido.api_key onfido.configuration.api_key_prefix['Authorization'] = 'Token' api = onfido.DefaultApi() globals()['_client'] = api return api
def get_asset_ids(app_user): app_id = get_app_id_from_app_user(app_user) if app_id != get_config(NAMESPACE).rogerthat.app_id and not DEBUG: return [] tokens = [TOKEN_TFT] if app_user: w_key = ThreeFoldWallet.create_key(app_user) w = w_key.get() if w and w.tokens: tokens = w.tokens return [get_asset_id_from_token(app_user, token) for token in tokens]
def user_registered(user_detail, origin, data): logging.info('User %s:%s registered', user_detail.email, user_detail.app_id) data = json.loads(data) required_scopes = get_config(IYO_AUTH_NAMESPACE).required_scopes.split(',') if origin == REGISTRATION_ORIGIN_QR: qr_type = data.get('qr_type', None) qr_content = data.get('qr_content', None) if not qr_type or not qr_content: logging.warn('No qr_type/qr_content in %s', data) return if qr_type != 'jwt': logging.warn('Unsupported qr_type %s', qr_type) return jwt = qr_content decoded_jwt = decode_jwt_cached(jwt) username = decoded_jwt.get('username', None) if not username: logging.warn('Could not find username in jwt.') return missing_scopes = [s for s in required_scopes if s and s not in decoded_jwt['scope']] if missing_scopes: logging.warn('Access token is missing required scopes %s', missing_scopes) elif origin == REGISTRATION_ORIGIN_OAUTH: access_token_data = data.get('result', {}) access_token = access_token_data.get('access_token') username = access_token_data.get('info', {}).get('username') if not access_token or not username: logging.warn('No access_token/username in %s', data) return scopes = [s for s in access_token_data.get('scope', '').split(',') if s] missing_scopes = [s for s in required_scopes if s and s not in scopes] if missing_scopes: logging.warn('Access token is missing required scopes %s', missing_scopes) scopes.append('offline_access') logging.debug('Creating JWT with scopes %s', scopes) jwt = create_jwt(access_token, scope=','.join(scopes)) decoded_jwt = decode_jwt_cached(jwt) else: return logging.debug('Decoded JWT: %s', decoded_jwt) scopes = decoded_jwt['scope'] # Creation session such that the JWT is automatically up to date _, session = create_session(username, scopes, jwt, secret=username)
def send_intercom_email(iyo_username, subject, message): intercom_plugin = get_intercom_plugin() if intercom_plugin: from_ = {'type': 'admin', 'id': get_config(NAMESPACE).intercom_admin_id} to_user = upsert_intercom_user(iyo_username) if to_user.unsubscribed_from_emails: logging.warning('Not sending email via intercom, user %s is unsubscribed from emails.', to_user.id) return None to = {'type': 'user', 'id': to_user.id} return intercom_plugin.send_message(from_, message, message_type='email', subject=subject, to=to) logging.debug('Not sending email with subject "%s" via intercom because intercom plugin was not found', subject) return None
def update_backend_settings_on_configurator(backend_server): from plugins.rogerthat_control_center.handlers.proxy import _try_or_refresh config = get_config(NAMESPACE) url = config.configurator_url + '/api/apps/bulk/constants/%s' % backend_server.id app_constants, cloud_constants = get_backend_constants(backend_server) body = json.dumps({ 'app_constants': app_constants, 'cloud_constants': cloud_constants }) headers = { 'Content-Type': 'application/json' } _try_or_refresh(url, urlfetch.PUT, headers, body, validate_certificate=False, follow_redirects=True)
def create_backend_server(backend_server_to): backend_server_to.id = backend_server_to.id.lower() key = BackendServer.create_key(backend_server_to.id) if key.get(): raise HttpConflictException('duplicate_backend_id', data={'backend_id': backend_server_to.id}) # Create this organization on itsyou.online if it does not exist already config = get_config(IYO_NAMESPACE) backends_organization = '%s.backends' % config.root_organization.name create_organization_with_roles('%s.%s' % (backends_organization, backend_server_to.id), PermissionType.BACKEND) create_organization_with_roles('%s.%s.apps' % (backends_organization, backend_server_to.id), PermissionType.APP_PERM) backend_server = BackendServer(key=key) return _save_backend(backend_server, backend_server_to)
def get(self): params = { 'source': SOURCE_APP } config = get_config(NAMESPACE) if config.login_with_organization: self.redirect('/login/organization?%s' % urllib.urlencode(params)) else: params['organization_id'] = config.root_organization.name if config.required_scopes and config.required_scopes is not MISSING: # provide extra scopes params['scope'] = config.required_scopes self.redirect('/login/redirect?%s' % urllib.urlencode(params))
def sync_payment_asset(app_user, asset_id): cfg = get_config(NAMESPACE) args = dict() args["app_user"] = app_user.email() args["asset_id"] = asset_id headers = {'Authorization': cfg.rogerthat.payment_secret} urlfetch.fetch(url=u"%s/payments/callbacks/threefold/sync?%s" % (cfg.rogerthat.url, urlencode(args)), method=urlfetch.GET, headers=headers, deadline=10)
def update_odoo_quotation(order_id, order_data): # type: (long, dict) -> None cfg = get_config(NAMESPACE) erp_client = _get_erp_client(cfg) sale_order = erp_client.model('sale.order').browse(order_id) try: logging.info('Updating sale.order %s with data %s', order_id, order_data) sale_order.write(order_data) except xmlrpclib.Fault as e: # Sale order has been deleted on odoo, ignore in case the state was 'cancel' if 'MissingError' not in e.faultCode or order_data.get( 'state') != QuotationState.CANCEL: raise e
def _create_quotation(app_user, order_id, pdf_url, attachment_name): order = get_node_order(order_id) config = get_config(NAMESPACE) assert isinstance(config, TffConfiguration) product_id = config.odoo.product_ids.get(order.socket) if not product_id: logging.warn('Could not find appropriate product for socket %s. Falling back to EU socket.', order.socket) product_id = config.odoo.product_ids['EU'] odoo_sale_order_id, odoo_sale_order_name = create_odoo_quotation(order.billing_info, order.shipping_info, product_id) order.odoo_sale_order_id = odoo_sale_order_id order.put() deferred.defer(_send_order_node_sign_message, app_user, order_id, pdf_url, attachment_name, odoo_sale_order_name)
def _handle_request(self, kwargs, write_result=True): """ Proxies requests incoming on /plugins/rcc/proxy/configurator to the app configurator server The url of this server must be set in the configuration Args: kwargs (dict): url parameters """ config = get_config(NAMESPACE) path = config.configurator_url + urllib.quote(kwargs['route']) lang = get_auth_plugin().get_user_language() or get_browser_language() self.request.headers['Accept-Language'] = str(lang) if DEBUG: # Pretty print in debug self.request.headers['Accept'] = 'application/json; indent=4' return _do_proxy(path, self.request, self.response, validate_certificate=True, follow_redirects=False, write_result=write_result)
def get_visible_modules(self): session = get_current_session() user_id = session.user_id scopes = session.scopes visible_modules = set() config = get_config(NAMESPACE) try: if config.login_with_organization: profile = Profile.create_key(user_id).get() if not profile: return [] # todo refactor to use current session scopes instead and remove organization_id property from Profile organization_id = profile.organization_id if not organization_id: return [] if organization_id == config.root_organization.name: return [u'its_you_online_settings'] organization = get_organization(organization_id) for plugin in get_plugins(): for module in plugin.get_modules(): if config.login_with_organization and module.name not in organization.modules: continue module_scopes = [] for scope in module.scopes: if Scopes.get_organization_scope(scope, organization_id) in scopes: module_scopes.append(True) else: module_scopes.append(False) if module.scopes and not any(module_scopes): continue visible_modules.add(module) else: auth_plugin = get_auth_plugin() for plugin in get_plugins(): if plugin != auth_plugin: for module in plugin.get_modules(): visible_modules.add(module) return map(lambda m: m.name, sorted(visible_modules, key=lambda m: m.sort_order)) except: logging.debug('Failed to get visible modules', exc_info=True) return []
def _get_base_organization(data, permission_type): """ Args: data (PermissionRequestDataTO) permission_type (unicode) """ root_org = get_config(IYO_NAMESPACE).root_organization.name backend_organization = '%s.backends.%s' % (root_org, data.backend) if permission_type == PermissionType.BACKEND: organization = backend_organization elif permission_type == PermissionType.APP: organization = '%s.apps.%s' % (backend_organization, data.app_id) elif permission_type == PermissionType.APP_PERM: organization = '%s.apps' % backend_organization elif permission_type == PermissionType.DEVELOPER_ACCOUNT: organization = '%s.developeraccounts.%s' % (root_org, data.developer_account) else: raise ValueError('Unknown permission type: %s' % permission_type) return organization
def get(self, register=False, **kwargs): # Redirect to /login/organization if an organization is required to login # else immediately redirect to to itsyou.online config = get_config(NAMESPACE) # type: ItsYouOnlineConfiguration if config.login_with_organization: self.redirect('/login/organization') else: params = { 'source': self.request.GET.get('source', SOURCE_WEB), 'organization_id': config.root_organization.name, 'scope': self.request.GET.get('scope') or '' } if register: params['register'] = 1 if config.required_scopes and config.required_scopes is not MISSING: # provide extra scopes if params['scope']: params['scope'] += ',' params['scope'] += config.required_scopes self.redirect(str('/login/redirect?%s' % urllib.urlencode(params)))
def _async_zero_robot_call(path, method=urlfetch.GET, payload=None): cfg = get_config(NAMESPACE) try: jwt = _refresh_jwt(cfg.orchestator.jwt) except: msg = 'Could not refresh JWT' logging.exception(msg) raise deferred.PermanentTaskFailure(msg) headers = { 'Cookie': 'caddyoauth=%s' % jwt, 'Content-Type': 'application/json' } url = u'https://zero-robot.threefoldtoken.com%s' % path rpc = urlfetch.create_rpc(deadline=30) urlfetch.make_fetch_call(rpc, payload=payload, method=method, url=url, headers=headers) return rpc
def _inform_support_of_new_investment(iyo_username, agreement_id, token_count): cfg = get_config(NAMESPACE) subject = "New purchase agreement signed" body = """Hello, We just received a new purchase agreement (%(agreement_id)s) from %(iyo_username)s for %(token_count_float)s tokens. Please visit %(base_url)s/investment-agreements/%(agreement_id)s to find more details, and collect all the money! """ % { "iyo_username": iyo_username, "agreement_id": agreement_id, 'base_url': get_base_url(), "token_count_float": token_count } # noQA for email in cfg.investor.support_emails: mail.send_mail(sender="*****@*****.**", to=email, subject=subject, body=body)
def get_node_id_from_odoo(order_id): cfg = get_config(NAMESPACE) erp_client = _get_erp_client(cfg) sale_order_model = erp_client.model('sale.order') stock_picking_model = erp_client.model('stock.picking') stock_move_model = erp_client.model('stock.move') stock_production_lot_model = erp_client.model('stock.production.lot') sale_order = sale_order_model.browse(order_id) for picking_id in sale_order.picking_ids.id: stock_picking = stock_picking_model.browse(picking_id) for move_line in stock_picking.move_lines.id: stock_move = stock_move_model.browse(move_line) for lot_id in stock_move.lot_ids.id: stock_production_lot = stock_production_lot_model.browse( lot_id) if stock_production_lot.product_id.id in cfg.odoo.product_ids.values( ): return stock_production_lot.ref return None
def _save_transaction_to_backlog(transaction_id, backlog_type): return # Temporarily disabled if backlog_type not in ('tierion', 'git'): raise Exception('Invalid backlog_type') cfg = get_config(NAMESPACE) if not (cfg.ledger.url or cfg.ledger.secret): if DEBUG: logging.warn('Transaction backlog is not filled in, doing nothing') return raise Exception('Backlog config is not filled in') transaction = ThreeFoldTransaction.get_by_id(transaction_id) if not transaction: raise BusinessException('ThreeFoldTransaction with id %s not found!' % transaction_id) data = { 'id': transaction.id, 'timestamp': transaction.timestamp, 'amount': transaction.amount } if transaction.from_user: data['from'] = hmac.new(cfg.ledger.secret.encode(), transaction.from_user.email(), hashlib.sha1).hexdigest() if transaction.to_user: data['to'] = hmac.new(cfg.ledger.secret.encode(), transaction.to_user.email(), hashlib.sha1).hexdigest() headers = {'Authorization': cfg.ledger.secret} url = cfg.ledger.url + '/transactions/%s' % backlog_type result = urlfetch.fetch(url, json.dumps(data), urlfetch.POST, headers, deadline=30) if result.status_code not in (200, 201): logging.info('Status:%s Content: %s', result.status_code, result.content) raise Exception('Failed to add transaction to backlog')
def get(self): organization_id = self.request.GET.get('organization_id', None) source = self.request.GET.get('source', SOURCE_WEB) error = None if organization_id: config = get_config(NAMESPACE) if organization_id != config.root_organization.name: try: get_organization(organization_id) except OrganizationNotFoundException as e: error = e.message if not error: self.redirect('/login/redirect?%s' % self.request.query) return template_parameters = { 'source': source, 'error': error } render_page(self.response, os.path.join('unauthenticated', 'organization.html'), plugin_name=NAMESPACE, template_parameters=template_parameters)
def get_iyo_organization_id(): config = get_config(IYO_AUTH_NAMESPACE) return config.root_organization.name
def get(self): organization_id = self.request.GET.get('organization_id', None) source = self.request.GET.get('source', SOURCE_WEB) extra_scopes = self.request.GET.get('scope', '').lstrip(',') register = self.request.GET.get('register', False) config = get_config(NAMESPACE) assert isinstance(config, ItsYouOnlineConfiguration) if not organization_id and config.login_with_organization: self.redirect('/login/organization') return if config.login_with_organization: if organization_id != config.root_organization.name: try: get_organization(organization_id) except OrganizationNotFoundException as e: render_error_page(self.response, httplib.BAD_REQUEST, e.message) return if source not in [SOURCE_WEB, SOURCE_APP]: render_error_page(self.response, httplib.BAD_REQUEST, 'Bad Request') return if config.login_with_organization: if organization_id == config.root_organization.name: if source == SOURCE_APP: render_error_page(self.response, httplib.BAD_REQUEST, 'Bad Request') return else: sub_org = organization_id else: sub_org = get_users_organization(config, organization_id) scope = 'user:memberof:%s' % sub_org elif config.require_memberof: scope = 'user:memberof:%s' % config.root_organization.name else: scope = '' if scope: scope += ',' scope += extra_scopes params = { 'response_type': 'code', 'client_id': config.root_organization.name, 'redirect_uri': get_redirect_uri(config, source), 'scope': scope, 'state': str(uuid.uuid4()) } login_state = OauthState(key=OauthState.create_key(params['state'])) login_state.timestamp = now() login_state.organization_id = organization_id login_state.source = source login_state.completed = False login_state.put() if register: params['register'] = 1 oauth_url = '%s/authorize?%s' % (get_auth_plugin().oauth_base_url, urllib.urlencode(params)) logging.info('Redirecting to %s', oauth_url) self.redirect(str(oauth_url))
def get(self): cfg = get_config(NAMESPACE) if cfg.orchestator and cfg.orchestator.jwt: deferred.defer(check_node_statuses)
def get(self): if get_config(NAMESPACE).fetch_information: run_job(_get_all_profiles, [], set_user_information, [], qry_transactional=False, worker_queue='iyo-requests')
def encrypt_filename(filename): encryption_key = get_config(NAMESPACE).cloudstorage_encryption_key return hmac.new(encryption_key.encode(), unicode(filename), hashlib.sha1).hexdigest()
def friend_invited(rt_settings, request_id, user_details, **kwargs): user_details = log_and_parse_user_details(user_details) if user_details[0].app_id == get_config(NAMESPACE).rogerthat.app_id: return ACCEPT_ID return DECLINE_ID
def _get_fiat_rate(): # Max 1000 calls / month with free account return _fetch('https://v3.exchangerate-api.com/bulk/%s/USD' % get_config(NAMESPACE).exchangerate_key)
def get_intercom_webhook_hub_secret(): return get_config(NAMESPACE)["intercom_webhook_hub_secret"]
def get_intercom_api_key(): return get_config(NAMESPACE)["intercom_api_access_key"]
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # @@license_version:1.5@@ from __future__ import unicode_literals import re from framework.bizz.authentication import get_current_session from framework.plugin_loader import get_config from plugins.its_you_online_auth.plugin_consts import NAMESPACE as IYO_NAMESPACE config = get_config(IYO_NAMESPACE) ROOT_ORGANIZATION = config.root_organization.name APP_REGEX = re.compile('^user:memberof:%s.backends.(.*?).apps.(.*?).(admins|editors)$' % ROOT_ORGANIZATION) APPS_PERM_REGEX = re.compile('^user:memberof:%s.backends.(.*?).apps.(admins|creators)$' % ROOT_ORGANIZATION) BACKEND_REGEX = re.compile('^user:memberof:%s.backends.(.*?).(admins|editors)$' % ROOT_ORGANIZATION) DEV_ACC_REGEX = re.compile('^user:memberof:%s.developeraccounts.(.*?).(admins|editors|viewers)$' % ROOT_ORGANIZATION) DEVELOPER_ACCOUNTS_ALL_REGEX = re.compile('^user:memberof:%s.developeraccounts.(admins|editors)$' % ROOT_ORGANIZATION) class Roles(object): ADMINS = 'admins' EDITORS = 'editors' VIEWERS = 'viewers' CREATORS = 'creators' @staticmethod
def get_rogerthat_api_key(): return get_config(NAMESPACE)["rogerthat_api_key"]