How to use the build in CRUD-Modell for insert and escape the datas on Codeigniter4 - codeigniter-4

I tried to understand the new ways and possibilities with Codeigniter4.
I see a shorter way by the build in Crud-Model to do the simplest job with a bit less of code.
Do I insert new datas in the controller with this code, after I setup the myModel with the protected variables.?
$this->myModel->insert(['filed1' => 'value1,
'field2' =>$this->request->getPost('field')...
]));
So that works fine.
Now I want to make it a bit more secure and I want to insert only escaped values.
For that CodeIgniter has a lot of built-in functions/helpers. So I try to use "escape()" in this way
$this->myModel->insert(escape(['filed1' => 'value1,
'field2' =>$this->request->getPost('field')...
])));
but it failed with the error "Call to undefined function App\Controllers\escape()"
So how I can insert only escaped values into my db with the nicest/fastest code/Way may which is supported with the build-in basic Crud functions?
Thanks to teach/help me in this point!

escape doesn't work in a global context because that method is a member of the Database class (or rather, a parent class that implements the ConnectionInterface interface).
esc is a global function, which is why that works in a global context.
However, esc is designed to escape data that's going into web pages, not databases.
The good news is, if you're using Query Builder methods, then input is already escaped for you automatically:
It also allows for safer queries, since the values are escaped
automatically by the system.
If for some reason you still need to manually escape input (e.g. using basic queries), there are a few options, including the escape method you were trying to use earlier.

I find a first way with "esc()"
$this->myModel->insert(['filed1' => esc('value1'),
'field2' => esc($this->request->getPost('field'))...
]));
maybe there is a better way or someone has another sugeestion?

Related

Any reason Origen::Parameter set contexts are hidden from the user?

Is there any reason the Origen::Parameters sets do not have a public method for retrieving all of the possible set ids? I do see a public method that works, though it isn't named like it is meant to be used publicly. Why is this not more visible?
[6] pry(#<PPEKit::Product>)> $dut.func._parameter_sets.ids
=> [:default,
:func_default,
:func_harvest_default,
EDIT
#Ginty, I tried your suggestion but it doesn't return the keys I am looking for. In the first sentence in the Parameter docs, the keys I am looking for are referred to 'parameter contexts'. The reason these would be useful would be to do something like this:
my_param_key = :my_param_key
if Origen.top_level.func.has_context? my_param_key
...
Specifically, I am creating parameter contexts from the information in my flow file and would like to verify that they exist before trying to access them. Essentially it is a handshake between my test flow and the test method parameters I am storing using unique (hopefully) parameter IDs/contexts.
thx
In your example, dut.func.params should return a hash-like object which contains all the parameter sets, so to get the IDs is just: dut.func.params.keys
EDIT
I see now that you want a collection containing the available contexts, but it doesn't seem like that is currently provided via an API.
I don't think there is any particular reason for that, probably hasn't been needed until now.
params.context returns the currently active context, I would recommend we add params.contexts and/or params.available_contexts to return an array of the available context names.
Origen now supports knowing the available parameter contexts.

create a new method in Brightway 2

This question is very similar to the one raised here. Is just that I cannot make work the proposed solution (and I don't have the reputation to add comments).
I want to create a method with just the global warming potential of CO2,CH4 and N2O associated with fossil fuel combustion.
looking into biosphere database, I created a list of tuples with the flow's keys and characterization factors:
flows_list=[]
for flow in bw.Database('biosphere3'):
if 'Carbon dioxide, fossil' in flow['name']:
flows_list.append((flow.key,1.0))
if flow['name']=='Methane':
flows_list.append((flow.key,29.7))
if flow['name']=='Dinitrogen monoxide':
flows_list.append((flow.key,264.8))
and then:
ipcc2013_onlyfossil=bw.Method(('IPCC2013_onlyfossil','climate change','GWP100a'))
ipcc2013_onlyfossil.register(**{'unit':'kg CO2eq',
'num_cfs':11,
'abbreviation':'nonexistent',
'description':'based on IPCC 2013 method but just for fossil CO2, CH4 and N2O',
'filename':'nonexistent'})
(I don't understand the purpose of the double ** or if we can leave keys in the dictionary metadata empty)
lastly:
ipcc2013_onlyfossil.write(flows_list)
I must be doing something wrong, because If I try to use this method I get an assertion error, Brightway can't find the model.
UPDATE: There was a error in my code, the new method works perfectly fine.
For instance, If I run:
[m for m in bw.methods if 'IPCC' in m[0]
and 'GWP100' in str(m)]
I get at list of methods, including the one I attempted to create and I can do LCA calculations with it.
(PS: it is not very clear to me how I should use the validate() method of the method class..)
There are a bunch of questions here...
How do I create and write a new method?
Your code works perfectly on my computer, and it should - it's doing the same thing that the base methods importer does. Maybe you can be more explicit on what "If I try to use this method I get an assertion error" means?
After running your code, you should be able to do ipcc2013_onlyfossil.metadata or ipcc2013_onlyfossil.load(). It is there!
How should I use the validate() function?
If you ask for the docstring in IPython, you get an idea:
> m.validate?
Signature: m.validate(data)
Docstring: Validate data. Must be called manually.
So you can do ipcc2013_onlyfossil.validate(flows_list), but you don't need to: your code is fine.
What metadata should I provide to Method.register()?
No metadata is required, and you should skip anything you don't know. abbreviation and 'num_cfs' are generated automatically.
What does ** mean?
Good answers already exist

How can I get NDepend to fail analysis if new calls are used to a deprecated type?

We have a type named OldThing which we want to deprecate over time.
We need an NDepend query/rule that says from this point on, don't add any more calls to 'OldThing'.
We currently use NDepend and have a baseline build for checking things like don't make large methods even larger.
So, we'd like to use NDepend to track any additional calls made to OldThing. I have the following CQL query:
// <Name>Don't use OldThing going forwards</Name>
warnif count > 0
let containsMethods = Methods.WithFullNameIn(
"MyNamespace.OldType.get_Foo()",
"MyNamespace.OldType.get_Bar()")
from m in Application.Methods.UsingAny(containsMethods)
where m.IsUsedRecently()
select m
... the trouble is, it doesn't seem to work; it doesn't find any new calls.
Is there a better way of doing this in NDepend (perhaps by utilising trend metrics)?
You don't need where m.IsUsedRecently(), this is only for third-party method calls.
Then you need to double check that the let expression is matching the proper deprecated methods (you could also match them all at once by using the ObsoleteAttribute).
Finally you should make this rule critical and it should work :)

ADO Command.Execute With Array of Parameters & SQL Injection

Quick question... I have to work with quite a bit of legacy ASP code that I am cleaning up, and it all uses queries that are vulnerable to SQL injection. I have a library that I put together to replace them with parameterized queries, and I'm wondering if there is a difference from a security standpoint between the following approaches.
Approach 1: This is the approach shown on most examples where parameter objects are individually built and added to the Command object. Here's an example from another question.
Approach 2: Use the Command.Execute method with an array of parameter values. Example:
Command.CommandText = "select foo, bar from baz where a = ? and b = ?"
Command.Execute , Array(1, "BBB")
Yes, the first parameter to Execute is ignored.
The first approach has each parameter built with its type, size, etc all specified, and it needs to match the database. But I've always had trouble with that approach, weird errors and the like if everything isn't "just" perfect. So I prefer the latter, and it in fact works with my coding style much better because I can encapsulate the DB logic into a class and pass around arrays as needed without having to litter my code with tons of DB calls.
Example of approach #2 using my wrapper DB.Query method:
set rs = DB.Query("select foo, bar from baz where a = ? and b = ?", Array(1, "BBB")
Or:
set rs = DB.Query("select foo, bar from baz", empty)
(passing keyword empty to denote the parameter is not used)
Given that, I'm wondering: Is approach #2 still safe from SQL injection attacks?
Thanks.
Edit The call to Execute was wrong and written from memory, it has been corrected.
From my sight: yes it is.
i wrote a quick example and then debugged it with Visual Studio. After the call to
Command.Execute , Array(1, "BBB")
the Parameters object of the ADODB.Command is properly filled with the given values from the Array. The datatype and length of the parameters is correctly set.
So in my opinion this approach is as safe as the approach #1 (with a manually created Parameters object).

Ignore certain TypeScript compile errors?

I am wondering if there is a way to ignore certain TypeScript errors upon compilation?
I basically have the same issues most people with large projects have around using the this keyword, and I don't want to put all my classes methods into the constructor.
So I have got an example like so:
TypeScript Example
Which seems to create perfectly valid JS and allows me to get around the this keyword issue, however as you can see in the example the typescript compiler tells me that I cannot compile that code as the keyword this is not valid within that scope. However I don't see why it is an error as it produces okay code.
So is there a way to tell it to ignore certain errors? I am sure given time there will be a nice way to manage the this keyword, but currently I find it pretty dire.
== Edit ==
(Do not read unless you care about context of this question and partial rant)
Just to add some context to all this to show that I'm not just some nut-job (I am sure a lot of you will still think I am) and that I have some good reasons why I want to be able to allow these errors to go through.
Here are some previous questions I have made which highlight some major problems (imo) with TypeScript current this implementation.
Using lawnchair with Typescript
Issue with child scoping of this in Typescript
https://typescript.codeplex.com/discussions/429350 (And some comments I make down the bottom)
The underlying problem I have is that I need to guarantee that all logic is within a consistent scope, I need to be able to access things within knockout, jQuery etc and the local instance of a class. I used to do this with the var self = this; within the class declaration in JavaScript and worked great. As mentioned in some of these previous questions I cannot do that now, so the only way I can guarantee the scope is to use lambda methods, and the only way I can define one of these as a method within a class is within the constructor, and this part is HEAVILY down to personal preference, but I find it horrific that people seem to think that using that syntax is classed as a recommended pattern and not just a work around.
I know TypeScript is in alpha phase and a lot will change, and I HOPE so much that we get some nicer way to deal with this but currently I either make everything a huge mess just to get typescript working (and this is within Hundreds of files which I'm migrating over to TypeScript ) or I just make the call that I know better than the compiler in this case (VERY DANGEROUS I KNOW) so I can keep my code nice and hopefully when a better pattern comes out for handling this I can migrate it then.
Also just on a side note I know a lot of people are loving the fact that TypeScript is embracing and trying to stay as close to the new JavaScript features and known syntax as possible which is great, but typescript is NOT the next version of JavaScript so I don't see a problem with adding some syntactic sugar to the language as people who want to use the latest and greatest official JavaScript implementation can still do so.
The author's specific issue with this seems to be solved but the question is posed about ignoring errors, and for those who end up here looking how to ignore errors:
If properly fixing the error or using more decent workarounds like already suggested here are not an option, as of TypeScript 2.6 (released on Oct 31, 2017), now there is a way to ignore all errors from a specific line using // #ts-ignore comments before the target line.
The mendtioned documentation is succinct enough, but to recap:
// #ts-ignore
const s : string = false
disables error reporting for this line.
However, this should only be used as a last resort when fixing the error or using hacks like (x as any) is much more trouble than losing all type checking for a line.
As for specifying certain errors, the current (mid-2018) state is discussed here, in Design Meeting Notes (2/16/2018) and further comments, which is basically
"no conclusion yet"
and strong opposition to introducing this fine tuning.
I think your question as posed is an XY problem. What you're going for is how can I ensure that some of my class methods are guaranteed to have a correct this context?
For that problem, I would propose this solution:
class LambdaMethods {
constructor(private message: string) {
this.DoSomething = this.DoSomething.bind(this);
}
public DoSomething() {
alert(this.message);
}
}
This has several benefits.
First, you're being explicit about what's going on. Most programmers are probably not going to understand the subtle semantics about what the difference between the member and method syntax are in terms of codegen.
Second, it makes it very clear, from looking at the constructor, which methods are going to have a guaranteed this context. Critically, from a performance, perspective, you don't want to write all your methods this way, just the ones that absolutely need it.
Finally, it preserves the OOP semantics of the class. You'll actually be able to use super.DoSomething from a derived class implementation of DoSomething.
I'm sure you're aware of the standard form of defining a function without the arrow notation. There's another TypeScript expression that generates the exact same code but without the compile error:
class LambdaMethods {
private message: string;
public DoSomething: () => void;
constructor(message: string) {
this.message = message;
this.DoSomething = () => { alert(this.message); };
}
}
So why is this legal and the other one isn't? Well according to the spec: an arrow function expression preserves the this of its enclosing context. So it preserves the meaning of this from the scope it was declared. But declaring a function at the class level this doesn't actually have a meaning.
Here's an example that's wrong for the exact same reason that might be more clear:
class LambdaMethods {
private message: string;
constructor(message: string) {
this.message = message;
}
var a = this.message; // can't do this
}
The way that initializer works by being combined with the constructor is an implementation detail that can't be relied upon. It could change.
I am sure given time there will be a nice way to manage the this keyword, but currently I find it pretty dire.
One of the high-level goals (that I love) in TypeScript is to extend the JavaScript language and work with it, not fight it. How this operates is tricky but worth learning.

Resources