mirror of
https://gitlab.com/MrFry/mrfrys-node-server
synced 2025-04-01 20:24:18 +02:00
Handling sessions, json response if not logged in
This commit is contained in:
parent
52ae2828e5
commit
4c2c617b96
7 changed files with 110 additions and 23 deletions
|
@ -54,16 +54,18 @@ function CreateDB () {
|
||||||
// TODO: check if path exists, create it if not
|
// TODO: check if path exists, create it if not
|
||||||
authDB = dbtools.GetDB(usersDBPath)
|
authDB = dbtools.GetDB(usersDBPath)
|
||||||
|
|
||||||
|
// TODO: foreign key
|
||||||
Object.keys(dbStruct).forEach((tableName) => {
|
Object.keys(dbStruct).forEach((tableName) => {
|
||||||
const tableData = dbStruct[tableName]
|
const tableData = dbStruct[tableName]
|
||||||
dbtools.CreateTable(authDB, tableName, tableData.tableStruct)
|
dbtools.CreateTable(authDB, tableName, tableData.tableStruct)
|
||||||
})
|
})
|
||||||
|
|
||||||
// dbtools.Insert(authDB, 'users', {
|
// TODO: fill with data
|
||||||
// pw: 2,
|
dbtools.Insert(authDB, 'users', {
|
||||||
// id: 1,
|
pw: 2,
|
||||||
// notes: 'hemnlo'
|
id: 1,
|
||||||
// })
|
notes: 'hemnlo'
|
||||||
|
})
|
||||||
// console.log(dbtools.TableInfo(authDB, 'users'))
|
// console.log(dbtools.TableInfo(authDB, 'users'))
|
||||||
}
|
}
|
||||||
CreateDB()
|
CreateDB()
|
||||||
|
@ -82,12 +84,15 @@ CreateDB()
|
||||||
//
|
//
|
||||||
// app.use(session(sess))
|
// app.use(session(sess))
|
||||||
|
|
||||||
|
const cookieSecret = uuidv4()
|
||||||
app.use(session({
|
app.use(session({
|
||||||
secret: uuidv4(),
|
secret: cookieSecret,
|
||||||
resave: false,
|
resave: false,
|
||||||
saveUninitialized: true
|
saveUninitialized: true
|
||||||
}))
|
}))
|
||||||
app.use(cookieParser())
|
app.use(cookieParser({
|
||||||
|
secret: cookieSecret
|
||||||
|
}))
|
||||||
app.use(bodyParser.urlencoded({
|
app.use(bodyParser.urlencoded({
|
||||||
limit: '10mb',
|
limit: '10mb',
|
||||||
extended: true
|
extended: true
|
||||||
|
@ -141,7 +146,9 @@ Load()
|
||||||
// -------------------------------------------------------------
|
// -------------------------------------------------------------
|
||||||
|
|
||||||
app.post('/login', (req, res) => {
|
app.post('/login', (req, res) => {
|
||||||
|
// TODO: user.logincount update in db
|
||||||
logger.LogReq(req)
|
logger.LogReq(req)
|
||||||
|
const isScript = req.body.script
|
||||||
const pw = req.body.pw
|
const pw = req.body.pw
|
||||||
const user = dbtools.Select(authDB, 'users', {
|
const user = dbtools.Select(authDB, 'users', {
|
||||||
pw: pw
|
pw: pw
|
||||||
|
@ -149,15 +156,48 @@ app.post('/login', (req, res) => {
|
||||||
|
|
||||||
if (user) {
|
if (user) {
|
||||||
const sessionID = uuidv4()
|
const sessionID = uuidv4()
|
||||||
|
|
||||||
|
// Setting session
|
||||||
req.session.user = user
|
req.session.user = user
|
||||||
|
req.session.sessionID = sessionID
|
||||||
|
|
||||||
|
// FIXME: Users now can only log in in one session, this might be too strict.
|
||||||
|
const existingSessions = dbtools.Select(authDB, 'sessions', {
|
||||||
|
userID: user.id
|
||||||
|
})
|
||||||
|
|
||||||
|
if (existingSessions.length > 0) {
|
||||||
|
logger.Log(`Multiple sessions ( ${existingSessions.length} ) for #${user.id}, deleting olds`, logger.GetColor('cyan'))
|
||||||
|
existingSessions.forEach((sess) => {
|
||||||
|
dbtools.Delete(authDB, 'sessions', {
|
||||||
|
id: sess.id
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
dbtools.Insert(authDB, 'sessions', {
|
dbtools.Insert(authDB, 'sessions', {
|
||||||
id: sessionID,
|
id: sessionID,
|
||||||
ip: req.headers['cf-connecting-ip'] || req.connection.remoteAddress,
|
ip: req.headers['cf-connecting-ip'] || req.connection.remoteAddress,
|
||||||
userID: user.id
|
userID: user.id,
|
||||||
|
createDate: new Date().toString()
|
||||||
|
})
|
||||||
|
|
||||||
|
// TODO: cookie age
|
||||||
|
res.cookie('sessionID', sessionID)
|
||||||
|
|
||||||
|
if (isScript) {
|
||||||
|
res.json({
|
||||||
|
result: 'success',
|
||||||
|
sessionID: sessionID
|
||||||
})
|
})
|
||||||
// FIXME: redirect to original url
|
|
||||||
res.cookie('sessionID', sessionID).redirect('/')
|
|
||||||
} else {
|
} else {
|
||||||
|
// FIXME: redirect to original url
|
||||||
|
res.redirect('/')
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Log(`Successfull login with user ID: #${user.id}`, logger.GetColor('cyan'))
|
||||||
|
} else {
|
||||||
|
logger.Log(`Login attempt with invalid pw: ${pw}`, logger.GetColor('cyan'))
|
||||||
res.json({
|
res.json({
|
||||||
msg: 'invalid pw'
|
msg: 'invalid pw'
|
||||||
})
|
})
|
||||||
|
@ -166,11 +206,20 @@ app.post('/login', (req, res) => {
|
||||||
|
|
||||||
app.post('/logout', (req, res) => {
|
app.post('/logout', (req, res) => {
|
||||||
logger.LogReq(req)
|
logger.LogReq(req)
|
||||||
// FIXME: redirect to original url
|
const sessionID = req.cookies.sessionID
|
||||||
const userID = req.session.user.id
|
const userID = req.session.user.id
|
||||||
|
|
||||||
|
// destroying session
|
||||||
req.session.destroy(function () {
|
req.session.destroy(function () {
|
||||||
logger.Log(`User ${userID} logout`)
|
logger.Log(`User ${userID} logout`, logger.GetColor('cyan'))
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// removing session from db
|
||||||
|
dbtools.Delete(authDB, 'sessions', {
|
||||||
|
id: sessionID
|
||||||
|
})
|
||||||
|
// TODO: remove old sessions every once in a while
|
||||||
|
// FIXME: redirect to original url
|
||||||
res.clearCookie('sessionID').redirect('/')
|
res.clearCookie('sessionID').redirect('/')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -402,7 +451,9 @@ app.get('/datacount', function (req, res) {
|
||||||
})
|
})
|
||||||
|
|
||||||
app.get('/infos', function (req, res) {
|
app.get('/infos', function (req, res) {
|
||||||
let result = {}
|
let result = {
|
||||||
|
result: 'success'
|
||||||
|
}
|
||||||
if (req.query.subjinfo) {
|
if (req.query.subjinfo) {
|
||||||
result.subjinfo = getSimplreRes()
|
result.subjinfo = getSimplreRes()
|
||||||
}
|
}
|
||||||
|
|
|
@ -34,6 +34,13 @@
|
||||||
"userID": {
|
"userID": {
|
||||||
"type": "number",
|
"type": "number",
|
||||||
"notNull": true
|
"notNull": true
|
||||||
|
},
|
||||||
|
"createDate": {
|
||||||
|
"type": "text",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"lastAccess": {
|
||||||
|
"type": "text"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
|
@ -6,12 +6,11 @@ const exceptions = [
|
||||||
'/login'
|
'/login'
|
||||||
]
|
]
|
||||||
|
|
||||||
// TODO: session table, dont store pw in cookie
|
|
||||||
|
|
||||||
module.exports = function (options) {
|
module.exports = function (options) {
|
||||||
const { authDB } = options
|
const { authDB } = options
|
||||||
|
|
||||||
return function (req, res, next) {
|
return function (req, res, next) {
|
||||||
|
const sessionID = req.cookies.sessionID || req.session.id
|
||||||
const isException = exceptions.some((exc) => {
|
const isException = exceptions.some((exc) => {
|
||||||
return req.url === exc
|
return req.url === exc
|
||||||
})
|
})
|
||||||
|
@ -22,14 +21,32 @@ module.exports = function (options) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
const user = req.session.user || GetUserBySessionID(authDB, req.cookies.sessionID, req)
|
const user = req.session.user || GetUserBySessionID(authDB, sessionID, req)
|
||||||
|
console.log(req.session)
|
||||||
|
|
||||||
|
// update 'sessiosn' table 'lastAccess' stuff
|
||||||
|
if (sessionID) {
|
||||||
|
dbtools.Update(authDB, 'sessions', {
|
||||||
|
lastAccess: new Date().toString()
|
||||||
|
}, {
|
||||||
|
id: sessionID
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(dbtools.SelectAll(authDB, 'sessions'))
|
||||||
|
|
||||||
|
// FIXME: invalidate when new ip or something
|
||||||
|
|
||||||
if (user) {
|
if (user) {
|
||||||
logger.DebugLog(`ID #${user.id}: ${req.url}`, 'auth', 1)
|
logger.DebugLog(`ID #${user.id}: ${req.url}`, 'auth', 1)
|
||||||
next()
|
next()
|
||||||
} else {
|
} else {
|
||||||
logger.DebugLog(`No user:${req.url}`, 'auth', 1)
|
logger.DebugLog(`No user:${req.url}`, 'auth', 1)
|
||||||
res.render('login')
|
// res.render('login')
|
||||||
|
res.json({
|
||||||
|
result: 'nouser',
|
||||||
|
msg: 'You are not logged in'
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -44,12 +61,17 @@ function GetUserBySessionID (db, sessionID, req) {
|
||||||
id: sessionID
|
id: sessionID
|
||||||
})[0]
|
})[0]
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
const user = dbtools.Select(db, 'users', {
|
const user = dbtools.Select(db, 'users', {
|
||||||
id: session.userID
|
id: session.userID
|
||||||
})[0]
|
})[0]
|
||||||
|
|
||||||
if (user) {
|
if (user) {
|
||||||
req.session.user = user
|
req.session.user = user
|
||||||
|
req.session.id = sessionID
|
||||||
return user
|
return user
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1 +1 @@
|
||||||
Subproject commit 86b01f443a306695a9a17f29785ba20b7f08f810
|
Subproject commit 72ea24c07133d02a983152b4416ff98eb5dc4369
|
|
@ -17,6 +17,7 @@
|
||||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
------------------------------------------------------------------------- */
|
------------------------------------------------------------------------- */
|
||||||
|
console.clear()
|
||||||
|
|
||||||
const startHTTPS = true
|
const startHTTPS = true
|
||||||
const port = 8080
|
const port = 8080
|
||||||
|
@ -38,7 +39,6 @@ const loggableKeywords = [
|
||||||
]
|
]
|
||||||
let modules = JSON.parse(utils.ReadFile(modulesFile))
|
let modules = JSON.parse(utils.ReadFile(modulesFile))
|
||||||
|
|
||||||
console.clear()
|
|
||||||
logger.Load()
|
logger.Load()
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
|
@ -5,7 +5,7 @@ module.exports = {
|
||||||
GetDB,
|
GetDB,
|
||||||
AddColumn,
|
AddColumn,
|
||||||
TableInfo,
|
TableInfo,
|
||||||
UpdateRecord,
|
Update,
|
||||||
Delete,
|
Delete,
|
||||||
CreateTable,
|
CreateTable,
|
||||||
SelectAll,
|
SelectAll,
|
||||||
|
@ -83,7 +83,7 @@ function TableInfo (db, table) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function UpdateRecord (db, table, newData, conditions) {
|
function Update (db, table, newData, conditions) {
|
||||||
try {
|
try {
|
||||||
const s = `UPDATE ${table} SET ${GetSqlQuerry(newData)} WHERE ${GetSqlQuerry(conditions)}`
|
const s = `UPDATE ${table} SET ${GetSqlQuerry(newData)} WHERE ${GetSqlQuerry(conditions)}`
|
||||||
DebugLog(s)
|
DebugLog(s)
|
||||||
|
@ -118,7 +118,8 @@ function CreateTable (db, name, columns) {
|
||||||
return acc
|
return acc
|
||||||
}, []).join(', ')
|
}, []).join(', ')
|
||||||
|
|
||||||
const s = `CREATE TABLE IF NOT EXISTS ${name}(${cols})`
|
// IF NOT EXISTS // TODO
|
||||||
|
const s = `CREATE TABLE ${name}(${cols})`
|
||||||
DebugLog(s)
|
DebugLog(s)
|
||||||
|
|
||||||
const stmt = db.prepare(s)
|
const stmt = db.prepare(s)
|
||||||
|
|
|
@ -118,7 +118,13 @@ function LogReq (req, toFile, sc) {
|
||||||
dl += C('red')
|
dl += C('red')
|
||||||
}
|
}
|
||||||
|
|
||||||
const hostname = req.hostname.replace('www.', '').split('.')[0]
|
let hostname
|
||||||
|
if (req.hostname) {
|
||||||
|
hostname = req.hostname.replace('www.', '').split('.')[0]
|
||||||
|
} else {
|
||||||
|
hostname = 'NOHOST'
|
||||||
|
Log('req.hostname is undefined! req.hostname: ' + req.hostname, GetColor('redbg'))
|
||||||
|
}
|
||||||
logEntry += dl + hostname + dl + req.headers['user-agent'] + dl + req.method + dl
|
logEntry += dl + hostname + dl + req.headers['user-agent'] + dl + req.method + dl
|
||||||
|
|
||||||
logEntry += GetRandomColor(req.url.split('?')[0]) + req.url
|
logEntry += GetRandomColor(req.url.split('?')[0]) + req.url
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue