Sails — Realtime MVC Framework For NodeJS

Let’s sail together !!

Features

Setup

adapter: ‘sails-mongo’,
url: ‘your connection url goes here’

Routes

module.exports = {
‘/’: {
view: ‘pages/homepage’
},
//authentication routes
'POST /signup' : 'AuthController.signup',
'POST /user-login' : 'AuthController.login'
}

Services

module.exports = {
attributes: {
email:{
required: true,
unique: true,
type:’string’,
},
password:{
required: true
},
name: {
required: true,
type:’string’
},
city: {
type:’string’,
defaultsTo:’’
}
}
}
signup: async function (req, res) {
if (req.body.email && req.body.password) {
let hashPwd = bcrypt.hashSync(req.body.password);
let finalUser = req.body;
finalUser[‘password’] = hashPwd;
let user = await User.create(finalUser).meta({ fetch: true });
if (user) {
return res.json({ message: ‘Signup successfull. Please login’ });
} else {
return res.json({ message: ‘Signup failed!!’ })
}
} else {
return res.json({ message: ‘Email or Password is not present.’ })
}
login: async function (req, res) {
let user = await User.findOne({ email: req.body.email })
let hashPwd = bcrypt.compareSync(req.body.password, user.password);
if (hashPwd) {
let finalUser = user;
finalUser[‘token’] = jwt.sign(user.email, ‘secret’)
return res.json({ data: finalUser, message: ‘Login success’, status: ‘SUCCESS’ });
} else {
return res.json({ message: ‘Authentication failed!!’, status:
ERROR’ });
}
}

Policy

//isAuthorized.jsvar jwt = require(‘jsonwebtoken’);
module.exports = async function (req, res, next) {
var token;
if (req.headers && req.headers.authorization) {
token = req.headers.authorization;
let verified = await jwt.verify(token, ‘secret’);
if (verified) {
req.user = verified;
next();
} else {
return res.json({ message: ‘Token does not exist!!’ })
}
} else {
return res.json({ message: ‘Authentication failed!! Token Required.’ })
}
}

Applying policies to a controller

//policies.js
module.exports.policies = {
// ‘*’: true,‘AuthController’ : {
‘*’ : true
},
‘UserController’ : {
‘addUser’: [‘isAuthorized’],
},
};

Lifecycle callbacks

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store