Пример #1
0
def check_registered_account(context):
    is_credentials_registered = configs.get('is_credentials_registered')
    assert_that(is_credentials_registered, equal_to('true'),
                "This test require a registered account")
    email = configs.get('email')
    password = configs.get('password')
    authenticate(email, password)
Пример #2
0
def login():
	error = None
	if request.method == 'POST':
		if authenticate(request.form['username'], request.form['password']) == 0:
			error = 'Invalid username or password'
		elif authenticate(request.form['username'], request.form['password']) == 1:
			session['logged_in'] = True
			flash('You were logged in')
			return redirect(url_for('show_entries'))
	return render_template('login.html', error=error)
Пример #3
0
def register(request):
  form = RegisterForm()
  if request.method == 'POST':
    form = RegisterForm(request.POST)
    if form.is_valid():
      user = form.save()
      mail_welcome(user)
      authenticate(request, user)
      util.add_success(request, "Welcome to %s" % ConfigData.get_configdata('SITE_NAME'))
      return redirect(reverse('admin_dashboard'))

  c = template.RequestContext(request, locals())
  return render_to_response('users_register.html', c)
Пример #4
0
def login(request):

  redirect_to = request.REQUEST.get('redirect_to', reverse('front'))
  redirect_to = clean.redirect_to(redirect_to)

  form = LoginForm()
  if request.method == 'POST':
    form = LoginForm(data=request.POST)
    if form.is_valid():
      user = form.get_user()
      authenticate(request, user)
      util.set_flash(request, "success_users_login")
      return redirect(redirect_to)
  
  c = template.RequestContext(request, locals())
  return render_to_response('users_login.html', c)
Пример #5
0
 def POST(self):
     post_data = web.input(username=None, password=None)
     user = users.authenticate(post_data.username, post_data.password)
     if user:
         users.login(user)
         web.redirect(url.url_for('home'))
     else:
         return render_template('login.html', data=post_data, bad_pass=True)
Пример #6
0
def login():
    user = users.authenticate(request.form['username'],
                              request.form['password'])
    if user:
        login_user(user)
        session['logged_in'] = True
        session['username'] = user.username
        session['user_id'] = user.id
    else:
        flash('Invalid Credentials! Try again.')
    return redirect(url_for('index'))
Пример #7
0
def install(request):
  area = 'install'

  if ConfigData.get_configdata('site_installed', default=False):
    util.add_error(request, "Site is already installed")
    return http.HttpResponseRedirect(reverse('front'))
  
  form = InstallForm()
  if request.method == 'POST':
    form = InstallForm(request.POST)
    if form.is_valid():
      user = form.save()
      ConfigData.set_configdata('site_installed', True)
      authenticate(request, user)
      util.add_success(request, "Site has been installed successfully")
      return http.HttpResponseRedirect(reverse('admin_dashboard'))

  c = template.RequestContext(request, locals())
  _flag_as_admin(c)
  return render_to_response('install.html', c)
Пример #8
0
    def POST(self):
        post = web.input(_method='POST')
        errors = {}
        try:
            user = users.authenticate(post['username'], post['password'])
            if user:
                users.login(user)
            else:
                errors['__all__'] = lang.AUTH_FAILURE
        except KeyError:
            errors['__all__'] = lang.AUTH_FAILURE

        if errors:
            return render('login.html', errors=errors, next=post.get('next'))
        else:
            return web.seeother(post.get('next','/summary/'))
Пример #9
0
    def POST(self):
        post = web.input(_method='POST')
        errors = {}
        try:
            user = users.authenticate(post['username'], post['password'])
            if user:
                users.login(user)
            else:
                errors['__all__'] = lang.AUTH_FAILURE
        except KeyError:
            errors['__all__'] = lang.AUTH_FAILURE

        if errors:
            return render('login.html', errors=errors, next=post.get('next'))
        else:
            # current_user = user
            return web.seeother(post.get('next', '/default/'))
Пример #10
0
def request_orb_authentication(context, email_status, password_status):
    assert_that(email_status, any_of(equal_to('correct'),
                                     equal_to('incorrect')),
                'unexpected email status')
    assert_that(password_status,
                any_of(equal_to('correct'), equal_to('incorrect')),
                'unexpected password status')
    email = configs.get('email')
    password = configs.get('password')
    if email_status == 'incorrect':
        email = insert_str(email, random_string(1), randint(0, len(email)))
    if password_status == 'incorrect':
        password = insert_str(password, random_string(1),
                              randint(0, len(password)))

    context.auth_response = authenticate(email, password, 401)
    assert_that(context.auth_response['error'],
                equal_to("failed to perform authentication over the entity"))
Пример #11
0
	def POST(self):
		st = time_stamp()
		post = web.input(_method='POST')
		errors = {}
		try:
			user = users.authenticate(post['username'], post['password'])
			if user:
				users.login(user)
				db.users.update({'username' : post['username']},{"$push" :{'updates' : {'time' : st, 'action' : "Login", 'info' : ""}}})
			else:
				errors['__all__'] = lang.AUTH_FAILURE
		except KeyError:
			errors['__all__'] = lang.AUTH_FAILURE
			
		if errors:
			return render('login.html', errors=errors, next=post.get('next'))
		else:
			# current_user = user
			return web.seeother(post.get('next' , '/' ))
Пример #12
0
def check_account_input(context, email, password, username, company):
    inputs = {
        'email': email,
        'password': password,
        'username': username,
        'company': company
    }
    for key, value in inputs.items():
        assert_that(value, any_of(equal_to('with'), equal_to('without')),
                    f"Not expected option to {key}")
    account_input = {
        'email': None,
        'password': None,
        'company': None,
        'username': None,
        'reg_status': 201,
        'auth_status': 201
    }
    if email == "without" or password == "without":
        account_input['reg_status'] = 400
        account_input['auth_status'] = 400
    elif email == "with":
        account_input['email'] = f"test_email_{random_string(3)}@email.com"
        if password == "without":
            account_input['auth_status'] = 403
    elif password == "with":
        account_input['password'] = configs.get('password')
    if username == "with":
        account_input['username'] = f"test_user {random_string(3)}"
    if company == "with":
        account_input['company'] = f"test_company {random_string(3)}"

    register_account(account_input['email'], account_input['password'],
                     account_input['company'], account_input['username'],
                     account_input['reg_status'])
    context.auth_response = authenticate(account_input['email'],
                                         account_input['password'],
                                         account_input['auth_status'])
Пример #13
0
def index():
    if request.method=="GET":
        if 'username' in session:
            return render_template("index.html", username = session['username'])
        else:
            return render_template("index.html")
    if request.method=="POST":
        button = request.form['submit']
        
        if button == "Logout":
            return redirect(url_for('logout'))
        
        if button == "Login":
            email = request.form['email']
            password = request.form['password']
            if (users.authenticate(email, password)):
                user = User(email, password, True)
                login_user(user, remember=False, force=False)
                flash("Logged in successfuly.")
                session['username'] = email
                return render_template("index.html", username = session['username'])
            else:
                return redirect(url_for("oops"))
Пример #14
0
 def decorated(*args, **kwargs):
     auth = request.authorization
     if not auth or not users.authenticate(auth.username, auth.password,
                                           groups):
         return authenticate_error()
     return f(*args, **kwargs)
Пример #15
0
def logs_in_orb_ui(context):
    orb_page(context)
    use_credentials(context)
    check_home_page(context)
    context.token = authenticate(user_email, user_password)['token']
Пример #16
0
def handler(post, path, remoteip, referer, querystring):
    """ Handles the various service method types.
    post:        The GET/POST parameters
    path:        The current system path/code.PATH
    remoteip:    The IP of the caller
    referer:     The referer HTTP header
    querystring: The complete querystring
    return value is a tuple containing MIME type, max-age, content
    """
    # Get service parameters
    account = post["account"]
    username = post["username"]
    password = post["password"]
    method = post["method"]
    animalid = post.integer("animalid")
    formid = post.integer("formid")
    seq = post.integer("seq")
    title = post["title"]
    strip_personal = post.integer("sensitive") == 0

    cache_key = querystring.replace(" ", "")

    # Do we have a cached response for these parameters?
    cached_response = get_cached_response(cache_key)
    if cached_response is not None:
        al.debug("cache hit for %s" % (cache_key), "service.handler")
        return cached_response

    # Are we dealing with multiple databases, but no account was specified?
    if account == "" and MULTIPLE_DATABASES:
        return ("text/plain", 0, 0, "ERROR: No database/alias specified")

    dbo = db.get_database(account)

    if dbo.database in ("FAIL", "DISABLED", "WRONGSERVER"):
        al.error(
            "auth failed - invalid smaccount %s from %s (%s)" %
            (account, remoteip, dbo.database), "service.handler", dbo)
        return ("text/plain", 0, 0,
                "ERROR: Invalid database (%s)" % dbo.database)

    # If the database has disabled the service API, stop now
    if not configuration.service_enabled(dbo):
        al.error("Service API is disabled (%s)" % method, "service.handler",
                 dbo)
        return ("text/plain", 0, 0, "ERROR: Service API is disabled")

    # Do any database updates need doing in this db?
    dbo.installpath = path
    if dbupdate.check_for_updates(dbo):
        dbupdate.perform_updates(dbo)

    # Does the method require us to authenticate? If so, do it.
    user = None
    securitymap = ""
    if method in AUTH_METHODS:
        # If the database has authenticated service methods disabled, stop now
        if not configuration.service_auth_enabled(dbo):
            al.error("Service API for auth methods is disabled (%s)" % method,
                     "service.handler", dbo)
            return ("text/plain", 0, 0,
                    "ERROR: Service API for authenticated methods is disabled")
        user = users.authenticate(dbo, username, password)
        if user is None:
            al.error(
                "auth failed - %s/%s is not a valid username/password from %s"
                % (username, password, remoteip), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid username and password")
        securitymap = users.get_security_map(dbo, user["USERNAME"])

    # Get the preferred locale and timezone for the site
    l = configuration.locale(dbo)
    dbo.locale = l
    dbo.timezone = configuration.timezone(dbo)
    al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title),
            "service.handler", dbo)

    if method == "animal_image":
        hotlink_protect("animal_image", referer)
        if utils.cint(animalid) == 0:
            al.error(
                "animal_image failed, %s is not an animalid" % str(animalid),
                "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            mediadate, data = media.get_image_file_data(
                dbo, "animal", utils.cint(animalid), seq)
            if data == "NOPIC":
                mediadate, data = media.get_image_file_data(dbo, "nopic", 0)
            return set_cached_response(cache_key, "image/jpeg", 86400, 3600,
                                       data)

    elif method == "animal_thumbnail":
        if utils.cint(animalid) == 0:
            al.error(
                "animal_thumbnail failed, %s is not an animalid" %
                str(animalid), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            mediadate, data = media.get_image_file_data(
                dbo, "animalthumb", utils.cint(animalid), seq)
            if data == "NOPIC":
                mediadate, data = media.get_image_file_data(dbo, "nopic", 0)
            return set_cached_response(cache_key, "image/jpeg", 86400, 86400,
                                       data)

    elif method == "animal_view":
        if utils.cint(animalid) == 0:
            al.error(
                "animal_view failed, %s is not an animalid" % str(animalid),
                "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            return set_cached_response(
                cache_key, "text/html", 86400, 120,
                publishers.html.get_animal_view(dbo, utils.cint(animalid)))

    elif method == "animal_view_adoptable_js":
        return set_cached_response(
            cache_key, "application/javascript", 10800, 600,
            publishers.html.get_animal_view_adoptable_js(dbo))

    elif method == "animal_view_adoptable_html":
        return set_cached_response(
            cache_key, "text/html", 86400, 120,
            publishers.html.get_animal_view_adoptable_html(dbo))

    elif method == "dbfs_image":
        hotlink_protect("dbfs_image", referer)
        return set_cached_response(
            cache_key, "image/jpeg", 86400, 86400,
            utils.iif(title.startswith("/"),
                      dbfs.get_string_filepath(dbo, title),
                      dbfs.get_string(dbo, title)))

    elif method == "extra_image":
        hotlink_protect("extra_image", referer)
        return set_cached_response(cache_key, "image/jpeg", 86400, 86400,
                                   dbfs.get_string(dbo, title, "/reports"))

    elif method == "json_adoptable_animal":
        if utils.cint(animalid) == 0:
            al.error(
                "json_adoptable_animal failed, %s is not an animalid" %
                str(animalid), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                       users.VIEW_ANIMAL)
            rs = publishers.base.get_animal_data(
                dbo,
                None,
                utils.cint(animalid),
                include_additional_fields=True)
            return set_cached_response(cache_key, "application/json", 3600,
                                       3600, utils.json(rs))

    elif method == "html_adoptable_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_adoptable_animals(dbo, style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid"), locationid=post.integer("locationid")))

    elif method == "html_adopted_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_adopted_animals(dbo, daysadopted=post.integer("days"), style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid")))

    elif method == "html_deceased_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_deceased_animals(dbo, daysdeceased=post.integer("days"), style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid")))

    elif method == "html_held_animals":
        return set_cached_response(cache_key, "text/html", 10800, 1800, \
            publishers.html.get_held_animals(dbo, style=post["template"], \
                speciesid=post.integer("speciesid"), animaltypeid=post.integer("animaltypeid")))

    elif method == "json_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = publishers.base.get_animal_data(dbo,
                                             None,
                                             include_additional_fields=True)
        if strip_personal: rs = strip_personal_data(rs)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = publishers.base.get_animal_data(dbo,
                                             None,
                                             include_additional_fields=True)
        if strip_personal: rs = strip_personal_data(rs)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_adoptable_animal":
        if utils.cint(animalid) == 0:
            al.error(
                "xml_adoptable_animal failed, %s is not an animalid" %
                str(animalid), "service.handler", dbo)
            return ("text/plain", 0, 0, "ERROR: Invalid animalid")
        else:
            users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                       users.VIEW_ANIMAL)
            rs = publishers.base.get_animal_data(
                dbo,
                None,
                utils.cint(animalid),
                include_additional_fields=True)
            return set_cached_response(cache_key, "application/xml", 3600,
                                       3600, html.xml(rs))

    elif method == "xml_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = publishers.base.get_animal_data(dbo,
                                             None,
                                             include_additional_fields=True)
        if strip_personal: rs = strip_personal_data(rs)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(rs))

    elif method == "json_found_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_FOUND_ANIMAL)
        rs = lostfound.get_foundanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_found_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_FOUND_ANIMAL)
        rs = lostfound.get_foundanimal_last_days(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_found_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_FOUND_ANIMAL)
        rs = lostfound.get_foundanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   html.xml(rs))

    elif method == "json_lost_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_LOST_ANIMAL)
        rs = lostfound.get_lostanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_lost_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_LOST_ANIMAL)
        rs = lostfound.get_lostanimal_last_days(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_lost_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_LOST_ANIMAL)
        rs = lostfound.get_lostanimal_last_days(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   html.xml(rs))

    elif method == "json_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(rs))

    elif method == "jsonp_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(rs)))

    elif method == "xml_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(rs))

    elif method == "html_report":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_REPORT)
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, post)
        rhtml = reports.execute(dbo, crid, username, p)
        return set_cached_response(cache_key, "text/html", 600, 600, rhtml)

    elif method == "csv_mail" or method == "csv_report":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_REPORT)
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, post)
        rows, cols = reports.execute_query(dbo, crid, username, p)
        mcsv = utils.csv(l, rows, cols, True)
        return set_cached_response(cache_key, "text/csv", 600, 600, mcsv)

    elif method == "jsonp_recent_changes":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_recent_changes(dbo)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(sa)))

    elif method == "json_recent_changes":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_recent_changes(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(sa))

    elif method == "xml_recent_changes":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_recent_changes(dbo)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(sa))

    elif method == "jsonp_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_shelter_animals(dbo)
        if strip_personal: sa = strip_personal_data(sa)
        return ("application/javascript", 0, 0,
                "%s(%s);" % (post["callback"], utils.json(sa)))

    elif method == "json_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_shelter_animals(dbo)
        if strip_personal: sa = strip_personal_data(sa)
        return set_cached_response(cache_key, "application/json", 3600, 3600,
                                   utils.json(sa))

    elif method == "xml_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        sa = animal.get_shelter_animals(dbo)
        if strip_personal: sa = strip_personal_data(sa)
        return set_cached_response(cache_key, "application/xml", 3600, 3600,
                                   html.xml(sa))

    elif method == "rss_timeline":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.VIEW_ANIMAL)
        return set_cached_response(cache_key, "application/rss+xml", 3600,
                                   3600, html.timeline_rss(dbo))

    elif method == "upload_animal_image":
        users.check_permission_map(l, user["SUPERUSER"], securitymap,
                                   users.ADD_MEDIA)
        media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid),
                                    post)
        return ("text/plain", 0, 0, "OK")

    elif method == "online_form_html":
        if formid == 0:
            raise utils.ASMError(
                "method online_form_html requires a valid formid")
        return set_cached_response(cache_key, "text/html; charset=utf-8", 120,
                                   120,
                                   onlineform.get_onlineform_html(dbo, formid))

    elif method == "online_form_json":
        if formid == 0:
            raise utils.ASMError(
                "method online_form_json requires a valid formid")
        return set_cached_response(cache_key,
                                   "application/json; charset=utf-8", 30, 30,
                                   onlineform.get_onlineform_json(dbo, formid))

    elif method == "online_form_post":
        flood_protect("online_form_post", remoteip, 15)
        onlineform.insert_onlineformincoming_from_form(dbo, post, remoteip)
        redirect = post["redirect"]
        if redirect == "":
            redirect = BASE_URL + "/static/pages/form_submitted.html"
        return ("redirect", 0, 0, redirect)

    elif method == "sign_document":
        if formid == 0:
            raise utils.ASMError(
                "method sign_document requires a valid formid")
        if post["sig"] == "":
            return set_cached_response(cache_key, "text/html", 2, 2,
                                       sign_document_page(dbo, formid))
        else:
            media.sign_document(dbo, "service", formid, post["sig"],
                                post["signdate"])
            media.create_log(dbo, "service", formid, "ES02",
                             _("Document signed", l))
            return ("text/plain", 0, 0, "OK")

    else:
        al.error("invalid method '%s'" % method, "service.handler", dbo)
        raise utils.ASMError("Invalid method '%s'" % method)
Пример #17
0
def check_users_account(context):
    email = configs.get('email')
    password = configs.get('password')
    auth_response = authenticate(email, password)
    assert_that(auth_response, has_key('token'),
                'Authentication token not found in login response!')
Пример #18
0
def handler(post, remoteip, referer):
    """
    Handles the various service method types.
    data: The GET/POST parameters 
    return value is a tuple containing MIME type, max-age, content
    """
    # Database info
    dbo = db.DatabaseInfo()

    # Get service parameters
    account = post["account"]
    username = post["username"]
    password = post["password"]
    method = post["method"]
    animalid = post.integer("animalid")
    formid = post.integer("formid")
    seq = post.integer("seq")
    title = post["title"]
    cache_key = "a" + account + "u" + username + "p" + password + "m" + method + \
        "i" + str(animalid) + "s" + str(seq) + "f" + str(formid) + "t" + title
    
    # cache keys aren't allowed spaces
    cache_key = cache_key.replace(" ", "")

    # Do we have a cached response for these parameters?
    cached_response = get_cached_response(cache_key)
    if cached_response is not None:
        al.debug("cache hit for %s/%s/%s/%s" % (account, method, animalid, title), "service.handler")
        return cached_response

    # Are we dealing with multiple databases, but no account was specified?
    if account == "" and MULTIPLE_DATABASES:
        return ("text/plan", 0, "ERROR: No database/alias specified")

    # Are we dealing with multiple databases and an account was specified?
    if account != "":
        if MULTIPLE_DATABASES:
            if MULTIPLE_DATABASES_TYPE == "smcom":
                # Is this sheltermanager.com? If so, we need to get the 
                # database connection info (dbo) before we can login.
                dbo = smcom.get_database_info(account)
            else:
                # Look up the database info from our map
                dbo  = db.get_multiple_database_info(account)
            if dbo.database == "FAIL" or dbo.database == "DISABLED": 
                al.error("auth failed - invalid smaccount %s from %s" % (account, remoteip), "service.handler", dbo)
                return ("text/plain", 0, "ERROR: Invalid database")

    # If the database has disabled the service API, stop now
    if not configuration.service_enabled(dbo):
        al.error("Service API is disabled (%s)" % method, "service.handler", dbo)
        return ("text/plain", 0, "ERROR: Service API is disabled")

    # Do any database updates need doing in this db?
    if dbupdate.check_for_updates(dbo):
        dbupdate.perform_updates(dbo)

    # Does the method require us to authenticate? If so, do it.
    user = None
    securitymap = ""
    if method in AUTH_METHODS:
        # If the database has authenticated service methods disabled, stop now
        if not configuration.service_auth_enabled(dbo):
            al.error("Service API for auth methods is disabled (%s)" % method, "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Service API for authenticated methods is disabled")
        user = users.authenticate(dbo, username, password)
        if user is None:
            al.error("auth failed - %s/%s is not a valid username/password from %s" % (username, password, remoteip), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid username and password")
        securitymap = users.get_security_map(dbo, user["USERNAME"])

    # Get the preferred locale and timezone for the site
    l = configuration.locale(dbo)
    dbo.locale = l
    dbo.timezone = configuration.timezone(dbo)
    al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title), "service.handler", dbo)

    if method =="animal_image":
        hotlink_protect("animal_image", referer)
        if animalid == "" or utils.cint(animalid) == 0:
            al.error("animal_image failed, %s is not an animalid" % str(animalid), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid animalid")
        else:
            if seq == 0: seq = 1
            mm = media.get_media_by_seq(dbo, media.ANIMAL, utils.cint(animalid), seq)
            if len(mm) == 0:
                return set_cached_response(cache_key, "image/jpeg", 86400, 120, dbfs.get_string(dbo, "nopic.jpg", "/reports"))
            else:
                return set_cached_response(cache_key, "image/jpeg", 86400, 120, dbfs.get_string(dbo, mm[0]["MEDIANAME"]))

    elif method == "animal_view":
        if animalid == "" or utils.cint(animalid) == 0:
            al.error("animal_view failed, %s is not an animalid" % str(animalid), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid animalid")
        else:
            return set_cached_response(cache_key, "text/html", 120, 120, publish.get_animal_view(dbo, int(animalid)))

    elif method =="dbfs_image":
        hotlink_protect("dbfs_image", referer)
        return set_cached_response(cache_key, "image/jpeg", 86400, 120, dbfs.get_string_filepath(dbo, title))

    elif method =="extra_image":
        hotlink_protect("extra_image", referer)
        return set_cached_response(cache_key, "image/jpeg", 86400, 120, dbfs.get_string(dbo, title, "/reports"))

    elif method == "json_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/json", 3600, 3600, html.json(rs))

    elif method == "jsonp_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return ("application/javascript", 0, "%s(%s);" % (post["callback"], html.json(rs)))

    elif method == "xml_adoptable_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/xml", 3600, 3600, html.xml(rs))

    elif method == "json_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/json", 3600, 3600, html.json(rs))

    elif method == "jsonp_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return ("application/javascript", 0, "%s(%s);" % (post["callback"], html.json(rs)))

    elif method == "xml_recent_adoptions":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/xml", 3600, 3600, html.xml(rs))

    elif method == "html_report":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_REPORT)
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, post)
        rhtml = reports.execute(dbo, crid, username, p)
        return set_cached_response(cache_key, "text/html", 3600, 3600, rhtml)

    elif method == "csv_mail" or method == "csv_report":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_REPORT)
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, post)
        rows, cols = reports.execute_query(dbo, crid, username, p)
        mcsv = utils.csv(l, rows, cols, True)
        return set_cached_response(cache_key, "text/csv", 3600, 3600, mcsv)

    elif method == "jsonp_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return ("application/javascript", 0, "%s(%s);" % (post["callback"], html.json(sa)))

    elif method == "json_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/json", 3600, 3600, html.json(sa))

    elif method == "xml_shelter_animals":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/xml", 3600, 3600, html.xml(sa))

    elif method == "rss_timeline":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.VIEW_ANIMAL)
        return set_cached_response(cache_key, "application/rss+xml", 3600, 3600, html.timeline_rss(dbo))

    elif method == "upload_animal_image":
        users.check_permission_map(l, user["SUPERUSER"], securitymap, users.ADD_MEDIA)
        media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid), post)
        return ("text/plain", 0, "OK")

    elif method == "online_form_html":
        if formid == 0:
            raise utils.ASMError("method online_form_html requires a valid formid")
        return set_cached_response(cache_key, "text/html; charset=utf-8", 120, 120, onlineform.get_onlineform_html(dbo, formid))

    elif method == "online_form_json":
        if formid == 0:
            raise utils.ASMError("method online_form_json requires a valid formid")
        return set_cached_response(cache_key, "text/json; charset=utf-8", 30, 30, onlineform.get_onlineform_json(dbo, formid))

    elif method == "online_form_post":
        flood_protect("online_form_post", remoteip, 15)
        onlineform.insert_onlineformincoming_from_form(dbo, post, remoteip)
        redirect = post["redirect"]
        if redirect == "":
            redirect = BASE_URL + "/static/pages/form_submitted.html"
        return ("redirect", 0, redirect)

    elif method == "sign_document":
        if formid == 0:
            raise utils.ASMError("method sign_document requires a valid formid")
        if post["sig"] == "":
            return set_cached_response(cache_key, "text/html", 2, 2, sign_document_page(dbo, formid))
        else:
            media.sign_document(dbo, "service", formid, post["sig"], post["signdate"])
            return ("text/plain", 0, "OK")

    else:
        al.error("invalid method '%s'" % method, "service.handler", dbo)
        raise utils.ASMError("Invalid method '%s'" % method)
Пример #19
0
def handler(data, remoteip, referer):
    """
    Handles the various service method types.
    data: The GET/POST parameters 
    return value is a tuple containing MIME type, max-age, content
    """
    # Database info
    dbo = db.DatabaseInfo()

    # Get service parameters
    account = utils.df_ks(data, "account")
    username = utils.df_ks(data, "username")
    password = utils.df_ks(data, "password")
    method = utils.df_ks(data, "method")
    animalid = utils.df_ki(data, "animalid")
    formid = utils.df_ki(data, "formid")
    title = utils.df_ks(data, "title")
    cache_key = "a" + account + "u" + username + "p" + password + "m" + method + "a" + str(animalid) + "f" + str(formid) + "t" + title
    
    # cache keys aren't allowed spaces
    cache_key = cache_key.replace(" ", "")

    # Do we have a cached response for these parameters?
    cached_response = get_cached_response(cache_key)
    if cached_response is not None:
        al.debug("cache hit for %s/%s/%s/%s" % (account, method, animalid, title), "service.handler")
        return cached_response

    # Are we dealing with multiple databases, but no account was specified?
    if account == "" and MULTIPLE_DATABASES:
        return ("text/plan", 0, "ERROR: No database/alias specified")

    # Are we dealing with multiple databases and an account was specified?
    if account != "":
        if MULTIPLE_DATABASES:
            if MULTIPLE_DATABASES_TYPE == "smcom":
                # Is this sheltermanager.com? If so, we need to get the 
                # database connection info (dbo) before we can login.
                dbo = smcom.get_database_info(account)
            else:
                # Look up the database info from our map
                dbo  = db.get_multiple_database_info(account)
            if dbo.database == "FAIL" or dbo.database == "DISABLED": 
                al.error("auth failed - invalid smaccount %s from %s" % (account, remoteip), "service.handler", dbo)
                return ("text/plain", 0, "ERROR: Invalid database")

    # Does the method require us to authenticate? If so, do it.
    user = None
    if method in AUTH_METHODS:
        user = users.authenticate(dbo, username, password)
        if user is None:
            al.error("auth failed - %s/%s is not a valid username/password from %s" % (username, password, remoteip), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid username and password")

    # Get the preferred locale for the site
    dbo.locale = configuration.locale(dbo)
    al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title), "service.handler", dbo)

    if method =="animal_image":
        # If we have a hotlinking restriction, enforce it
        if referer != "" and IMAGE_HOTLINKING_ONLY_FROM_DOMAIN != "" and referer.find(IMAGE_HOTLINKING_ONLY_FROM_DOMAIN) == -1:
            raise utils.ASMPermissionError("Image hotlinking is forbidden.")
        if animalid == "" or utils.cint(animalid) == 0:
            al.error("animal_image failed, %s is not an animalid" % str(animalid), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid animalid")
        # If the option is on, forbid hotlinking
        else:
            seq = utils.df_ki(data, "seq")
            if seq == 0: seq = 1
            mm = media.get_media_by_seq(dbo, media.ANIMAL, utils.cint(animalid), seq)
            if len(mm) == 0:
                return ("image/jpeg", 86400, dbfs.get_string(dbo, "nopic.jpg", "/reports"))
            else:
                return ("image/jpeg", 86400, dbfs.get_string(dbo, mm[0]["MEDIANAME"]))

    elif method =="extra_image":
        return ("image/jpeg", 86400, dbfs.get_string(dbo, title, "/reports"))

    elif method == "json_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/json", 3600, html.json(rs))

    elif method == "xml_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/xml", 3600, html.xml(rs))

    elif method == "json_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/json", 3600, html.json(rs))

    elif method == "xml_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/xml", 3600, html.xml(rs))

    elif method == "html_report":
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, data)
        rhtml = reports.execute(dbo, crid, username, p)
        return set_cached_response(cache_key, "text/html", 3600, rhtml)

    elif method == "jsonp_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/javascript", 3600, str(utils.df_ks(data, "callback")) + "(" + html.json(sa) + ")")

    elif method == "json_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/json", 3600, html.json(sa))

    elif method == "xml_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/xml", 3600, html.json(sa))

    elif method == "upload_animal_image":
        media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid), data)
        return ("text/plain", 0, "OK")

    elif method == "online_form_html":
        if formid == 0:
            raise utils.ASMError("method online_form_html requires a valid formid")
        return set_cached_response(cache_key, "text/html", 120, onlineform.get_onlineform_html(dbo, formid))

    elif method == "online_form_post":
        onlineform.insert_onlineformincoming_from_form(dbo, data, remoteip)
        redirect = utils.df_ks(data, "redirect")
        if redirect == "":
            redirect = BASE_URL + "/static/pages/form_submitted.html"
        return ("redirect", 0, redirect)

    else:
        al.error("invalid method '%s'" % method, "service.handler", dbo)
        raise utils.ASMError("Invalid method '%s'" % method)
Пример #20
0
def handler(data, remoteip, referer):
    """
    Handles the various service method types.
    data: The GET/POST parameters 
    return value is a tuple containing MIME type, max-age, content
    """
    # Database info
    dbo = db.DatabaseInfo()

    # Get service parameters
    account = utils.df_ks(data, "account")
    username = utils.df_ks(data, "username")
    password = utils.df_ks(data, "password")
    method = utils.df_ks(data, "method")
    animalid = utils.df_ki(data, "animalid")
    formid = utils.df_ki(data, "formid")
    title = utils.df_ks(data, "title")
    cache_key = "a" + account + "u" + username + "p" + password + "m" + method + "a" + str(
        animalid) + "f" + str(formid) + "t" + title

    # cache keys aren't allowed spaces
    cache_key = cache_key.replace(" ", "")

    # Do we have a cached response for these parameters?
    cached_response = get_cached_response(cache_key)
    if cached_response is not None:
        al.debug(
            "cache hit for %s/%s/%s/%s" % (account, method, animalid, title),
            "service.handler")
        return cached_response

    # Are we dealing with multiple databases, but no account was specified?
    if account == "" and MULTIPLE_DATABASES:
        return ("text/plan", 0, "ERROR: No database/alias specified")

    # Are we dealing with multiple databases and an account was specified?
    if account != "":
        if MULTIPLE_DATABASES:
            if MULTIPLE_DATABASES_TYPE == "smcom":
                # Is this sheltermanager.com? If so, we need to get the
                # database connection info (dbo) before we can login.
                dbo = smcom.get_database_info(account)
            else:
                # Look up the database info from our map
                dbo = db.get_multiple_database_info(account)
            if dbo.database == "FAIL" or dbo.database == "DISABLED":
                al.error(
                    "auth failed - invalid smaccount %s from %s" %
                    (account, remoteip), "service.handler", dbo)
                return ("text/plain", 0, "ERROR: Invalid database")

    # Does the method require us to authenticate? If so, do it.
    user = None
    if method in AUTH_METHODS:
        user = users.authenticate(dbo, username, password)
        if user is None:
            al.error(
                "auth failed - %s/%s is not a valid username/password from %s"
                % (username, password, remoteip), "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid username and password")

    # Get the preferred locale for the site
    dbo.locale = configuration.locale(dbo)
    al.info("call %s->%s [%s %s]" % (username, method, str(animalid), title),
            "service.handler", dbo)

    if method == "animal_image":
        # If we have a hotlinking restriction, enforce it
        if referer != "" and IMAGE_HOTLINKING_ONLY_FROM_DOMAIN != "" and referer.find(
                IMAGE_HOTLINKING_ONLY_FROM_DOMAIN) == -1:
            raise utils.ASMPermissionError("Image hotlinking is forbidden.")
        if animalid == "" or utils.cint(animalid) == 0:
            al.error(
                "animal_image failed, %s is not an animalid" % str(animalid),
                "service.handler", dbo)
            return ("text/plain", 0, "ERROR: Invalid animalid")
        # If the option is on, forbid hotlinking
        else:
            seq = utils.df_ki(data, "seq")
            if seq == 0: seq = 1
            mm = media.get_media_by_seq(dbo, media.ANIMAL,
                                        utils.cint(animalid), seq)
            if len(mm) == 0:
                return ("image/jpeg", 86400,
                        dbfs.get_string(dbo, "nopic.jpg", "/reports"))
            else:
                return ("image/jpeg", 86400,
                        dbfs.get_string(dbo, mm[0]["MEDIANAME"]))

    elif method == "extra_image":
        return ("image/jpeg", 86400, dbfs.get_string(dbo, title, "/reports"))

    elif method == "json_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/json", 3600,
                                   html.json(rs))

    elif method == "xml_adoptable_animals":
        pc = publish.PublishCriteria(configuration.publisher_presets(dbo))
        rs = publish.get_animal_data(dbo, pc, True)
        return set_cached_response(cache_key, "application/xml", 3600,
                                   html.xml(rs))

    elif method == "json_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/json", 3600,
                                   html.json(rs))

    elif method == "xml_recent_adoptions":
        rs = movement.get_recent_adoptions(dbo)
        return set_cached_response(cache_key, "application/xml", 3600,
                                   html.xml(rs))

    elif method == "html_report":
        crid = reports.get_id(dbo, title)
        p = reports.get_criteria_params(dbo, crid, data)
        rhtml = reports.execute(dbo, crid, username, p)
        return set_cached_response(cache_key, "text/html", 3600, rhtml)

    elif method == "jsonp_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(
            cache_key, "application/javascript", 3600,
            str(utils.df_ks(data, "callback")) + "(" + html.json(sa) + ")")

    elif method == "json_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/json", 3600,
                                   html.json(sa))

    elif method == "xml_shelter_animals":
        sa = animal.get_animal_find_simple(dbo, "", "shelter")
        return set_cached_response(cache_key, "application/xml", 3600,
                                   html.json(sa))

    elif method == "upload_animal_image":
        media.attach_file_from_form(dbo, username, media.ANIMAL, int(animalid),
                                    data)
        return ("text/plain", 0, "OK")

    elif method == "online_form_html":
        if formid == 0:
            raise utils.ASMError(
                "method online_form_html requires a valid formid")
        return set_cached_response(cache_key, "text/html", 120,
                                   onlineform.get_onlineform_html(dbo, formid))

    elif method == "online_form_post":
        onlineform.insert_onlineformincoming_from_form(dbo, data, remoteip)
        redirect = utils.df_ks(data, "redirect")
        if redirect == "":
            redirect = BASE_URL + "/static/pages/form_submitted.html"
        return ("redirect", 0, redirect)

    else:
        al.error("invalid method '%s'" % method, "service.handler", dbo)
        raise utils.ASMError("Invalid method '%s'" % method)