What is setMethod() and populateModel() in coldbox framework - coldfusion

What are setMethod(parameter) and populateModel(string) in the given code of the ColdBox framework?
function addUser(event,rc,prc)
{
LOCAL.userBean = populateModel("userBean").init(5,prc.siteid,event.getValue('userid',0));
rc.user = securityService.getUser(LOCAL.userBean);
LOCAL.userBean.setMethod(3);
rc.genderList=globalsService.getGlobals(LOCAL.userBean);
LOCAL.userBean.setMethod(7);
rc.stateList=globalsService.getGlobals(LOCAL.userBean);
event.setLayout("Window");
event.setView("purchase/addUser");
}

SetMethod() would be something specific to the UserBean itself. That isn't something in ColdBox.
PopulateModel although can do a lot more, is usually a way to populate a model by passing a struct. The populate model will loop through the keys in the struct, and if there is a matching property in the model, it will set it.
So model.setUsername( rc.username ) for example, if there is a key called username.
PopulateModel assumes you're sending the rc scope in, but its usually best to validate, and add restrictions so someone can't pass a password via url and set that to a user for example.
Shawn's links are good ones, hope that all helps.

Related

Using ColdBox Framework, How Can I Use BuildLink() Inside of My Model?

I have a CFML ColdBox framework model service which needs to build links. However, models don't have access to the framework SuperType thus don't have access to event.buildLink().
How can I give services within my model the ability to create links? Is there a way to make the buildLink() functionality available through some kind of dependency injection?
Sample model service:
component
singleton
{
function getLinkToUser( required numeric userId ) {
return event.buildLink( "users.#arguments.usersId#" );
}
}
--Update--
Many of the comments suggest that embedding framework functionality into the model may be a mistake, and that buildLink() should really only be used within views. For the most part, I agree, and feel introducing framework services into the model violates encapsulation and concerns.
That being said, let's expand the above code example to a more real-world situation:
Let's say you have a model service which generates emails to customers and the content of those emails is very much determined by complex business rules. In this case, I could see an argument for generating the email content in the model because that is where business rules live.
If you instead generate the email content in the view, you would be executing business logic into a layer which should really only be used for display/output.
Assuming that generating the email body text in the model layer is the right thing to do, doesn't it also make sense that it should also be able to build HTML links based on framework routes within those emails there as well?
I recommend using something like CBMailService and then in the send mail you would render the layout/view, and inside of those, you have access to the event to be able to buildLinks.
You can pass in bodyTokens for variables, into the views, and it will handle the rendering for you.
Hope this helps.
var mail = mailservice.newMail(
to = arguments.recipients,
from = '"Do not reply" <postmaster#noreply>',
subject = arguments.emailSubject,
bodyTokens = bodyTokens,
type = 'html',
additionalInfo = { categories: categories }
);
mail.setBody(
renderer.get()
.renderLayout(
view = "/modules/core/views/email/emailSigninSheet",
layout = "/modules/core/layouts/email"
)
);

Ember Data Model attribute sanitization/escaping to prevent XSS?

How can I perform sanitization on string attributes to prevent XSS? Right now my thoughts are to override my base model's save method and iterate over all the strings in the model and set all the string inputs to safe strings. Would this be a good way to approach this problem or is there a better way?
EDIT:
Problem occurs when saving a name attribute ( alert('xss')) for a person in the app. It saves it in a non-sanitized manner into the database. Then that name is loaded in our other site which does not sanitize the output and that's where the script injection occurs! I'd like to sanitize it before saving it to the DB
Handlebars automatically sanitizes strings. If you want to avoid this, you must explicitly use the triple-brace syntax:
{{{myHtmlString}}}
Rather than trying to sanitise the input, you really ought to change that other site to make sure it html-escapes the data it is presenting from the database. Even if you would "sanitise" things on the Ember side, can you guarantee there are no other vulnerabilities which allow someone to inject HTML in the database?
Always escaping anything being presented is really the only safe way to deal with XSS. If you're filtering input you are very likely to not catch every possible way of injecting unexpected input.

RESTful API and Foreign key handling for POSTs and PUTs

I'm helping develop a new API for an existing database.
I'm using Python 2.7.3, Django 1.5 and the django-rest-framework 2.2.4 with PostgreSQL 9.1
I need/want good documentation for the API, but I'm shorthanded and I hate writing/maintaining documentation (one of my many flaws).
I need to allow consumers of the API to add new "POS" (points of sale) locations. In the Postgres database, there is a foreign key from pos to pos_location_type. So, here is a simplified table structure.
pos_location_type(
id serial,
description text not null
);
pos(
id serial,
pos_name text not null,
pos_location_type_id int not null references pos_location_type(id)
);
So, to allow them to POST a new pos, they will need to give me a "pos_name" an a valid pos_location_type. So, I've been reading about this stuff all weekend. Lots of debates out there.
How is my API consumers going to know what a pos_location_type is? Or what value to pass here?
It seems like I need to tell them where to get a valid list of pos_locations. Something like:
GET /pos_location/
As a quick note, examples of pos_location_type descriptions might be: ('school', 'park', 'office').
I really like the "Browseability" of of the Django REST Framework, but, it doesn't seem to address this type of thing, and I actually had a very nice chat on IRC with Tom Christie earlier today, and he didn't really have an answer on what to do here (or maybe I never made my question clear).
I've looked at Swagger, and that's a very cool/interesting project, but take a look at their "pet" resource on their demo here. Notice it is pretty similar to what I need to do. To add a new pet, you need to pass a category, which they define as class Category(id: long, name: string). How is the consumer suppose to know what to pass here? What's a valid id? or name?
In Django rest framework, I can define/override what is returned in the OPTION call. I guess I could come up with my own little "system" here and return some information like:
pos-location-url: '/pos_location/'
in the generic form, it would be: {resource}-url: '/path/to/resource_list'
and that would sort of work for the documentation side, but I'm not sure if that's really a nice solution programmatically. What if I change the resources location. That would mean that my consumers would need to programmatically make and OPTIONS call for the resource to figure out all of the relations. Maybe not a bad thing, but feels like a little weird.
So, how do people handle this kind of thing?
Final notes: I get the fact that I don't really want a "leaking" abstaction here and have my database peaking thru the API layer, but the fact remains that there is a foreign_key constraint on this existing database and any insert that doesn't have a valid pos_location_type_id is raising an error.
Also, I'm not trying to open up the URI vs. ID debate. Whether the user has to use the pos_location_type_id int value or a URI doesn't matter for this discussion. In either case, they have no idea what to send me.
I've worked with this kind of stuff in the past. I think there is two ways of approaching this problem, the first you already said it, allow an endpoint for users of the API to know what is the id-like value of the pos_location_type. Many API's do this because a person developing from your API is gonna have to read your documentation and will know where to get the pos_location_type values from. End-users should not worry about this, because they will have an interface showing probably a dropdown list of text values.
On the other hand, the way I've also worked this, not very RESTful-like. Let's suppose you have a location in New York, and the POST could be something like:
POST /pos/new_york/
You can handle /pos/(location_name)/ by normalizing the text, then just search on the database for the value or some similarity, if place does not exist then you just create a new one. That in case users can add new places, if not, then the user would have to know what fixed places exist, which again is the first situation we are in.
that way you can avoid pos_location_type in the request data, you could programatically map it to a valid ID.

Django - How to pass dynamic models between pages

I have made a django app that creates models and database tables on the fly. This is, as far as I can tell, the only viable way of doing what I need. The problem arises of how to pass a dynamically created model between pages.
I can think of a few ways of doing such but they all sound horrible. The methods I can think of are:
Use global variables within views.py. This seems like a horrible hack and likely to cause conflicts if there are multiple simultaneous users.
Pass a reference in the URL and use some eval hackery to try and refind the model. This is probably stupid as the model could potentially be garbage collected en route.
Use a place-holder app. This seems like a bad idea due to conflicts between multiple users.
Having an invisible form that posts the model when a link is clicked. Again very hacky.
Is there a good way of doing this, and if not, is one of these methods more viable than the others?
P.S. In case it helps my app receives data (as a json string) from a pre-existing database, and then caches it locally (i.e. on the webserver) creating an appropriate model and table on the fly. The idea is then to present this data and do various filtering and drill downs on it with-out placing undue strain on the main database (as each query returns a few hundred results out of a database of hundreds of millions of data points.) W.R.T. 3, the tables are named based on a hash of the query and time stamp, however a place-holder app would have a predetermined name.
Thanks,
jhoyla
EDITED TO ADD: Thanks guys, I have now solved this problem. I ended up using both answers together to give a complete answer. As I can only accept one I am going to accept the contenttypes one, sadly I don't have the reputation to give upvotes yet, however if/when I ever do I will endeavor to return and upvote appropriately.
The solution in it's totality,
from django.contrib.contenttypes.models import ContentType
view_a(request):
model = create_model(...)
request.session['model'] = ContentType.objects.get_for_model(model)
...
view_b(request):
ctmodel = request.session.get('model', None)
if not ctmodel:
return Http404
model = ctmodel.model_class()
...
My first thought would be to use content types and to pass the type/model information via the url.
You could also use Django's sessions framework, e.g.
def view_a(request):
your_model = request.session.get('your_model', None)
if type(your_model) == YourModel
your_model.name = 'something_else'
request.session['your_model'] = your_model
...
def view_b(request):
your_model = request.session.get('your_model', None)
...
You can store almost anything in the session dictionary, and managing it is also easy:
del request.session['your_model']

GAE: Using properties for keys() in ModelChoiceProperty boxes

I have a model User which appears as a ReferenceProperty in another model, Group.
When I create a form for Group, using Meta, the form's values contain lots of generated strings. I'd like to stop this, and use the username field of User instead.
I already define a key_name. However, str(user.key()) still gives a generated string. I could override key(), but that would be bad. Any thoughts? I want the Group form to use usernames for the ModelChoiceProperty values, and the form to still validate and save. Currently the form prints the string value of key(), according to the source.
The key() in a db.model is an object that contains a bunch of different information, including the kind of object, its name and an id.
So I'm thinking that key().name() would return what you want?
In the docs, it describes all of this.
Having thought about this a little bit harder, I think the correct answer is "don't do that". The Entitys will still have keys, and those keys will correspond to a generated string. The form would have to be hacked to make it work too, so this looks like a ton of hassle to essentially make the code a tiny bit prettier looking.