Skip to content

Commit

Permalink
added simple auth module and its solution
Browse files Browse the repository at this point in the history
  • Loading branch information
julianitor committed Feb 24, 2015
1 parent 8f4a71b commit 2101095
Show file tree
Hide file tree
Showing 8 changed files with 310 additions and 0 deletions.
78 changes: 78 additions & 0 deletions soluciones/tema3/simpleAuthModule/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/* Dependencies */

var express = require("express")
, env = process.env.NODE_ENV || "development"
, auth = require("./simpleauth")
, logger = require("morgan")
, bodyParser = require("body-parser")
, cookieParser = require("cookie-parser")
, cookieSession = require("cookie-session")

var users = [
{
id: 0,
username: "[email protected]",
pass: "asdf"
}
]

auth.setStrategy({
serializeUser: function(user) {
return user.id
},
deserializeUser: function(userId, cb) {
if (userId in users) {
cb(users[userId])
} else {
cb(false)
}
},
checkCredentials: function(username, pass, cb) {
console.log(username, pass)
var user = users.filter(function(i) { return i.username === username })[0]
if (!user || user.pass !== pass) {
cb(null, false);
} else {
cb(null, user)
}
},
loginRoute: "/login.html"
})

var app = express()

app.set('port', process.env.PORT || 3000)
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))


app.use(cookieParser('secret'))
app.use(cookieSession({keys: ['secret']}))

app.use(express.static(__dirname + '/public'))

/* Rutas */

app.get('/', function(req, res) {
res.redirect('/login.html');
})

app.post("/session", auth.createSession({ redirect: "/ok" }))

app.get("/ok", auth.requiresSession, function(req, res) {
res.end("OK!")
})

app.get("/secret", auth.requiresSession, function(req, res) {
res.end("Hola, " + req.user.username)
})

app.get("/logout", auth.requiresSession, function(req, res) {
auth.destroySession(res)
res.redirect("/login.html")
})

app.listen(3000)

/* TODO: Explain sessions and implement it properly using express sessions */
14 changes: 14 additions & 0 deletions soluciones/tema3/simpleAuthModule/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "redradix-nodejs-simpleauth",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "*",
"lodash": "*",
"morgan": "*",
"body-parser": "*",
"method-override": "*",
"cookie-parser": "*",
"cookie-session": "*"
}
}
9 changes: 9 additions & 0 deletions soluciones/tema3/simpleAuthModule/public/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<html>
<body>
<form action="session" method="post" accept-charset="utf-8">
<input type="text" name="username" placeholder="usernmae">
<input type="password" name="password" placeholder="pass">
<p><input type="submit" value="Continue &rarr;"></p>
</form>
</body>
</html>
60 changes: 60 additions & 0 deletions soluciones/tema3/simpleAuthModule/simpleauth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
var _ = require("lodash")

strategy = {
serializeUser: function(user) {
},
deserializeUser: function(userId, cb) {
},
checkCredentials: function(username, pass, done) {
},
loginRoute: "/login"
}

exports.setStrategy = function(customStrategy) {
strategy = _.extend({}, strategy, customStrategy)
}

exports.createSession = function(options) {
var config = {
username: "username",
password: "password",
redirect: "/me",
failRedirect: strategy.loginRoute
}
config = _.extend({}, config, options)
return function(req, res, next) {
var username = req.body[config.username],
pass = req.body[config.password]
strategy.checkCredentials(username, pass, function(err, user) {
if (!err && user) {
res.cookie("user", strategy.serializeUser(user), {signed: true, maxAge: 1000*60*60*24*7})
res.redirect(config.redirect)
} else {
console.log("Credenciales incorrectas")
res.redirect(config.failRedirect)
}
})
}
}

exports.requiresSession = function(req, res, next) {
if (req.signedCookies.user) {
strategy.deserializeUser(req.signedCookies.user, function(user) {
if (!user) {
console.log("El usuario no existe!")
res.clearCookie("user")
res.redirect(strategy.loginRoute)
} else {
req.user = user
next()
}
})
} else {
console.log("No existe la sesión...")
res.redirect(strategy.loginRoute)
}
}

exports.destroySession = function(res) {
res.clearCookie("user")
}
66 changes: 66 additions & 0 deletions tema3/simpleAuthModule/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/* Dependencies */

var express = require("express")
, env = process.env.NODE_ENV || "development"
, auth = require("./simpleauth")
, logger = require("morgan")
, bodyParser = require("body-parser")
, cookieParser = require("cookie-parser")
, cookieSession = require("cookie-session")

var users = [
{
id: 0,
username: "[email protected]",
pass: "asdf"
}
]

auth.setStrategy({
serializeUser: function(user) {

},
deserializeUser: function(userId, cb) {

},
checkCredentials: function(username, pass, cb) {

},
loginRoute: "/login.html"
})

var app = express()

app.set('port', process.env.PORT || 3000)
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))


app.use(cookieParser('secret'))
app.use(cookieSession({keys: ['secret']}))

app.use(express.static(__dirname + '/public'))

/* Rutas */

app.get('/', function(req, res) {
res.redirect('/login.html');
})

app.post("/session", auth.createSession({ redirect: "/ok" }))

app.get("/ok", auth.requiresSession, function(req, res) {
res.end("OK!")
})

app.get("/secret", auth.requiresSession, function(req, res) {
res.end("Hola, " + req.user.username)
})

app.get("/logout", auth.requiresSession, function(req, res) {
auth.destroySession(res)
res.redirect("/login.html")
})

app.listen(3000);
14 changes: 14 additions & 0 deletions tema3/simpleAuthModule/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "redradix-nodejs-simpleauth",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "*",
"lodash": "*",
"morgan": "*",
"body-parser": "*",
"method-override": "*",
"cookie-parser": "*",
"cookie-session": "*"
}
}
9 changes: 9 additions & 0 deletions tema3/simpleAuthModule/public/login.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<html>
<body>
<form action="session" method="post" accept-charset="utf-8">
<input type="text" name="username" placeholder="usernmae">
<input type="password" name="password" placeholder="pass">
<p><input type="submit" value="Continue &rarr;"></p>
</form>
</body>
</html>
60 changes: 60 additions & 0 deletions tema3/simpleAuthModule/simpleauth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
var _ = require("lodash")

strategy = {
serializeUser: function(user) {
},
deserializeUser: function(userId, cb) {
},
checkCredentials: function(username, pass, done) {
},
loginRoute: "/login"
}

exports.setStrategy = function(customStrategy) {
strategy = _.extend({}, strategy, customStrategy)
}

exports.createSession = function(options) {
var config = {
username: "username",
password: "password",
redirect: "/me",
failRedirect: strategy.loginRoute
}
config = _.extend({}, config, options)
return function(req, res, next) {
var username = req.body[config.username],
pass = req.body[config.password]
strategy.checkCredentials(username, pass, function(err, user) {
if (!err && user) {
res.cookie("user", strategy.serializeUser(user), {signed: true, maxAge: 1000*60*60*24*7})
res.redirect(config.redirect)
} else {
console.log("Credenciales incorrectas")
res.redirect(config.failRedirect)
}
})
}
}

exports.requiresSession = function(req, res, next) {
if (req.signedCookies.user) {
strategy.deserializeUser(req.signedCookies.user, function(user) {
if (!user) {
console.log("El usuario no existe!")
res.clearCookie("user")
res.redirect(strategy.loginRoute)
} else {
req.user = user
next()
}
})
} else {
console.log("No existe la sesión...")
res.redirect(strategy.loginRoute)
}
}

exports.destroySession = function(res) {
res.clearCookie("user")
}

0 comments on commit 2101095

Please sign in to comment.