Why does authenticate directive lead to "Error: type mismatch"? - spray

I'm getting this error in my spray project.
Error:(41, 28) type mismatch;
found : spray.routing.authentication.ContextAuthenticator[co.s4n.authentication.entities.Usuario]
(which expands to) spray.routing.RequestContext => scala.concurrent.Future[scala.util.Either[spray.routing.Rejection,co.s4n.authentication.entities.Usuario]]
required: spray.routing.directives.AuthMagnet[?]
authenticate(validateToken) {
^
This is my TokenValidator trait
trait TokenValidator {
def validateToken: ContextAuthenticator[Usuario] = {
ctx =>
val header = ctx.request.headers.find(_.name == "Access_Token")
if (header isDefined) {
doAuth(header.get)
}
else {
Future(Left(AuthenticationFailedRejection(AuthenticationFailedRejection.CredentialsMissing, List())))
}
}
def doAuth(header: HttpHeader): Future[Authentication[Usuario]] = {
Dao.validateToken(header.value).map {
case Some(usuario) => Right(usuario)
case None => Left(AuthenticationFailedRejection(AuthenticationFailedRejection.CredentialsRejected, List()))
}
}
}
and this is the line where I¡m getting that error
//#DELETE
//localhost:9090/authenticacion/users/{{userEmail}}
val `users/{{email}}` =
pathPrefix(`path-prefix`) {
pathPrefix(`users-path-prefix` / Segment) {
emailRef => {
delete {
authenticate(validateToken) { **HERE!!!!**
usuario =>
.....
}
}
}
}
}
Does anyone know what am I doing wrong?
Thak you all in advance!

The only thing I was missing was to have ExecutionContext in scope and import ExecutionContext.Implicits.global worked fine.
It's to let Futures work as they declare an implicit ExecutionContext parameter.

I know it's a long time since the actual question came, but the way to go with this for Spray is to determine the execution context with the tools that Spray provides:
implicit def executionContext = actorRefFactory.dispatcher

Related

How to throw messages to http response from case class require?

Given a case class with any require
case class Foo(id: Int, value: Int) {
require(value < 0 "value must be bigger than zero")
}
Is possible to throw this messages to http?
val routes = pathPrefix("foos") {
pathEnd {
post {
entity(as[Foo]) { foo =>
saveFoo(foo) match {
case Success(p) => {
complete(StatusCodes.Created)
}
case Failure(f) => {
println(f.getMessage) // unknown error
complete(BadRequest, f.getMessage)
}
}
}
}
}
The Akka-HTTP infrastructure will already convert all errors occurring during unmarshalling into a 400 (BadRequest) error, and the exception message will be automatically used.
With your same code I am getting that behaviour for free. Small changes I made:
the business logic error is now a 500, to avoid confusion
the case class requirement is now consistent with the message (> is required instead of <).
case class Foo(id: Int, value: Int) {
require(value > 0, "value must be bigger than zero")
}
def saveFoo(foo: Foo): Try[Unit] = Success(())
val route = pathPrefix("foos") {
pathEnd {
post {
entity(as[Foo]) { foo =>
saveFoo(foo) match {
case Success(p) => {
complete(StatusCodes.Created)
}
case Failure(f) => {
println(f.getMessage) // unknown error
complete(StatusCodes.InternalServerError, f.getMessage)
}
}
}
}
}
}

Common way to execute a stored proc from both ColdFusion and Railo

I think I've gotten the most simplest scenario built. I just want to pass it by everyone for a sanity check. Here's the idea:
GetErrorCodes.cfm does the following:
<cfscript>
response = new ErrorCodes().WhereXXX(); // ACF or Railo, doesn't matter
</cfscript>
ErrorCodes.cfc:
function WhereXXX() {
return new sproc().exec('app.GetErrorCodes'); // All my functions will do this instead of executing the sproc themselves.
}
sproc.cfc:
component {
function exec(procedure) {
local.result = {};
if (server.ColdFusion.productname == 'Railo') {
return new Railo().exec(arguments.procedure); // Has to be outside of sproc.cfc because ColdFusion throws a syntax error otherwise.
}
local.svc = new storedProc();
local.svc.setProcedure(arguments.procedure);
local.svc.addProcResult(name='qry');
try {
local.obj = local.svc.execute();
local.result.Prefix = local.obj.getPrefix();
local.result.qry = local.obj.getProcResultSets().qry;
} catch(any Exception) {
request.msg = Exception.Detail;
}
return local.result;
}
Railo.cfc:
component {
function exec(procedure) {
local.result = {};
try {
storedproc procedure=arguments.procedure result="local.result.Prefix" returncode="yes" {
procresult name="local.result.qry";
}
} catch(any Exception) {
request.msg = Exception.Message;
}
return local.result;
}
}
So I've been working on this all day, but tell me, is this a sane way to keep the source code the same if it's to be run on either a ColdFusion server or a Railo server?
Um... just use <cfstoredproc> instead of trying to use two different CFScript approaches that are mutually exclusive to each other of the CFML platforms.

Why am I getting this error in a basic Rails+Ember app?

I am trying to do a simple CRUD app using Ember + Rails and I'm getting the following error when trying to go to the /workouts route.
Error while loading route: TypeError {} ember.js?body=1:415
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = meta(this), proto = m.proto;
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
for (var keyName in properties) {
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
Ember.assert("`actions` must be provided at extend time, not at create time, when Ember.ActionHandler is used (i.e. views, controllers & routes).", !((keyName === 'actions') && Ember.ActionHandler.detect(this)));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
this.init.apply(this, arguments);
m.proto = proto;
finishChains(this);
sendEvent(this, "init");
} has no method 'find'
My code is located here: https://github.com/ecl1pse/ember-workouts
What am I doing wrong?
Edit: Upon further investigation I believe the culprit is
EmberWorkouts.WorkoutsRoute = Ember.Route.extend(
model: -> EmberWorkouts.Workout.find()
This doesn't actually return anything. How do I debug from there?
If I replace that with this
EmberWorkouts.WorkoutsRoute = Ember.Route.extend
model: -> [{title: 'hi'}, {title: 'damn'}]
The view actually renders content.
How do I get the model to collect from Rails properly?
Ember Data's interface has changed a little with the current release:
You can clear out the store.js file entirely. Ember Data will automatically set up a data store for you using the REST Adapter (unless you tell it otherwise).
Use model: -> #store.find('workout') instead.
I tested this with your app and it works.
If you haven't read through the Ember Data Guide in the last week or two (it's changed a lot), I would spend a few minutes on it.
The fix for this error (as of ember-data 1.0.0.beta.6) for me was to make sure that the JSON returned from the server included an "id" field for each model, BUT not to explicitly declare the id when setting up the Ember DS.Model.
jbuilder template:
json.scans do
json.array! #scans do |scan|
json.id scan.id # This prop has to be there
json.name scan.name
end
end
Ember model:
EmberApp.Scan = DS.Model.extend(
// Don't include the id prop here
name: DS.attr("string")
)

Criteria building in GORM

if (params.filters) {
def o = JSON.parse(params.filters);
def groupOp = o.groupOp
def fields = o.rules.field
def values = o.rules.data
def op = o.rules.op
println fields
println values
if(groupOp == "AND") {
fields.eachWithIndex {a, i ->
println op[i]
if(op[i].equals( "eq")) {
and{ eq(fields[i], values[i])}
}
if(op[i].equals("ne")) {
and{ ne(fields[i], values[i])}
}
if(op[i].equals("ge")) {
def valu = Double.valueOf( values[i]);
and{ ge(fields[i], valu)}
}
}
}
if(groupOp == "OR") {
fields.eachWithIndex {a, i ->
println op[i]
if(op[i].equals( "eq")) {
println 'eq';
or{ eq(fields[i], values[i])}
}
if(op[i].equals("ne")) {
println 'ne';
or{ ne(fields[i], values[i])}
}
if(op[i].equals("ge")) {
def valu = Double.valueOf( values[i]);
or{ ge(fields[i], valu)}
}
}
}
}
where params.filters is following JSON text.
{
"groupOp":"OR",
"rules":[
{
"field":"foo1",
"op":"le",
"data":"9.5"
},
{
"field":"foo2",
"op":"eq",
"data":"12345-123"
},
{
"field":"foo3",
"op":"cn",
"data":"IDM"
}
]
}
This data is coming from JQuery data grid.
Is there a better way of doing this?
In the code I have just listed only 3 operators, but in real I have 14 operations.
You can use String as Criteria operation, like:
A.withCriteria {
'eq' (id, 1)
}
so you might come to something like
A.withCriteria {
(groupOp) {
for (???) {
(op[i]) (fields[i], parsedVals[i])
}
}
}
Anyway you'll need to sanitize the web-submitted query for only allowed subset of operations. You don't want to receive end execute arbitrary sqlRestriction, right? :D So the code is going to be more complex then this anyway.
Note: wrapping and{} or or {} around single statement has no point, you need to put it around whole block of if-s.
I suggest that you have a look at the source code of the FilterPane plugin. Its service does essentially what you are doing and may give you some ideas for enhancements.

how to use validationResover

Like shown here I want to use the validationResolver to dynamically validate user inputs in my App. Therefore I want to proove, if a condition is true in my controller. If the condition is true, I want to validate with an own validator.
For that I tried that:
public function createAction(Object $newObject) {
$TS = $newObject->getSomeProperty();
$ABT = $newObject->getSomeOtherProperty();
if ($TS === 'specialvalue') {
$validatorResolver->createValidator('Your.Package:Foo'));
}
But I get (of course) an 500-exception:
#1: Notice: Undefined variable: validatorResolver in /var/www...
Please give me a hint how to use the $validatorResolver.
I did it now this way:
public function createAction(Object $newObject) {
$TS = $newObject->getSomeProperty();
$ABT = $newObject->getSomeOtherProperty();
if ($ABT === 'specialvalue') {
$validatorResolver = new \TYPO3\Flow\Validation\ValidatorResolver();
$customValidator = $validatorResolver->createValidator('Your.Package:Foo');
$result = $customValidator->validate($TS);
if ($result->hasErrors()) {
$this->flashMessageContainer->addMessage(new \TYPO3\Flow\Error\Error('Here you can type in the error message!'));
$this->errorAction()->forwardToReferringRequest();
}
}
....
....
}

Resources