almost finished admin auth system

This commit is contained in:
2023-07-16 13:40:40 +02:00
parent afdaf13048
commit 8b6c190e15
7 changed files with 438 additions and 22 deletions

66
src/server/admin/2fa.js Normal file
View File

@@ -0,0 +1,66 @@
/*
* libreevent - 2fa.js
*
* Created by Janis Hutz 07/11/2023, Licensed under the GPL V3 License
* https://janishutz.com, development@janishutz.com
*
*
*/
const token = require( '../backend/token.js' );
// let createSSRApp = require( 'vue' ).createSSRApp;
// let renderToString = require( 'vue/server-renderer' ).renderToString;
class TwoFA {
constructor () {
this.tokenStore = {};
this.references = {};
}
registerStandardAuthentication () {
let tok = token.generateToken( 60 );
while ( this.tokenStore[ tok ] ) {
tok = token.generateToken( 60 );
}
this.tokenStore[ tok ] = { 'mode': 'standard' };
return { 'token': tok };
}
registerEnhancedAuthentication () {
let tok = token.generateToken( 60 );
while ( this.tokenStore[ tok ] ) {
tok = token.generateToken( 60 );
}
let code = token.generateNumber( 6 );
this.tokenStore[ tok ] = { 'mode': 'enhanced', 'code': code };
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' ) {
if ( this.tokenStore[ token ].code == number ) {
delete this.tokenStore[ token ];
return true;
} else return false;
} else return false;
}
verifySimple ( token ) {
if ( this.tokenStore[ token ]?.mode === 'standard' ) {
delete this.tokenStore[ token ];
return 'standard';
} else if ( this.tokenStore[ token ]?.mode === 'enhanced' ) return 'enhanced';
else return 'invalid';
}
}
module.exports = TwoFA;

View File

@@ -20,7 +20,7 @@ const db = require( '../backend/db/db.js' );
module.exports.checkpassword = function checkpassword ( username, password ) {
return new Promise( resolve => {
db.getData( 'admin', username ).then( data => {
db.getDataSimple( 'admin', 'email', username ).then( data => {
resolve( bcrypt.compareSync( password, data ) );
} );
} );

View File

@@ -7,7 +7,13 @@
*
*/
// const db = require( './db/db.js' );
const pwdmanager = require( './pwdmanager.js' );
const auth = require( './2fa.js' );
const twoFA = new auth();
const path = require( 'path' );
let responseObjects = {};
module.exports = ( app, settings ) => {
/*
@@ -15,19 +21,68 @@ module.exports = ( app, settings ) => {
*/
app.post( '/admin/auth', ( request, response ) => {
pwdmanager.checkpassword( request.body.mail, request.body.pwd ).then( data => {
if ( request.body.mail && request.body.password ) {
pwdmanager.checkpassword( request.body.mail, request.body.password ).then( data => {
request.session.username = request.body.mail;
if ( data ) {
if ( settings.twoFA ) {
// TODO: Support both methods of 2fa
response.send( '2fa' );
// TODO: Send mails
// TODO: Check if user has 2fa enabled
if ( settings.twoFA === 'standard' ) {
let tok = twoFA.registerStandardAuthentication()[ 'token' ];
request.session.token = tok;
console.log( 'http://localhost:8081/admin/2fa?token=' + tok );
response.send( { 'status': '2fa' } );
} else if ( settings.twoFA === 'enhanced' ) {
let res = twoFA.registerEnhancedAuthentication();
console.log( 'http://localhost:8081/admin/2fa?token=' + res.token );
request.session.token = res.token;
response.send( { 'status': '2fa+', 'code': res.code } );
} else {
request.session.loggedInAdmin = true;
response.send( 'ok' );
request.session.loggedInUser = true;
response.send( { 'status': 'ok' } );
}
} else {
response.send( 'pwErr' );
response.send( { 'status': 'pwErr' } );
}
} );
} else {
response.send( 'missingCredentials' );
}
} );
app.get( '/admin/2fa', ( request, response ) => {
// TODO: Add multi language
let tokType = twoFA.verifySimple( request.query.token );
if ( tokType === 'standard' ) {
request.session.loggedInAdmin = 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/2faEnhancedAdmin.html' ) );
} else {
response.sendFile( path.join( __dirname + '/../ui/en/2fa/2faInvalid.html' ) );
}
} );
app.post( '/admin/2fa/verify', ( request, response ) => {
let verified = twoFA.verifyEnhanced( request.body.token, request.body.code );
if ( verified ) {
request.session.loggedInAdmin = true;
responseObjects[ request.body.token ].write( 'data: authenticated\n\n' );
response.send( 'ok' );
} else response.send( 'wrong' );
} );
app.get( '/admin/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;
} );
app.get( '/test/login', ( request, response ) => {

View File

@@ -0,0 +1,132 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Two Factor Authentication Invalid</title>
<style>
body, html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
background-color: rgb(41, 40, 40);
color: white;
font-size: 150%;
}
.content {
width: 70%;
}
#code {
padding: 0.75%;
border: solid white 1px;
border-radius: 7px;
font-size: 100%;
text-align: center;
}
.submit {
margin-top: 2%;
background: linear-gradient(90deg, rgb(30, 36, 131), rgb(87, 66, 184), rgb(105, 115, 214), rgb(30, 36, 131), rgb(41, 128, 109), rgb(146, 50, 47));
background-size: 300px;
padding: 10px 20px;
border: none;
border-radius: 20px;
cursor: pointer;
transition: all 3s;
font-size: 75%;
color: white;
}
.submit:hover {
background-size: 200%;
background-position: -100%;
}
#popup {
border: none;
border-radius: 20px;
padding: 5%;
background-color: rgb(34, 34, 34);
color: white;
max-width: 70%;
}
#popup::backdrop {
background-color: rgba( 0, 0, 0, 0.8 );
}
</style>
</head>
<body>
<div class="content">
<h1>Two-Factor Authen&shy;tication</h1>
<p id="text">Please enter the code displayed on the login page down below to finish the Two-Factor Authentication.</p>
<form onsubmit="return submitFunction()" id="form">
<input type="text" name="code" id="code"><br>
<input type="submit" value="Submit" class="submit">
</form>
<dialog id="popup">
<p id="popup-message"></p>
<form method="dialog">
<input type="submit" value="Ok" class="submit">
</form>
</dialog>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
function submitFunction () {
let code = document.getElementById( 'code' ).value;
let data = '';
if ( code.includes( ' ' ) ) {
for ( let letter in code ) {
if ( code[ letter ] != ' ' ) {
data += code[ letter ];
}
}
} else {
data = code;
}
if ( data.length == 6 ) {
let fetchOptions = {
method: 'post',
body: JSON.stringify( { 'code': data, 'token': location.search.substring( 7 ) } ),
headers: {
'Content-Type': 'application/json',
'charset': 'utf-8'
}
};
fetch( '/admin/2fa/verify', fetchOptions ).then( res => {
res.text().then( data => {
if ( data === 'ok' ) {
document.getElementById( 'text' ).innerText = 'Two-Factor Authentication is complete! Head back to the original page!';
document.getElementById( 'form' ).innerHTML = '';
openPopup( 'You have successfully authorised this login. You may now close this tab and head back to the original tab.' );
} else {
openPopup( 'This code you specified is invalid (or no longer valid). Please try again.' );
}
} );
} );
} else {
openPopup( 'Please enter a six-character code to proceed' );
}
return false;
}
function openPopup ( message ) {
document.getElementById( 'popup-message' ).innerHTML = message;
document.getElementById( 'popup' ).showModal();
}
</script>
</body>
</html>

View File

@@ -48,6 +48,14 @@ export default [
title: 'Login :: Admin - libreevent'
}
},
{
path: '/admin/twoFactors',
name: 'admin2FA',
component: () => import( '../views/admin/TwoFA.vue' ),
meta: {
title: 'Two Factor Authentication :: Admin - libreevent'
}
},
{
path: '/signup',
name: 'signup',

View File

@@ -1,7 +1,7 @@
<!--
* libreevent - AdminLoginView.vue
*
* Created by Janis Hutz 05/14/2023, Licensed under the GPL V3 License
* Created by Janis Hutz 07/16/2023, Licensed under the GPL V3 License
* https://janishutz.com, development@janishutz.com
*
*
@@ -12,32 +12,80 @@
<div class="login-app">
<h1>Log into your admin account</h1>
<form>
<label for="mail">Email address</label><br>
<label for="mail">Email</label><br>
<input type="email" v-model="formData[ 'mail' ]" name="mail" id="mail" required><br><br>
<label for="password">Password</label><br>
<input type="text" v-model="formData[ 'password' ]" name="password" id="password" required>
<input type="password" v-model="formData[ 'password' ]" name="password" id="password" required>
</form>
<button @click="login();" class="button">Log in</button>
</div>
<notifications ref="notification" location="topright" size="bigger"></notifications>
</div>
</template>
<script>
import { useUserStore } from '@/stores/userStore';
import { mapStores } from 'pinia';
import notifications from '@/components/notifications/notifications.vue';
export default {
data () {
return {
formData: {}
}
},
components: {
notifications,
},
computed: {
...mapStores( useUserStore )
},
methods: {
login () {
this.$router.push( '/admin' );
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 ),
headers: {
'Content-Type': 'application/json',
'charset': 'utf-8'
}
};
fetch( localStorage.getItem( 'url' ) + '/admin/auth', fetchOptions ).then( res => {
res.json().then( json => {
if ( json.status === 'ok' ) {
this.userStore.setAdminAuth( true );
this.$router.push( sessionStorage.getItem( 'redirect' ) ? sessionStorage.getItem( 'redirect' ) : '/account' );
sessionStorage.removeItem( 'redirect' );
} else if ( json.status === '2fa' ) {
this.userStore.setAdmin2fa( true );
this.$router.push( '/admin/twoFactors' );
} else if ( json.status === '2fa+' ) {
this.userStore.setAdmin2fa( true );
sessionStorage.setItem( '2faCode', json.code );
this.$router.push( '/admin/twoFactors' );
} else {
this.$refs.notification.cancelNotification( progress );
this.$refs.notification.createNotification( 'The credentials you provided do not match our records.', 5, 'error', 'normal' );
}
} );
} );
} else {
this.$refs.notification.createNotification( 'A password is required to log in', 5, 'error', 'normal' );
}
} else {
this.$refs.notification.createNotification( 'An email address is required to log in', 5, 'error', 'normal' );
}
},
},
}
</script>
<style scoped>
/* TODO: Update colour to image */
.login {
background-color: green;
width: 100%;
@@ -66,10 +114,13 @@
padding: 5px 10px;
margin-top: 2%;
}
</style>
<style>
nav {
display: block;
display: initial;
}
#missing-email, #missing-password, #credentials-wrong {
display: none;
margin-bottom: 20px;
}
</style>

View File

@@ -1,6 +1,110 @@
<template>
<div id="2fa">
<h1>Two Factor Authentication</h1>
<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[ 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: 'twoFAAdmin',
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' ) + '/admin/2fa/check', { withCredentials: true } );
let self = this;
source.onmessage = ( e ) => {
if ( e.data === 'authenticated' ) {
self.userStore.setAdminAuth( true );
self.$router.push( '/admin' );
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 ) };
},
}
</script>
<style scoped>
#twoFA, .code-container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.code-container {
width: fit-content;
padding: 5% 8%;
border: var( --primary-color ) solid 2px;
border-radius: 10px;
margin-top: 3%;
background-color: var( --popup-color );
}
.code {
background-color: var( --hover-color );
padding: 7% 10%;
margin-bottom: 0;
width: fit-content;
border-radius: 10px;
font-size: 200%;
font-family: monospace;
display: block;
}
.code-sub {
display: inline-block;
}
#code-part2 {
margin-left: 7px;
}
</style>