def before_request():

    # check that the wsgi's environ set to an app subdomain
    if not service.is_app_domain():
        abort(404)

    # check for app in our system
    host = request.url.split('/')[2]
    domain = host.split(':')[0]
    account_name = domain.split('.')[0]
    account = Account.get_by_name(account_name)
    if account is None:
        return app.response_account_not_found()

    # if this app served as a custom domain, check that the app is allowed
    if request.environ['MUH_IS_CUSTOM_DOMAIN'] and \
       not account.custom_domain:
        return app.response_account_not_found()
    
    # check if the account has a canonical domain setup
    if account.custom_domain and \
       account.canonical_domain and \
       account.canonical_domain != request.environ['MUH_HTTP_HOST']:
        new_url = request.url.replace(
            request.environ['HTTP_HOST'],
            account.canonical_domain,
            1
        )
        return redirect(new_url, code=301)


    # check the app is not over the current month's transfer limit
    if account.transfer: # 0 is unlimited
        rds_key = 'xferm:{account_id}'.format(account_id=account.id)
        rds_field = year_month()
        xfer = rds.hget(rds_key, rds_field)
        if xfer is not None and int(xfer) > account.transfer:
            return app.response_account_transfer_exceeded()

    # new registrations might not have any app uploaded
    if account.application is None:
        return app.response_account_missing()

    # OK, you can go now
    g.account = account
    s = sha1()
    s.update(str(g.account.application.id))
    g.application_hash = s.hexdigest()