Initial commit

This commit is contained in:
2020-10-19 19:00:17 +02:00
parent 634ead79db
commit 48140f557b
61 changed files with 18269 additions and 0 deletions

1
backend/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.env

130
backend/app.ts Normal file
View File

@@ -0,0 +1,130 @@
import { bold } from 'chalk';
import * as figlet from 'figlet';
import * as mongoose from 'mongoose';
import { exit } from 'process';
import { hash } from 'argon2';
import { config as dconfig } from 'dotenv';
import * as winston from 'winston';
import * as express from 'express';
import { User } from './models/user/user.model';
import { UserType } from './models/user/user.interface';
import bodyParser = require('body-parser');
import { DeleteUser, GetUser, LoginUser, MW_User, PatchUser } from './endpoints/user';
import { hashPassword, randomPepper, randomString } from './lib/crypto';
import { config } from './config';
// Load .env
dconfig({ debug: true, encoding: 'UTF-8' });
export const MONGO_URI = process.env.MONGO_URI || "";
export const JWT_SECRET = process.env.JWT_SECRET;
export const IS_DEBUG = process.env.DEBUG == 'true'
export let logger: winston.Logger;
async function run() {
const { combine, timestamp, label, printf, prettyPrint } = winston.format;
const myFormat = printf(({ level, message, label, timestamp }) => {
return `${timestamp} ${level} ${message}`;
});
/**
* Printing starting screen
*/
console.log(figlet.textSync('Livebeat', {
font: 'Doom'
}));
console.log(`Starting up version ${bold("1.0.0")} of Livebeat ...
============================================`)
/**
* Setting up logger
*/
logger = winston.createLogger({
level: IS_DEBUG ? 'debug' : 'info',
levels: winston.config.syslog.levels,
format: combine(
timestamp(),
prettyPrint(),
myFormat
),
defaultMeta: { },
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// Adding seperate logger for files (with color)
logger.add(new winston.transports.Console({
format: combine(
winston.format.colorize({ level: true }),
timestamp(),
prettyPrint(),
myFormat
)
}));
logger.info("Logger started");
if (IS_DEBUG) {
logger.info("Debug mode is enabled. Do not use this in production!")
}
if (JWT_SECRET == undefined) {
logger.crit("No JWT secret was provided. Make sure you add JWT_SECRET=YOUR_SECRET to your .env file.");
exit(1);
}
/**
* Database connection
*/
const connection = await mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }).catch((err) => {
logger.crit("Database connection could not be made: ", err);
exit(1);
});
logger.info(`Database connection made to ${mongoose.connection.host}`);
// Check if admin account doesn't exists
if((await User.countDocuments({ type: UserType.ADMIN })) == 0) {
const randomPassword = "$1" + randomString(12);
const salt = randomString(config.authentification.salt_length);
await User.create({
name: 'admin',
password: await hashPassword(randomPassword + salt + randomPepper()),
salt,
createdAt: Date.now(),
lastLogin: 0,
type: UserType.ADMIN
});
logger.info("===================================================");
logger.info("ADMIN USER HAS BEEN CREATED! Username: admin\tPassword: " + randomPassword);
logger.info("===================================================");
} else {
logger.debug("At least one admin user already exists, skip.");
}
/**
* HTTP server
*/
const app = express();
app.use(express.json());
app.use(bodyParser.json({ limit: '5kb' }));
app.get('/user/', MW_User, (req, res) => GetUser(req, res));
app.get('/user/:id', MW_User, (req, res) => GetUser(req, res));
app.patch('/user/:id', MW_User, (req, res) => PatchUser(req, res));
app.delete('/user/:id', MW_User, (req, res) => DeleteUser(req, res));
app.post('/user/login', (req, res) => LoginUser(req, res));
app.listen(config.http.port, config.http.host, () => {
logger.info(`HTTP server is running at ${config.http.host}:${config.http.port}`);
});
}
run();

32
backend/config.ts Normal file
View File

@@ -0,0 +1,32 @@
/**
* Here you can change various settings like database credentials, http settings and more.
*
* Debug mode and MongoDB connections are set via enviroment variables for security reasons.
*/
export const config: IConfig = {
authentification: {
pepper: 'J3%_zö\\^',
salt_length: 8,
argonTimecost: 8,
minPasswordLength: 4,
maxPasswordLength: 150
},
http: {
port: 8040,
host: "0.0.0.0"
}
}
export interface IConfig {
authentification: {
pepper: string,
salt_length: number,
argonTimecost: number,
minPasswordLength: number,
maxPasswordLength: number
},
http: {
port: number,
host: string
}
}

86
backend/endpoints/user.ts Normal file
View File

@@ -0,0 +1,86 @@
import { Request, Response } from "express";
import { verifyPassword } from "../lib/crypto";
import { User } from "../models/user/user.model";
import { sign, decode, verify } from 'jsonwebtoken';
import { JWT_SECRET, logger } from "../app";
import { IUser } from "../models/user/user.interface";
export async function GetUser(req: Request, res: Response) {
}
export async function DeleteUser(req: Request, res: Response) {
}
export async function PatchUser(req: Request, res: Response) {
}
export async function LoginUser(req: Request, res: Response) {
const username = req.body.username;
const password = req.body.password;
const twoFA = req.body.twoFA;
const user = await User.findOne({ name: username });
// Check if user exists
if (user == undefined) {
setTimeout(() => {
res.status(404).send({ message: "Either the username or password is wrong." });
}, Math.random() * 1500 + 400);
return;
}
// Check if 2FA is turned on (the attack doesn't know yet if the password is wrong)
if (user.twoFASecret != undefined) {
if (twoFA == undefined) {
res.status(401).send({ message: "2FA code is required." });
return;
}
// TODO: Implement 2FA logic here
}
// Check if password is wrong
if (!await verifyPassword(password + user.salt, user.password)) {
res.status(404).send({ message: 'Either the username or password is wrong.' });
return;
}
// We're good. Create JWT token.
const token = sign({ user: user._id }, JWT_SECRET!, { notBefore: Date.now(), expiresIn: '30d' });
logger.info(`User ${user.name} logged in.`)
res.status(200).send({ token });
}
/**
* This middleware validates any tokens that are required to access most of the endpoints.
* Note: This validation doesn't contain any permission checking.
*/
export async function MW_User(req: Request, res: Response, next: () => void) {
if (req.headers.token === undefined) {
res.status(401).send();
return;
}
const token = req.headers.token.toString();
try {
// Verify token
if(await verify(token, JWT_SECRET!, { algorithms: ['HS256'] })) {
// Token is valid, now look if user is in db (in case he got deleted)
const id: number = Number(decode(token, { json: true })!.id);
const db = await User.findOne({ where: { id } });
if (db !== undefined) {
next();
return;
} else {
res.status(401).send();
}
} else {
res.status(401).send();
}
} catch (err) {
if (err) res.status(401).send();
}
}

105
backend/lib/crypto.ts Normal file
View File

@@ -0,0 +1,105 @@
import { hash, verify } from 'argon2';
import { config } from '../config';
import { IS_DEBUG, logger } from '../app';
export async function hashPassword(input: string): Promise<string> {
const start = Date.now();
return new Promise<string>(async (resolve, reject) => {
// Get real password (remove salt and pepper)
const realPassword = input.substring(0, input.length - config.authentification.salt_length - 1);
if (!check_password_requirements(realPassword)) {
if (!IS_DEBUG) reject("This password does not meet the minimum requirements!");
else {
reject(`This password does not meet the minimum requirements! (${input} => ${realPassword})`);
}
return;
}
try {
const hashed = await hash(input, {
hashLength: 42,
memoryCost: 1024*32,
parallelism: 2,
timeCost: config.authentification.argonTimecost
});
const finished = Date.now();
logger.debug("Hashing took " + (finished-start) + "ms to finish! " + input);
resolve(hashed);
} catch(err) {
reject(err);
}
});
}
/**
* Verfiy If given password matches with provided hash by brute forcing the pepper.
* @param password Password with salt appended
* @param hashInput Hash from database
*/
export async function verifyPassword(password: string, hashInput: string): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
const start = Date.now();
const peppers = config.authentification.pepper.split('');
const realPassword = password.substring(0, password.length - config.authentification.salt_length);
while (peppers.length !== 0) {
const pepper = peppers[Math.floor(Math.random()*peppers.length)];
if (IS_DEBUG) {
logger.debug(`Try ${password}}${pepper} (left: ${peppers})`);
} else {
// Show censored (with fixed length) password in non-debug mode to prevent password leaking.
logger.debug(`Try ********${password.replace(realPassword, '')}${pepper} (left: ${peppers})`);
}
if (await verify(hashInput, password + pepper)) {
const finished = Date.now();
logger.debug("Verifying took " + (finished-start) + "ms to complete!");
resolve(true);
return;
} else {
peppers.splice(peppers.indexOf(pepper), 1);
}
}
resolve(false);
});
}
export function randomString(length: number): string {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const charactersLength = characters.length;
for ( let i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
export function randomPepper(): string {
return config.authentification.pepper.charAt(Math.floor(Math.random() * config.authentification.pepper.length));
}
/**
* Requirements are:
* - at least 8 characters
* - min one upper-, lowercase- and special character
* - min one number
*/
export function check_password_requirements(password: string): boolean {
// Check for length
if (password.length < config.authentification.minPasswordLength ||
password.length > config.authentification.maxPasswordLength) return false;
// Check for one lowercase
if (!(/^(?=.*[a-z]).+$/.test(password))) return false;
// Check for one uppercase
if (!(/^(?=.*[A-Z]).+$/.test(password))) return false;
// Check for one uppercase
if (!(/^(?=.*[0-9]).+$/.test(password))) return false;
// Check for special characters
if (!(/[^A-Za-z0-9]/.test(password))) return false;
return true;
}

View File

@@ -0,0 +1,12 @@
import { Document } from 'mongoose';
import { IUser } from '../user/user.interface';
export interface IPhone extends Document {
displayName: String,
modelName: String,
operatingSystem: String,
architecture: String,
user: IUser,
updatedAt?: Date,
createdAt?: Date
}

View File

@@ -0,0 +1,6 @@
import { Model, model } from 'mongoose';
import { IPhone } from './phone.interface';
import { schemaPhone } from './phone.schema';
const modelPhone: Model<IPhone> = model<IPhone>('Phone', schemaPhone , 'Phone');
export { modelPhone as Phone };

View File

@@ -0,0 +1,17 @@
import { Schema } from 'mongoose';
import { User } from '../user/user.model';
const schemaPhone = new Schema({
displayName: { type: String, required: true },
modelName: { type: String, required: false },
operatingSystem: { type: String, required: false },
architecture: { type: String, required: false },
user: { type: User, required: true }
}, {
timestamps: {
createdAt: true,
updatedAt: true
}
});
export { schemaPhone };

View File

@@ -0,0 +1,11 @@
import { Document } from 'mongoose';
import { IPhone } from '../phone/phone.interface';
export interface ITrack extends Document {
coordinate?: number[],
velocity?: number,
battery?: number,
magneticField?: number,
phone: IPhone,
createdAt?: Date
}

View File

@@ -0,0 +1,6 @@
import { Model, model } from 'mongoose';
import { ITrack } from './track.interface';
import { schemaTrack } from './track.schema';
const modelTrack: Model<ITrack> = model<ITrack>('Track', schemaTrack, 'Track');
export { modelTrack as Phone };

View File

@@ -0,0 +1,16 @@
import { Schema } from 'mongoose';
import { Phone } from '../phone/phone.model';
const schemaTrack = new Schema({
coordinate: { type: [Number], required: false },
velocity: { type: Number, required: false },
battery: { type: Number, required: false },
magneticField: { type: Number, required: false },
phone: { type: Phone, required: true, default: 'user' }
}, {
timestamps: {
createdAt: true
}
});
export { schemaTrack };

View File

@@ -0,0 +1,17 @@
import { Document } from 'mongoose';
export enum UserType {
ADMIN = 'admin',
USER = 'user',
GUEST = 'guest'
}
export interface IUser extends Document {
name: string,
password: string,
salt: string,
type: UserType,
lastLogin: Date,
twoFASecret?: string,
createdAt?: Date
}

View File

@@ -0,0 +1,6 @@
import { Model, model } from 'mongoose';
import { IUser } from "./user.interface";
import { schemaUser } from './user.schema';
const modelUser: Model<IUser> = model<IUser>('User', schemaUser , 'User');
export { modelUser as User };

View File

@@ -0,0 +1,16 @@
import { Schema } from 'mongoose';
const schemaUser = new Schema({
name: { type: String, required: true },
password: { type: String, required: true },
salt: { type: String, required: true },
type: { type: String, required: true, default: 'user' }, // This could be user, admin, guest
twoFASecret: { type: String, required: false },
lastLogin: { type: Date, required: true, default: Date.now },
}, {
timestamps: {
createdAt: true
}
});
export { schemaUser }

2953
backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

46
backend/package.json Normal file
View File

@@ -0,0 +1,46 @@
{
"name": "livebeat",
"version": "1.0.0",
"description": "Backend of Livebeat",
"main": "app.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "ts-node app.ts",
"start:dev": "nodemon dist/app.js",
"build:dev": "tsc --watch --preserveWatchOutput",
"dev": "concurrently \"npm:build:dev\" \"npm:start:dev\""
},
"repository": {
"type": "git",
"url": "https://nicolasklier.de:3000/Nicolas/Livebeat.git"
},
"author": "Mondei1",
"license": "GPL-3.0-or-later",
"dependencies": {
"argon2": "^0.27.0",
"body-parser": "^1.19.0",
"chalk": "^4.1.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"figlet": "^1.5.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.10.9",
"ts-node": "^9.0.0",
"typescript": "^4.0.3",
"winston": "^3.3.3"
},
"devDependencies": {
"@types/argon2": "0.15.0",
"@types/body-parser": "1.19.0",
"@types/chalk": "2.2.0",
"@types/dotenv": "8.2.0",
"@types/express": "4.17.8",
"@types/figlet": "1.2.0",
"@types/mongoose": "5.7.36",
"@types/typescript": "2.0.0",
"@types/winston": "2.4.4",
"concurrently": "^5.3.0",
"nodemon": "^2.0.5",
"@types/jsonwebtoken": "8.5.0"
}
}

10
backend/tsconfig.json Normal file
View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./",
"strict": true,
"forceConsistentCasingInFileNames": true
}
}

3
backend_python/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

8
backend_python/.idea/backend.iml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

7
backend_python/.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.8" project-jdk-type="Python SDK" />
<component name="PyCharmProfessionalAdvertiser">
<option name="shown" value="true" />
</component>
</project>

8
backend_python/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/backend.iml" filepath="$PROJECT_DIR$/.idea/backend.iml" />
</modules>
</component>
</project>

6
backend_python/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

Binary file not shown.

Binary file not shown.

17
backend_python/main.py Normal file
View File

@@ -0,0 +1,17 @@
from flask import Flask, jsonify
from flask_restful import Api, Resource, reqparse, abort
import pymongo, pika
import vars
import resources.user as user
app = Flask(__name__)
api = Api(app)
api.add_resource(user.UserLogin, "/user/login")
if __name__ == '__main__':
vars.db = pymongo.MongoClient("mongodb+srv://backend:Rjmzs75W9EYwW8G7@cluster0.qxerq.mongodb.net/livebeat?retryWrites=true&w=majority")
print(vars.db.list_databases())
rabbit = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = rabbit.channel()
app.run(debug=True)

View File

@@ -0,0 +1,7 @@
from flask_restful import Api, Resource, reqparse, abort
import vars
class UserLogin(Resource):
def get(self):
print(vars.db['livebeat'])
return

6
backend_python/vars.py Normal file
View File

@@ -0,0 +1,6 @@
"""
This file contains all variables that are shared across the entire application.
For example: Database connection, sockets, etc.
"""
db = None

18
frontend/.browserslistrc Normal file
View File

@@ -0,0 +1,18 @@
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# For the full list of supported browsers by the Angular framework, please see:
# https://angular.io/guide/browser-support
# You can see what browsers were selected by your queries by running:
# npx browserslist
last 1 Chrome version
last 1 Firefox version
last 2 Edge major versions
last 2 Safari major versions
last 2 iOS major versions
Firefox ESR
not IE 9-10 # Angular support for IE 9-10 has been deprecated and will be removed as of Angular v11. To opt-in, remove the 'not' prefix on this line.
not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line.

16
frontend/.editorconfig Normal file
View File

@@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false

46
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,46 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/tmp
/out-tsc
# Only exists if Bazel was run
/bazel-out
# dependencies
/node_modules
# profiling files
chrome-profiler-events*.json
speed-measure-plugin*.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db

27
frontend/README.md Normal file
View File

@@ -0,0 +1,27 @@
# Livebeat
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 10.1.6.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).

128
frontend/angular.json Normal file
View File

@@ -0,0 +1,128 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"Livebeat": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/Livebeat",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": true,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "Livebeat:build"
},
"configurations": {
"production": {
"browserTarget": "Livebeat:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "Livebeat:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"tsconfig.app.json",
"tsconfig.spec.json",
"e2e/tsconfig.json"
],
"exclude": [
"**/node_modules/**"
]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "Livebeat:serve"
},
"configurations": {
"production": {
"devServerTarget": "Livebeat:serve:production"
}
}
}
}
}},
"defaultProject": "Livebeat"
}

View File

@@ -0,0 +1,36 @@
// @ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter, StacktraceOption } = require('jasmine-spec-reporter');
/**
* @type { import("protractor").Config }
*/
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
capabilities: {
browserName: 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json')
});
jasmine.getEnv().addReporter(new SpecReporter({
spec: {
displayStacktrace: StacktraceOption.PRETTY
}
}));
}
};

View File

@@ -0,0 +1,23 @@
import { AppPage } from './app.po';
import { browser, logging } from 'protractor';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Livebeat app is running!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});

View File

@@ -0,0 +1,11 @@
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo(): Promise<unknown> {
return browser.get(browser.baseUrl) as Promise<unknown>;
}
getTitleText(): Promise<string> {
return element(by.css('app-root .content span')).getText() as Promise<string>;
}
}

View File

@@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/e2e",
"module": "commonjs",
"target": "es2018",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}

32
frontend/karma.conf.js Normal file
View File

@@ -0,0 +1,32 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/Livebeat'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};

13851
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

52
frontend/package.json Normal file
View File

@@ -0,0 +1,52 @@
{
"name": "livebeat",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~10.1.5",
"@angular/cdk": "^10.2.1",
"@angular/common": "~10.1.5",
"@angular/compiler": "~10.1.5",
"@angular/core": "~10.1.5",
"@angular/forms": "~10.1.5",
"@angular/platform-browser": "~10.1.5",
"@angular/platform-browser-dynamic": "~10.1.5",
"@angular/router": "~10.1.5",
"@nebular/auth": "^6.2.1",
"@nebular/eva-icons": "^6.2.1",
"@nebular/theme": "^6.2.1",
"eva-icons": "^1.1.3",
"rxjs": "~6.6.0",
"tslib": "^2.0.0",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.1001.6",
"@angular/cli": "~10.1.6",
"@angular/compiler-cli": "~10.1.5",
"@schematics/angular": "~10.1.6",
"@types/jasmine": "~3.5.0",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^12.11.1",
"codelyzer": "^6.0.0",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~5.0.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "~3.0.2",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"protractor": "~7.0.0",
"ts-node": "~8.3.0",
"tslint": "~6.1.0",
"typescript": "~4.0.2"
}
}

View File

@@ -0,0 +1,24 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NbAuthComponent, NbLoginComponent } from '@nebular/auth';
const routes: Routes = [
{
path: '',
component: NbAuthComponent,
children: [
{
path: '',
component: NbLoginComponent
}
]
}
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [RouterModule]
})
export class AppRoutingModule { }

View File

@@ -0,0 +1,3 @@
<nb-auth-block>
<nb-login></nb-login>
</nb-auth-block>

View File

View File

@@ -0,0 +1,35 @@
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'Livebeat'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('Livebeat');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement;
expect(compiled.querySelector('.content span').textContent).toContain('Livebeat app is running!');
});
});

View File

@@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
title = 'Livebeat';
}

View File

@@ -0,0 +1,40 @@
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NbEvaIconsModule } from '@nebular/eva-icons';
import { NbPasswordAuthStrategy, NbAuthModule, NbDummyAuthStrategy } from '@nebular/auth';
import { NbCardModule, NbLayoutModule, NbSidebarModule, NbThemeModule } from '@nebular/theme';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
HttpClientModule,
NbThemeModule.forRoot({ name: 'dark' }),
NbLayoutModule,
NbEvaIconsModule,
NbLayoutModule,
NbCardModule,
NbSidebarModule,
NbAuthModule.forRoot({
strategies: [
NbDummyAuthStrategy.setup({
name: 'email',
alwaysFail: false
})
],
forms: {}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

View File

View File

@@ -0,0 +1,3 @@
export const environment = {
production: true
};

View File

@@ -0,0 +1,16 @@
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/dist/zone-error'; // Included with Angular CLI.

BIN
frontend/src/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 948 B

13
frontend/src/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Livebeat</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>

12
frontend/src/main.ts Normal file
View File

@@ -0,0 +1,12 @@
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));

63
frontend/src/polyfills.ts Normal file
View File

@@ -0,0 +1,63 @@
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/guide/browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/**
* Web Animations `@angular/platform-browser/animations`
* Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
* Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
*/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
* because those flags need to be set before `zone.js` being loaded, and webpack
* will put import in the top of bundle, so user need to create a separate file
* in this directory (for example: zone-flags.ts), and put the following flags
* into that file, and then add the following code before importing zone.js.
* import './zone-flags';
*
* The flags allowed in zone-flags.ts are listed here.
*
* The following flags will work for all browsers.
*
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*
* (window as any).__Zone_enable_cross_context_check = true;
*
*/
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js/dist/zone'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/

10
frontend/src/styles.scss Normal file
View File

@@ -0,0 +1,10 @@
@import 'themes';
@import '~@nebular/auth/styles/globals';
@import '~@nebular/theme/styles/globals';
@include nb-install() {
@include nb-theme-global();
@include nb-auth-global();
};
/* You can add global styles to this file, and also import other style files */

25
frontend/src/test.ts Normal file
View File

@@ -0,0 +1,25 @@
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: {
context(path: string, deep?: boolean, filter?: RegExp): {
keys(): string[];
<T>(id: string): T;
};
};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

18
frontend/src/themes.scss Normal file
View File

@@ -0,0 +1,18 @@
@import '~@nebular/theme/styles/theming';
@import '~@nebular/theme/styles/themes/dark';
$nb-themes: nb-register-theme((
// add your variables here like:
// color-primary-100: #f2f6ff,
// color-primary-200: #d9e4ff,
// color-primary-300: #a6c1ff,
// color-primary-400: #598bff,
// color-primary-500: #3366ff,
// color-primary-600: #274bdb,
// color-primary-700: #1a34b8,
// color-primary-800: #102694,
// color-primary-900: #091c7a,
), dark, dark);

View File

@@ -0,0 +1,15 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}

20
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,20 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"module": "es2020",
"lib": [
"es2018",
"dom"
]
}
}

View File

@@ -0,0 +1,18 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"files": [
"src/test.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}

152
frontend/tslint.json Normal file
View File

@@ -0,0 +1,152 @@
{
"extends": "tslint:recommended",
"rulesDirectory": [
"codelyzer"
],
"rules": {
"align": {
"options": [
"parameters",
"statements"
]
},
"array-type": false,
"arrow-return-shorthand": true,
"curly": true,
"deprecation": {
"severity": "warning"
},
"eofline": true,
"import-blacklist": [
true,
"rxjs/Rx"
],
"import-spacing": true,
"indent": {
"options": [
"spaces"
]
},
"max-classes-per-file": false,
"max-line-length": [
true,
140
],
"member-ordering": [
true,
{
"order": [
"static-field",
"instance-field",
"static-method",
"instance-method"
]
}
],
"no-console": [
true,
"debug",
"info",
"time",
"timeEnd",
"trace"
],
"no-empty": false,
"no-inferrable-types": [
true,
"ignore-params"
],
"no-non-null-assertion": true,
"no-redundant-jsdoc": true,
"no-switch-case-fall-through": true,
"no-var-requires": false,
"object-literal-key-quotes": [
true,
"as-needed"
],
"quotemark": [
true,
"single"
],
"semicolon": {
"options": [
"always"
]
},
"space-before-function-paren": {
"options": {
"anonymous": "never",
"asyncArrow": "always",
"constructor": "never",
"method": "never",
"named": "never"
}
},
"typedef": [
true,
"call-signature"
],
"typedef-whitespace": {
"options": [
{
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
},
{
"call-signature": "onespace",
"index-signature": "onespace",
"parameter": "onespace",
"property-declaration": "onespace",
"variable-declaration": "onespace"
}
]
},
"variable-name": {
"options": [
"ban-keywords",
"check-format",
"allow-pascal-case"
]
},
"whitespace": {
"options": [
"check-branch",
"check-decl",
"check-operator",
"check-separator",
"check-type",
"check-typecast"
]
},
"component-class-suffix": true,
"contextual-lifecycle": true,
"directive-class-suffix": true,
"no-conflicting-lifecycle": true,
"no-host-metadata-property": true,
"no-input-rename": true,
"no-inputs-metadata-property": true,
"no-output-native": true,
"no-output-on-prefix": true,
"no-output-rename": true,
"no-outputs-metadata-property": true,
"template-banana-in-box": true,
"template-no-negated-async": true,
"use-lifecycle-interface": true,
"use-pipe-transform-interface": true,
"directive-selector": [
true,
"attribute",
"app",
"camelCase"
],
"component-selector": [
true,
"element",
"app",
"kebab-case"
]
}
}