...
import configRoutes from '../../routes'
...
render() {
return (
<Provider store={store}>
<Router history={routerHistory}>
{configRoutes(store)}
</Router>
</Provider>
)
}
...
<Route path='/secret-area' component={SecretAreaContainer} onEnter={_ensureAuthenticated}>
...
export default function configRoutes(store) {
function _ensureAuthenticated(nextState, replace, callback) {
const { dispatch } = store
const { session } = store.getState()
const { currentUser } = session // данные по юзеру
let nextUrl
if (!currentUser && localStorage.getItem('token')) {
dispatch(getCurrentAccount())
}
} else if (!localStorage.getItem('token')) {
nextUrl = location.pathname + location.search.replace('?', '&')
replace('/signin')
}
callback()
}
// здесь ваши роуты
export function signIn(email, password) {
return (dispatch, getState) => {
dispatch({
type: USER_SIGN_IN_REQUEST,
})
const params = {
email,
password,
}
httpPost(`${API_ROOT_V1}/api/authenticate`, params)
.then((data) => {
saveParamsToLS(data) // здесь токен можно сохранить, например
dispatch(push('/account')) // ваш РЕДИРЕКТ, используется push из react-router-redux (что необязательно)
})
.catch((error) => {
console.warn(`Sign in error: ${JSON.stringify(error)}`) //eslint-disable-line no-console
dispatch({
type: USER_SIGN_IN_FAILURE,
error: error,
})
})
}
}
demo-app/views/index.jade
node ./bin/www
npm start
app.get('/ab(cd)?e', function(req, res) {
res.send('ab(cd)?e'); // здесь может быть что-нибудь, например: покажи страницу с такой-то картинкой
});
const express = require('express')
const router = express.Router()
const User = require('../models/user')
const v4 = require('node-uuid').v4
const jwt = require('jsonwebtoken')
router.post('/signup', (req, res, next) => {
req.check('email', 'Please enter a valid email').len(1).isEmail()
req.check('password', 'Please enter a password with a length between 4 and 34 digits').len(4, 34)
const errors = req.validationErrors()
if (errors) {
return res.status(400).json({ errors })
} else {
User.hashPassword(req.body.password, (err, passwordHash) => {
if (err) {
return res.status(400).json({ error: err.message })
}
const user = new User({
name: req.body.name,
nickname: req.body.nickname,
email: req.body.email,
password: req.body.password,
})
user.passwordHash = passwordHash
user.save((err, item) => {
if (err) {
return res.status(400).json({ error: err.message })
}
const payload = {
_id: item._id,
iss: 'http://localhost:3000',
permissions: 'poll',
}
const options = {
expiresIn: '7d',
jwtid: v4(),
}
const secret = new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64')
jwt.sign(payload, secret, options, (err, token) => {
return res.json({ data: token })
})
})
})
}
})
router.post('/signin', (req, res, next) => {
req.check('email', 'Please enter a valid email').len(1).isEmail()
req.check('password', 'Please enter a password with a length between 4 and 34 digits').len(4, 34)
const errors = req.validationErrors()
const password = req.body.password
if (errors) {
return res.status(400).json({ errors })
} else {
User.findOne({ email: req.body.email }, (err, user) => {
if (err) {
return res.status(400).json({ error: err.message })
}
if (!user) {
return res.status(400).json({ error: 'User not found' })
}
User.comparePasswordAndHash(password, user.passwordHash, (err, areEqual) => {
if (err) {
return res.status(400).json({ error: err.message })
}
if (!areEqual) {
return res.status(400).json({ error: 'Wrong password' })
}
const payload = {
_id: user._id,
iss: 'http://localhost:3000',
permissions: 'poll',
}
const options = {
expiresIn: '7d',
jwtid: v4(),
}
const secret = new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64')
jwt.sign(payload, secret, options, (err, token) => {
return res.json({ data: token })
})
})
})
}
})
module.exports = router;
const payload = {
_id: item._id,
iss: 'http://localhost:3000',
permissions: 'poll',
}
Как на счет jwt ?
const express = require('express')
const router = express.Router()
const User = require('../models/user')
const v4 = require('node-uuid').v4
const jwt = require('jsonwebtoken')
router.post('/signup', (req, res, next) => {
req.check('email', 'Please enter a valid email').len(1).isEmail()
req.check('password', 'Please enter a password with a length between 4 and 34 digits').len(4, 34)
const errors = req.validationErrors()
if (errors) {
return res.status(400).json({ errors })
} else {
User.hashPassword(req.body.password, (err, passwordHash) => {
if (err) {
return res.status(400).json({ error: err.message })
}
const user = new User({
name: req.body.name,
nickname: req.body.nickname,
email: req.body.email,
password: req.body.password,
})
user.passwordHash = passwordHash
user.save((err, item) => {
if (err) {
return res.status(400).json({ error: err.message })
}
const payload = {
_id: item._id,
iss: 'http://localhost:3000',
permissions: 'poll',
}
const options = {
expiresIn: '7d',
jwtid: v4(),
}
const secret = new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64')
jwt.sign(payload, secret, options, (err, token) => {
return res.json({ data: token })
})
})
})
}
})
router.post('/signin', (req, res, next) => {
req.check('email', 'Please enter a valid email').len(1).isEmail()
req.check('password', 'Please enter a password with a length between 4 and 34 digits').len(4, 34)
const errors = req.validationErrors()
const password = req.body.password
if (errors) {
return res.status(400).json({ errors })
} else {
User.findOne({ email: req.body.email }, (err, user) => {
if (err) {
return res.status(400).json({ error: err.message })
}
if (!user) {
return res.status(400).json({ error: 'User not found' })
}
User.comparePasswordAndHash(password, user.passwordHash, (err, areEqual) => {
if (err) {
return res.status(400).json({ error: err.message })
}
if (!areEqual) {
return res.status(400).json({ error: 'Wrong password' })
}
const payload = {
_id: user._id,
iss: 'http://localhost:3000',
permissions: 'poll',
}
const options = {
expiresIn: '7d',
jwtid: v4(),
}
const secret = new Buffer(process.env.AUTH0_CLIENT_SECRET, 'base64')
jwt.sign(payload, secret, options, (err, token) => {
return res.json({ data: token })
})
})
})
}
})
module.exports = router;
const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const Schema = mongoose.Schema
let bcrypt_cost = 12
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true },
passwordHash: String,
})
userSchema.statics.hashPassword = (passwordRaw, cb) => {
if (process.env.NODE_ENV === 'test') {
bcrypt_cost = 1
}
bcrypt.hash(passwordRaw, bcrypt_cost, cb)
}
userSchema.statics.comparePasswordAndHash = (password, passwordHash, cb) => {
bcrypt.compare(password, passwordHash, cb)
}
const User = mongoose.model('User', userSchema)
module.exports = User