From 322232791a269b38c2bee19de4811ad69727ba59 Mon Sep 17 00:00:00 2001 From: Zuhra Sofyan Date: Wed, 28 Dec 2016 11:04:35 +0700 Subject: [PATCH] INIT --- .editorconfig | 10 ++ .gitignore | 120 +++++++++++++++++++++ .sailsrc | 8 ++ README.md | 38 +++++++ api/controllers/.gitkeep | 0 api/controllers/AuthController.js | 27 +++++ api/controllers/QuoteController.js | 17 +++ api/controllers/UserController.js | 60 +++++++++++ api/models/.gitkeep | 0 api/models/User.js | 53 +++++++++ api/policies/hasToken.js | 4 + api/policies/sessionAuth.js | 21 ++++ api/responses/badRequest.js | 76 +++++++++++++ api/responses/created.js | 60 +++++++++++ api/responses/forbidden.js | 89 ++++++++++++++++ api/responses/notFound.js | 94 ++++++++++++++++ api/responses/ok.js | 60 +++++++++++ api/responses/serverError.js | 89 ++++++++++++++++ api/services/.gitkeep | 0 api/services/auth.js | 49 +++++++++ api/services/quoter.js | 7 ++ api/services/quotes.json | 43 ++++++++ app.js | 60 +++++++++++ config/blueprints.js | 165 +++++++++++++++++++++++++++++ config/bootstrap.js | 17 +++ config/cors.js | 78 ++++++++++++++ config/csrf.js | 64 +++++++++++ config/env/development.js | 24 +++++ config/env/production.js | 38 +++++++ config/globals.js | 63 +++++++++++ config/http.js | 98 +++++++++++++++++ config/i18n.js | 57 ++++++++++ config/locales/_README.md | 28 +++++ config/locales/de.json | 4 + config/locales/en.json | 4 + config/locales/es.json | 4 + config/locales/fr.json | 4 + config/log.js | 29 +++++ config/models.js | 32 ++++++ config/passport.js | 43 ++++++++ config/policies.js | 65 ++++++++++++ config/routes.js | 57 ++++++++++ config/sockets.js | 141 ++++++++++++++++++++++++ config/tokenSecret.js | 1 + config/views.js | 95 +++++++++++++++++ package.json | 33 ++++++ 46 files changed, 2129 insertions(+) create mode 100755 .editorconfig create mode 100755 .gitignore create mode 100755 .sailsrc create mode 100755 README.md create mode 100755 api/controllers/.gitkeep create mode 100755 api/controllers/AuthController.js create mode 100755 api/controllers/QuoteController.js create mode 100755 api/controllers/UserController.js create mode 100755 api/models/.gitkeep create mode 100755 api/models/User.js create mode 100755 api/policies/hasToken.js create mode 100755 api/policies/sessionAuth.js create mode 100755 api/responses/badRequest.js create mode 100755 api/responses/created.js create mode 100755 api/responses/forbidden.js create mode 100755 api/responses/notFound.js create mode 100755 api/responses/ok.js create mode 100755 api/responses/serverError.js create mode 100755 api/services/.gitkeep create mode 100755 api/services/auth.js create mode 100755 api/services/quoter.js create mode 100755 api/services/quotes.json create mode 100755 app.js create mode 100755 config/blueprints.js create mode 100755 config/bootstrap.js create mode 100755 config/cors.js create mode 100755 config/csrf.js create mode 100755 config/env/development.js create mode 100755 config/env/production.js create mode 100755 config/globals.js create mode 100755 config/http.js create mode 100755 config/i18n.js create mode 100755 config/locales/_README.md create mode 100755 config/locales/de.json create mode 100755 config/locales/en.json create mode 100755 config/locales/es.json create mode 100755 config/locales/fr.json create mode 100755 config/log.js create mode 100755 config/models.js create mode 100755 config/passport.js create mode 100755 config/policies.js create mode 100755 config/routes.js create mode 100755 config/sockets.js create mode 100755 config/tokenSecret.js create mode 100755 config/views.js create mode 100755 package.json diff --git a/.editorconfig b/.editorconfig new file mode 100755 index 0000000..0f09989 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,10 @@ +# editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..19045a5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,120 @@ +################################################ +############### .gitignore ################## +################################################ +# +# This file is only relevant if you are using git. +# +# Files which match the splat patterns below will +# be ignored by git. This keeps random crap and +# sensitive credentials from being uploaded to +# your repository. It allows you to configure your +# app for your machine without accidentally +# committing settings which will smash the local +# settings of other developers on your team. +# +# Some reasonable defaults are included below, +# but, of course, you should modify/extend/prune +# to fit your needs! +################################################ + + + + +################################################ +# Local Configuration +# +# Explicitly ignore files which contain: +# +# 1. Sensitive information you'd rather not push to +# your git repository. +# e.g., your personal API keys or passwords. +# +# 2. Environment-specific configuration +# Basically, anything that would be annoying +# to have to change every time you do a +# `git pull` +# e.g., your local development database, or +# the S3 bucket you're using for file uploads +# development. +# +################################################ + +config/local.js +config/connections.js +config/session.js + + + + + +################################################ +# Dependencies +# +# When releasing a production app, you may +# consider including your node_modules and +# bower_components directory in your git repo, +# but during development, its best to exclude it, +# since different developers may be working on +# different kernels, where dependencies would +# need to be recompiled anyway. +# +# More on that here about node_modules dir: +# http://www.futurealoof.com/posts/nodemodules-in-git.html +# (credit Mikeal Rogers, @mikeal) +# +# About bower_components dir, you can see this: +# http://addyosmani.com/blog/checking-in-front-end-dependencies/ +# (credit Addy Osmani, @addyosmani) +# +################################################ + +node_modules +bower_components + + + + +################################################ +# Sails.js / Waterline / Grunt +# +# Files generated by Sails and Grunt, or related +# tasks and adapters. +################################################ +.tmp +dump.rdb + + + + + +################################################ +# Node.js / NPM +# +# Common files generated by Node, NPM, and the +# related ecosystem. +################################################ +lib-cov +*.seed +*.log +*.out +*.pid +npm-debug.log + + + + + +################################################ +# Miscellaneous +# +# Common files generated by text editors, +# operating systems, file systems, etc. +################################################ + +*~ +*# +.DS_STORE +.netbeans +nbproject +.idea +.node_history diff --git a/.sailsrc b/.sailsrc new file mode 100755 index 0000000..0d2c3d9 --- /dev/null +++ b/.sailsrc @@ -0,0 +1,8 @@ +{ + "generators": { + "modules": {} + }, + "hooks": { + "grunt": false + } +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100755 index 0000000..db7b9ce --- /dev/null +++ b/README.md @@ -0,0 +1,38 @@ +# sails-passport + +Boilerplate to generate quick pure RESTful API with sailsjs + MySQL + passport and jwt token authentication + +## Available Routes: +* POST /register (with new email & password key value) +* POST /auth/login (with existed email & password key value) -> return token +* GET /auth/validate_token (with key:Authorization & value: 'Bearer ``' in header) +* GET /quote/open (to access random Chuck Norris quote) +* GET /quote/protected (with valid token in header to access protected random Chuck Norris quote) + +## Key Features: +### Version 0.0.1 +* Sailsjs web framework with all their features +* Authentification with passportjs (local) and JSON Web Token +* MySQL database connection +* Enable CORS for access from different application +* Password encrypted (with bcrypt) +* Email checking +* Random Chuck Norris Quote! + +## HOW TO: +* Clone this repo and `cd` to your destined folder +* Make sure your MySQL server is running +* Change the value of `mysqlServer` in `/config/connections` to reflect your own MySQL setup conf (make sure to use new dedicated database since it will alter the database, unless you change the config in connections.js ) +* run `npm install` +* run `sails lift` + +### DISCLAIMER! +This is as minimal as it can be. Use it as your boilerplate to startup your REST API server, and as your playground to understand sailsjs concept + setup Passport authentification in server. +For Accessing the functionality, you can use postman or better yet, download my other repo [angular-passport](https://github.com/zuhrasofyan/angular-passport). +[MIT License](https://github.com/angular/angular.js/blob/master/LICENSE) + +Copyright 2016 © Zuhra Sofyan + + + + diff --git a/api/controllers/.gitkeep b/api/controllers/.gitkeep new file mode 100755 index 0000000..e69de29 diff --git a/api/controllers/AuthController.js b/api/controllers/AuthController.js new file mode 100755 index 0000000..239f045 --- /dev/null +++ b/api/controllers/AuthController.js @@ -0,0 +1,27 @@ +/** + * AuthController + * + * @description :: Server-side logic for managing auths + * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers + */ + +var auth = require('../services/auth'); + +module.exports = { + register: function (req,res) { + auth.register(req,res); + }, + login: function (req, res) { + auth.login(req, res); + }, + validate_token: function (req, res) { + auth.isvalidtoken(req, res); + }, + logout: function(req, res){ + //req.logout is passportjs function to clear user information. see http://passportjs.org/docs + req.logout(); + req.session.destroy(); + res.send(200); + } +}; + diff --git a/api/controllers/QuoteController.js b/api/controllers/QuoteController.js new file mode 100755 index 0000000..d5f083e --- /dev/null +++ b/api/controllers/QuoteController.js @@ -0,0 +1,17 @@ +/** + * QuoteController + * + * @description :: Server-side logic for managing quotes + * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers + */ + +module.exports = { + getQuote: function(req, res) { + return res.json({ quote: quoter.getRandomOne() }); + }, + + getProtectedQuote: function(req, res) { + return res.json({ quote: quoter.getRandomOne() }); + } +}; + diff --git a/api/controllers/UserController.js b/api/controllers/UserController.js new file mode 100755 index 0000000..2ca0a4c --- /dev/null +++ b/api/controllers/UserController.js @@ -0,0 +1,60 @@ +/** + * UserController + * + * @description :: Server-side logic for managing users + * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers + */ +var EmailAddresses = require('machinepack-emailaddresses'); + +module.exports = { + register: function (req, res) { + var email = req.param('email'); + var password = req.param('password'); + + //validate request + if (_.isUndefined(req.param('email'))) {   +        return res.badRequest('An email address is required!');  +    } + if (_.isUndefined(req.param('password'))) { + return res.badRequest('A password is required'); + } + if (req.param('password').length < 6) { + return res.badRequest('A password must be at least 6 character') + } + EmailAddresses.validate({ + string: email + }).exec({ + error : function (err) { + return res.serverError(err); + }, + invalid: function () { + return res.badRequest('Does not looks like an email address for me :)'); + }, + success : function () { + User.findOne({email:email}).exec(function (err, result){ + //validate from database + if (err) { + return res.serverError(err); + } else if (result) { + return res.badRequest('Email already used!'); + } else { + + User.create({username:email, email:email, password:password}).exec(function (err, result){ + if (err) { + return res.serverError(err); + //return res.badRequest('Error create user'); + } + return res.ok(); + }) + } + }); + } + + }) + + + + //res.send({message: 'TODO: register User'}); + } +}; + diff --git a/api/models/.gitkeep b/api/models/.gitkeep new file mode 100755 index 0000000..e69de29 diff --git a/api/models/User.js b/api/models/User.js new file mode 100755 index 0000000..b231fdb --- /dev/null +++ b/api/models/User.js @@ -0,0 +1,53 @@ +/** + * User.js + * + * @description :: TODO: You might write a short summary of how this model works and what it represents here. + * @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models + */ + +var bcrypt = require('bcrypt-nodejs'); +var auth = require('../services/auth'); + +module.exports = { + + attributes: { + username: { + type: 'STRING', + required: true, + unique: true + }, + email: { + type: 'STRING', + required: true, + unique: true + }, + password: { + type: 'STRING', + required: true + }, + isAdmin: { + type: 'BOOLEAN', + defaultsTo: false + }, + isDeleted: { + type: 'BOOLEAN', + defaultsTo: false + }, + toJSON: function () { + var obj = this.toObject(); + delete obj.password; + return obj; + } + }, + beforeCreate: function (user, cb) { + delete user.password_confirmation; + bcrypt.genSalt(10, function (err, salt) { + bcrypt.hash(user.password, salt, function () { + }, function (err, hash) { + user.password = hash; + cb(null, user); + }); + }); + } +}; + diff --git a/api/policies/hasToken.js b/api/policies/hasToken.js new file mode 100755 index 0000000..37b0d03 --- /dev/null +++ b/api/policies/hasToken.js @@ -0,0 +1,4 @@ +var expressJwt = require('express-jwt'); +var secret = sails.config.secret; + +module.exports = expressJwt({secret: secret}); \ No newline at end of file diff --git a/api/policies/sessionAuth.js b/api/policies/sessionAuth.js new file mode 100755 index 0000000..8f9a264 --- /dev/null +++ b/api/policies/sessionAuth.js @@ -0,0 +1,21 @@ +/** + * sessionAuth + * + * @module :: Policy + * @description :: Simple policy to allow any authenticated user + * Assumes that your login action in one of your controllers sets `req.session.authenticated = true;` + * @docs :: http://sailsjs.org/#!/documentation/concepts/Policies + * + */ +module.exports = function(req, res, next) { + + // User is allowed, proceed to the next policy, + // or if this is the last policy, the controller + if (req.session.authenticated) { + return next(); + } + + // User is not allowed + // (default res.forbidden() behavior can be overridden in `config/403.js`) + return res.forbidden('You are not permitted to perform this action.'); +}; diff --git a/api/responses/badRequest.js b/api/responses/badRequest.js new file mode 100755 index 0000000..0d37825 --- /dev/null +++ b/api/responses/badRequest.js @@ -0,0 +1,76 @@ +/** + * 400 (Bad Request) Handler + * + * Usage: + * return res.badRequest(); + * return res.badRequest(data); + * return res.badRequest(data, 'some/specific/badRequest/view'); + * + * e.g.: + * ``` + * return res.badRequest( + * 'Please choose a valid `password` (6-12 characters)', + * 'trial/signup' + * ); + * ``` + */ + +module.exports = function badRequest(data, options) { + + // Get access to `req`, `res`, & `sails` + var req = this.req; + var res = this.res; + var sails = req._sails; + + // Set status code + res.status(400); + + // Log error to console + if (data !== undefined) { + sails.log.verbose('Sending 400 ("Bad Request") response: \n',data); + } + else sails.log.verbose('Sending 400 ("Bad Request") response'); + + // Only include errors in response if application environment + // is not set to 'production'. In production, we shouldn't + // send back any identifying information about errors. + if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) { + data = undefined; + } + + // If the user-agent wants JSON, always respond with JSON + // If views are disabled, revert to json + if (req.wantsJSON || sails.config.hooks.views === false) { + return res.jsonx(data); + } + + // If second argument is a string, we take that to mean it refers to a view. + // If it was omitted, use an empty object (`{}`) + options = (typeof options === 'string') ? { view: options } : options || {}; + + // Attempt to prettify data for views, if it's a non-error object + var viewData = data; + if (!(viewData instanceof Error) && 'object' == typeof viewData) { + try { + viewData = require('util').inspect(data, {depth: null}); + } + catch(e) { + viewData = undefined; + } + } + + // If a view was provided in options, serve it. + // Otherwise try to guess an appropriate view, or if that doesn't + // work, just send JSON. + if (options.view) { + return res.view(options.view, { data: viewData, title: 'Bad Request' }); + } + + // If no second argument provided, try to serve the implied view, + // but fall back to sending JSON(P) if no view can be inferred. + else return res.guessView({ data: viewData, title: 'Bad Request' }, function couldNotGuessView () { + return res.jsonx(data); + }); + +}; + diff --git a/api/responses/created.js b/api/responses/created.js new file mode 100755 index 0000000..3140113 --- /dev/null +++ b/api/responses/created.js @@ -0,0 +1,60 @@ +/** + * 201 (CREATED) Response + * + * Usage: + * return res.created(); + * return res.created(data); + * return res.created(data, 'auth/login'); + * + * @param {Object} data + * @param {String|Object} options + * - pass string to render specified view + */ + +module.exports = function created (data, options) { + + // Get access to `req`, `res`, & `sails` + var req = this.req; + var res = this.res; + var sails = req._sails; + + sails.log.silly('res.created() :: Sending 201 ("CREATED") response'); + + // Set status code + res.status(201); + + // If appropriate, serve data as JSON(P) + // If views are disabled, revert to json + if (req.wantsJSON || sails.config.hooks.views === false) { + return res.jsonx(data); + } + + // If second argument is a string, we take that to mean it refers to a view. + // If it was omitted, use an empty object (`{}`) + options = (typeof options === 'string') ? { view: options } : options || {}; + + // Attempt to prettify data for views, if it's a non-error object + var viewData = data; + if (!(viewData instanceof Error) && 'object' == typeof viewData) { + try { + viewData = require('util').inspect(data, {depth: null}); + } + catch(e) { + viewData = undefined; + } + } + + // If a view was provided in options, serve it. + // Otherwise try to guess an appropriate view, or if that doesn't + // work, just send JSON. + if (options.view) { + return res.view(options.view, { data: viewData, title: 'Created' }); + } + + // If no second argument provided, try to serve the implied view, + // but fall back to sending JSON(P) if no view can be inferred. + else return res.guessView({ data: viewData, title: 'Created' }, function couldNotGuessView () { + return res.jsonx(data); + }); + +}; diff --git a/api/responses/forbidden.js b/api/responses/forbidden.js new file mode 100755 index 0000000..ca94852 --- /dev/null +++ b/api/responses/forbidden.js @@ -0,0 +1,89 @@ +/** + * 403 (Forbidden) Handler + * + * Usage: + * return res.forbidden(); + * return res.forbidden(err); + * return res.forbidden(err, 'some/specific/forbidden/view'); + * + * e.g.: + * ``` + * return res.forbidden('Access denied.'); + * ``` + */ + +module.exports = function forbidden (data, options) { + + // Get access to `req`, `res`, & `sails` + var req = this.req; + var res = this.res; + var sails = req._sails; + + // Set status code + res.status(403); + + // Log error to console + if (data !== undefined) { + sails.log.verbose('Sending 403 ("Forbidden") response: \n',data); + } + else sails.log.verbose('Sending 403 ("Forbidden") response'); + + // Only include errors in response if application environment + // is not set to 'production'. In production, we shouldn't + // send back any identifying information about errors. + if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) { + data = undefined; + } + + // If the user-agent wants JSON, always respond with JSON + // If views are disabled, revert to json + if (req.wantsJSON || sails.config.hooks.views === false) { + return res.jsonx(data); + } + + // If second argument is a string, we take that to mean it refers to a view. + // If it was omitted, use an empty object (`{}`) + options = (typeof options === 'string') ? { view: options } : options || {}; + + // Attempt to prettify data for views, if it's a non-error object + var viewData = data; + if (!(viewData instanceof Error) && 'object' == typeof viewData) { + try { + viewData = require('util').inspect(data, {depth: null}); + } + catch(e) { + viewData = undefined; + } + } + + // If a view was provided in options, serve it. + // Otherwise try to guess an appropriate view, or if that doesn't + // work, just send JSON. + if (options.view) { + return res.view(options.view, { data: viewData, title: 'Forbidden' }); + } + + // If no second argument provided, try to serve the default view, + // but fall back to sending JSON(P) if any errors occur. + else return res.view('403', { data: viewData, title: 'Forbidden' }, function (err, html) { + + // If a view error occured, fall back to JSON(P). + if (err) { + // + // Additionally: + // • If the view was missing, ignore the error but provide a verbose log. + if (err.code === 'E_VIEW_FAILED') { + sails.log.verbose('res.forbidden() :: Could not locate view for error page (sending JSON instead). Details: ',err); + } + // Otherwise, if this was a more serious error, log to the console with the details. + else { + sails.log.warn('res.forbidden() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err); + } + return res.jsonx(data); + } + + return res.send(html); + }); + +}; + diff --git a/api/responses/notFound.js b/api/responses/notFound.js new file mode 100755 index 0000000..8f0cd03 --- /dev/null +++ b/api/responses/notFound.js @@ -0,0 +1,94 @@ +/** + * 404 (Not Found) Handler + * + * Usage: + * return res.notFound(); + * return res.notFound(err); + * return res.notFound(err, 'some/specific/notfound/view'); + * + * e.g.: + * ``` + * return res.notFound(); + * ``` + * + * NOTE: + * If a request doesn't match any explicit routes (i.e. `config/routes.js`) + * or route blueprints (i.e. "shadow routes", Sails will call `res.notFound()` + * automatically. + */ + +module.exports = function notFound (data, options) { + + // Get access to `req`, `res`, & `sails` + var req = this.req; + var res = this.res; + var sails = req._sails; + + // Set status code + res.status(404); + + // Log error to console + if (data !== undefined) { + sails.log.verbose('Sending 404 ("Not Found") response: \n',data); + } + else sails.log.verbose('Sending 404 ("Not Found") response'); + + // Only include errors in response if application environment + // is not set to 'production'. In production, we shouldn't + // send back any identifying information about errors. + if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) { + data = undefined; + } + + // If the user-agent wants JSON, always respond with JSON + // If views are disabled, revert to json + if (req.wantsJSON || sails.config.hooks.views === false) { + return res.jsonx(data); + } + + // If second argument is a string, we take that to mean it refers to a view. + // If it was omitted, use an empty object (`{}`) + options = (typeof options === 'string') ? { view: options } : options || {}; + + // Attempt to prettify data for views, if it's a non-error object + var viewData = data; + if (!(viewData instanceof Error) && 'object' == typeof viewData) { + try { + viewData = require('util').inspect(data, {depth: null}); + } + catch(e) { + viewData = undefined; + } + } + + // If a view was provided in options, serve it. + // Otherwise try to guess an appropriate view, or if that doesn't + // work, just send JSON. + if (options.view) { + return res.view(options.view, { data: viewData, title: 'Not Found' }); + } + + // If no second argument provided, try to serve the default view, + // but fall back to sending JSON(P) if any errors occur. + else return res.view('404', { data: viewData, title: 'Not Found' }, function (err, html) { + + // If a view error occured, fall back to JSON(P). + if (err) { + // + // Additionally: + // • If the view was missing, ignore the error but provide a verbose log. + if (err.code === 'E_VIEW_FAILED') { + sails.log.verbose('res.notFound() :: Could not locate view for error page (sending JSON instead). Details: ',err); + } + // Otherwise, if this was a more serious error, log to the console with the details. + else { + sails.log.warn('res.notFound() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err); + } + return res.jsonx(data); + } + + return res.send(html); + }); + +}; + diff --git a/api/responses/ok.js b/api/responses/ok.js new file mode 100755 index 0000000..eb70144 --- /dev/null +++ b/api/responses/ok.js @@ -0,0 +1,60 @@ +/** + * 200 (OK) Response + * + * Usage: + * return res.ok(); + * return res.ok(data); + * return res.ok(data, 'auth/login'); + * + * @param {Object} data + * @param {String|Object} options + * - pass string to render specified view + */ + +module.exports = function sendOK (data, options) { + + // Get access to `req`, `res`, & `sails` + var req = this.req; + var res = this.res; + var sails = req._sails; + + sails.log.silly('res.ok() :: Sending 200 ("OK") response'); + + // Set status code + res.status(200); + + // If appropriate, serve data as JSON(P) + // If views are disabled, revert to json + if (req.wantsJSON || sails.config.hooks.views === false) { + return res.jsonx(data); + } + + // If second argument is a string, we take that to mean it refers to a view. + // If it was omitted, use an empty object (`{}`) + options = (typeof options === 'string') ? { view: options } : options || {}; + + // Attempt to prettify data for views, if it's a non-error object + var viewData = data; + if (!(viewData instanceof Error) && 'object' == typeof viewData) { + try { + viewData = require('util').inspect(data, {depth: null}); + } + catch(e) { + viewData = undefined; + } + } + + // If a view was provided in options, serve it. + // Otherwise try to guess an appropriate view, or if that doesn't + // work, just send JSON. + if (options.view) { + return res.view(options.view, { data: viewData, title: 'OK' }); + } + + // If no second argument provided, try to serve the implied view, + // but fall back to sending JSON(P) if no view can be inferred. + else return res.guessView({ data: viewData, title: 'OK' }, function couldNotGuessView () { + return res.jsonx(data); + }); + +}; diff --git a/api/responses/serverError.js b/api/responses/serverError.js new file mode 100755 index 0000000..537c248 --- /dev/null +++ b/api/responses/serverError.js @@ -0,0 +1,89 @@ +/** + * 500 (Server Error) Response + * + * Usage: + * return res.serverError(); + * return res.serverError(err); + * return res.serverError(err, 'some/specific/error/view'); + * + * NOTE: + * If something throws in a policy or controller, or an internal + * error is encountered, Sails will call `res.serverError()` + * automatically. + */ + +module.exports = function serverError (data, options) { + + // Get access to `req`, `res`, & `sails` + var req = this.req; + var res = this.res; + var sails = req._sails; + + // Set status code + res.status(500); + + // Log error to console + if (data !== undefined) { + sails.log.error('Sending 500 ("Server Error") response: \n',data); + } + else sails.log.error('Sending empty 500 ("Server Error") response'); + + // Only include errors in response if application environment + // is not set to 'production'. In production, we shouldn't + // send back any identifying information about errors. + if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) { + data = undefined; + } + + // If the user-agent wants JSON, always respond with JSON + // If views are disabled, revert to json + if (req.wantsJSON || sails.config.hooks.views === false) { + return res.jsonx(data); + } + + // If second argument is a string, we take that to mean it refers to a view. + // If it was omitted, use an empty object (`{}`) + options = (typeof options === 'string') ? { view: options } : options || {}; + + // Attempt to prettify data for views, if it's a non-error object + var viewData = data; + if (!(viewData instanceof Error) && 'object' == typeof viewData) { + try { + viewData = require('util').inspect(data, {depth: null}); + } + catch(e) { + viewData = undefined; + } + } + + // If a view was provided in options, serve it. + // Otherwise try to guess an appropriate view, or if that doesn't + // work, just send JSON. + if (options.view) { + return res.view(options.view, { data: viewData, title: 'Server Error' }); + } + + // If no second argument provided, try to serve the default view, + // but fall back to sending JSON(P) if any errors occur. + else return res.view('500', { data: viewData, title: 'Server Error' }, function (err, html) { + + // If a view error occured, fall back to JSON(P). + if (err) { + // + // Additionally: + // • If the view was missing, ignore the error but provide a verbose log. + if (err.code === 'E_VIEW_FAILED') { + sails.log.verbose('res.serverError() :: Could not locate view for error page (sending JSON instead). Details: ',err); + } + // Otherwise, if this was a more serious error, log to the console with the details. + else { + sails.log.warn('res.serverError() :: When attempting to render error page view, an error occured (sending JSON instead). Details: ', err); + } + return res.jsonx(data); + } + + return res.send(html); + }); + +}; + diff --git a/api/services/.gitkeep b/api/services/.gitkeep new file mode 100755 index 0000000..e69de29 diff --git a/api/services/auth.js b/api/services/auth.js new file mode 100755 index 0000000..17d997a --- /dev/null +++ b/api/services/auth.js @@ -0,0 +1,49 @@ +var passport = require('passport'); +var jwt = require('jsonwebtoken'); +//var User = + +module.exports = { + login: function (req, res) { + passport.authenticate('local', function (err, user) { + if (!user) { + res.status(400).send({ + success: false, + message: 'invalidLogin' + }); + return; + } else { + if (err) { + res.status(400).send({ + success: false, + message: 'unknownError', + error: err + }); + } else { + //token expired in 1 day + var token = jwt.sign(user[0], sails.config.secret, {expiresIn: 60 * 60 * 24}); + // Set persistent cookie + req.session.cookie.token = token; + res.send({ + success: true, + user: {email:user[0].email, username:user[0].username }, + token: token + }); + } + } + })(req, res); + }, + isvalidtoken: function (req, res) { + if (req.headers.authorization) { + jwt.verify(req.headers.authorization.replace('Bearer ', ''), sails.config.secret, function (err, decoded) { + //418 = I'm a teapot! + if (err) return res.status(401).send({success: false, message: 'invalid'}); + if (decoded) { + console.log(decoded[0]); + return res.send({success: true, user: decoded}); + } + }); + } else { + return res.status(401).send({success: false, message: 'token invalid'}); + } + } +}; diff --git a/api/services/quoter.js b/api/services/quoter.js new file mode 100755 index 0000000..0813e2f --- /dev/null +++ b/api/services/quoter.js @@ -0,0 +1,7 @@ +var quotes = require('./quotes.json'); + +module.exports.getRandomOne = function() { + var totalAmount = quotes.length; + var rand = Math.floor(Math.random() * totalAmount); + return quotes[rand]; +} \ No newline at end of file diff --git a/api/services/quotes.json b/api/services/quotes.json new file mode 100755 index 0000000..a32bc4d --- /dev/null +++ b/api/services/quotes.json @@ -0,0 +1,43 @@ +["Chuck Norris doesn't call the wrong number. You answer the wrong phone.", +"Chuck Norris has already been to Mars; that's why there are no signs of life.", +"Chuck Norris and Superman once fought each other on a bet. The loser had to start wearing his underwear on the outside of his pants.", +"Some magicans can walk on water, Chuck Norris can swim through land.", +"Chuck Norris once urinated in a semi truck's gas tank as a joke....that truck is now known as Optimus Prime.", +"Chuck Norris doesn't flush the toilet, he scares the sh*t out of it", +"Chuck Norris counted to infinity - twice.", +"Chuck Norris can cut through a hot knife with butter", +"Chuck Norris is the reason why Waldo is hiding.", +"Death once had a near-Chuck Norris experience", +"When the Boogeyman goes to sleep every night, he checks his closet for Chuck Norris.", +"Chuck Norris can slam a revolving door.", +"Chuck Norris once kicked a horse in the chin. Its descendants are known today as Giraffes.", +"Chuck Norris will never have a heart attack. His heart isn't nearly foolish enough to attack him.", +"Chuck Norris once got bit by a rattle snake........ After three days of pain and agony ..................the rattle snake died", +"Chuck Norris can win a game of Connect Four in only three moves.", +"When Chuck Norris does a pushup, he isn't lifting himself up, he's pushing the Earth down.", +"There is no theory of evolution. Just a list of animals Chuck Norris allows to live.", +"Chuck Norris can light a fire by rubbing two ice-cubes together.", +"Chuck Norris doesn’t wear a watch. HE decides what time it is.", +"The original title for Alien vs. Predator was Alien and Predator vs Chuck Norris. The film was cancelled shortly after going into preproduction. No one would pay nine dollars to see a movie fourteen seconds long.", +"Chuck Norris doesn't read books. He stares them down until he gets the information he wants.", +"Chuck Norris made a Happy Meal cry.", +"Outer space exists because it's afraid to be on the same planet with Chuck Norris.", +"If you spell Chuck Norris in Scrabble, you win. Forever.", +"Chuck Norris can make snow angels on a concrete slab.", +"Chuck Norris destroyed the periodic table, because Chuck Norris only recognizes the element of surprise.", +"Chuck Norris has to use a stunt double when he does crying scenes.", +"Chuck Norris' hand is the only hand that can beat a Royal Flush.", +"Chuck Norris does not sleep. He waits.", +"Chuck Norris tells a GPS which way to go.", +"Some people wear Superman pajamas. Superman wears Chuck Norris pajamas.", +"Chuck Norris's tears cure cancer ..... too bad he has never cried", +"Chuck Norris doesn't breathe, he holds air hostage.", +"Chuck Norris had a staring contest with Medusa, and won.", +"When life hands Chuck Norris lemons, he makes orange juice.", +"When Chuck Norris goes on a picnic, the ants bring him food.", +"Chuck Norris gives Freddy Krueger nightmares.", +"They once made a Chuck Norris toilet paper, but there was a problem: It wouldn't take shit from anybody.", +"Chuck Norris can punch a cyclops between the eyes.", +"Chuck Norris doesn't mow his lawn, he stands on the porch and dares it to grow", +"Chuck Norris put out a forest fire. using only gasoline", +"Chuck Norris CAN believe it's not butter."] \ No newline at end of file diff --git a/app.js b/app.js new file mode 100755 index 0000000..6b75170 --- /dev/null +++ b/app.js @@ -0,0 +1,60 @@ +/** + * app.js + * + * Use `app.js` to run your app without `sails lift`. + * To start the server, run: `node app.js`. + * + * This is handy in situations where the sails CLI is not relevant or useful. + * + * For example: + * => `node app.js` + * => `forever start app.js` + * => `node debug app.js` + * => `modulus deploy` + * => `heroku scale` + * + * + * The same command-line arguments are supported, e.g.: + * `node app.js --silent --port=80 --prod` + */ + + +// Ensure we're in the project directory, so cwd-relative paths work as expected +// no matter where we actually lift from. +// > Note: This is not required in order to lift, but it is a convenient default. +process.chdir(__dirname); + +// Attempt to import `sails`. +var sails; +try { + sails = require('sails'); +} catch (e) { + console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.'); + console.error('To do that, run `npm install sails`'); + console.error(''); + console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.'); + console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,'); + console.error('but if it doesn\'t, the app will run with the global sails instead!'); + return; +} + +// --• +// Try to get `rc` dependency (for loading `.sailsrc` files). +var rc; +try { + rc = require('rc'); +} catch (e0) { + try { + rc = require('sails/node_modules/rc'); + } catch (e1) { + console.error('Could not find dependency: `rc`.'); + console.error('Your `.sailsrc` file(s) will be ignored.'); + console.error('To resolve this, run:'); + console.error('npm install rc --save'); + rc = function () { return {}; }; + } +} + + +// Start server +sails.lift(rc('sails')); diff --git a/config/blueprints.js b/config/blueprints.js new file mode 100755 index 0000000..c935fe4 --- /dev/null +++ b/config/blueprints.js @@ -0,0 +1,165 @@ +/** + * Blueprint API Configuration + * (sails.config.blueprints) + * + * These settings are for the global configuration of blueprint routes and + * request options (which impact the behavior of blueprint actions). + * + * You may also override any of these settings on a per-controller basis + * by defining a '_config' key in your controller definition, and assigning it + * a configuration object with overrides for the settings in this file. + * A lot of the configuration options below affect so-called "CRUD methods", + * or your controllers' `find`, `create`, `update`, and `destroy` actions. + * + * It's important to realize that, even if you haven't defined these yourself, as long as + * a model exists with the same name as the controller, Sails will respond with built-in CRUD + * logic in the form of a JSON API, including support for sort, pagination, and filtering. + * + * For more information on the blueprint API, check out: + * http://sailsjs.org/#!/documentation/reference/blueprint-api + * + * For more information on the settings in this file, see: + * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.blueprints.html + * + */ + +module.exports.blueprints = { + + /*************************************************************************** + * * + * Action routes speed up the backend development workflow by * + * eliminating the need to manually bind routes. When enabled, GET, POST, * + * PUT, and DELETE routes will be generated for every one of a controller's * + * actions. * + * * + * If an `index` action exists, additional naked routes will be created for * + * it. Finally, all `actions` blueprints support an optional path * + * parameter, `id`, for convenience. * + * * + * `actions` are enabled by default, and can be OK for production-- * + * however, if you'd like to continue to use controller/action autorouting * + * in a production deployment, you must take great care not to * + * inadvertently expose unsafe/unintentional controller logic to GET * + * requests. * + * * + ***************************************************************************/ + + // actions: true, + actions: false, + rest: false, + shortcuts: false, + + /*************************************************************************** + * * + * RESTful routes (`sails.config.blueprints.rest`) * + * * + * REST blueprints are the automatically generated routes Sails uses to * + * expose a conventional REST API on top of a controller's `find`, * + * `create`, `update`, and `destroy` actions. * + * * + * For example, a BoatController with `rest` enabled generates the * + * following routes: * + * ::::::::::::::::::::::::::::::::::::::::::::::::::::::: * + * GET /boat -> BoatController.find * + * GET /boat/:id -> BoatController.findOne * + * POST /boat -> BoatController.create * + * PUT /boat/:id -> BoatController.update * + * DELETE /boat/:id -> BoatController.destroy * + * * + * `rest` blueprint routes are enabled by default, and are suitable for use * + * in a production scenario, as long you take standard security precautions * + * (combine w/ policies, etc.) * + * * + ***************************************************************************/ + + // rest: true, + + /*************************************************************************** + * * + * Shortcut routes are simple helpers to provide access to a * + * controller's CRUD methods from your browser's URL bar. When enabled, * + * GET, POST, PUT, and DELETE routes will be generated for the * + * controller's`find`, `create`, `update`, and `destroy` actions. * + * * + * `shortcuts` are enabled by default, but should be disabled in * + * production. * + * * + ***************************************************************************/ + + // shortcuts: true, + + /*************************************************************************** + * * + * An optional mount path for all blueprint routes on a controller, * + * including `rest`, `actions`, and `shortcuts`. This allows you to take * + * advantage of blueprint routing, even if you need to namespace your API * + * methods. * + * * + * (NOTE: This only applies to blueprint autoroutes, not manual routes from * + * `sails.config.routes`) * + * * + ***************************************************************************/ + + // prefix: '', + + /*************************************************************************** + * * + * An optional mount path for all REST blueprint routes on a controller. * + * And it do not include `actions` and `shortcuts` routes. * + * This allows you to take advantage of REST blueprint routing, * + * even if you need to namespace your RESTful API methods * + * * + ***************************************************************************/ + + // restPrefix: '', + + /*************************************************************************** + * * + * Whether to pluralize controller names in blueprint routes. * + * * + * (NOTE: This only applies to blueprint autoroutes, not manual routes from * + * `sails.config.routes`) * + * * + * For example, REST blueprints for `FooController` with `pluralize` * + * enabled: * + * GET /foos/:id? * + * POST /foos * + * PUT /foos/:id? * + * DELETE /foos/:id? * + * * + ***************************************************************************/ + + // pluralize: false, + + /*************************************************************************** + * * + * Whether the blueprint controllers should populate model fetches with * + * data from other models which are linked by associations * + * * + * If you have a lot of data in one-to-many associations, leaving this on * + * may result in very heavy api calls * + * * + ***************************************************************************/ + + // populate: true, + + /**************************************************************************** + * * + * Whether to run Model.watch() in the find and findOne blueprint actions. * + * Can be overridden on a per-model basis. * + * * + ****************************************************************************/ + + // autoWatch: true, + + /**************************************************************************** + * * + * The default number of records to show in the response from a "find" * + * action. Doubles as the default size of populated arrays if populate is * + * true. * + * * + ****************************************************************************/ + + // defaultLimit: 30 + +}; diff --git a/config/bootstrap.js b/config/bootstrap.js new file mode 100755 index 0000000..96208a1 --- /dev/null +++ b/config/bootstrap.js @@ -0,0 +1,17 @@ +/** + * Bootstrap + * (sails.config.bootstrap) + * + * An asynchronous bootstrap function that runs before your Sails app gets lifted. + * This gives you an opportunity to set up your data model, run jobs, or perform some special logic. + * + * For more information on bootstrapping your app, check out: + * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.bootstrap.html + */ + +module.exports.bootstrap = function(cb) { + + // It's very important to trigger this callback method when you are finished + // with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap) + cb(); +}; diff --git a/config/cors.js b/config/cors.js new file mode 100755 index 0000000..ada5fd4 --- /dev/null +++ b/config/cors.js @@ -0,0 +1,78 @@ +/** + * Cross-Origin Resource Sharing (CORS) Settings + * (sails.config.cors) + * + * CORS is like a more modern version of JSONP-- it allows your server/API + * to successfully respond to requests from client-side JavaScript code + * running on some other domain (e.g. google.com) + * Unlike JSONP, it works with POST, PUT, and DELETE requests + * + * For more information on CORS, check out: + * http://en.wikipedia.org/wiki/Cross-origin_resource_sharing + * + * Note that any of these settings (besides 'allRoutes') can be changed on a per-route basis + * by adding a "cors" object to the route configuration: + * + * '/get foo': { + * controller: 'foo', + * action: 'bar', + * cors: { + * origin: 'http://foobar.com,https://owlhoot.com' + * } + * } + * + * For more information on this configuration file, see: + * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.cors.html + * + */ + +module.exports.cors = { + + /*************************************************************************** + * * + * Allow CORS on all routes by default? If not, you must enable CORS on a * + * per-route basis by either adding a "cors" configuration object to the * + * route config, or setting "cors:true" in the route config to use the * + * default settings below. * + * * + ***************************************************************************/ + + allRoutes: true, + + /*************************************************************************** + * * + * Which domains which are allowed CORS access? This can be a * + * comma-delimited list of hosts (beginning with http:// or https://) or * + * "*" to allow all domains CORS access. * + * * + ***************************************************************************/ + + origin: '*', + + /*************************************************************************** + * * + * Allow cookies to be shared for CORS requests? * + * * + ***************************************************************************/ + + credentials: true, + + /*************************************************************************** + * * + * Which methods should be allowed for CORS requests? This is only used in * + * response to preflight requests (see article linked above for more info) * + * * + ***************************************************************************/ + + methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD', + + /*************************************************************************** + * * + * Which headers should be allowed for CORS requests? This is only used in * + * response to preflight requests. * + * * + ***************************************************************************/ + + headers: 'content-type, Authorization' + +}; diff --git a/config/csrf.js b/config/csrf.js new file mode 100755 index 0000000..50bdbc2 --- /dev/null +++ b/config/csrf.js @@ -0,0 +1,64 @@ +/** + * Cross-Site Request Forgery Protection Settings + * (sails.config.csrf) + * + * CSRF tokens are like a tracking chip. While a session tells the server that a user + * "is who they say they are", a csrf token tells the server "you are where you say you are". + * + * When enabled, all non-GET requests to the Sails server must be accompanied by + * a special token, identified as the '_csrf' parameter. + * + * This option protects your Sails app against cross-site request forgery (or CSRF) attacks. + * A would-be attacker needs not only a user's session cookie, but also this timestamped, + * secret CSRF token, which is refreshed/granted when the user visits a URL on your app's domain. + * + * This allows us to have certainty that our users' requests haven't been hijacked, + * and that the requests they're making are intentional and legitimate. + * + * This token has a short-lived expiration timeline, and must be acquired by either: + * + * (a) For traditional view-driven web apps: + * Fetching it from one of your views, where it may be accessed as + * a local variable, e.g.: + *
+ * + *
+ * + * or (b) For AJAX/Socket-heavy and/or single-page apps: + * Sending a GET request to the `/csrfToken` route, where it will be returned + * as JSON, e.g.: + * { _csrf: 'ajg4JD(JGdajhLJALHDa' } + * + * + * Enabling this option requires managing the token in your front-end app. + * For traditional web apps, it's as easy as passing the data from a view into a form action. + * In AJAX/Socket-heavy apps, just send a GET request to the /csrfToken route to get a valid token. + * + * For more information on CSRF, check out: + * http://en.wikipedia.org/wiki/Cross-site_request_forgery + * + * For more information on this configuration file, including info on CSRF + CORS, see: + * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.csrf.html + * + */ + +/**************************************************************************** +* * +* Enabled CSRF protection for your site? * +* * +****************************************************************************/ + +// module.exports.csrf = false; + +/**************************************************************************** +* * +* You may also specify more fine-grained settings for CSRF, including the * +* domains which are allowed to request the CSRF token via AJAX. These * +* settings override the general CORS settings in your config/cors.js file. * +* * +****************************************************************************/ + +// module.exports.csrf = { +// grantTokenViaAjax: true, +// origin: '' +// } diff --git a/config/env/development.js b/config/env/development.js new file mode 100755 index 0000000..3716916 --- /dev/null +++ b/config/env/development.js @@ -0,0 +1,24 @@ +/** + * Development environment settings + * + * This file can include shared settings for a development team, + * such as API keys or remote database passwords. If you're using + * a version control solution for your Sails app, this file will + * be committed to your repository unless you add it to your .gitignore + * file. If your repository will be publicly viewable, don't add + * any private information to this file! + * + */ + +module.exports = { + + /*************************************************************************** + * Set the default database connection for models in the development * + * environment (see config/connections.js and config/models.js ) * + ***************************************************************************/ + + // models: { + // connection: 'someMongodbServer' + // } + +}; diff --git a/config/env/production.js b/config/env/production.js new file mode 100755 index 0000000..60dd602 --- /dev/null +++ b/config/env/production.js @@ -0,0 +1,38 @@ +/** + * Production environment settings + * + * This file can include shared settings for a production environment, + * such as API keys or remote database passwords. If you're using + * a version control solution for your Sails app, this file will + * be committed to your repository unless you add it to your .gitignore + * file. If your repository will be publicly viewable, don't add + * any private information to this file! + * + */ + +module.exports = { + + /*************************************************************************** + * Set the default database connection for models in the production * + * environment (see config/connections.js and config/models.js ) * + ***************************************************************************/ + + // models: { + // connection: 'someMysqlServer' + // }, + + /*************************************************************************** + * Set the port in the production environment to 80 * + ***************************************************************************/ + + // port: 80, + + /*************************************************************************** + * Set the log level in production environment to "silent" * + ***************************************************************************/ + + // log: { + // level: "silent" + // } + +}; diff --git a/config/globals.js b/config/globals.js new file mode 100755 index 0000000..c1819c3 --- /dev/null +++ b/config/globals.js @@ -0,0 +1,63 @@ +/** + * Global Variable Configuration + * (sails.config.globals) + * + * Configure which global variables which will be exposed + * automatically by Sails. + * + * For more information on configuration, check out: + * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.globals.html + */ +module.exports.globals = { + + /**************************************************************************** + * * + * Expose the lodash installed in Sails core as a global variable. If this * + * is disabled, like any other node module you can always run npm install * + * lodash --save, then var _ = require('lodash') at the top of any file. * + * * + ****************************************************************************/ + + // _: true, + + /**************************************************************************** + * * + * Expose the async installed in Sails core as a global variable. If this is * + * disabled, like any other node module you can always run npm install async * + * --save, then var async = require('async') at the top of any file. * + * * + ****************************************************************************/ + + // async: true, + + /**************************************************************************** + * * + * Expose the sails instance representing your app. If this is disabled, you * + * can still get access via req._sails. * + * * + ****************************************************************************/ + + // sails: true, + + /**************************************************************************** + * * + * Expose each of your app's services as global variables (using their * + * "globalId"). E.g. a service defined in api/models/NaturalLanguage.js * + * would have a globalId of NaturalLanguage by default. If this is disabled, * + * you can still access your services via sails.services.* * + * * + ****************************************************************************/ + + // services: true, + + /**************************************************************************** + * * + * Expose each of your app's models as global variables (using their * + * "globalId"). E.g. a model defined in api/models/User.js would have a * + * globalId of User by default. If this is disabled, you can still access * + * your models via sails.models.*. * + * * + ****************************************************************************/ + + // models: true +}; diff --git a/config/http.js b/config/http.js new file mode 100755 index 0000000..9b39a7b --- /dev/null +++ b/config/http.js @@ -0,0 +1,98 @@ +/** + * HTTP Server Settings + * (sails.config.http) + * + * Configuration for the underlying HTTP server in Sails. + * Only applies to HTTP requests (not WebSockets) + * + * For more information on configuration, check out: + * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.http.html + */ + +module.exports.http = { + + /**************************************************************************** + * * + * Express middleware to use for every Sails request. To add custom * + * middleware to the mix, add a function to the middleware config object and * + * add its key to the "order" array. The $custom key is reserved for * + * backwards-compatibility with Sails v0.9.x apps that use the * + * `customMiddleware` config option. * + * * + ****************************************************************************/ + + middleware: { + + /*************************************************************************** + * * + * The order in which middleware should be run for HTTP request. (the Sails * + * router is invoked by the "router" middleware below.) * + * * + ***************************************************************************/ + + passportInit : require('passport').initialize(), + passportSession : require('passport').session(), + + order: [ + 'startRequestTimer', + 'cookieParser', + 'session', + 'passportInit', + 'passportSession', + 'myRequestLogger', + 'bodyParser', + 'handleBodyParserError', + 'compress', + 'methodOverride', + 'poweredBy', + '$custom', + 'router', + 'www', + 'favicon', + '404', + '500' + ], + + /**************************************************************************** + * * + * Example custom middleware; logs each request to the console. * + * * + ****************************************************************************/ + + // myRequestLogger: function (req, res, next) { + // console.log("Requested :: ", req.method, req.url); + // return next(); + // } + + + /*************************************************************************** + * * + * The body parser that will handle incoming multipart HTTP requests. By * + * default as of v0.10, Sails uses * + * [skipper](http://github.com/balderdashy/skipper). See * + * http://www.senchalabs.org/connect/multipart.html for other options. * + * * + * Note that Sails uses an internal instance of Skipper by default; to * + * override it and specify more options, make sure to "npm install skipper" * + * in your project first. You can also specify a different body parser or * + * a custom function with req, res and next parameters (just like any other * + * middleware function). * + * * + ***************************************************************************/ + + // bodyParser: require('skipper')({strict: true}) + + }, + + /*************************************************************************** + * * + * The number of seconds to cache flat files on disk being served by * + * Express static middleware (by default, these files are in `.tmp/public`) * + * * + * The HTTP static cache is only active in a 'production' environment, * + * since that's the only time Express will cache flat-files. * + * * + ***************************************************************************/ + + // cache: 31557600000 +}; diff --git a/config/i18n.js b/config/i18n.js new file mode 100755 index 0000000..facf707 --- /dev/null +++ b/config/i18n.js @@ -0,0 +1,57 @@ +/** + * Internationalization / Localization Settings + * (sails.config.i18n) + * + * If your app will touch people from all over the world, i18n (or internationalization) + * may be an important part of your international strategy. + * + * + * For more informationom i18n in Sails, check out: + * http://sailsjs.org/#!/documentation/concepts/Internationalization + * + * For a complete list of i18n options, see: + * https://github.com/mashpie/i18n-node#list-of-configuration-options + * + * + */ + +module.exports.i18n = { + + /*************************************************************************** + * * + * Which locales are supported? * + * * + ***************************************************************************/ + + // locales: ['en', 'es', 'fr', 'de'], + + /**************************************************************************** + * * + * What is the default locale for the site? Note that this setting will be * + * overridden for any request that sends an "Accept-Language" header (i.e. * + * most browsers), but it's still useful if you need to localize the * + * response for requests made by non-browser clients (e.g. cURL). * + * * + ****************************************************************************/ + + // defaultLocale: 'en', + + /**************************************************************************** + * * + * Automatically add new keys to locale (translation) files when they are * + * encountered during a request? * + * * + ****************************************************************************/ + + // updateFiles: false, + + /**************************************************************************** + * * + * Path (relative to app root) of directory to store locale (translation) * + * files in. * + * * + ****************************************************************************/ + + // localesDirectory: '/config/locales' + +}; diff --git a/config/locales/_README.md b/config/locales/_README.md new file mode 100755 index 0000000..5f89b15 --- /dev/null +++ b/config/locales/_README.md @@ -0,0 +1,28 @@ +# Internationalization / Localization Settings + +> Also see the official docs on internationalization/localization: +> http://links.sailsjs.org/docs/config/locales + +## Locales +All locale files live under `config/locales`. Here is where you can add translations +as JSON key-value pairs. The name of the file should match the language that you are supporting, which allows for automatic language detection based on request headers. + +Here is an example locale stringfile for the Spanish language (`config/locales/es.json`): +```json +{ + "Hello!": "Hola!", + "Hello %s, how are you today?": "¿Hola %s, como estas?", +} +``` +## Usage +Locales can be accessed in controllers/policies through `res.i18n()`, or in views through the `__(key)` or `i18n(key)` functions. +Remember that the keys are case sensitive and require exact key matches, e.g. + +```ejs +

<%= __('Welcome to PencilPals!') %>

+

<%= i18n('Hello %s, how are you today?', 'Pencil Maven') %>

+

<%= i18n('That\'s right-- you can use either i18n() or __()') %>

+``` + +## Configuration +Localization/internationalization config can be found in `config/i18n.js`, from where you can set your supported locales. diff --git a/config/locales/de.json b/config/locales/de.json new file mode 100755 index 0000000..12f23d9 --- /dev/null +++ b/config/locales/de.json @@ -0,0 +1,4 @@ +{ + "Welcome": "Willkommen", + "A brand new app.": "Eine neue App." +} diff --git a/config/locales/en.json b/config/locales/en.json new file mode 100755 index 0000000..6eeeb33 --- /dev/null +++ b/config/locales/en.json @@ -0,0 +1,4 @@ +{ + "Welcome": "Welcome", + "A brand new app.": "A brand new app." +} diff --git a/config/locales/es.json b/config/locales/es.json new file mode 100755 index 0000000..bc6edbf --- /dev/null +++ b/config/locales/es.json @@ -0,0 +1,4 @@ +{ + "Welcome": "Bienvenido", + "A brand new app.": "Una nueva aplicación." +} diff --git a/config/locales/fr.json b/config/locales/fr.json new file mode 100755 index 0000000..972935c --- /dev/null +++ b/config/locales/fr.json @@ -0,0 +1,4 @@ +{ + "Welcome": "Bienvenue", + "A brand new app.": "Une toute nouvelle application." +} diff --git a/config/log.js b/config/log.js new file mode 100755 index 0000000..e192529 --- /dev/null +++ b/config/log.js @@ -0,0 +1,29 @@ +/** + * Built-in Log Configuration + * (sails.config.log) + * + * Configure the log level for your app, as well as the transport + * (Underneath the covers, Sails uses Winston for logging, which + * allows for some pretty neat custom transports/adapters for log messages) + * + * For more information on the Sails logger, check out: + * http://sailsjs.org/#!/documentation/concepts/Logging + */ + +module.exports.log = { + + /*************************************************************************** + * * + * Valid `level` configs: i.e. the minimum log level to capture with * + * sails.log.*() * + * * + * The order of precedence for log levels from lowest to highest is: * + * silly, verbose, info, debug, warn, error * + * * + * You may also set the level to "silent" to suppress all logs. * + * * + ***************************************************************************/ + + // level: 'info' + +}; diff --git a/config/models.js b/config/models.js new file mode 100755 index 0000000..418a76d --- /dev/null +++ b/config/models.js @@ -0,0 +1,32 @@ +/** + * Default model configuration + * (sails.config.models) + * + * Unless you override them, the following properties will be included + * in each of your models. + * + * For more info on Sails models, see: + * http://sailsjs.org/#!/documentation/concepts/ORM + */ + +module.exports.models = { + + /*************************************************************************** + * * + * Your app's default connection. i.e. the name of one of your app's * + * connections (see `config/connections.js`) * + * * + ***************************************************************************/ + connection: 'mysqlServer', + + /*************************************************************************** + * * + * How and whether Sails will attempt to automatically rebuild the * + * tables/collections/etc. in your schema. * + * * + * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * + * * + ***************************************************************************/ + migrate: 'alter' + +}; diff --git a/config/passport.js b/config/passport.js new file mode 100755 index 0000000..055c4aa --- /dev/null +++ b/config/passport.js @@ -0,0 +1,43 @@ +/** + * Passport configuration file where you should configure strategies + */ + +var passport = require('passport'); +var LocalStrategy = require('passport-local').Strategy; +//var JwtStrategy = require('passport-jwt').Strategy; +var bcrypt = require('bcrypt-nodejs'); + +passport.use(new LocalStrategy( + function(username, password, done) { + User.find({username:username}).exec(function(err, user) { + + if (err) { + return done(null, err); + } + if (!user || user.length < 1) { + return done(null, false, { + message: 'Incorrect User' + }); + } + + bcrypt.compare(password, user[0].password, function(err, res) { + if (err || !res) { + return done(null, false, { + message: 'Invalid Password' + }); + } else { + return done(null,user); + } + }); + }); + }) +); + +module.exports = { + http: { + customMiddleware: function(app) { + app.use(passport.initialize()); + app.use(passport.session()); + } + } +}; \ No newline at end of file diff --git a/config/policies.js b/config/policies.js new file mode 100755 index 0000000..9e754bb --- /dev/null +++ b/config/policies.js @@ -0,0 +1,65 @@ +/** + * Policy Mappings + * (sails.config.policies) + * + * Policies are simple functions which run **before** your controllers. + * You can apply one or more policies to a given controller, or protect + * its actions individually. + * + * Any policy file (e.g. `api/policies/authenticated.js`) can be accessed + * below by its filename, minus the extension, (e.g. "authenticated") + * + * For more information on how policies work, see: + * http://sailsjs.org/#!/documentation/concepts/Policies + * + * For more information on configuring policies, check out: + * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.policies.html + */ + + +module.exports.policies = { + + /*************************************************************************** + * * + * Default policy for all controllers and actions (`true` allows public * + * access) * + * * + ***************************************************************************/ + + //'*': true, + + + //zuhra + '*': "hasToken", + UserController: { + register: true + }, + AuthController: { + '*': true + }, + QuoteController: { + getQuote: true, + getProtectedQuote: "hasToken" + } + + /*************************************************************************** + * * + * Here's an example of mapping some policies to run before a controller * + * and its actions * + * * + ***************************************************************************/ + // RabbitController: { + + // Apply the `false` policy as the default for all of RabbitController's actions + // (`false` prevents all access, which ensures that nothing bad happens to our rabbits) + // '*': false, + + // For the action `nurture`, apply the 'isRabbitMother' policy + // (this overrides `false` above) + // nurture : 'isRabbitMother', + + // Apply the `isNiceToAnimals` AND `hasRabbitFood` policies + // before letting any users feed our rabbits + // feed : ['isNiceToAnimals', 'hasRabbitFood'] + // } +}; diff --git a/config/routes.js b/config/routes.js new file mode 100755 index 0000000..62d1a17 --- /dev/null +++ b/config/routes.js @@ -0,0 +1,57 @@ +/** + * Route Mappings + * (sails.config.routes) + * + * Your routes map URLs to views and controllers. + * + * If Sails receives a URL that doesn't match any of the routes below, + * it will check for matching files (images, scripts, stylesheets, etc.) + * in your assets directory. e.g. `http://localhost:1337/images/foo.jpg` + * might match an image file: `/assets/images/foo.jpg` + * + * Finally, if those don't match either, the default 404 handler is triggered. + * See `api/responses/notFound.js` to adjust your app's 404 logic. + * + * Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies + * flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or + * CoffeeScript for the front-end. + * + * For more information on configuring custom routes, check out: + * http://sailsjs.org/#!/documentation/concepts/Routes/RouteTargetSyntax.html + */ + +module.exports.routes = { + + /*************************************************************************** + * * + * Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, * + * etc. depending on your default view engine) your home page. * + * * + * (Alternatively, remove this and add an `index.html` file in your * + * `assets` directory) * + * * + ***************************************************************************/ + + // '/': { + // view: 'homepage' + // } + + //this is, combined with disabling blueprints will restrict access to the required action based on controller + 'POST /auth/login': 'AuthController.login', + 'GET /auth/validate_token' : 'AuthController.validate_token', + 'GET /auth/logout': 'AuthController.logout', + 'POST /register' : 'UserController.register', + 'GET /quote/open' : 'QuoteController.getQuote', + 'GET /quote/protected' : 'QuoteController.getProtectedQuote', + + /*************************************************************************** + * * + * Custom routes here... * + * * + * If a request to a URL doesn't match any of the custom routes above, it * + * is matched against Sails route blueprints. See `config/blueprints.js` * + * for configuration options and examples. * + * * + ***************************************************************************/ + +}; diff --git a/config/sockets.js b/config/sockets.js new file mode 100755 index 0000000..5c2e377 --- /dev/null +++ b/config/sockets.js @@ -0,0 +1,141 @@ +/** + * WebSocket Server Settings + * (sails.config.sockets) + * + * These settings provide transparent access to the options for Sails' + * encapsulated WebSocket server, as well as some additional Sails-specific + * configuration layered on top. + * + * For more information on sockets configuration, including advanced config options, see: + * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.sockets.html + */ + +module.exports.sockets = { + + + /*************************************************************************** + * * + * Node.js (and consequently Sails.js) apps scale horizontally. It's a * + * powerful, efficient approach, but it involves a tiny bit of planning. At * + * scale, you'll want to be able to copy your app onto multiple Sails.js * + * servers and throw them behind a load balancer. * + * * + * One of the big challenges of scaling an application is that these sorts * + * of clustered deployments cannot share memory, since they are on * + * physically different machines. On top of that, there is no guarantee * + * that a user will "stick" with the same server between requests (whether * + * HTTP or sockets), since the load balancer will route each request to the * + * Sails server with the most available resources. However that means that * + * all room/pubsub/socket processing and shared memory has to be offloaded * + * to a shared, remote messaging queue (usually Redis) * + * * + * Luckily, Socket.io (and consequently Sails.js) apps support Redis for * + * sockets by default. To enable a remote redis pubsub server, uncomment * + * the config below. * + * * + * Worth mentioning is that, if `adapter` config is `redis`, but host/port * + * is left unset, Sails will try to connect to redis running on localhost * + * via port 6379 * + * * + ***************************************************************************/ + // adapter: 'memory', + + // + // -OR- + // + + // adapter: 'socket.io-redis', + // host: '127.0.0.1', + // port: 6379, + // db: 0, + // pass: '', + + + + /*************************************************************************** + * * + * Whether to expose a 'get /__getcookie' route with CORS support that sets * + * a cookie (this is used by the sails.io.js socket client to get access to * + * a 3rd party cookie and to enable sessions). * + * * + * Warning: Currently in this scenario, CORS settings apply to interpreted * + * requests sent via a socket.io connection that used this cookie to * + * connect, even for non-browser clients! (e.g. iOS apps, toasters, node.js * + * unit tests) * + * * + ***************************************************************************/ + + // grant3rdPartyCookie: true, + + + + /*************************************************************************** + * * + * `beforeConnect` * + * * + * This custom beforeConnect function will be run each time BEFORE a new * + * socket is allowed to connect, when the initial socket.io handshake is * + * performed with the server. * + * * + * By default, when a socket tries to connect, Sails allows it, every time. * + * (much in the same way any HTTP request is allowed to reach your routes. * + * If no valid cookie was sent, a temporary session will be created for the * + * connecting socket. * + * * + * If the cookie sent as part of the connection request doesn't match any * + * known user session, a new user session is created for it. * + * * + * In most cases, the user would already have a cookie since they loaded * + * the socket.io client and the initial HTML page you're building. * + * * + * However, in the case of cross-domain requests, it is possible to receive * + * a connection upgrade request WITHOUT A COOKIE (for certain transports) * + * In this case, there is no way to keep track of the requesting user * + * between requests, since there is no identifying information to link * + * him/her with a session. The sails.io.js client solves this by connecting * + * to a CORS/jsonp endpoint first to get a 3rd party cookie(fortunately this* + * works, even in Safari), then opening the connection. * + * * + * You can also pass along a ?cookie query parameter to the upgrade url, * + * which Sails will use in the absence of a proper cookie e.g. (when * + * connecting from the client): * + * io.sails.connect('http://localhost:1337?cookie=smokeybear') * + * * + * Finally note that the user's cookie is NOT (and will never be) accessible* + * from client-side javascript. Using HTTP-only cookies is crucial for your * + * app's security. * + * * + ***************************************************************************/ + // beforeConnect: function(handshake, cb) { + // // `true` allows the connection + // return cb(null, true); + // + // // (`false` would reject the connection) + // }, + + + /*************************************************************************** + * * + * `afterDisconnect` * + * * + * This custom afterDisconnect function will be run each time a socket * + * disconnects * + * * + ***************************************************************************/ + // afterDisconnect: function(session, socket, cb) { + // // By default: do nothing. + // return cb(); + // }, + + /*************************************************************************** + * * + * `transports` * + * * + * A array of allowed transport methods which the clients will try to use. * + * On server environments that don't support sticky sessions, the "polling" * + * transport should be disabled. * + * * + ***************************************************************************/ + // transports: ["polling", "websocket"] + +}; diff --git a/config/tokenSecret.js b/config/tokenSecret.js new file mode 100755 index 0000000..28fc2b7 --- /dev/null +++ b/config/tokenSecret.js @@ -0,0 +1 @@ +module.exports.secret = "ewfn09q7kjgdfiodgrvm*&$-+<>"; \ No newline at end of file diff --git a/config/views.js b/config/views.js new file mode 100755 index 0000000..5b6496f --- /dev/null +++ b/config/views.js @@ -0,0 +1,95 @@ +/** + * View Engine Configuration + * (sails.config.views) + * + * Server-sent views are a classic and effective way to get your app up + * and running. Views are normally served from controllers. Below, you can + * configure your templating language/framework of choice and configure + * Sails' layout support. + * + * For more information on views and layouts, check out: + * http://sailsjs.org/#!/documentation/concepts/Views + */ + +module.exports.views = { + + /**************************************************************************** + * * + * View engine (aka template language) to use for your app's *server-side* * + * views * + * * + * Sails+Express supports all view engines which implement TJ Holowaychuk's * + * `consolidate.js`, including, but not limited to: * + * * + * ejs, jade, handlebars, mustache underscore, hogan, haml, haml-coffee, * + * dust atpl, eco, ect, jazz, jqtpl, JUST, liquor, QEJS, swig, templayed, * + * toffee, walrus, & whiskers * + * * + * For more options, check out the docs: * + * https://github.com/balderdashy/sails-wiki/blob/0.9/config.views.md#engine * + * * + ****************************************************************************/ + + engine: 'ejs', + + + /**************************************************************************** + * * + * Layouts are simply top-level HTML templates you can use as wrappers for * + * your server-side views. If you're using ejs or jade, you can take * + * advantage of Sails' built-in `layout` support. * + * * + * When using a layout, when one of your views is served, it is injected * + * into the `body` partial defined in the layout. This lets you reuse header * + * and footer logic between views. * + * * + * NOTE: Layout support is only implemented for the `ejs` view engine! * + * For most other engines, it is not necessary, since they implement * + * partials/layouts themselves. In those cases, this config will be * + * silently ignored. * + * * + * The `layout` setting may be set to one of the following: * + * * + * If `false`, layouts will be disabled. Otherwise, if a string is * + * specified, it will be interpreted as the relative path to your layout * + * file from `views/` folder. (the file extension, ".ejs", should be * + * omitted) * + * * + ****************************************************************************/ + + /**************************************************************************** + * * + * Using Multiple Layouts * + * * + * If you're using the default `ejs` or `handlebars` Sails supports the use * + * of multiple `layout` files. To take advantage of this, before rendering a * + * view, override the `layout` local in your controller by setting * + * `res.locals.layout`. (this is handy if you parts of your app's UI look * + * completely different from each other) * + * * + * e.g. your default might be * + * layout: 'layouts/public' * + * * + * But you might override that in some of your controllers with: * + * layout: 'layouts/internal' * + * * + ****************************************************************************/ + + layout: 'layout', + + /**************************************************************************** + * * + * Partials are simply top-level snippets you can leverage to reuse template * + * for your server-side views. If you're using handlebars, you can take * + * advantage of Sails' built-in `partials` support. * + * * + * If `false` or empty partials will be located in the same folder as views. * + * Otherwise, if a string is specified, it will be interpreted as the * + * relative path to your partial files from `views/` folder. * + * * + ****************************************************************************/ + + partials: false + + +}; \ No newline at end of file diff --git a/package.json b/package.json new file mode 100755 index 0000000..2cef94f --- /dev/null +++ b/package.json @@ -0,0 +1,33 @@ +{ + "name": "sails-passport", + "private": true, + "version": "0.0.1", + "description": "REST API boilerplate with sailsjs and authentification-ready application", + "keywords": [], + "dependencies": { + "bcrypt": "^1.0.1", + "bcrypt-nodejs": "0.0.3", + "express-jwt": "^5.1.0", + "include-all": "^1.0.0", + "jsonwebtoken": "^7.2.1", + "machinepack-emailaddresses": "^0.4.0", + "passport": "^0.3.2", + "passport-jwt": "^2.2.1", + "passport-local": "^1.0.0", + "rc": "1.0.1", + "sails": "~0.12.10", + "sails-disk": "~0.10.9", + "sails-mysql": "^0.11.5" + }, + "scripts": { + "debug": "node debug app.js", + "start": "node app.js" + }, + "main": "app.js", + "repository": { + "type": "git", + "url": "git://github.com/macPendler/sails-passport.git" + }, + "author": "macPendler", + "license": "" +}