diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..a137540 --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,45 @@ +const { dest, src, task, watch } = require('gulp'); +const { createProject } = require('gulp-typescript'); + +const tsconf = createProject('tsconfig.json'); + +/** + * @param {String} dir + */ +const copy = (dir) => { + return src([`${dir}/**/*`]).pipe(dest(dir.replace('src', 'dist'))); +}; + +const build = () => { + return src('src/**/*.ts').pipe(tsconf()).js.pipe(dest('dist')); +}; + +task('build', () => { + copy('src/public'); + copy('src/app/views'); + return build(); +}); + +task('copy', () => { + copy('src/public'); + return copy('src/app/views'); +}); + +task('default', () => { + let space = String(); + + for (let _ = 0; _ < process.stdout.columns; _++) { + space += "-"; + } + + console.log(space); + console.error("No default task has been created"); + console.log(space); +}); + +task('watch', () => { + return watch(['src/public/**/*', 'src/app/views/**/*'], () => { + copy('src/public'); + return copy('src/app/views'); + }); +}); \ No newline at end of file diff --git a/src/app.ts b/src/app.ts new file mode 100644 index 0000000..66bed57 --- /dev/null +++ b/src/app.ts @@ -0,0 +1,84 @@ +import { json as bpjson, urlencoded } from 'body-parser' +import session from 'cookie-session' +import { config as InitEnv } from 'dotenv' +import express from 'express' +import mongoose from 'mongoose' +import passport from 'passport' +import { Strategy as LocalStrategy } from 'passport-local' +import path from 'path' +import UserDB, { UserModel } from './app/models/user.model' +import * as Routes from './app/routes/routes' +import * as Logging from './app/utils/logs' + +InitEnv() + +declare global { + namespace Express { + interface User extends UserModel { } + } +} + + +const app = express() + +app.set('view engine', 'ejs') +app.set('views', path.join(__dirname, './app/Views')) + +app.use(express.static(__dirname + '/public')) +app.use(bpjson()) +app.use(urlencoded({ + extended: true +})) +app.use(session({ + secret: '16ed0626a1d2b5-kc6zy6e8', +})) + +mongoose.connect(`mongodb://${process.env.MONGO_URL}/GeolosysConfigGen`, { + useNewUrlParser: true, + useUnifiedTopology: true, +}).then(() => { + console.log('DB Connected! 😄') +}).catch((ex) => { + console.log('DB Connection Failed 💩') + console.error(ex) + process.exit(1) +}) + +app.use(passport.initialize()) +app.use(passport.session()) +passport.use(new LocalStrategy((username: string, password: string, callback: Function) => { + UserDB.findOne({ + 'username': username + }, (err, user) => { + if (err) { + return callback(err) + } else if (!user) { + return callback(null, false) + } else if (!user.validPassword(password)) { + return callback(null, false) + } + return callback(null, user) + }) +})) + +passport.serializeUser((user: UserModel, callback: Function) => { + callback(null, user.id) +}) + +passport.deserializeUser((id: mongoose.Types.ObjectId, callback: Function) => { + UserDB.findById(id, (err, user) => { + callback(err, user) + }) +}) + +Routes.init(app, passport) + +if (app.get('env') == 'production') { + Logging.init(`${__dirname}/..`) +} + +const port = process.env.PORT || 3035 + +app.listen(port, () => { + process.stdout.write(`Listening on port ${port}\n`) +}) diff --git a/src/app/models/user.model.ts b/src/app/models/user.model.ts new file mode 100644 index 0000000..ac652f5 --- /dev/null +++ b/src/app/models/user.model.ts @@ -0,0 +1,41 @@ +import bcrypt from 'bcrypt' +import { Document, model, Schema, Types } from 'mongoose' + +const UserSchema = new Schema({ + username: String, + password: String, + configs: [{ + name: String, + conf: Object, + }] +}) + +UserSchema.methods.generateHash = function (password: string) { + return bcrypt.hashSync(password, bcrypt.genSaltSync(8)) +} + +UserSchema.methods.validPassword = function (password: string) { + return bcrypt.compareSync(password, String(this.password)) +} + +UserSchema.methods.changePassword = function (password: string, newPassword: string) { + if (bcrypt.compareSync(password, this.password)) { + this.password = newPassword + } +} + +interface INamedConfig { + name: string, + conf: object +} + +export type UserModel = Document & { + username: string, + password: string, + configs: Array, + generateHash: Function, + validPassword: Function, + changePassword: Function +} + +export default model('users', UserSchema, 'users') \ No newline at end of file diff --git a/src/app/routes/auth.ts b/src/app/routes/auth.ts new file mode 100644 index 0000000..0c92cc0 --- /dev/null +++ b/src/app/routes/auth.ts @@ -0,0 +1,45 @@ +import { Application } from "express" +import { PassportStatic } from "passport" +import UserDB from '../models/user.model' + +export const init = (app: Application, passport: PassportStatic) => { + app.get('/login', (req, res) => { + if (req.isAuthenticated()) { + res.redirect('/') + } else { + if (req.query.origin) { + req.session!.returnTo = req.query.origin + } + res.render('login') + } + }) + + app.get('/logout', (req, res) => { + req.logout() + res.redirect('/login') + }) + + app.post('/login', passport.authenticate('local', { + failureRedirect: '/login?error' + }), async (req, res) => { + /* Don't keep the pass reset id if the user can log in... */ + if (req.session?.returnTo) { + res.redirect(req.session.returnTo) + } else { + res.redirect('/') + } + }) + + app.post('/register', async (req, res) => { + const exUser = await UserDB.findOne({ 'email': req.body.email }) + if (exUser) { + res.redirect('/register?exists') + } else { + let user = new UserDB() + user.username = req.body.username + user.password = user.generateHash(req.body.password) + user.configs = Array() + await user.save() + } + }) +} \ No newline at end of file diff --git a/src/app/routes/routes.ts b/src/app/routes/routes.ts new file mode 100644 index 0000000..3bb4796 --- /dev/null +++ b/src/app/routes/routes.ts @@ -0,0 +1,28 @@ +import { Application } from "express" +import { PassportStatic } from "passport" +import * as Auth from './auth' + +export const init = (app: Application, passport: PassportStatic) => { + app.get('/', async (req, res) => { + if (req.isAuthenticated() && req.user) { + res.render('home') + } else { + res.redirect('/login?origin=/') + } + }) + + app.put('/', async (req, res) => { + if (req.isAuthenticated() && req.user) { + req.user.configs.push({ + name: req.body.name, + conf: req.body.config + }) + } else { + res.status(401).send({ + error: 'Not logged in!' + }) + } + }) + + Auth.init(app, passport) +} \ No newline at end of file diff --git a/src/app/utils/logs.ts b/src/app/utils/logs.ts new file mode 100644 index 0000000..f2b1200 --- /dev/null +++ b/src/app/utils/logs.ts @@ -0,0 +1,28 @@ +import fs from 'fs' + +export const init = (baseDir: string) => { + if (!fs.existsSync(`${baseDir}/logs`)) { + fs.mkdirSync(`${baseDir}/logs`) + } + + let date = new Date() + + let logs: fs.WriteStream | null = null + let errs: fs.WriteStream | null = null + + console.log = (item: any) => { + if (!logs) { + logs = fs.createWriteStream(baseDir + `/logs/logs-${date.toISOString()}.log`, { flags: 'a' }) + } + + logs.write(`[${new Date().toISOString()}]: ${item}\n`) + } + + console.error = (item: any) => { + if (!errs) { + errs = fs.createWriteStream(baseDir + `/logs/errors-${date.toISOString()}.log`, { flags: 'a' }) + } + + errs.write(`[${new Date().toISOString()}]: ${item}\n`) + } +} \ No newline at end of file diff --git a/src/app/views/home.ejs b/src/app/views/home.ejs new file mode 100644 index 0000000..e69de29 diff --git a/src/app/views/login.ejs b/src/app/views/login.ejs new file mode 100644 index 0000000..5797a81 --- /dev/null +++ b/src/app/views/login.ejs @@ -0,0 +1,60 @@ + + + + + + + Geolosys Configurator Login + + + + + + + + +
+
+

+ Geolosys Configurator Login +

+

+ By: oitsjustjose (Jose) +

+
+
+
+ + +
+
+ + +
+ +
+
+ + + + + + \ No newline at end of file diff --git a/src/public/Custom/js/login.js b/src/public/Custom/js/login.js new file mode 100644 index 0000000..6c47287 --- /dev/null +++ b/src/public/Custom/js/login.js @@ -0,0 +1,21 @@ +window.addEventListener('load', () => { + const queries = new URLSearchParams(location.search) + if (queries.has('error')) { + makeNotification('Failed to Log In', ` + Failed to log you in! Confirm that your username and + password are correct or contact your administration + if you do not have an account. + `) + } + + history.replaceState(null, '', location.href.replace('?error', '')) +}) + +const makeNotification = (title, contents) => { + const modal = document.getElementById('notification') + + modal.querySelector('.modal-title').innerHTML = title + modal.querySelector('.modal-body').innerHTML = contents + + new bootstrap.Modal(modal).show() +} \ No newline at end of file