fix bugs, full two fa system done

This commit is contained in:
2023-07-13 15:00:58 +02:00
parent 9f5d5a3be3
commit 5270317e2d
13 changed files with 158 additions and 19 deletions

View File

@@ -15,39 +15,52 @@ const bodyParser = require( 'body-parser' );
const cookieParser = require( 'cookie-parser' );
const http = require( 'http' );
const fs = require( 'fs' );
const mail = require( './backend/mail/mailSender.js' );
const mailManager = new mail();
const dbh = require( './backend/db/mysqldb.js' );
const db = new dbh();
db.connect();
// const env = process.env.PROD || false;
const settings = JSON.parse( fs.readFileSync( path.join( __dirname + '/config/settings.config.json' ) ) );
if ( !settings.init ) {
db.setupDB( 'janishut_libreeventTest' );
}
// const mail = require( './backend/mail/mailSender.js' );
// const mailManager = new mail();
// const dbh = require( './backend/db/mysqldb.js' );
// const db = new dbh();
// db.connect();
// const env = process.env.PROD || false;
// if ( !settings.init ) {
// db.setupDB( 'janishut_libreeventTest' );
// }
// const responseTime = require( 'response-time' );
// app.use( responseTime( ( request, response, time ) => {
// console.log( time );
// } ) );
app.use( express.static( '../webapp/dist' ) );
// app.use( express.static( '.' ) );
// initialise express with middlewares
// TODO: Generate random token
app.use( expressSession( {
secret: 'gaoevgoawefgo083tq2rfvöfaf0p8',
resave: true,
saveUninitialized: true
saveUninitialized: true,
cookie: {
sameSite: 'none'
}
} ) );
app.use( bodyParser.urlencoded( { extended: false } ) );
app.use( bodyParser.json() );
app.use( cookieParser() );
app.use( express.static( '../webapp/dist' ) );
require( './admin/routes.js' )( app, settings ); // admin routes
require( './backend/userRoutes.js' )( app, settings ); // user routes
app.use( ( request, response ) => {
console.log( 'index fallback' );
response.sendFile( path.join( __dirname + '/../webapp/dist/index.html' ) );
} );

View File

@@ -14,6 +14,7 @@ const token = require( '../token.js' );
class TwoFA {
constructor () {
this.tokenStore = {};
this.references = {};
}
registerStandardAuthentication () {
@@ -35,6 +36,14 @@ class TwoFA {
return { 'code': code, 'token': tok };
}
storeTokenReference ( token, sessionID ) {
this.references[ token ] = sessionID;
}
getTokenReference ( token ) {
return this.references[ token ];
}
verifyEnhanced ( token, number = '' ) {
if ( this.tokenStore[ token ]?.mode === 'standard' ) return true;
else if ( this.tokenStore[ token ]?.mode === 'enhanced' ) {

View File

@@ -19,7 +19,9 @@ const db = require( '../db/db.js' );
module.exports.checkpassword = function checkpassword ( username, password ) {
return new Promise( resolve => {
db.getData( 'user', username ).then( data => {
resolve( bcrypt.compareSync( password, data ) );
bcrypt.compare( password, data ).then( data => {
resolve( data );
} );
} );
} );
};

View File

@@ -13,6 +13,8 @@ const auth = require( './credentials/2fa.js' );
const twoFA = new auth();
const path = require( 'path' );
let responseObjects = {};
module.exports = ( app, settings ) => {
app.post( '/api/reserveTicket', ( request, response ) => {
db.getData( 'test', request.body );
@@ -23,11 +25,16 @@ module.exports = ( app, settings ) => {
if ( request.body.mail && request.body.password ) {
pwdmanager.checkpassword( request.body.mail, request.body.password ).then( data => {
if ( data ) {
// TODO: Send mails
if ( settings.twoFA === 'standard' ) {
let tok = twoFA.registerStandardAuthentication()[ 'token' ];
request.session.token = tok;
console.log( 'http://localhost:8081/user/2fa?token=' + tok );
response.send( { 'status': '2fa' } );
} else if ( settings.twoFA === 'enhanced' ) {
let res = twoFA.registerEnhancedAuthentication();
console.log( 'http://localhost:8081/user/2fa?token=' + res.token );
request.session.token = res.token;
response.send( { 'status': '2fa+', 'code': res.code } );
} else {
request.session.loggedInUser = true;
@@ -47,6 +54,7 @@ module.exports = ( app, settings ) => {
let tokType = twoFA.verifySimple( request.query.token );
if ( tokType === 'standard' ) {
request.session.loggedInUser = true;
responseObjects[ request.query.token ].write( 'data: authenticated\n\n' );
response.sendFile( path.join( __dirname + '/../ui/en/2fa/2faSimple.html' ) );
} else if ( tokType === 'enhanced' ) {
response.sendFile( path.join( __dirname + '/../ui/en/2fa/2faEnhanced.html' ) );
@@ -59,7 +67,20 @@ module.exports = ( app, settings ) => {
let verified = twoFA.verifyEnhanced( request.body.token, request.body.code );
if ( verified ) {
request.session.loggedInUser = true;
responseObjects[ request.query.token ].write( 'data: authenticated\n\n' );
response.send( 'ok' );
} else response.send( 'wrong' );
} );
app.get( '/user/2fa/check', ( request, response ) => {
response.writeHead( 200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
} );
response.status( 200 );
response.flushHeaders();
response.write( 'data: connected\n\n' );
responseObjects[ request.session.token ] = response;
} );
};

View File

@@ -1,4 +1,4 @@
{
"init": false,
"twoFA": "enhanced"
"twoFA": "standard"
}

View File

@@ -45,6 +45,7 @@
"path-exists": "^5.0.0",
"readjson": "^2.2.2",
"relateurl": "^0.2.7",
"response-time": "^2.3.2",
"simport": "^1.2.0",
"source-map": "^0.6.1",
"source-map-support": "^0.5.21",
@@ -1602,6 +1603,28 @@
"node": ">= 0.10"
}
},
"node_modules/response-time": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/response-time/-/response-time-2.3.2.tgz",
"integrity": "sha512-MUIDaDQf+CVqflfTdQ5yam+aYCkXj1PY8fjlPDQ6ppxJlmgZb864pHtA750mayywNg8tx4rS7qH9JXd/OF+3gw==",
"dev": true,
"dependencies": {
"depd": "~1.1.0",
"on-headers": "~1.0.1"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/response-time/node_modules/depd": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
"integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==",
"dev": true,
"engines": {
"node": ">= 0.6"
}
},
"node_modules/rimraf": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",

View File

@@ -31,6 +31,7 @@
"path-exists": "^5.0.0",
"readjson": "^2.2.2",
"relateurl": "^0.2.7",
"response-time": "^2.3.2",
"simport": "^1.2.0",
"source-map": "^0.6.1",
"source-map-support": "^0.5.21",

11
src/server/test.html Normal file
View File

@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
New test
</body>
</html>

9
src/server/test.js Normal file
View File

@@ -0,0 +1,9 @@
const express = require( 'express' );
let app = express();
const http = require( 'http' );
app.use( express.static( '.' ) );
const PORT = process.env.PORT || 8081;
http.createServer( app ).listen( PORT );

View File

@@ -186,7 +186,8 @@ export default {
document.documentElement.classList.add( 'light' );
this.theme = '&#9789;';
}
localStorage.setItem( 'url', 'http://localhost:8081' );
// localStorage.setItem( 'url', 'http://localhost:8081' );
localStorage.setItem( 'url', '' );
}
}
</script>

View File

@@ -22,7 +22,8 @@ let userStore = useUserStore();
let prod = true;
if ( prod ) {
fetch( 'http://localhost:8081/api/getAuth' ).then( res => {
fetch( '/api/getAuth' ).then( res => {
// fetch( 'http://localhost:8081/api/getAuth' ).then( res => {
res.json().then( data => {
userStore.setUserAuth( data.user );
userStore.setAdminAuth( data.admin );

View File

@@ -45,6 +45,7 @@
login () {
if ( this.formData.mail ) {
if ( this.formData.password ) {
let progress = this.$refs.notification.createNotification( 'Logging you in', 20, 'progress', 'normal' );
let fetchOptions = {
method: 'post',
body: JSON.stringify( this.formData ),
@@ -67,6 +68,7 @@
sessionStorage.setItem( '2faCode', json.code );
this.$router.push( '/twoFactors' );
} else {
this.$refs.notification.cancelNotification( progress );
this.$refs.notification.createNotification( 'The credentials you provided do not match our records.', 5, 'error', 'normal' );
}
} );

View File

@@ -2,25 +2,71 @@
<div id="twoFA">
<h1>Two-Factor Authentication</h1>
<p>We have sent you an email containing a link for Authentication.</p>
<div class="code-container" v-if="code != ''">
<div class="code-container" v-if="code[ 1 ] != ''">
<p>Open the link in the email and enter this code:</p>
<div class="code">
<div class="code-sub" id="code-part1">{{ code[1] }}</div>
<div class="code-sub" id="code-part2">{{ code[2] }}</div>
</div>
</div>
<notifications ref="notification" location="bottomright" size="bigger"></notifications>
</div>
</template>
<script>
import notifications from '@/components/notifications/notifications.vue';
import { useUserStore } from '@/stores/userStore';
import { mapStores } from 'pinia';
export default {
name: 'twoFA',
components: {
notifications
},
data () {
return {
code: { '1': '', '2': '' }
}
},
computed: {
...mapStores( useUserStore ),
},
created () {
if ( !!window.EventSource ) {
setTimeout( () => {
let startNotification = this.$refs.notification.createNotification( 'Connecting to status service', 20, 'progress', 'normal' );
let source = new EventSource( localStorage.getItem( 'url' ) + '/user/2fa/check', { withCredentials: true } );
let self = this;
source.onmessage = ( e ) => {
if ( e.data === 'authenticated' ) {
self.userStore.setUserAuth( true );
self.$router.push( '/account' );
console.log( e.data );
}
}
source.onopen = e => {
self.$refs.notification.createNotification( 'Connected to status service', 5, 'ok', 'normal' );
self.$refs.notification.cancelNotification( startNotification );
};
source.addEventListener( 'error', function(e) {
if (e.eventPhase == EventSource.CLOSED) source.close();
if (e.target.readyState == EventSource.CLOSED) {
console.log( e );
self.$refs.notification.cancelNotification( startNotification );
self.$refs.notification.createNotification( 'Could not connect to status service', 5, 'error', 'normal' );
}
}, false)
}, 300 );
} else {
setTimeout( () => {
this.$refs.notification.createNotification( 'Unsupported browser detected. Redirection might take longer to occur!', 20, 'warning', 'normal' );
}, 300 );
}
let code = sessionStorage.getItem( '2faCode' ) ? sessionStorage.getItem( '2faCode' ) : '';
this.code = { '1': code.slice( 0, 3 ), '2': code.substring( 3 ) };
},