Init -- well, everything.
This commit is contained in:
parent
0b2fa17341
commit
4645561d33
9 changed files with 352 additions and 0 deletions
84
src/app.ts
Normal file
84
src/app.ts
Normal file
|
|
@ -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`)
|
||||
})
|
||||
41
src/app/models/user.model.ts
Normal file
41
src/app/models/user.model.ts
Normal file
|
|
@ -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<INamedConfig>,
|
||||
generateHash: Function,
|
||||
validPassword: Function,
|
||||
changePassword: Function
|
||||
}
|
||||
|
||||
export default model<UserModel>('users', UserSchema, 'users')
|
||||
45
src/app/routes/auth.ts
Normal file
45
src/app/routes/auth.ts
Normal file
|
|
@ -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()
|
||||
}
|
||||
})
|
||||
}
|
||||
28
src/app/routes/routes.ts
Normal file
28
src/app/routes/routes.ts
Normal file
|
|
@ -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)
|
||||
}
|
||||
28
src/app/utils/logs.ts
Normal file
28
src/app/utils/logs.ts
Normal file
|
|
@ -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`)
|
||||
}
|
||||
}
|
||||
0
src/app/views/home.ejs
Normal file
0
src/app/views/home.ejs
Normal file
60
src/app/views/login.ejs
Normal file
60
src/app/views/login.ejs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Geolosys Configurator Login</title>
|
||||
|
||||
<link rel="stylesheet" href="/Libraries/font-awesome/css/all.min.css">
|
||||
<link rel="stylesheet" href="/Libraries/bootstrap/css/bootstrap.css">
|
||||
<script src="/Libraries/bootstrap/js/bootstrap.js"></script>
|
||||
<script src="/Custom/js/login.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container d-flex flex-column justify-content-center"
|
||||
style="width: 98vw; height: 100vh; max-width: 768px; max-height: 100vh">
|
||||
<div class="d-block text-center header">
|
||||
<h2>
|
||||
Geolosys Configurator Login
|
||||
</h2>
|
||||
<h4>
|
||||
By: oitsjustjose (Jose)
|
||||
</h4>
|
||||
</div>
|
||||
<form action="/login" method="POST">
|
||||
<div class="mb-3">
|
||||
<label for="username" class="form-label">Username</label>
|
||||
<input type="text" class="form-control" name="username" id="username">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="password" class="form-label">Password</label>
|
||||
<input type="password" class="form-control" name="password" id="password">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Log In</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="modal" tabindex="-1" id="notification">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title"></h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p></p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
21
src/public/Custom/js/login.js
Normal file
21
src/public/Custom/js/login.js
Normal file
|
|
@ -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()
|
||||
}
|
||||
Loading…
Reference in a new issue