redux-security
Version:
91 lines (77 loc) • 2.62 kB
JavaScript
import Promise from 'bluebird'
import cuid from 'cuid'
import { write, error } from 'redux-journal'
import { manager } from 'redux-manager'
import { actions } from '../actions'
import { SERVICE, TAGS } from '../config'
import { select } from '../select'
const tags = `${TAGS}.api.local`
export const configAPILocal = (
{ serviceName = SERVICE } =
{ serviceName: SERVICE }
) => {
const state = () => manager.getStore().getState()[serviceName]
const check = ({ username, password }) => Promise.try(() => {
write(`({ username = '${username}', password = '${password}' })`, `${tags}.check`)
const users = select(state())
const docs = users.docs.all()
const user = docs.find(doc => doc.username == username && doc.password == password)
write(`user = ${JSON.stringify(user)}`, `${tags}.check.found`)
if (user) return { userID: user._id }
throw new Error('User not found')
})
const codeGenerate = ({ userID }) => Promise.try(() => {
const code = cuid()
update({ _id: userID, code })
return { code }
})
const confirmEmail = ({ userID }) => Promise.try(() => {
update({ _id: userID, code: undefined, confirmed: true })
})
const create = ({ username, password, email }) => Promise.try(() => {
const userID = cuid()
insert({ _id: userID, username, password, email })
return { userID }
})
const get = ({ userID }) => Promise.try(() => {
const users = select(state())
const docs = users.docs.all()
const user = docs.find(doc => doc._id == userID)
if (user) { return user }
throw new Error('User not found')
})
const getByCode = ({ code }) => Promise.try(() => {
const users = select(state())
const docs = users.docs.all()
const user = docs.find(doc => doc.code = code)
if (user) { return user }
throw new Error('User not found')
})
const getByName = ({ name }) => Promise.try(() => {
const docs = selectDocs(state())
const user = docs.find(doc => doc.name = name)
if (user) { return user }
throw new Error('User not found')
})
const insert = (payload) => Promise.try(() => {
manager.dispatch(actions.insert(payload), serviceName)
})
const remove = (payload) => Promise.try(() => {
manager.dispatch(actions.remove(payload), serviceName)
})
const update = (payload) => Promise.try(() => {
manager.dispatch(actions.update(payload), serviceName)
})
return {
check,
codeGenerate,
confirmEmail,
create,
get,
getByCode,
getByName,
insert,
remove,
update
}
}