Example #1
0
    def current_view_html(self):
        """ This func uses session's 'current_view' attribute to render the html
        for that view.

        In a best case, we want this function to initialize a class (e.g. a
        Settlement or a Survivor or a User, etc.) and then use one of the render
        methods of that class to get html and return it.

        The whole thing is decorated in a function that captures failures and
        asks users to report them (and kills their session, logging them out, so
        they don't get stuck in a state where they can't stop re-creating the
        error, etc.
        """

        output = html.meta.saved_dialog
        output += html.meta.corner_loader
        self.get_current_view() # sets self.current_view

        body = None

        output += html.meta.full_page_loader

        if self.current_view == "dashboard":
            body = "dashboard"
            output += self.render_dashboard()
            output += admin.dashboard_alert()
            if get_user_agent().browser.family == "Safari":
                output += html.meta.safari_warning.safe_substitute(vers=get_user_agent().browser.version_string)

        elif self.current_view == "view_campaign":
            output += html.dashboard.refresh_button
            self.set_current_settlement()
            output += self.Settlement.render_html_summary(user_id=self.User.user["_id"])

        elif self.current_view == "new_settlement":
            output += html.settlement.new

        elif self.current_view == "view_settlement":
            output += html.dashboard.refresh_button
            output += self.render_user_asset_sheet("settlements")

        elif self.current_view == "view_survivor":
            output += html.dashboard.refresh_button
            output += self.render_user_asset_sheet("survivors")

        elif self.current_view == "panel":
            if self.User.is_admin():
                P = admin.Panel(self.User.user["login"])
                body = "helvetica"
                output += P.render_html()
            else:
                self.logger.warn("[%s] attempted to view admin panel and is not an admin!" % self.User)
                raise Exception("Authorization failure!")

        else:
            self.logger.error("[%s] requested unhandled view '%s'" % (self.User, self.current_view))
            raise Exception("Unknown View!")


        return output, body
Example #2
0
def get_model_template(addr, session, model, revision):
    url = 'http://%s:%s/api/template' % (addr, utils.get_port())
    headers = {'User-Agent': utils.get_user_agent()}
    cookies = {'medlinkToken': session}
    payload = {'modelSeries': model, 'revision': revision}

    i = 0

    while i < 3:
        r = ensure_success(lambda: requests.get(url,
                                                headers=headers,
                                                params=payload,
                                                cookies=cookies,
                                                verify=False))
        conent = r.content.decode("UTF-8")
        try:
            if conent != None:
                return json.loads(conent)
        except Exception:
            print(i)

        i += 1
        print(r)

        return Verdict.MUMBLE("Check api/template")
Example #3
0
def check_proxy(i, proxy):
        proxy_auth = proxy[1]
        service_args = [
            '--proxy={}'.format(proxy[0]),
            '--proxy-type=http',
            '--ignore-ssl-errors=true'
        ]
        
        if proxy_auth:
            service_args.append('--proxy-auth={}'.format(proxy_auth))

        print("")
        logging.info("[{}/{}] Testing proxy: {}".format(i + 1, len(proxies), proxy))

        user_agent = get_user_agent()
        desired_capabilities = get_desired_capabilities_phantom(user_agent)
        browser = webdriver.PhantomJS(executable_path=find_path('phantomjs'), service_args=service_args, desired_capabilities=desired_capabilities)
        browser.set_page_load_timeout(30)

        # Proxy testing
        try:
            browser.get('http://tools.yzy.io/ip.php')
            element = WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.TAG_NAME, "body")))

            if not element:
                logging.error('[{}/{}] Proxy could not load URL: {}'.format(i + 1, len(proxies), 'http://tools.yzy.io/ip.php'))
                return

            logging.info('[{}/{}] Proxy using IP: {}'.format(i + 1, len(proxies), element.text))
        except TimeoutException:
            logging.error('[{}/{}] Proxy Time-out: {}'.format(i + 1, len(proxies), proxy))
            return
        except Exception as e:
            logging.error('[{}/{}] {}'.format(i + 1, len(proxies), e))
            return

        try:
            browser.get(PRODUCT_URL)

            if ('you have been blocked' in browser.page_source.lower()) or ('a security issue was automatically identified' in browser.page_source.lower()):
                logging.error('[{}/{}] Proxy Banned on {}'.format(i + 1, len(proxies), PRODUCT_URL))
                return

            element = WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.TAG_NAME, "div")))
            if not element:
                logging.error('[{}/{}] Proxy could not load URL: {}'.format(i + 1, len(proxies), PRODUCT_URL))

            logging.info('[{}/{}] Proxy Test Success'.format(i + 1, len(proxies)))
            time.sleep(5)
            faceless_browsers.append({
                'browser': browser,
                'user_agent': user_agent,
                'proxy': proxy
            })
        except TimeoutException:
            logging.error('[{}/{}] Proxy Time-out: {}'.format(i + 1, len(proxies), proxy))
            return
        except Exception as e:
            logging.error('[{}/{}] {}'.format(i + 1, len(proxies), e))
            return
Example #4
0
def id_convert(values, idtype=None):
    """
    Get data from the id converter API.
    https://www.ncbi.nlm.nih.gov/pmc/tools/id-converter-api/
    """
    base = 'http://www.pubmedcentral.nih.gov/utils/idconv/v1.0/'
    ua = get_user_agent()
    params = {
        'ids': values,
        'format': 'json',
    }
    if idtype is not None:
        params['idtype'] = idtype

    #Make request with user agent.
    resp = requests.get(base, params=params, headers=ua)
    raw = resp.json()
    records = raw.get('records')
    if records is None:
        return None
    status = records[0].get('status')
    if status == u"error":
        return None

    return raw['records'][0]
Example #5
0
def _transfer_test():
    # which proxy to use? 0 = first
    # TODO: add a better way to specify the proxy
    PROXY_INDEX = 0

    # Session Transfer Testing
    PROXIES = import_proxies_from_file()

    proxy, proxy_auth = PROXIES[PROXY_INDEX]
    service_args = [
        '--proxy={}'.format(proxy), '--proxy-type=html',
        '--ignore-ssl-errors=true'
    ]
    if proxy_auth:
        service_args.append('--proxy-auth={}'.format(proxy_auth))

    browser = webdriver.PhantomJS(executable_path='bin/phantomjs',
                                  service_args=service_args)
    browser.set_page_load_timeout(30)

    add_to_cart(browser, cc='US')

    payload = {
        'browser': browser,
        'user_agent': get_user_agent(),
        'proxy': proxy
    }

    # Test transferring session (go to ipecho.net to see ip, got to cart to see if in cart)
    threading.Thread(target=transfer_session, kwargs={
        'browser': payload
    }).start()

    time.sleep(60 * 60)
Example #6
0
def doi_search(doi):
    """
    Search Pubmed by DOI to get a Pubmed ID.

    For some reason, this returns more results than above.
    """
    if doi is None:
        raise Exception("No DOI passed to search.")
    base = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term={}[doi]&retmode=json"
    surl = base.format(doi)
    ua = get_user_agent()
    #Make request with user agent.
    resp = requests.get(surl, headers=ua)
    raw = resp.json()
    results = raw.get('esearchresult')
    if results is not None:
        id_list = results.get('idlist')
        #Check empty list or null value.
        if (id_list == []) or (id_list is None):
            return None
        elif len(id_list) > 1:
            raise Exception("Multiple PMID ids returned for Pubmed DOI search.")
        else:
            return id_list[0]
    return None
Example #7
0
def get_supported_bodies(addr, session):
    url = 'http://%s:%s/api/bodymodels' % (addr, utils.get_port())
    headers = {'User-Agent': utils.get_user_agent()}
    cookies = {'medlinkToken': session}
    r = ensure_success(lambda: requests.get(
        url, headers=headers, cookies=cookies, verify=False))

    return json.loads(r.content.decode("UTF-8"))
Example #8
0
def add_executor(addr, id, apikey):
    url = 'http://%s/executor' % addr
    headers = {'User-Agent': utils.get_user_agent()}
    payload = {"ExecutorId": id,
           'ExecutorApiKey': apikey
           }
    r = ensure_success(lambda: requests.put(url, headers=headers, data=json.dumps(payload), verify=False))
    return payload
Example #9
0
def fetch(url, proxy=None):

    s = requests.session()
    s.headers.update({'user-agent': get_user_agent()})
    proxies = None
    if proxy is not None:
        proxies = {'http': proxy}
    return s.get(url, timeout=TIMEOUT, proxies=proxies)
Example #10
0
    def verify_user_email(self, request):
        self.verified_at = now()
        self.verif_ua = get_user_agent(request)
        self.verif_ip = get_client_ip(request)
        self.save()

        auth_user = self.auth_user
        auth_user.email_verified = True
        auth_user.save()
Example #11
0
    def verify_user_email(self, request):
        self.verified_at = now()
        self.verif_ua = get_user_agent(request)
        self.verif_ip = get_client_ip(request)
        self.save()

        auth_user = self.auth_user
        auth_user.email_verified = True
        auth_user.save()
Example #12
0
def get_executor(addr, id, apikey):
    url = 'http://%s/executor' % addr
    headers = {'User-Agent': utils.get_user_agent()}
    payload = {
        'ExecutorId': id,
        'ExecutorApiKey': apikey}
    r = ensure_success(lambda: requests.get(url, headers=headers, data=json.dumps(payload), verify=False))

    return json.loads(r.content.decode("UTF-8"))
Example #13
0
def add_command(addr, id, apikey, command_name):
    url = 'http://%s/command' % addr
    headers = {'User-Agent': utils.get_user_agent()}
    payload = {
        'ExecutorId': id,
        'ExecutorApiKey': apikey,
        'CommandName': command_name
    }
    r = ensure_success(lambda: requests.put(url, headers=headers, data=json.dumps(payload), verify=False))
Example #14
0
def register_user(addr):
    url = 'http://%s:%s/api/signin' % (addr, utils.get_port())
    headers = {'User-Agent': utils.get_user_agent()}
    user = {"login": utils.get_name(), "password": utils.get_password()}
    r = ensure_success(
        lambda: requests.post(url, headers=headers, data=user, verify=False))

    user["session"] = r.content.decode("UTF-8")
    return user
Example #15
0
def add_victim(addr, id, apikey, name, informer):
    url = 'http://%s/victim' % addr
    headers = {'User-Agent': utils.get_user_agent()}
    payload = {
        'ExecutorId': id,
        'ExecutorApiKey': apikey,
        'VictimName': name,
        'InformerName': informer
    }
    r = ensure_success(lambda: requests.put(url, headers=headers, data=json.dumps(payload), verify=False))
Example #16
0
 def fetch(self, pmid):
     doc_url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=%s&retmode=json' % pmid
     ua = get_user_agent()
     resp = requests.get(doc_url, headers=ua)
     raw = resp.json()
     if raw.get('error') is None:
         meta = raw['result'][pmid]
         return meta
     else:
         raise Exception("No PMID found with this ID {0}.".format(doc_url))
Example #17
0
def put_body(addr, session, body_model, token):
    url = 'http://%s:%s/api/bodymodel' % (addr, utils.get_port())
    headers = {'User-Agent': utils.get_user_agent()}
    cookies = {'medlinkToken': session}
    payload = {'vendorToken': token}
    r = ensure_success(lambda: requests.put(url,
                                            headers=headers,
                                            json=body_model,
                                            params=payload,
                                            cookies=cookies,
                                            verify=False))
Example #18
0
 def http_request(self, req):
     # 默认的头信息
     req.add_header('Accept-Encoding', 'gzip, deflate')
     req.add_header('User-Agent', get_user_agent())
     req.add_header('Accept-Language',
                    'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3')
     if self.additional_headers is not None:
         req.headers.update(self.additional_headers)
     if self.cookiejar is not None:
         self.cookiejar.add_cookie_header(req)
     return req
Example #19
0
 def http_request(self, req):
     # 默认的头信息
     req.add_header('Accept-Encoding', 'gzip, deflate')
     req.add_header('User-Agent', get_user_agent())
     req.add_header('Accept-Language',
                    'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3')
     if self.additional_headers is not None:
         req.headers.update(self.additional_headers)
     if self.cookiejar is not None:
         self.cookiejar.add_cookie_header(req)
     return req
Example #20
0
def metadata_search(search_string):
    """
    Search the metadata API.
    """
    base = "http://search.crossref.org/dois?q={0}".format(search_string)
    ua = get_user_agent()
    resp = requests.get(base, headers=ua)
    data = resp.json()
    if len(data) == 0:
        raise CrossRefSearchException("No CR metadata search results")
    else:
        return data
def metadata_search(search_string):
    """
    Search the metadata API.
    """
    base = "http://search.crossref.org/dois?q={0}".format(search_string)
    ua = get_user_agent()
    resp = requests.get(base, headers=ua)
    data = resp.json()
    if len(data) == 0:
        raise CrossRefSearchException("No CR metadata search results")
    else:
        return data
Example #22
0
 def post(self, xml):
     """
     Post the given doc to the service, parse the returned
     PMIDs into a list, and return list.
     """
     url = SERVICE_URL
     headers = {'Content-Type': 'text/xml'}
     ua = get_user_agent()
     headers.update(ua)
     resp = requests.post(url, data=xml, headers=headers)
     logger.debug("Disambiguation service status code.", resp.status_code)
     return resp.text
Example #23
0
    def new(self, login, password):
        """ Creates a new session. Needs a valid user login and password..

        Updates the session with a User object ('self.User') and a new Session
        object ('self.session'). """

        user = mdb.users.find_one({"login": login})
        mdb.sessions.remove({"login": user["login"]})

        # new! get a JWT token and add it to your sesh so that your sesh can be
        # used to add it to your cookie

        token = api.get_jwt_token(login, password)

        if token:
            self.logger.debug("[%s (%s)] JWT token retrieved!" %
                              (user["login"], user["_id"]))

        session_dict = {
            "login": login,
            "created_on": datetime.now(),
            "created_by": user["_id"],
            "current_view": "dashboard",
            "user_agent": {
                "is_mobile": get_user_agent().is_mobile,
                "browser": get_user_agent().browser
            },
            "access_token": token,
        }

        session_id = mdb.sessions.insert(session_dict)
        self.session = mdb.sessions.find_one({"_id": session_id})

        # update the user with the session ID
        user["current_session"] = session_id
        mdb.users.save(user)

        self.User = assets.User(user["_id"], session_object=self)

        return session_id  # passes this back to the html.create_cookie_js()
Example #24
0
def signup(request):
    user = request.user
    if user.is_authenticated:
        return HttpResponseRedirect(reverse_lazy('dashboard'))
    form = RegistrationForm()
    if request.method == 'POST':
        form = RegistrationForm(data=request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            existing_user = get_object_or_None(AuthUser, email=email)

            if existing_user:
                msg = _('That email already belongs to someone, please login:'******'Login Successful')
                messages.success(request, msg)

                return HttpResponseRedirect(reverse_lazy('dashboard'))

    elif request.method == 'GET':
        # Preseed name and/or email if passed through GET string
        email = request.GET.get('e')
        full_name = request.GET.get('name')
        if email or full_name:
            form = RegistrationForm(initial={
                'email': email,
                'full_name': full_name,
                })

    return {
            'form': form,
            'is_input_page': True,
            }
Example #25
0
def signup(request):
    user = request.user
    if user.is_authenticated():
        return HttpResponseRedirect(reverse_lazy('dashboard'))
    form = RegistrationForm()
    if request.method == 'POST':
        form = RegistrationForm(data=request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            existing_user = get_object_or_None(AuthUser, email=email)

            if existing_user:
                msg = _('That email already belongs to someone, please login:'******'Login Successful')
                messages.success(request, msg)

                return HttpResponseRedirect(reverse_lazy('dashboard'))

    elif request.method == 'GET':
        # Preseed name and/or email if passed through GET string
        email = request.GET.get('e')
        full_name = request.GET.get('name')
        if email or full_name:
            form = RegistrationForm(initial={
                'email': email,
                'full_name': full_name,
                })

    return {
            'form': form,
            'is_input_page': True,
            }
Example #26
0
def get_body(addr, session, model, revision, token):
    url = 'http://%s:%s/api/bodymodel' % (addr, utils.get_port())
    headers = {'User-Agent': utils.get_user_agent()}
    cookies = {'medlinkToken': session}
    payload = {
        'modelSeries': model,
        'revision': revision,
        'vendorToken': token
    }
    r = ensure_success(lambda: requests.get(
        url, headers=headers, params=payload, cookies=cookies, verify=False))

    return json.loads(r.content.decode("UTF-8"))
def fetch(url):
    s = requests.Session()
    s.headers.update({'user-agent': get_user_agent()})
    proxies = {
        'http': Proxy.get_random()['address'],
    }
    html_text = s.get(url, timeout=TIMEOUT, proxies=proxies).text
    js_url = gen_js_url(url)
    try:
        js_data = s.get(js_url, timeout=TIMEOUT, proxies=proxies).json()
    except JSONDecodeError:
        raise RequestException()
    return html_text, js_data
Example #28
0
def fetch(url):
    s = requests.Session()
    s.headers.update({'user-agent': get_user_agent()})
    proxies = {
        'http': Proxy.get_random()['address'],
    }
    html_text = s.get(url, timeout=TIMEOUT, proxies=proxies).text
    js_url = gen_js_url(url)
    try:
        js_data = s.get(js_url, timeout=TIMEOUT, proxies=proxies).json()
    except JSONDecodeError:
        raise RequestException()
    return html_text, js_data
def get_crossref_rdf(doi):
    if doi.startswith(doi_prefix):
        pass
    else:
        doi = doi_prefix + doi
    h = {"Accept": "application/rdf+xml"}
    ua = get_user_agent()
    h.update(ua)
    handle = requests.get(doi, headers=h)
    print handle.request.headers
    try:
        graph = Graph().parse(data=handle.text)
    except Exception, e:
        logger.info("Bad DOI:" + doi + "\n" + e)
        return
Example #30
0
def get_crossref_rdf(doi):
    if doi.startswith(doi_prefix):
        pass
    else:
        doi = doi_prefix + doi
    h = {'Accept': 'application/rdf+xml'}
    ua = get_user_agent()
    h.update(ua)
    handle = requests.get(doi, headers=h)
    print handle.request.headers
    try:
        graph = Graph().parse(data=handle.text)
    except Exception, e:
        logger.info("Bad DOI:" + doi + "\n" + e)
        return
Example #31
0
 def log_webhook(cls, request, api_name):
     try:
         data_from_post = json.loads(request.body.decode())
     except Exception:
         client.captureException()
         data_from_post = None
     return cls.objects.create(
             ip_address=get_client_ip(request),
             user_agent=get_user_agent(request),
             api_name=api_name,
             hostname=request.get_host(),
             request_path=request.path,
             uses_https=request.is_secure(),
             data_from_get=request.GET,
             data_from_post=data_from_post,
             )
Example #32
0
 def log_webhook(cls, request, api_name):
     try:
         data_from_post = json.loads(request.body.decode())
     except Exception:
         client.captureException()
         data_from_post = None
     return cls.objects.create(
         ip_address=get_client_ip(request),
         user_agent=get_user_agent(request),
         api_name=api_name,
         hostname=request.get_host(),
         request_path=request.path,
         uses_https=request.is_secure(),
         data_from_get=request.GET,
         data_from_post=data_from_post,
     )
Example #33
0
    def __init__(self, email, password):
        self._email = email
        self._password = password

        self.links = list()
        self._token = None
        self._fp_id = None

        self._session = requests.Session()
        self._session.proxies.update(proxies)
        self._user_agent = utils.get_user_agent()
        headers = {
            'user-agent': self._user_agent
        }
        self._session.headers.update(headers)
        self._driver = self._firefox_config()
        self._driver.implicitly_wait(30)
def get_citeproc(doi):
    """
    Get citeproc from CrossRef.
    """
    if doi.startswith(doi_prefix):
        pass
    else:
        doi = doi_prefix + doi
    h = {"Accept": "application/citeproc+json"}
    ua = get_user_agent()
    h.update(ua)
    handle = requests.get(doi, headers=h)
    try:
        return handle.json()
    except Exception, e:
        logger.error("Bad DOI {0}".format(doi))
        logger.error(e)
        return
Example #35
0
def get_citeproc(doi):
    """
    Get citeproc from CrossRef.
    """
    if doi.startswith(doi_prefix):
        pass
    else:
        doi = doi_prefix + doi
    h = {'Accept': 'application/citeproc+json'}
    ua = get_user_agent()
    h.update(ua)
    handle = requests.get(doi, headers=h)
    try:
        return handle.json()
    except Exception, e:
        logger.error("Bad DOI {0}".format(doi))
        logger.error(e)
        return
async def fetch(url, retry=0):
    proxy = 'http://{}'.format(Proxy.get_random()['address'])
    headers = {'user-agent': get_user_agent()}
    conn = aiohttp.ProxyConnector(proxy=proxy)

    js_url = gen_js_url(url)

    try:
        with aiohttp.ClientSession(connector=conn) as session:
            with aiohttp.Timeout(TIMEOUT):
                async with session.get(url, headers=headers) as resp:
                    html_text = await resp.text()

                async with session.get(js_url, headers=headers) as resp:
                    js_data = await resp.json()
    except:
        retry += 1
        if retry > 5:
            raise CrawlerError()
        await asyncio.sleep(1)
        return await fetch(url, retry=retry)
    return html_text, js_data
async def fetch(url, retry=0):
    proxy = 'http://{}'.format(Proxy.get_random()['address'])
    headers = {'user-agent': get_user_agent()}
    conn = aiohttp.ProxyConnector(proxy=proxy)

    js_url = gen_js_url(url)

    try:
        with aiohttp.ClientSession(connector=conn) as session:
            with aiohttp.Timeout(TIMEOUT):
                async with session.get(url, headers=headers) as resp:
                    html_text = await resp.text()

                async with session.get(js_url, headers=headers) as resp:
                    js_data = await resp.json()
    except:
        retry += 1
        if retry > 5:
            raise CrawlerError()
        await asyncio.sleep(1)
        return await fetch(url, retry=retry)
    return html_text, js_data
Example #38
0
def _transfer_test():
    PROXY_INDEX = 0

    # Session Transfer Testing
    proxy, proxy_auth = get_proxy(PROXY_INDEX)
    service_args = [
        '--proxy={}'.format(proxy), '--proxy-type=html',
        '--ignore-ssl-errors=true'
    ]
    if proxy_auth:
        service_args.append('--proxy-auth={}'.format(proxy_auth))

    driver = webdriver.PhantomJS(executable_path=PHANTOM_JS_LOCATION,
                                 service_args=service_args)
    add_to_cart(driver, cc='US')

    # Test transferring session (go to ipecho.net to see ip, got to cart to see if in cart)
    transfer_session(driver,
                     proxy,
                     proxy_auth,
                     user_agent=get_user_agent(PROXY_INDEX))

    time.sleep(60 * 60)
async def fetch(retry=0):
    proxy = 'http://{}'.format(Proxy.get_random()['address'])
    headers = {'user-agent': get_user_agent()}
    conn = aiohttp.ProxyConnector(proxy=proxy)

    url = 'http://httpbin.org/ip'

    try:
        with aiohttp.ClientSession(connector=conn) as session:
            with aiohttp.Timeout(TIMEOUT):
                async with session.get(url, headers=headers) as resp:
                    return await resp.json()
    except (ProxyConnectionError, TimeoutError):
        try:
            p = Proxy.objects.get(address=proxy)
            if p:
                p.delete()
        except DoesNotExist:
            pass
        retry += 1
        if retry > 5:
            raise TimeoutError()
        await asyncio.sleep(1)
        return await fetch(retry=retry)
Example #40
0
def setup_address_forwarding(request, coin_symbol):

    # kind of tricky because we have to deal with both logged in and new users
    already_authenticated = request.user.is_authenticated()

    initial = {'coin_symbol': coin_symbol}

    if already_authenticated:
        form = KnownUserAddressForwardingForm(initial=initial)
    else:
        form = NewUserAddressForwardingForm(initial=initial)

    if request.method == 'POST':
        if already_authenticated:
            form = KnownUserAddressForwardingForm(data=request.POST)
        else:
            form = NewUserAddressForwardingForm(data=request.POST)

        if form.is_valid():
            coin_symbol = form.cleaned_data['coin_symbol']
            destination_address = form.cleaned_data['coin_address']
            user_email = form.cleaned_data.get('email')
            # optional. null in case of KnownUserAddressForwardingForm

            if already_authenticated:
                auth_user = request.user
            else:
                auth_user = None

                if user_email:
                    # Check for existing user with that email
                    existing_user = get_object_or_None(AuthUser, email=user_email)
                    if existing_user:
                        msg = _('Please first login to this account to create a notification')
                        messages.info(request, msg)
                        return HttpResponseRedirect(existing_user.get_login_uri())

                    else:
                        # Create user with unknown (random) password
                        auth_user = AuthUser.objects.create_user(
                                email=user_email,
                                password=None,  # it will create a random pw
                                creation_ip=get_client_ip(request),
                                creation_user_agent=get_user_agent(request),
                                )

                        # Login the user
                        # http://stackoverflow.com/a/3807891/1754586
                        auth_user.backend = 'django.contrib.auth.backends.ModelBackend'
                        login(request, auth_user)

                        # Log the login
                        LoggedLogin.record_login(request)
                else:
                    # No user email given, proceed anonymously
                    # FIXME: confirm this
                    pass

            # Setup Payment Forwarding
            forwarding_address_details = get_forwarding_address_details(
                    destination_address=destination_address,
                    api_key=BLOCKCYPHER_API_KEY,
                    callback_url=None,  # notifications happen separately (and not always)
                    coin_symbol=coin_symbol,
                    )

            if 'error' in forwarding_address_details:
                # Display error message back to user
                messages.warning(request, forwarding_address_details['error'], extra_tags='safe')

            else:

                initial_address = forwarding_address_details['input_address']

                # create forwarding object
                address_forwarding_obj = AddressForwarding.objects.create(
                        coin_symbol=coin_symbol,
                        initial_address=initial_address,
                        destination_address=destination_address,
                        auth_user=auth_user,
                        blockcypher_id=forwarding_address_details['id'],
                        )

                subscribe_uri = reverse('subscribe_address', kwargs={'coin_symbol': coin_symbol})
                uri_qs = {'a': initial_address}
                if user_email:
                    uri_qs['e'] = user_email
                if already_authenticated:
                    uri_qs['e'] = auth_user.email
                subscribe_uri = '%s?%s' % (subscribe_uri, urlencode(uri_qs))

                initial_addr_uri = reverse('address_overview', kwargs={
                    'coin_symbol': coin_symbol,
                    'address': initial_address,
                    })
                destination_addr_uri = reverse('address_overview', kwargs={
                    'coin_symbol': coin_symbol,
                    'address': destination_address,
                    })
                msg_merge_dict = {
                        'initial_address': initial_address,
                        'initial_addr_uri': initial_addr_uri,
                        'destination_address': destination_address,
                        'destination_addr_uri': destination_addr_uri,
                        'subscribe_uri': subscribe_uri,
                        'small_payments_msg': SMALL_PAYMENTS_MSG,
                        }
                if auth_user:
                    msg_merge_dict['user_email'] = auth_user.email

                if user_email or (already_authenticated and form.cleaned_data['wants_email_notification']):

                    # Create an address subscription for all of these cases

                    # Hit blockcypher and return subscription id
                    callback_uri = reverse('address_webhook', kwargs={
                        'secret_key': WEBHOOK_SECRET_KEY,
                        # hack for rare case of two webhooks requested on same address:
                        'ignored_key': simple_pw_generator(num_chars=10),
                        })
                    callback_url = uri_to_url(callback_uri)
                    bcy_id = subscribe_to_address_webhook(
                            subscription_address=initial_address,
                            callback_url=callback_url,
                            coin_symbol=coin_symbol,
                            api_key=BLOCKCYPHER_API_KEY,
                            )

                    # only notify for deposits
                    AddressSubscription.objects.create(
                            coin_symbol=coin_symbol,
                            b58_address=initial_address,
                            auth_user=auth_user,
                            blockcypher_id=bcy_id,
                            notify_on_deposit=True,
                            notify_on_withdrawal=False,
                            address_forwarding_obj=address_forwarding_obj,
                            )

                    if user_email:
                        # New signup
                        msg = _('''
                        Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
                        will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>,
                        but you must confirm your email to receive notifications.
                        <br /><br /> <i>%(small_payments_msg)s</i>
                        ''' % msg_merge_dict)
                        messages.success(request, msg, extra_tags='safe')

                        address_forwarding_obj.send_forwarding_welcome_email()
                        return HttpResponseRedirect(reverse('unconfirmed_email'))
                    else:
                        if auth_user.email_verified:

                            msg = _('''
                            Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
                            will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>,
                            and you will immediately receive an email notification at <b>%(user_email)s</b>.
                            <br /><br /> <i>%(small_payments_msg)s</i>
                            ''' % msg_merge_dict)
                            messages.success(request, msg, extra_tags='safe')

                            return HttpResponseRedirect(reverse('dashboard'))

                        else:
                            # existing unconfirmed user
                            msg = _('''
                            Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
                            will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>,
                            but you must confirm your email to receive notifications.
                            <br /><br /> <i>%(small_payments_msg)s</i>
                            ''' % msg_merge_dict)
                            messages.success(request, msg, extra_tags='safe')

                            address_forwarding_obj.send_forwarding_welcome_email()

                            return HttpResponseRedirect(reverse('unconfirmed_email'))

                elif already_authenticated:
                    # already authenticated and doesn't want subscriptions
                    msg = _('''
                    Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
                    will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>.
                    You will not receive email notifications (<a href="%(subscribe_uri)s">subscribe</a>).
                    <br /><br /> <i>%(small_payments_msg)s</i>
                    ''' % msg_merge_dict)
                    messages.success(request, msg, extra_tags='safe')

                    return HttpResponseRedirect(reverse('dashboard'))

                else:
                    # New signup sans email
                    msg = _('''
                    Transactions sent to <a href="%(initial_addr_uri)s">%(initial_address)s</a>
                    will now be automatically forwarded to <a href="%(destination_addr_uri)s">%(destination_address)s</a>.
                    You will not receive email notifications (<a href="%(subscribe_uri)s">subscribe</a>).
                    <br /><br /> <i>%(small_payments_msg)s</i>
                    ''' % msg_merge_dict)
                    messages.success(request, msg, extra_tags='safe')

                    return HttpResponseRedirect(destination_addr_uri)

    elif request.method == 'GET':
        coin_address = request.GET.get('a')
        subscriber_email = request.GET.get('e')
        if coin_address:
            initial['coin_address'] = coin_address
        if subscriber_email and not already_authenticated:
            initial['email'] = subscriber_email
        if coin_address or subscriber_email:
            if already_authenticated:
                form = KnownUserAddressForwardingForm(initial=initial)
            else:
                form = NewUserAddressForwardingForm(initial=initial)

    return {
            'form': form,
            'coin_symbol': coin_symbol,
            'is_input_page': True,
            }
Example #41
0
def subscribe_address(request, coin_symbol):

    already_authenticated = request.user.is_authenticated()
    # kind of tricky because we have to deal with both logged in and new users

    initial = {'coin_symbol': coin_symbol}

    if already_authenticated:
        form = KnownUserAddressSubscriptionForm(initial=initial)
    else:
        form = NewUserAddressSubscriptionForm(initial=initial)

    if request.method == 'POST':
        if already_authenticated:
            form = KnownUserAddressSubscriptionForm(data=request.POST)
        else:
            form = NewUserAddressSubscriptionForm(data=request.POST)

        if form.is_valid():
            coin_symbol = form.cleaned_data['coin_symbol']
            coin_address = form.cleaned_data['coin_address']

            if already_authenticated:
                auth_user = request.user
            else:
                user_email = form.cleaned_data['email']
                # Check for existing user with that email
                existing_user = get_object_or_None(AuthUser, email=user_email)
                if existing_user:
                    msg = _('Please first login to this account to create a notification')
                    messages.info(request, msg)
                    return HttpResponseRedirect(existing_user.get_login_uri())

                else:
                    # Create user with unknown (random) password
                    auth_user = AuthUser.objects.create_user(
                            email=user_email,
                            password=None,  # it will create a random pw
                            creation_ip=get_client_ip(request),
                            creation_user_agent=get_user_agent(request),
                            )

                    # Login the user
                    # http://stackoverflow.com/a/3807891/1754586
                    auth_user.backend = 'django.contrib.auth.backends.ModelBackend'
                    login(request, auth_user)

                    # Log the login
                    LoggedLogin.record_login(request)

            existing_subscription_cnt = AddressSubscription.objects.filter(
                    auth_user=auth_user,
                    b58_address=coin_address).count()
            if existing_subscription_cnt:
                msg = _("You're already subscribed to that address. Please choose another address.")
                messages.warning(request, msg)
            else:
                # TODO: this is inefficiently happening before email verification

                # Hit blockcypher and return subscription id
                callback_uri = reverse('address_webhook', kwargs={
                    'secret_key': WEBHOOK_SECRET_KEY,
                    # hack for rare case of two webhooks requested on same address:
                    'ignored_key': simple_pw_generator(num_chars=10),
                    })
                callback_url = uri_to_url(callback_uri)
                bcy_id = subscribe_to_address_webhook(
                        subscription_address=coin_address,
                        callback_url=callback_url,
                        coin_symbol=coin_symbol,
                        api_key=BLOCKCYPHER_API_KEY,
                        )

                address_subscription = AddressSubscription.objects.create(
                        coin_symbol=coin_symbol,
                        b58_address=coin_address,
                        auth_user=auth_user,
                        blockcypher_id=bcy_id,
                        )

                address_uri = reverse('address_overview', kwargs={
                    'coin_symbol': coin_symbol,
                    'address': coin_address,
                    })
                if already_authenticated and auth_user.email_verified:
                    msg = _('You will now be emailed notifications for <a href="%(address_uri)s">%(coin_address)s</a>' % {
                        'coin_address': coin_address,
                        'address_uri': address_uri,
                        })
                    messages.success(request, msg, extra_tags='safe')
                    return HttpResponseRedirect(reverse('dashboard'))
                else:
                    address_subscription.send_notifications_welcome_email()
                    return HttpResponseRedirect(reverse('unconfirmed_email'))

    elif request.method == 'GET':
        coin_address = request.GET.get('a')
        subscriber_email = request.GET.get('e')
        if coin_address:
            initial['coin_address'] = coin_address
        if subscriber_email and not already_authenticated:
            initial['email'] = subscriber_email
        if coin_address or subscriber_email:
            if already_authenticated:
                form = KnownUserAddressSubscriptionForm(initial=initial)
            else:
                form = NewUserAddressSubscriptionForm(initial=initial)

    return {
            'form': form,
            'coin_symbol': coin_symbol,
            'is_input_page': True,
            }
Example #42
0
 def record_login(cls, request):
     return cls.objects.create(
             auth_user=request.user,
             ip_address=get_client_ip(request),
             user_agent=get_user_agent(request),
             )