sails
Realtime MVC Framework for Node.js
Sails.js | Realtime MVC Framework for Node.js sails.js makes it easy to build custom, enterprise-grade node.js apps. it is designed to resemble the mvc architecture from frameworks like ruby on rails, but with support for the more modern, data-oriented style of web app development. it's especially good for building realtime features like chat.
How to handle multiple auth strategies on a sails.js SPA ?
I'm building a single page app built on Angular for the front-end and sailsjs for the backend. Right now I'm using sails-auth (which uses passportjs internally) to bind my authentication logic to my user model.
I have multiple passport providers installed and available on my frontend, such as passport-github
and passport-facebook
, but also a classic passport-local
so that the user can also signup and login with just his username & password.
I would like my clients (The single page app, and maybe others in the future) to use a token after the auth instead of cookies/sessions so that it's easier to scale and cross-domain requests will also be easier. It will also make mobile integration much easier.
I know I have to use callbacks for OAuth providers, here is the flow that I'm aiming for :
I know that I can replace my sail-auth's sessionAuth
policy by a tokenAuth
policy that can read the token from the headers and query a Tokens
model for example, but then my questions are :
- When using username/password for login, the request can be made with a simple AJAX call so it is easy to pass the token back to the SPA. When using providers like github, etc., when the callback is called, should I just embed the token dynamically into the HTML that I'm serving?
- sail-auth's
policies/passport.js
shows that by default it relies on built-in sessions to persist login/to serialize&deserialize the userID. How do I decouple it from sails built-in sessions so that it generates a token for the user and serve back my index with the token embedded?
Thank you in advance!
Source: (StackOverflow)
Now Using sailsjs v0.10 .
Configure connections.js and models.js and change it to connection: 'localMongodbServer' ,installed npm install sails-mongo.
Aftet all this it shows error
var des = Object.keys(dbs[collectionName].schema).length === 0 ?
^
TypeError: Cannot read property 'schema' of undefined
at Object.module.exports.adapter.describe (app1_test/node_modules/sails-mongo/lib/adapter.js:70:48)
If change collections.js to adapter.js shows error
[err] In model (model1), invalid connection :: someMongodbServer
[err] Must contain an `adapter` key referencing the adapter to use.
Source: (StackOverflow)
So basically I want to do something that I can do in ember with handlebars but without using ember just sails.js and handlebars.
I set up sails project like so: sails new fooProject --template=handlebars
after running npm install sails-generate-views-handlebars
.
Great I have a layout file, all my files end in .handlebars
woot.
But I would like to do something like this:
Views:
views/index.handlebars
{{>header}}
{{yield}}
{{>footer}}
/views/partials/foo.handlebars
<div class="foo stuff">...</div>
Router:
config/routes.js
'/': {
view: 'index',
controller: 'FooController',
action: 'index'
}
Controller:
controllers/FooController
index: function(req, res){
return res.view({partials: 'partials/foo'}); // <-- I want foo partial in the yield.
}
So that I end up with this output:
<header>...</header>
<div class="foo stuff">
<footer>...</footer>
Anytime my user navigates I'd like to render the new partial into that {{yield}}
block without reloading the page. But that doesn't work, (I've tried).
So how would I accomplish this?
To help clarify what I'm going for is a Single Page Application feel without having to use a front-end framework as well.
Source: (StackOverflow)
I'm trying to get authentication working over sockets with sailsjs
and passport
.
The challenge seems to be the fact that a socket connection doesn't have a session, and that sailsjs mocks a request object, causing it to not have Passport middleware setup. This caused nodejs to throw an error, saying that the req
object didn't have a method called logIn
.
So, I've tried following the code snippet as provided by @xdissent here: Sails.js + Passport.js authentication through websockets which, indeed allows me to sign in without throwing errors. Or does it..? It turns out that it does something, But I have no idea what. Because upon fetching req.user
through a different (socket) request, I get an empty object returned.
I've looked in redis, too. This came out of it:
redis 127.0.0.1:6379> keys *
1) "waterline:broadcasting:_sequences:id"
2) "sess:aDJI0YHzh17E3AMjtKsZSijs"
redis 127.0.0.1:6379> get "sess:aDJI0YHzh17E3AMjtKsZSijs"
"{\"cookie\":{\"httpOnly\":true,\"path\":\"/\"}}"
redis 127.0.0.1:6379>
So there is a session, just no user stored in it.
So long story short, how do I get Passport and sailsjs to play nice over sockets.
Update:
I'd like some information about sessions, sockets and cookies with sails in general. So if I set stuff in a session, and refresh the browser, I'd like it to still be there. If I make an xhr call on the same page as the socket connection, shouldn't that be the same session?
Source: (StackOverflow)
I have limited experience deploying Node.js apps -- how can I deploy a Sails.js app to Heroku?
I've heroku login
ed and heroku create
d my app already.
Source: (StackOverflow)
I really like working with SailsJS (http://sailsjs.org). Especially because it automatically generates a RESTful CRUD API. However, working for small clients, I don't always have the opportunity of working in a NodeJS environment. Mostly their webapps run on an Apache (PHP/MySQL) server.
My question: Is there any framework that provides an automatically generated RESTful CRUD API?
If not, what is the best approach to write it myself?
I'm aware of frameworks that handle routing, however I'm looking for something that automatically generates CRUD API (based on blueprints or linked to the database tables).
For speeding up the development process and keeping my code clean I also like ORM's. It would be nice if I could link the automatically generated API to the ORM schema/blueprint. So once again, what is the best way to approach this?
I couldn't find any frameworks that provide this. Hope you guys can help me out.
Thanks in advance!
Dennis
Source: (StackOverflow)
I am attempting to use the subscribe function described here. However, when editing /assets/js/app.js
, I am getting this error:
Uncaught ReferenceError: Room is not defined
So, I am not entirely sure why, but it cannot find my model. Here is my code:
Room.subscribe(req, [{id: "5278861ab9a0d2cd0e000001"}], function (response) {
console.log('subscribed?');
console.log(response);
});
and here is is in the context of app.js
(function (io) {
// as soon as this file is loaded, connect automatically,
var socket = io.connect();
if (typeof console !== 'undefined') {
log('Connecting to Sails.js...');
}
socket.on('connect', function socketConnected() {
// Listen for Comet messages from Sails
socket.on('message', function messageReceived(message) {
///////////////////////////////////////////////////////////
// Replace the following with your own custom logic
// to run when a new message arrives from the Sails.js
// server.
///////////////////////////////////////////////////////////
log('New comet message received :: ', message);
//////////////////////////////////////////////////////
});
///////////////////////////////////////////////////////////
// Here's where you'll want to add any custom logic for
// when the browser establishes its socket connection to
// the Sails.js server.
///////////////////////////////////////////////////////////
log(
'Socket is now connected and globally accessible as `socket`.\n' +
'e.g. to send a GET request to Sails, try \n' +
'`socket.get("/", function (response) ' +
'{ console.log(response); })`'
);
///////////////////////////////////////////////////////////
// This is the part I added:
Room.subscribe(req, [{id: "5278861ab9a0d2cd0e000001"}], function (response) {
console.log('subscribed?');
console.log(response);
});
//
});
// Expose connected `socket` instance globally so that it's easy
// to experiment with from the browser console while prototyping.
window.socket = socket;
// Simple log function to keep the example simple
function log () {
if (typeof console !== 'undefined') {
console.log.apply(console, arguments);
}
}
})(
Am I going about this the right way? should I be storing this directly in app.js?
Source: (StackOverflow)
I'm working on an API with NodeJS and Express (and more stuff like mongo, sockets, etc) but i'm stuck on a very simple step i believe, i'm just trying to get the information from the POST req
object, but i get an error when trying to access req.body
Here's what i have:
var express = require('express'),
http = require('http'),
path = require('path'),
fs = require('fs'),
io = require('socket.io');
dynroute = require('dynroute');
var app = express();
app.set('port', process.env.PORT || 3999);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(app.router);
app.use(express.bodyParser());
app.post('/user', function(req, res) {
console.log(JSON.stringify(req.body));
res.send(req.body.self);
});
http.createServer(app).listen(app.get('port'), function ()
{
console.log('App Server is now running at:' + app.get('port'));
});
On the console.log(JSON.stringify(req.body));
i get undefined
and on the res.send(req.body.self);
i get TypeError: Cannot read property 'self' of undefined
I've been seaching for this type of errors and usually the issue is that people do not include app.use(express.bodyParser());
middleware , i also tryied using app.use(express.urlencoded());
and app.use(express.json());
, didn't worked either.
If i do a console.log(req)
i can see the entire object but i do not get to see body
or any of the content i'm passing when doing the POST request from a client (i'm passing it as JSON).
*I know i could use restify
or sails.js
to build APIs within Node but i want to do everything by my own so i can learn from the experience.
Thanks
EDIT:
I had to put the bodyparser
middleware before the app.router
middleware, that fix it!
Source: (StackOverflow)
I have created a web app with node.js, express, and angular.js in the past. I am starting a new project and I want to also use MongoDB. That would be the MEAN stack. Using just MEAN, I could start a project with this: http://mean.io/.
Now, I have written REST API's in the past and I have heard about sails.js which sounds very compelling. It can automatically create REST API's for you.
So my question is, what steps would I follow to start a new project with the MEAN stack AND sails.js?
Options:
- Would I clone the mean.io stack, run the npm install and then also npm install sails.js?
- Or, it seems like sails.js has it's own idea of what to do for a directory structure. So would I install sails.js as per their instructions http://sailsjs.org/#!getStarted and then npm install Angular and Mongo? (I think I would not need Mongoose since sails.js has its own ORM, waterline).
I am actually going to try option 2 today, but I would be very glad to know what steps have worked for others.
Thank you very much!
Source: (StackOverflow)
According to this closed issue in sails:
https://github.com/balderdashy/sails/issues/835
CRUD Blueprint Overrides
"absolutely, this is coming in v0.10"
I'd like to modify the blueprints in my sailsjs service to allow named roots (consuming in ember).
Currently I'm having to customize every controller I create with actions that are largely duplicates of what is already in the blueprints.
I suspect that I can move this code out of my controllers now and into a blueprints override area, but I'm not clear on where to put that code.
Any examples or even just a pointer to the relevant code in sails the .10 repo would be greatly appreciated.
Source: (StackOverflow)
How can I select or update multiple records in oriento
like in waterline we can
offersModel.update({id:items_ids,status:INACTIVE},{status:ACTIVE})
But in waterline transaction is not available. so i want to use
var db = offersModel.getDB();
var trans = db.begin();
trans.update('offers')
.set({status:INACTIVE})
.where({id:items_ids,status:ENM.SELLING_STATUS.ACTIVE})//.exec()
.then(function(offers){
if (offers.length != items_ids.length) {trans.rollback(); /* send error here*/}
else trans.commit();
})
Thanks
Source: (StackOverflow)
When I use Sails.js with Passport.js, the isAuthenticated method does not exist on the req object when requested through websocket.
Could anyone tell me why this happens?
Source: (StackOverflow)
I'm converting an app of mine from Express to sails.js - is there a way I can do something like this in Sails?
From my app.js
file in Express:
var globals = {
name: 'projectName',
author: 'authorName'
};
app.get('/', function (req, res) {
globals.page_title = 'Home';
res.render('index', globals);
});
This let me access those variables on every view without having to hardcode them into the template. Not sure how/where to do it in Sails though.
Source: (StackOverflow)
I've got myself a question regarding associations in Sails.js version 0.10-rc5. I've been building an app in which multiple models are associated to one another, and I've arrived at a point where I need to get to nest associations somehow.
There's three parts:
First there's something like a blog post, that's being written by a user. In the blog post I want to show the associated user's information like their username. Now, everything works fine here. Until the next step: I'm trying to show comments which are associated with the post.
The comments are a separate Model, called Comment. Each of which also has an author (user) associated with it. I can easily show a list of the Comments, although when I want to display the User's information associated with the comment, I can't figure out how to populate the Comment with the user's information.
In my controller i'm trying to do something like this:
Post
.findOne(req.param('id'))
.populate('user')
.populate('comments') // I want to populate this comment with .populate('user') or something
.exec(function(err, post) {
// Handle errors & render view etc.
});
In my Post's 'show' action i'm trying to retrieve the information like this (simplified):
<ul>
<%- _.each(post.comments, function(comment) { %>
<li>
<%= comment.user.name %>
<%= comment.description %>
</li>
<% }); %>
</ul>
The comment.user.name will be undefined though. If I try to just access the 'user' property, like comment.user, it'll show it's ID. Which tells me it's not automatically populating the user's information to the comment when I associate the comment with another model.
Anyone any ideals to solve this properly :)?
Thanks in advance!
P.S.
For clarification, this is how i've basically set up the associations in different models:
// User.js
posts: {
collection: 'post'
},
hours: {
collection: 'hour'
},
comments: {
collection: 'comment'
}
// Post.js
user: {
model: 'user'
},
comments: {
collection: 'comment',
via: 'post'
}
// Comment.js
user: {
model: 'user'
},
post: {
model: 'post'
}
Source: (StackOverflow)