summaryrefslogtreecommitdiff
path: root/app
diff options
context:
space:
mode:
Diffstat (limited to 'app')
-rw-r--r--app/client/api/crud.fetch.js6
-rw-r--r--app/client/auth/auth.actions.js89
-rw-r--r--app/client/auth/login.component.js4
-rw-r--r--app/client/auth/signup.component.js18
-rw-r--r--app/server/db/model.js55
-rw-r--r--app/server/db/models.js4
-rw-r--r--app/server/util/auth.js55
7 files changed, 116 insertions, 115 deletions
diff --git a/app/client/api/crud.fetch.js b/app/client/api/crud.fetch.js
index 421510b..a160175 100644
--- a/app/client/api/crud.fetch.js
+++ b/app/client/api/crud.fetch.js
@@ -50,7 +50,7 @@ function _get_headers() {
},
}
}
-function post(data) {
+export function post(data) {
return {
method: 'POST',
body: JSON.stringify(data),
@@ -69,7 +69,7 @@ export function postBody(data) {
},
}
}
-function put(data) {
+export function put(data) {
return {
method: 'PUT',
body: JSON.stringify(data),
@@ -79,7 +79,7 @@ function put(data) {
},
}
}
-function destroy(data) {
+export function destroy(data) {
return {
method: 'DELETE',
body: JSON.stringify(data),
diff --git a/app/client/auth/auth.actions.js b/app/client/auth/auth.actions.js
index 5968f87..991a3f9 100644
--- a/app/client/auth/auth.actions.js
+++ b/app/client/auth/auth.actions.js
@@ -1,4 +1,5 @@
-import * as types from '../types';
+import types from '../types'
+import { put } from '../api/crud.fetch'
export const setToken = (data) => {
return { type: types.auth.set_token, data }
@@ -10,73 +11,81 @@ export const setCurrentUser = (data) => {
return { type: types.auth.set_current_user, data }
}
export function logout() {
- return { type: types.auth.logout_user };
+ return { type: types.auth.logout_user }
}
export function authLoading() {
- return { type: types.auth.loading };
+ return { type: types.auth.loading }
}
export function InvalidCredentialsException(message) {
- this.message = message;
- this.name = 'InvalidCredentialsException';
+ this.message = message
+ this.name = 'InvalidCredentialsException'
+}
+
+const api = {
+ login: '/api/login',
+ logout: '/api/logout',
+ signup: '/api/signup',
+ checkin: '/api/checkin',
}
export function login(username, password) {
return (dispatch) => {
- dispatch(authLoading());
- apiClient()
- .post(api.GET_TOKEN, {
+ dispatch(authLoading())
+ fetch(api.login, put({
username,
password
+ }))
+ .then(req => req.json())
+ .then(data => {
+ dispatch(setToken(data.token))
+ dispatch(checkin())
})
- .then(function (response) {
- dispatch(setToken(response.data.token));
- dispatch(getCurrentUser());
- })
- .catch(function (error) {
- dispatch(setError(true));
+ .catch(error => {
+ dispatch(setError(true))
if (error.response.status === 400) {
- throw new InvalidCredentialsException(error);
+ throw new InvalidCredentialsException(error)
}
- throw error;
- });
- };
+ throw error
+ })
+ }
}
export function signup(data) {
return (dispatch) => {
- dispatch(authLoading());
- apiClient()
- .post(api.SIGNUP, data)
- .then(function (response) {
- console.log(response.data);
- dispatch(login(data.username, data.password));
+ dispatch(authLoading())
+ fetch(api.signup, put(data))
+ .then(req => req.json())
+ .then(data => {
+ console.log(data)
+ dispatch(login(data.username, data.password))
})
- .catch(function (error) {
+ .catch(error => {
console.log(error)
if (error.response.status === 400) {
// dispatch(accountError("There was an error creating your account."))
- throw new InvalidCredentialsException(error);
+ throw new InvalidCredentialsException(error)
}
- throw error;
- });
- };
+ throw error
+ })
+ }
}
-export function getCurrentUser() {
+export function checkin() {
return (dispatch) => {
- dispatch(authLoading());
- apiClient()
- .get(api.CURRENT_USER)
- .then(function (response) {
- dispatch(setCurrentUser(response.data));
+ dispatch(authLoading())
+ fetch(api.checkin)
+ .then(req => req.json())
+ .then(data => {
+ console.log(data)
+ dispatch(setCurrentUser(data))
console.log('set current user')
})
- .catch(function (error) {
+ .catch(error => {
if (error.response.status === 400) {
- throw new InvalidCredentialsException(error);
+ throw new InvalidCredentialsException(error)
}
- throw error;
- });
- };
+ throw error
+ })
+ }
}
diff --git a/app/client/auth/login.component.js b/app/client/auth/login.component.js
index 4ffab34..58c3eaf 100644
--- a/app/client/auth/login.component.js
+++ b/app/client/auth/login.component.js
@@ -46,14 +46,14 @@ class Login extends Component {
name="username"
type="text"
value={this.state.username}
- onChange={this.handleChange}
+ onInput={this.handleChange}
/>
<TextInput
title="Password"
name="password"
type="password"
value={this.state.password}
- onChange={this.handleChange}
+ onInput={this.handleChange}
/>
<Button
loading={this.props.auth.loading}
diff --git a/app/client/auth/signup.component.js b/app/client/auth/signup.component.js
index c86d31b..e54084b 100644
--- a/app/client/auth/signup.component.js
+++ b/app/client/auth/signup.component.js
@@ -2,7 +2,7 @@ import { h, Component } from 'preact';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
-import actions from './auth.actions';
+import * as actions from './auth.actions';
import { Group, Param, TextInput, Button } from '../common';
@@ -17,12 +17,9 @@ class Signup extends Component {
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
- handleChange(e) {
- const name = e.target.name
- const value = e.target.value
+ handleChange(value, name) {
this.setState({
[name]: value,
- error: null,
})
}
validate(){
@@ -36,7 +33,8 @@ class Signup extends Component {
if (!this.validate) {
return this.props.actions.setError('bad password')
}
- this.props.actions.signup(this.state)
+ let { ...user } = this.state
+ this.props.actions.signup(user)
}
render(){
if (this.props.auth.isAuthenticated) {
@@ -54,26 +52,26 @@ class Signup extends Component {
name="username"
type="text"
value={this.state.username}
- onChange={this.handleChange}
+ onInput={this.handleChange}
/>
<TextInput
title="Password"
name="password"
type="password"
value={this.state.password}
- onChange={this.handleChange}
+ onInput={this.handleChange}
/>
<TextInput
title="Password again :)"
name="password2"
type="password"
value={this.state.password2}
- onChange={this.handleChange}
+ onInput={this.handleChange}
/>
<Button
loading={this.props.auth.loading}
>
- Login
+ Sign up
</Button>
{this.renderAuthError()}
</Group>
diff --git a/app/server/db/model.js b/app/server/db/model.js
index dd851bf..c829c85 100644
--- a/app/server/db/model.js
+++ b/app/server/db/model.js
@@ -17,9 +17,8 @@ module.exports = function modelScope(type, db_model, _props) {
crud: crud,
index: (query) => {
-
- return new Promise( (resolve, reject) => {
- crud.index(query).then( (data) => {
+ return new Promise((resolve, reject) => {
+ crud.index(query).then(data => {
if (! props.hasOne) {
resolve(data ? data.toJSON() : [])
@@ -27,13 +26,13 @@ module.exports = function modelScope(type, db_model, _props) {
else {
let recs = data.toJSON()
const loader = new Loader ()
- loader.onReady( () => {
+ loader.onReady(() => {
// console.log(type, 'ready')
resolve(recs)
})
// console.log('hasOne')
loader.register('hasOne')
- Object.keys(props.hasOne).forEach( (key,i) => {
+ Object.keys(props.hasOne).forEach((key, i) => {
loader.register(key)
// console.log('register', key)
const type = props.hasOne[key]
@@ -45,7 +44,7 @@ module.exports = function modelScope(type, db_model, _props) {
})
// console.log('\n\n%%%%%%%%%%%%%%%%%%%%%%%% index > hasOne ' + key + '\n\n\n')
// console.log(recs.length, Object.keys(id_lookup).length)
- db_crud(type).show_ids(Object.keys(id_lookup)).then( (sub_recs) => {
+ db_crud(type).show_ids(Object.keys(id_lookup)).then(sub_recs => {
// console.log(key, 'sub_recs', sub_recs)
const short_key = key.replace('_id','')
sub_recs.toJSON().forEach(rec => {
@@ -57,49 +56,51 @@ module.exports = function modelScope(type, db_model, _props) {
})
loader.ready('hasOne')
}
- }) // }).catch( () => res.sendStatus(500) )
+ })
})
},
- show: (id) => {
- return new Promise( (resolve, reject) => {
- crud.show(id).then( (data) => {
- if (! props.hasOne) {
+ show: (id, field = 'id') => {
+ return new Promise((resolve, reject) => {
+ crud.show(id, field).then(data => {
+ if (!data) {
+ resolve()
+ } else if (! props.hasOne) {
resolve(data.toJSON())
}
else {
let rec = data.toJSON()
const loader = new Loader ()
- loader.onReady( () => {
+ loader.onReady(() => {
resolve(rec)
})
loader.register('hasOne')
- Object.keys(props.hasOne).forEach( (key,i) => {
+ Object.keys(props.hasOne).forEach((key, i) => {
loader.register(key)
const type = props.hasOne[key]
- db_crud(type).show(rec[key + '_id']).then( (sub_rec) => {
+ db_crud(type).show(rec[key + '_id']).then((sub_rec) => {
rec[key] = sub_rec
loader.ready(key)
})
})
loader.ready('hasOne')
}
- }) // .catch( (err) => res.sendStatus(500) )
+ })
})
},
findOrCreate: (data) => {
- return new Promise( (resolve, reject) => {
+ return new Promise((resolve, reject) => {
let query = Object.assign({}, data)
query.limit = 1
- crud.index(query).then( (recs) => {
+ crud.index(query).then((recs) => {
if (recs && recs.length) {
const rec = recs.at(0)
// console.log('found rec', data.name)
return resolve(rec)
}
// console.log('creating rec', data.name)
- model.create(data).then( (rec) => {
+ model.create(data).then((rec) => {
resolve(rec)
})
})
@@ -107,12 +108,12 @@ module.exports = function modelScope(type, db_model, _props) {
},
create: (data) => {
- return new Promise( (resolve, reject) => {
+ return new Promise((resolve, reject) => {
const should_relay = data.should_relay === 'true'
- crud.create( model.sanitize(data) ).then( (rec) => {
+ crud.create( model.sanitize(data) ).then((rec) => {
resolve(rec.toJSON())
props.afterCreate && props.afterCreate(rec, should_relay)
- }).catch( (e) => {
+ }).catch(e => {
console.error('error creating', e)
reject()
})
@@ -121,10 +122,10 @@ module.exports = function modelScope(type, db_model, _props) {
update: (id, data) => {
// console.log('update', id)
- return new Promise( (resolve, reject) => {
- crud.update(id, model.sanitize(data)).then( (data) => {
+ return new Promise((resolve, reject) => {
+ crud.update(id, model.sanitize(data)).then(data => {
resolve(data.toJSON())
- }).catch( (e) => {
+ }).catch(e => {
console.error('error updating', e)
reject()
})
@@ -132,7 +133,7 @@ module.exports = function modelScope(type, db_model, _props) {
},
destroy: (id) => {
- return new Promise( (resolve, reject) => {
+ return new Promise((resolve, reject) => {
crud.show(id).then( data => {
if (! data) {
console.error('no record found', id)
@@ -141,9 +142,9 @@ module.exports = function modelScope(type, db_model, _props) {
if (type === 'file') {
upload.destroyFile(data)
}
- crud.destroy(id).then( (destroyData) => {
+ crud.destroy(id).then((destroyData) => {
resolve(data.toJSON())
- })// .catch( () => res.sendStatus(500) )
+ })
})
})
},
diff --git a/app/server/db/models.js b/app/server/db/models.js
index 24be774..8bf6d9a 100644
--- a/app/server/db/models.js
+++ b/app/server/db/models.js
@@ -21,7 +21,7 @@ let Task = bookshelf.Model.extend({
jsonColumns: ['opt'],
})
let User = bookshelf.Model.extend({
- tableName: 'user',
+ tableName: 'users',
hasTimestamps: true,
}, {
jsonColumns: ['profile'],
@@ -61,7 +61,7 @@ module.exports = {
// bridge.processTasks()
}
}),
- user: model('user', Task, {
+ user: model('user', User, {
fields: "username password realname level avatar lastseen profile created_at updated_at".split(" "),
afterCreate: (user) => {
console.log('created user')
diff --git a/app/server/util/auth.js b/app/server/util/auth.js
index d280927..fde0263 100644
--- a/app/server/util/auth.js
+++ b/app/server/util/auth.js
@@ -1,8 +1,9 @@
-let passport = require('passport')
-let LocalStrategy = require('passport-local').Strategy
-let crypto = require('crypto')
-// let fs = require('fs')
-let db = require('../db')
+import passport from 'passport'
+import { Strategy as LocalStrategy } from 'passport-local'
+import crypto from 'crypto'
+import db from '../db'
+
+const { user: userModel } = db.models
export function route(app, serve_index){
passport.serializeUser(serializeUser)
@@ -36,32 +37,38 @@ export function ensureAuthenticated(req, res, next) {
}
export function checkIfUserExists(req, res, next) {
- db.getUserByUsername(sanitizeName(req.body.username)).then((user) => {
+ userModel.show(sanitizeName(req.body.username), 'username').then((user) => {
+ console.log('gotta user?', !!user);
user ? res.json({ error: "user exists" }) : next()
+ }).catch(err => {
+ console.error('error', err)
})
}
-export function sanitizeName(s) { return (s || "").replace(new RegExp("[^-_a-zA-Z0-9]", 'g'), "") }
+export function sanitizeName(s) { return (s || "").replace(new RegExp('[^-_a-zA-Z0-9]', 'g'), "") }
export function sanitizeUser(req_user) {
// sanitize user object
- var user = JSON.parse(JSON.stringify(req_user))
+ let user = JSON.parse(JSON.stringify(req_user))
delete user.password
return user
}
export function createUser(req, res, next) {
- if (req.body.password !== req.body.password2) {
+ const { username, password, password2 } = req.body
+ if (password !== password2) {
return res.json({ error: "passwords don't match" })
}
let data = {
- username: sanitizeName(req.body.username),
- realname: sanitize(req.body.realname),
- password: makePassword(username, req.body.password),
- firstseen: new Date(),
+ username: sanitizeName(username),
+ realname: sanitizeName(username),
+ password: makePassword(username, password),
lastseen: new Date(),
- // lastsession: util.now(),
+ level: 0,
+ profile: {},
}
- db.createUser(data).then(() => next())
+ userModel.create(data)
+ .then(user => next(user))
+ .catch(err => res.json({ error }))
}
export function login(req, res) {
@@ -101,11 +108,11 @@ export function validPassword(user, password) {
}
export function changePassword(req, res, next) {
- if (! req.body.oldpassword && ! req.body.newpassword) return next()
+ if (!req.body.oldpassword && !req.body.newpassword) return next()
if (req.body.newpassword !== req.body.newpassword2) {
return res.send({ error: 'Passwords don\'t match.' })
}
- if (! validPassword(res.user, req.body.oldpassword)) {
+ if (!validPassword(res.user, req.body.oldpassword)) {
return res.send({ error: 'Password is incorrect.' })
}
let username = req.user.get('username')
@@ -113,19 +120,6 @@ export function changePassword(req, res, next) {
res.user.set('password', newPassword)
res.user.save().then(() => next()).catch(err => res.send({ error: err }))
}
-export function changePasswordDangerously(req, res, next) {
- if (! req.body.password && ! req.body.newpassword) return next()
- if (req.body.newpassword !== req.body.newpassword2) {
- return res.send({ error: 'Passwords don\'t match.' })
- }
- if (! validPassword(req.user, req.body.password)) {
- return res.send({ error: 'Password is incorrect.' })
- }
- let username = res.user.get('username')
- let newPassword = makePassword(username, req.body.newpassword)
- res.user.set('password', newPassword)
- res.user.save().then(() => next()).catch(err => res.send({ error: err }))
-}
export function verifyLocalUser(username, password, done) {
// handle passwords!!
@@ -142,7 +136,6 @@ export function verifyLocalUser(username, password, done) {
})
}
-
export function checkin(req, res) {
res.json({ user: sanitizeUser(req.user) })
}