Compare commits

...

11 Commits

75 changed files with 9746 additions and 413 deletions

4
.docker.env.example Normal file
View File

@@ -0,0 +1,4 @@
DB_ROOT_PASS=root
DB_USER=user
DB_PASS=password

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
.docker.env
mariadb/

59
api/.githooks/pre-push Executable file
View File

@@ -0,0 +1,59 @@
#!/bin/bash
# @link https://gist.github.com/mattscilipoti/8424018
#
# Called by "git push" after it has checked the remote status,
# but before anything has been pushed.
#
# If this script exits with a non-zero status nothing will be pushed.
#
# Steps to install, from the root directory of your repo...
# 1. Copy the file into your repo at `.git/hooks/pre-push`
# 2. Set executable permissions, run `chmod +x .git/hooks/pre-push`
# 3. Or, use `rake hooks:pre_push` to install
#
# Try a push to master, you should get a message `*** [Policy] Never push code directly to...`
#
# The commands below will not be allowed...
# `git push origin master`
# `git push --force origin master`
# `git push --delete origin master`
protected_branch='master'
policy="\n\n[Policy] Never push code directly to the "$protected_branch" branch! (Prevented with pre-push hook.)\n\n"
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
push_command=$(ps -ocommand= -p $PPID)
is_destructive='force|delete|\-f'
will_remove_protected_branch=':'$protected_branch
do_exit(){
echo -e $policy
exit 1
}
if [[ $push_command =~ $is_destructive ]] && [ $current_branch = $protected_branch ]; then
do_exit
fi
if [[ $push_command =~ $is_destructive ]] && [[ $push_command =~ $protected_branch ]]; then
do_exit
fi
if [[ $push_command =~ $will_remove_protected_branch ]]; then
do_exit
fi
# Prevent ALL pushes to protected_branch
if [[ $push_command =~ $protected_branch ]] || [ $current_branch = $protected_branch ]; then
do_exit
fi
unset do_exit
exit 0

3
api/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
node_modules/
src/.env
*.log

15
api/.prettierrc Normal file
View File

@@ -0,0 +1,15 @@
{
"tabWidth": 4,
"useTabs": true,
"singleQuote": true,
"semi": false,
"trailingComma": "none",
"jsxSingleQuote": true,
"jsxBracketSameLine": true,
"printWidth": 200,
"bracketSpacing": true,
"vueIndentScriptAndStyle": true,
"arrowParens": "always",
"bracketSameLine": false,
"endOfLine": "lf"
}

1
api/README.md Normal file
View File

@@ -0,0 +1 @@
# New Project

12
api/norkconfig.json Normal file
View File

@@ -0,0 +1,12 @@
{
"project_name": "api",
"lang": "ts",
"author": "Filip Rojek",
"database": {
"db": "mysql",
"orm": "sequelize"
},
"website": "https://filiprojek.cz",
"email": "filip@filiprojek.cz",
"version": "3.0.5"
}

7812
api/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

75
api/package.json Normal file
View File

@@ -0,0 +1,75 @@
{
"name": "api",
"version": "1.0.0",
"description": "",
"main": "dist/server.js",
"private": "true",
"keywords": [],
"author": "Filip Rojek <filip@filiprojek.cz> (https://filiprojek.cz)",
"repository": "github:username/repo",
"license": "ISC",
"scripts": {
"start": "node dist/server.js",
"start:dev": "nodemon src/server.ts",
"test": "jest",
"clean": "rimraf dist/*",
"copy-assets": "npx ts-node src/utils/copyAssets",
"tsc": "tsc -p .",
"build": "npm-run-all clean tsc copy-assets",
"format": "npx prettier --write ."
},
"dependencies": {
"bcrypt": "^5.1.1",
"colors": "1.4.0",
"cookie-parser": "^1.4.5",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"ejs": "^3.1.6",
"express": "^4.17.1",
"express-validator": "^6.14.2",
"fs-extra": "^10.0.0",
"jsonwebtoken": "^9.0.2",
"mariadb": "^3.2.3",
"mongoose": "^8.0.3",
"sequelize": "^6.15.0"
},
"devDependencies": {
"@types/bcrypt": "^5.0.2",
"@types/cookie-parser": "^1.4.2",
"@types/cors": "^2.8.10",
"@types/ejs": "^3.0.6",
"@types/express": "^4.17.11",
"@types/fs-extra": "^9.0.12",
"@types/jest": "^27.5.2",
"@types/jsonwebtoken": "^8.5.8",
"@types/mongoose": "^5.11.97",
"@types/morgan": "^1.9.2",
"@types/node": "^14.14.41",
"@types/shelljs": "^0.8.9",
"jest": "^27.0.6",
"morgan": "^1.10.0",
"nodemon": "^3.0.2",
"npm-run-all": "^4.1.5",
"rimraf": "^3.0.2",
"shelljs": "^0.8.4",
"ts-jest": "^27.1.5",
"ts-node": "^10.8.1",
"typescript": "^4.2.4"
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "node"
},
"nodemonConfig": {
"ignore": [
"**/*.test.ts",
"**/*.spec.ts",
".git",
"node_modules"
],
"watch": [
"src"
],
"ext": "ts, js"
}
}

5
api/setup-repo.sh Executable file
View File

@@ -0,0 +1,5 @@
#!/bin/bash
cp .githooks/* .git/hooks
echo "hooks have been copied"

26
api/src/.env.example Normal file
View File

@@ -0,0 +1,26 @@
# General
APP_PORT = 6060
APP_HOSTNAME = 'localhost'
APP_HOST = 'http://localhost:8080' # frontend url
# Timezone
TZ = 'Europe/Prague'
CORS_WHITELIST = http://172.15.46.21:8080;http://192.168.0.1:8080
JWT_SECRET = ''
# MongoDB
DB_URI = 'mongodb://username:password@localhost:27017/database?authSource=admin'
# PostgreSQL
DB_PORT = 5432
DB_HOST = '127.0.0.1'
DB_USERNAME = ''
DB_PASSWORD = ''
DB_DATABASE = ''
# SMTP
SMTP_HOST = ''
SMTP_USER = ''
SMTP_PASS = ''
SMTP_FROM = ''

42
api/src/app.ts Normal file
View File

@@ -0,0 +1,42 @@
import express from 'express'
import morgan from 'morgan'
import path from 'path'
import cors from 'cors'
import cookieParser from 'cookie-parser'
import { router as routes } from './routes'
import { router as middlewares } from './middlewares'
import env from './config/environment'
export let corsWhitelist: Array<string>
if (env.CORS_WHITELIST != 'undefined') {
corsWhitelist = [...['http://localhost:8080', 'http://localhost:6040'], ...env.CORS_WHITELIST.split(';')]
} else {
corsWhitelist = ['http://localhost:8080', 'http://localhost:6040']
}
const corsOptions = {
origin: function (origin: any, callback: any) {
if (!origin || corsWhitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
},
optionsSuccessStatus: 200,
credentials: true
}
export const app = express()
// Middlewares
app.use(middlewares)
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views'))
app.use(cors(corsOptions))
app.use(morgan('dev'))
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(express.static(path.join(__dirname, 'public')))
app.use(cookieParser())
// Routes
app.use(routes)

View File

@@ -0,0 +1,36 @@
import env from './environment'
import { Err, Succ } from '../services/globalService'
import db from './sequelize.config'
import Client from '../models/Client'
import Project from '../models/Project'
import Task from '../models/Task'
import User from '../models/User'
async function connect() {
if (!env.NORK.database) {
new Err(500, 'no database is in norkcfg.json')
return false
}
if (env.NORK.database.orm == 'sequelize') {
await User.sync()
await Client.sync()
await Project.sync()
await Task.sync({ alter: true })
db.sync()
.then(() => {
new Succ(200, 'connected to db')
return true
})
.catch((err: any) => {
new Err(500, `Can't connect to db\n${err}`)
return false
})
}
//if (env.NORK.database.db.length > 0) {
// new Err(500, `unsupported database ${env.NORK.database.db}`)
// return false
//}
}
export default connect

View File

@@ -0,0 +1,59 @@
import path from 'path'
import fs from 'fs-extra'
import { Err } from '../services/globalService'
import dotenv from 'dotenv'
const env_path = process.env.NODE_ENV ? `../.env.${process.env.NODE_ENV}` : '../.env'
dotenv.config({ path: path.join(__dirname, env_path) })
const norkcfg = fs.readJSONSync(path.join(__dirname, '../../norkconfig.json'))
if (norkcfg.database) {
if (norkcfg.database.db == 'postgresql') {
if (!process.env.DB_PORT) {
process.env.DB_PORT = '5432'
}
if (!process.env.DB_HOST) {
process.env.DB_HOST = '127.0.0.1'
}
if (!process.env.DB_USERNAME || !process.env.DB_PASSWORD || !process.env.DB_DATABASE) {
new Err(500, 'missing DB parameters in .env file')
process.exit(1)
}
}
}
if (!fs.existsSync(path.join(__dirname, env_path))) {
console.log('$env_path = ', env_path)
console.log('$__dirname = ', __dirname)
new Err(500, `.env file for ${process.env.NODE_ENV ? process.env.NODE_ENV : ''} environment does not exists`)
process.exit()
}
if (process.env.JWT_SECRET === undefined || process.env.JWT_SECRET == '') {
new Err(500, 'JWT_SECRET is not set!')
process.exit()
}
export default {
// General
APP_PORT: Number(process.env.APP_PORT),
APP_HOST: String(process.env.APP_HOST),
APP_HOSTNAME: process.env.APP_HOSTNAME !== undefined ? String(process.env.APP_HOSTNAME) : null,
CORS_WHITELIST: String(process.env.CORS_WHITELIST),
JWT_SECRET: String(process.env.JWT_SECRET),
// MongoDB
DB_URI: String(process.env.DB_URI),
// PostgreSQL
DB_PORT: Number(process.env.DB_PORT),
DB_HOST: String(process.env.DB_HOST),
DB_USERNAME: String(process.env.DB_USERNAME),
DB_PASSWORD: String(process.env.DB_PASSWORD),
DB_DATABASE: String(process.env.DB_DATABASE),
// Nork
NORK: norkcfg,
// SMTP
SMTP_HOST: String(process.env.SMTP_HOST),
SMTP_USER: String(process.env.SMTP_USER),
SMTP_PASS: String(process.env.SMTP_PASS),
SMTP_FROM: String(process.env.SMTP_FROM)
}

View File

@@ -0,0 +1,10 @@
import { Sequelize } from 'sequelize'
import env from './environment'
const db = new Sequelize(env.DB_DATABASE, env.DB_USERNAME, env.DB_PASSWORD, {
host: env.DB_HOST,
dialect: 'mariadb',
logging: true
})
export default db

View File

@@ -0,0 +1,6 @@
import { Request, Response } from 'express'
export function root_get(req: Request, res: Response) {
res.render('home')
return true
}

View File

@@ -0,0 +1,45 @@
import { Request, Response } from 'express'
import Task from '../models/Task'
import { Err, Succ } from '../services/globalService'
export async function get(req: Request, res: Response) {
try {
const data = await Task.findAll()
res.json(data)
} catch (error) {
res.status(500).send(error)
}
}
export async function add(req: Request, res: Response) {
try {
const payload = req.body
payload.author_id = res.locals.user._id
console.log(payload)
const task = await Task.create(payload)
res.json(task)
} catch (error) {
res.status(500).send(error)
}
}
export async function edit(req: Request, res: Response) {
try {
const payload = req.body
payload.author_id = res.locals.user._id
const task: any = await Task.findByPk(payload._id)
if (!task) {
return res.status(400).json(new Err(400, 'Task not found'))
}
task.title = payload.title
task.timeEnd = payload.timeEnd
task.timeStart = payload.timeStart
await task.save()
return res.json(new Succ(200, 'Task updated succesfully'))
} catch (error) {
return res.status(500).json(new Err(400, 'something went wrong', error))
}
}

View File

@@ -0,0 +1,76 @@
import { Request, Response } from 'express'
import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import env from '../config/environment'
import User from '../models/User'
import { Err, Succ } from '../services/globalService'
export async function login(req: Request, res: Response) {}
export async function signup(req: Request, res: Response) {
try {
const payload = req.body
payload.password = await bcrypt.hash(payload.password, 12)
const user = await User.create(payload)
res.status(201).json(new Succ(201, 'user was successfully signed up'))
} catch (err: any) {
new Err(500, err)
res.status(500).json(new Err(500, 'something went wrong'))
}
}
export async function signin(req: Request, res: Response) {
try {
const payload = req.body
const user: any = await User.findOne({ where: { email: payload.email } })
if (!user) {
res.cookie('jwt', '', { httpOnly: true, maxAge: 0 })
res.cookie('auth', false, { httpOnly: false, maxAge: 0 })
res.status(401).json(new Err(401, 'email or password is wrong'))
return
}
if (await bcrypt.compare(payload.password, user.password)) {
const maxAge = 3 * 24 * 60 * 60 // 3 days in seconds
const createToken = (id: any) => {
return jwt.sign({ id }, env.JWT_SECRET, {
expiresIn: maxAge
})
}
const token = createToken(user._id)
res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 })
res.cookie('auth', true, { httpOnly: false, maxAge: maxAge * 1000 })
res.json(new Succ(200, 'user is logged in'))
return
}
res.cookie('jwt', '', { httpOnly: true, maxAge: 0 })
res.cookie('auth', false, { httpOnly: false, maxAge: 0 })
res.status(401).json(new Err(401, 'email or password is wrong'))
} catch (err: any) {
new Err(500, err)
res.status(500).json(new Err(500, 'something went wrong'))
}
}
export function logout(req: Request, res: Response) {
res.cookie('jwt', '', { httpOnly: true, maxAge: 0 })
res.cookie('auth', false, { httpOnly: false, maxAge: 0 })
res.json(new Succ(200, 'user was logged out'))
}
export function status(req: Request, res: Response) {
try {
let userObject = res.locals.user
userObject.password = undefined
userObject.__v = undefined
res.status(200).json(new Succ(200, 'user is logged in', userObject))
} catch (error) {
res.status(500).json(new Err(500, 'somehting went wrong', error))
}
}

View File

@@ -0,0 +1,4 @@
export interface ErrType {
code: number
message: string
}

View File

@@ -0,0 +1,55 @@
import { Request, Response, NextFunction } from 'express'
import jwt from 'jsonwebtoken'
import env from '../config/environment'
import { Err, Succ } from '../services/globalService'
import User from '../models/User' // uncomment this
export function requireAuth(req: Request, res: Response, next: NextFunction) {
const token = req.cookies.jwt
//new Err(500, 'uncomment code in authMiddleware before using!')
if (token) {
jwt.verify(token, env.JWT_SECRET, async (err: any, decodedToken: any) => {
if (err) {
// console.error(err.message)
res.status(401).json(new Err(401, 'user is not authenticated'))
}
if (!err) {
const user = await User.findByPk(decodedToken.id)
console.log('TADY', user)
if (user === null) {
console.log('1')
res.status(401).json(new Err(401, 'user is not authenticated'))
return
}
res.locals.user = user
console.log('2')
new Succ(100, 'user is authenticated')
next()
}
})
}
if (!token) {
console.log('3')
res.status(401).json(new Err(401, 'user is not authenticated'))
}
}
export function requireVerified(req: Request, res: Response, next: NextFunction) {
if (res.locals.user._id) {
if (res.locals.user.verified) {
new Succ(100, 'user is verified')
next()
return
}
res.status(403).json(new Err(403, 'user is not verified'))
return
}
if (!res.locals.user._id) {
res.status(401).json(new Err(401, 'user is not authenticated'))
return
}
}

View File

@@ -0,0 +1,16 @@
import { Request, Response, NextFunction } from 'express'
import { validationResult } from 'express-validator'
import { Err } from '../services/globalService'
class Middleware {
handleValidationError(req: Request, res: Response, next: NextFunction) {
const error = validationResult(req)
if (!error.isEmpty()) {
new Err(400, error)
return res.status(400).json(new Err(400, 'validation error', error.array()[0]))
}
next()
}
}
export default new Middleware()

View File

@@ -0,0 +1,6 @@
import { Router } from 'express'
import { router as sayHiMiddleware } from '../middlewares/sayHiMiddleware'
export const router = Router()
// router.use(sayHiMiddleware)

View File

@@ -0,0 +1,9 @@
import { Router, Request, Response, NextFunction } from 'express'
export const router = Router()
router.use((req: Request, res: Response, next: NextFunction) => {
console.log('Hi :)')
next()
})

44
api/src/models/Client.ts Normal file
View File

@@ -0,0 +1,44 @@
import { DataTypes, Model } from 'sequelize'
import path from 'path'
import db from '../config/sequelize.config'
import User from './User'
class Instance extends Model {}
Instance.init(
{
_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
allowNull: false,
unique: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
hourlyRate: {
type: DataTypes.INTEGER,
allowNull: true
},
contact: {
type: DataTypes.STRING,
allowNull: true
},
author_id: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: User,
key: '_id'
}
}
},
{
sequelize: db,
tableName: path.basename(__filename).split('.')[0].toLowerCase()
}
)
export default Instance

49
api/src/models/Project.ts Normal file
View File

@@ -0,0 +1,49 @@
import { DataTypes, Model } from 'sequelize'
import path from 'path'
import db from '../config/sequelize.config'
import User from './User'
import Client from './Client'
class Instance extends Model {}
Instance.init(
{
_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
allowNull: false,
unique: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
hourlyRate: {
type: DataTypes.INTEGER,
allowNull: true
},
client_id: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: Client,
key: '_id'
}
},
author_id: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: User,
key: '_id'
}
}
},
{
sequelize: db,
tableName: path.basename(__filename).split('.')[0].toLowerCase()
}
)
export default Instance

54
api/src/models/Task.ts Normal file
View File

@@ -0,0 +1,54 @@
import { DataTypes, Model } from 'sequelize'
import path from 'path'
import db from '../config/sequelize.config'
import User from './User'
import Client from './Client'
import Project from './Project'
class Instance extends Model {}
Instance.init(
{
_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
allowNull: false,
unique: true
},
title: {
type: DataTypes.STRING,
allowNull: true
},
timeStart: {
type: DataTypes.BIGINT,
allowNull: false
},
timeEnd: {
type: DataTypes.BIGINT,
allowNull: true
},
project_id: {
type: DataTypes.UUID,
allowNull: true,
references: {
model: Project,
key: '_id'
}
},
author_id: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: User,
key: '_id'
}
}
},
{
sequelize: db,
tableName: path.basename(__filename).split('.')[0].toLowerCase()
}
)
export default Instance

36
api/src/models/User.ts Normal file
View File

@@ -0,0 +1,36 @@
import { DataTypes, Model } from 'sequelize'
import path from 'path'
import db from '../config/sequelize.config'
class Instance extends Model {}
Instance.init(
{
_id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
allowNull: false,
unique: true
},
username: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
}
},
{
sequelize: db,
tableName: path.basename(__filename).split('.')[0].toLowerCase()
}
)
export default Instance

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.8 KiB

View File

@@ -0,0 +1,16 @@
import { Router } from 'express'
import * as taskController from '../controllers/taskController'
import * as userController from '../controllers/userController'
import { requireAuth } from '../middlewares/authMiddleware'
export const router = Router()
//const mws = [handleValidation.handleValidationError]
router.get('/task/get', requireAuth, taskController.get)
router.post('/task/add', requireAuth, taskController.add)
router.post('/task/edit', requireAuth, taskController.edit)
router.post('/auth/signup', userController.signup)
router.post('/auth/signin', userController.signin)
router.post('/auth/logout', requireAuth, userController.logout)
router.get('/auth/status', requireAuth, userController.status)

13
api/src/routes/index.ts Normal file
View File

@@ -0,0 +1,13 @@
import { Request, Response, Router } from 'express'
import { router as rootRoutes } from './rootRoutes'
import { router as apiRoutes } from './apiRoutes'
export const router = Router()
router.use(rootRoutes)
router.use("/api/v1", apiRoutes)
// 404
router.use((req: Request, res: Response) => {
res.status(404).send('E404')
})

View File

@@ -0,0 +1,9 @@
import { Router } from 'express'
import * as rootController from '../controllers/rootController'
import rootValidator from '../validators/rootValidator'
import handleValidation from '../middlewares/handleValidation'
export const router = Router()
const mws = [handleValidation.handleValidationError]
router.get('/', rootValidator.checkRootGet(), mws, rootController.root_get)

22
api/src/server.ts Normal file
View File

@@ -0,0 +1,22 @@
import http from 'http'
import { app } from './app'
import env from './config/environment'
import { Succ } from './services/globalService'
import database from './config/database'
const port: number = env.APP_PORT || 8080
const hostname: string = env.APP_HOSTNAME || 'localhost'
export const server = http.createServer(app)
// Server
export function runServer(): void {
server.listen(port, hostname, () => {
new Succ(200, `Server is listening on http://${hostname}:${port}`)
})
}
if (!env.NORK.database) {
runServer()
} else {
const db_connection = database()
runServer()
}

View File

@@ -0,0 +1,173 @@
import colors from 'colors'
import fs from 'fs'
import path from 'path'
export interface ErrType {
code: number
message: string
data?: any
}
export class Err implements ErrType {
code: number
message: string
data: any
constructor(code: number, message: string | object, data: any = null) {
this.code = code
typeof message === 'object' ? (this.message = JSON.stringify(message)) : (this.message = message)
data ? (this.data = data) : false
// typeof data === 'object' ? (this.data = JSON.stringify(data)) : (this.data = data)
this.drop()
}
drop() {
if (this.data) {
console.log(colors.bgRed(`${this.code}`) + colors.bgBlack.red(` ${this.message}`) + this.data)
Log.make('Err', this.code, this.message, this.data)
return {
code: this.code,
message: this.message,
data: this.data
}
}
console.log(colors.bgRed(`${this.code}`) + colors.bgBlack.red(` ${this.message}`))
Log.make('Err', this.code, this.message)
return {
code: this.code,
message: this.message
}
}
}
export class Succ {
code: number
message: string
data?: any
constructor(code: number, message: string, data: any = null) {
this.code = code
this.message = message
data ? (this.data = data) : false
this.drop()
}
drop() {
if (this.data) {
console.log(colors.bgGreen.black(`${this.code}`) + colors.green.bgBlack(` ${this.message}`) + this.data)
return {
code: this.code,
message: this.message,
data: this.data
}
}
console.log(colors.bgGreen.black(`${this.code}`) + colors.green.bgBlack(` ${this.message}`))
return {
code: this.code,
message: this.message
}
}
}
export interface LogType {
type: 'Err' | 'Succ' | 'Info'
code?: number
message?: string
data?: any
logFile?: string
}
export class Log implements LogType {
type: 'Err' | 'Succ' | 'Info'
code?: number
message?: string
data?: any
logFile?: string
/**
* @param type
* - Type of log
* - Err | Succ | Info
* @param code
* - not required
* - HTTP status code
* @param message
* - could be anything
* @param data
* - could be anything
* @param logFile
* - name of logFile
* - default is log type file
*/
constructor(type: 'Err' | 'Succ' | 'Info', code?: number, message?: string, data?: any, logFile?: string) {
this.type = type
this.code = code
this.message = message
this.data = data
this.logFile = logFile
if (!this.logFile) {
this.logFile = `${type}.global.log`
} else {
this.logFile = this.logFile + '.log'
}
this.logFile = path.join(__dirname, this.logFile)
}
static pathMake(type: string, name?: string) {
let logName
if (!name) {
logName = `${type}.global.log`
} else {
logName = name + '.log'
}
return path.join(__dirname, '../logs/' + logName)
}
/**
* returns current date in my custom format
*/
static dateNow(): string {
/**
* @param num: number
*
* receives number and returns two digits number
* example:
* input num = 9 => returns string 09
*/
function add0(num: number): string {
if (num.toString().length <= 1) {
return '0' + String(num)
}
return String(num)
}
const d = new Date()
return `${d.getFullYear()}-${add0(d.getMonth() + 1)}-${add0(d.getDate())} ${add0(d.getHours())}:${add0(d.getMinutes())}:${add0(d.getSeconds())}`
}
static make(type: 'Err' | 'Succ' | 'Info', code?: number, message?: string, data?: any, logFile?: string) {
let realPath = Log.pathMake(type, logFile)
let formattedData = `Date: "${Log.dateNow()}" Type: "${type}"`
code ? (formattedData += ` Code: "${code}"`) : false
message ? (formattedData += ` Message: "${message}"`) : false
if (data) {
if (typeof data === 'object') {
data = JSON.stringify(data)
}
formattedData += ` Data: "${data}"`
}
formattedData += '\n'
if (fs.existsSync(realPath)) {
fs.appendFileSync(realPath, formattedData)
} else {
fs.writeFileSync(realPath, formattedData)
}
}
}

View File

@@ -0,0 +1,3 @@
export const helloWorld = () => {
console.log('hello world')
}

View File

@@ -0,0 +1,7 @@
import * as shell from 'shelljs'
// Copy all the view templates
shell.cp('-R', 'src/views', 'dist/')
shell.cp('-R', 'src/public', 'dist/')
shell.cp('-R', 'src/models', 'dist/')
shell.cp('-u', 'src/.env', 'dist/')

View File

@@ -0,0 +1,9 @@
import { body, param, query } from 'express-validator'
class rootValidator {
checkRootGet() {
return []
}
}
export default new rootValidator()

69
api/src/views/home.ejs Normal file
View File

@@ -0,0 +1,69 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Project</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Open Sans', sans-serif;
}
.content {
width: 100vw;
height: 100vh;
display: flex;
justify-content: space-between;
padding-top: 5rem;
flex-direction: column;
}
footer, .welcome {
display: flex;
justify-content: center;
}
.welcome {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
img {
width: 200px;
padding-top: 2rem;
}
footer {
padding-bottom: 2rem;
text-align: center;
}
.logos {
display: flex;
align-items: center;
gap: 1rem;
}
</style>
</head>
<body>
<div class="content">
<div class="welcome">
<h1>Let's make something amazing!</h1>
<div class="logos">
<img src="/nodejs_logo.svg" alt="node.js logo">
<img src="/expressjs.png" alt="express.js logo">
</div>
</div>
<footer>
<div class="author">
<p>Made by </p><a href="http://www.filiprojek.cz">filiprojek.cz</a>
</div>
</footer>
</div>
</body>
</html>

63
api/tsconfig.json Normal file
View File

@@ -0,0 +1,63 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es6",
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs",
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist",
/* Redirect output structure to the directory. */
"rootDir": "./src",
/* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true,
/* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
"baseUrl": "./",
"esModuleInterop": true,
/* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"resolveJsonModule": true,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Experimental Options */
"experimentalDecorators": true,
/* Enables experimental support for ES7 decorators. */
"emitDecoratorMetadata": true,
/* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true,
/* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true
/* Disallow inconsistently-cased references to the same file. */
},
"exclude": ["src/tests"]
}

32
docker-compose.yaml Normal file
View File

@@ -0,0 +1,32 @@
version: '3'
networks:
db:
driver: bridge
services:
mariadb:
image: mariadb:10.6
restart: always
env_file: .docker.env
environment:
MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASS}
MYSQL_USER: ${DB_USER}
MYSQL_PASSWORD: ${DB_PASS}
ports:
- "3306:3306"
volumes:
- ./mariadb:/var/lib/mysql
networks:
db:
phpmyadmin:
image: phpmyadmin
restart: always
ports:
- "8080:80"
environment:
- PMA_HOST=mariadb
- PMA_PORT=3306
networks:
db:

View File

@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<link rel="icon" href="/src/assets/svg/tim.svg">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TiM</title>
</head>

View File

@@ -4,15 +4,31 @@ import { RouterLink, RouterView } from 'vue-router'
<template>
<header>
<nav>
<RouterLink to="/">Home</RouterLink>
<nav>
<div class="left">
<RouterLink to="/tracker">Tracker</RouterLink>
<RouterLink to="/dashboard">Dashboard</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
</div>
<div class="right">
<RouterLink to="/profile">{{ username }}</RouterLink>
</div>
</nav>
</header>
<RouterView />
</template>
<style scoped>
<script>
import AppStore from './stores/AppStore'
</style>
export default {
data() {
return {
username: AppStore.data.user.username
}
},
methods: {},
async created() {}
}
</script>

47
frontend/src/api/user.js Normal file
View File

@@ -0,0 +1,47 @@
const api_url = 'http://localhost:6060'
const userAPIS = {
async getUserStatus() {
const res = await fetch(`${api_url}/api/v1/auth/status`, {
credentials: 'include'
})
return res.json()
},
async loginUser(formState) {
const res = await fetch(`${api_url}/api/v1/auth/signin`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formState)
})
return await res.json()
},
async logoutUser() {
const res = await fetch(`${api_url}/api/v1/auth/logout`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({})
})
return await res.json()
},
async registerUser(formState) {
const res = await fetch(`${api_url}/api/v1/auth/signup`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formState)
})
return res.json()
}
}
export default userAPIS

View File

@@ -1,86 +0,0 @@
/* color palette from <https://github.com/vuejs/theme> */
:root {
--vt-c-white: #ffffff;
--vt-c-white-soft: #f8f8f8;
--vt-c-white-mute: #f2f2f2;
--vt-c-black: #181818;
--vt-c-black-soft: #222222;
--vt-c-black-mute: #282828;
--vt-c-indigo: #2c3e50;
--vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
--vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
--vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
--vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
--vt-c-text-light-1: var(--vt-c-indigo);
--vt-c-text-light-2: rgba(60, 60, 60, 0.66);
--vt-c-text-dark-1: var(--vt-c-white);
--vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
}
/* semantic color variables for this project */
:root {
--color-background: var(--vt-c-white);
--color-background-soft: var(--vt-c-white-soft);
--color-background-mute: var(--vt-c-white-mute);
--color-border: var(--vt-c-divider-light-2);
--color-border-hover: var(--vt-c-divider-light-1);
--color-heading: var(--vt-c-text-light-1);
--color-text: var(--vt-c-text-light-1);
--section-gap: 160px;
}
@media (prefers-color-scheme: dark) {
:root {
--color-background: var(--vt-c-black);
--color-background-soft: var(--vt-c-black-soft);
--color-background-mute: var(--vt-c-black-mute);
--color-border: var(--vt-c-divider-dark-2);
--color-border-hover: var(--vt-c-divider-dark-1);
--color-heading: var(--vt-c-text-dark-1);
--color-text: var(--vt-c-text-dark-2);
}
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
font-weight: normal;
}
body {
min-height: 100vh;
color: var(--color-text);
background: var(--color-background);
transition:
color 0.5s,
background-color 0.5s;
line-height: 1.6;
font-family:
Inter,
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
Oxygen,
Ubuntu,
Cantarell,
'Fira Sans',
'Droid Sans',
'Helvetica Neue',
sans-serif;
font-size: 15px;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

View File

@@ -0,0 +1,24 @@
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
font-family: 'Open Sans', sans-serif;
background-color: var(--clr-3);
}
a, p {
color: white;
}
.f-col {
display: flex;
flex-direction: column;
}
.f-row {
display: flex;
flex-direction: row;
}

View File

@@ -0,0 +1,5 @@
@import './base.css';
@import './nav.css';
@import './vars.css';
@import './tracker.css';
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,500;0,700;0,800;1,400;1,700&display=swap');

View File

@@ -0,0 +1,15 @@
header nav {
display: flex;
justify-content: space-between;
padding: 2rem;
background-color: var(--clr-1);
}
header nav div {
display: flex;
gap: 1rem;
}
header nav a {
text-decoration: none;
}

View File

@@ -0,0 +1,37 @@
.header, .task-wrapper, .task, .task span {
display: flex;
flex-direction: row;
justify-content: space-between;
width: 100%;
}
main {
margin: 1rem 1rem;
display: flex;
flex-direction: column;
gap: 1rem;
}
.header {
justify-content: space-between;
background-color: var(--clr-1);
}
.task {
background-color: var(--clr-2);
}
.task, .header, .task-new-wrapper {
padding: .5rem;
}
.task-new-wrapper {
background-color: var(--clr-2);
}
.task-new-wrapper .f-row {
gap: 1rem;
}
img {
cursor: pointer;
}

View File

@@ -0,0 +1,9 @@
:root {
--clr-1: #031326;
--clr-2: #172B40;
--clr-3: #2F435B;
--clr-4: #495C74;
--clr-5: #7B94A7;
--clr-blk: black;
--clr-wht: white;
}

View File

@@ -1,35 +0,0 @@
@import './base.css';
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
font-weight: normal;
}
a,
.green {
text-decoration: none;
color: hsla(160, 100%, 37%, 1);
transition: 0.4s;
padding: 3px;
}
@media (hover: hover) {
a:hover {
background-color: hsla(160, 100%, 37%, 0.2);
}
}
@media (min-width: 1024px) {
body {
display: flex;
place-items: center;
}
#app {
display: grid;
grid-template-columns: 1fr 1fr;
padding: 0 2rem;
}
}

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M441-120v-86q-53-12-91.5-46T293-348l74-30q15 48 44.5 73t77.5 25q41 0 69.5-18.5T587-356q0-35-22-55.5T463-458q-86-27-118-64.5T313-614q0-65 42-101t86-41v-84h80v84q50 8 82.5 36.5T651-650l-74 32q-12-32-34-48t-60-16q-44 0-67 19.5T393-614q0 33 30 52t104 40q69 20 104.5 63.5T667-358q0 71-42 108t-104 46v84h-80Z"/></svg>

After

Width:  |  Height:  |  Size: 408 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M480-160q-33 0-56.5-23.5T400-240q0-33 23.5-56.5T480-320q33 0 56.5 23.5T560-240q0 33-23.5 56.5T480-160Zm0-240q-33 0-56.5-23.5T400-480q0-33 23.5-56.5T480-560q33 0 56.5 23.5T560-480q0 33-23.5 56.5T480-400Zm0-240q-33 0-56.5-23.5T400-720q0-33 23.5-56.5T480-800q33 0 56.5 23.5T560-720q0 33-23.5 56.5T480-640Z"/></svg>

After

Width:  |  Height:  |  Size: 408 B

View File

Before

Width:  |  Height:  |  Size: 276 B

After

Width:  |  Height:  |  Size: 276 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M320-200v-560l440 280-440 280Zm80-280Zm0 134 210-134-210-134v268Z"/></svg>

After

Width:  |  Height:  |  Size: 171 B

View File

@@ -0,0 +1,136 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="120"
height="120"
viewBox="0 0 120 120"
version="1.1"
id="svg1"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs1" />
<g
id="layer1">
<g
id="g1"
transform="translate(12.027507)">
<ellipse
id="path3213"
style="display:inline;fill:none;stroke:#000000;stroke-width:7.32083"
cx="48.122433"
cy="70.19529"
rx="44.462025"
ry="46.144321" />
<g
id="g4013"
transform="matrix(1.796537,0,0,1.8645118,133.64377,-1753.068)"
style="display:inline">
<g
id="g4017">
<rect
id="rect4009"
ry="1.2627"
style="fill:#000000"
transform="translate(0,949.6)"
height="8.3338003"
width="9.849"
y="-9.3710003"
x="-52.653999" />
<rect
id="rect4011"
style="fill:#000000"
transform="translate(0,949.6)"
ry="0"
height="2.9042001"
width="3.7881"
y="-1.2266999"
x="-49.624001" />
</g>
</g>
<g
id="g4021"
transform="matrix(0.89951448,-0.93354909,0.89951448,0.93354909,-795.968,-897.59404)"
style="display:inline">
<g
id="g4023">
<rect
id="rect4025"
style="fill:#000000"
transform="translate(0,949.6)"
ry="1.2627"
height="8.3338003"
width="9.849"
y="-9.3710003"
x="-52.653999" />
<rect
id="rect4027"
ry="0"
style="fill:#000000"
transform="translate(0,949.6)"
height="2.9042001"
width="3.7881"
y="-1.2266999"
x="-49.624001" />
</g>
</g>
<path
id="path4061"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097"
d="m 48.134614,30.042394 v 4.490837" />
<path
id="path4065"
d="M 86.760262,70.129607 H 82.433249"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097" />
<path
id="path4067"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097"
d="m 48.134614,110.21681 v -4.49073" />
<path
id="path4069"
d="M 9.5078909,70.129607 H 13.834906"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097" />
<path
id="path4071"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097"
d="M 67.446997,35.413355 65.28344,39.302438" />
<path
id="path4073"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097"
d="m 81.585211,50.085899 -3.747694,2.245417" />
<path
id="path4075"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097"
d="M 81.585211,90.173717 77.83791,87.928304" />
<path
id="path4077"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097"
d="M 67.446997,104.84688 65.28344,100.95769" />
<path
id="path4079"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097"
d="m 28.821252,104.84688 2.163557,-3.88919" />
<path
id="path4081"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097"
d="m 14.68304,90.173717 3.747398,-2.245413" />
<path
id="path4083"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097"
d="m 14.68304,50.085899 3.747693,2.245417" />
<path
id="path4085"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097"
d="m 28.821252,35.413355 2.163557,3.889186" />
<path
id="path4087"
style="display:inline;fill:none;stroke:#000000;stroke-width:0.915097"
d="m 28.821252,35.413355 2.163557,3.889186" />
<path
d="m 45.085541,98.493237 v -6.796138 q -4.035622,-0.948305 -6.967158,-3.635143 -2.931537,-2.686846 -4.302127,-7.58639 l 5.634642,-2.370746 q 1.142157,3.793192 3.388398,5.768816 2.246245,1.975621 5.901153,1.975621 3.121893,0 5.291991,-1.46196 2.170098,-1.46196 2.170098,-4.543932 0,-2.765868 -1.675164,-4.385877 -1.675161,-1.620009 -7.766666,-3.674654 -6.548371,-2.133671 -8.984975,-5.097106 -2.436604,-2.963429 -2.436604,-7.230773 0,-5.136616 3.198043,-7.981511 3.19804,-2.844894 6.548369,-3.240017 v -6.638089 h 6.091506 v 6.638089 q 3.807192,0.6322 6.28187,2.884407 2.474671,2.252208 3.616831,5.492227 l -5.634645,2.528793 q -0.913729,-2.528793 -2.58889,-3.793193 -1.675166,-1.264397 -4.568632,-1.264397 -3.350326,0 -5.101636,1.540985 -1.751309,1.540984 -1.751309,3.832706 0,2.60782 2.284315,4.109291 2.284317,1.501474 7.918961,3.160995 5.253922,1.580497 7.957024,5.01808 2.703112,3.437579 2.703112,7.941997 0,5.610764 -3.198043,8.534687 -3.198042,2.923914 -7.918958,3.635144 v 6.638088 z"
id="path1"
style="stroke-width:0.0775709" />
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 5.2 KiB

View File

@@ -0,0 +1,37 @@
<script setup>
defineProps(['btn-txt', 'api-endpoint'])
</script>
<template>
<form>
<slot></slot>
<button @click="formAction">{{ btnTxt }}</button>
</form>
</template>
<script>
import AppStore from '@/stores/AppStore'
export default {
data() {
return {
d: {
email: undefined,
password: undefined,
username: undefined
}
}
},
methods: {
formAction() {
console.log(this.d)
//AppStore.sendAdd(null, this.$props.apiEndpoint)
}
}
}
</script>
<style scoped>
form {
display: flex;
flex-direction: column;
align-items: center;
}
</style>

View File

@@ -1,44 +0,0 @@
<script setup>
defineProps({
msg: {
type: String,
required: true
}
})
</script>
<template>
<div class="greetings">
<h1 class="green">{{ msg }}</h1>
<h3>
Youve successfully created a project with
<a href="https://vitejs.dev/" target="_blank" rel="noopener">Vite</a> +
<a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>.
</h3>
</div>
</template>
<style scoped>
h1 {
font-weight: 500;
font-size: 2.6rem;
position: relative;
top: -10px;
}
h3 {
font-size: 1.2rem;
}
.greetings h1,
.greetings h3 {
text-align: center;
}
@media (min-width: 1024px) {
.greetings h1,
.greetings h3 {
text-align: left;
}
}
</style>

View File

@@ -0,0 +1,21 @@
<template>
<div class="header">
<div class="left">
<p>{{ date }}</p>
</div>
<div class="right">
<p>Total: {{ totalTime }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
totalTime: '00:00:00',
date: 'Wed, Dec 14'
}
}
}
</script>

View File

@@ -0,0 +1,72 @@
<script setup>
import { computed } from 'vue'
const props = defineProps(['task'])
function normalizeTime(time) {
let d = new Date(Number(time))
let h = d.getHours().toString().padStart(2, '0')
let m = d.getMinutes().toString().padStart(2, '0')
let s = d.getSeconds().toString().padStart(2, '0')
return `${h}:${m}:${s}`
}
function formatDuration(durationInSeconds) {
let h = Math.floor(durationInSeconds / 3600)
.toString()
.padStart(2, '0')
let m = Math.floor((durationInSeconds % 3600) / 60)
.toString()
.padStart(2, '0')
let s = (durationInSeconds % 60).toString().padStart(2, '0')
return `${h}:${m}:${s}`
}
const normalizedTimeStart = computed(() => normalizeTime(props.task.timeStart))
const normalizedTimeEnd = computed(() => normalizeTime(props.task.timeEnd))
const durationInSeconds = computed(() =>
Math.floor((props.task.timeEnd - props.task.timeStart) / 1000)
)
const normalizedDuration = computed(() => formatDuration(durationInSeconds.value))
</script>
<template>
<div class="task">
<span>
<input
type="text"
class="title"
placeholder="What are you working on?"
:value="props.task.title"
/>
</span>
<span>
<p>{{ props.task.project }}</p>
<p>{{ props.task.client }}</p>
</span>
<!--
<span>
<img src="/src/assets/svg/dollar.svg" alt="" />
</span>
-->
<span>
<input type="time" :value="normalizedTimeStart" />
<p>-</p>
<input type="time" :value="normalizedTimeEnd" />
</span>
<span>
<input type="text" :value="normalizedDuration" />
</span>
<!--
<span>
<img src="/src/assets/svg/play.svg" alt="" />
</span>
<span>
<img src="/src/assets/svg/dots.svg" alt="" />
</span>
-->
</div>
</template>
<script></script>

View File

@@ -1,88 +0,0 @@
<script setup>
import WelcomeItem from './WelcomeItem.vue'
import DocumentationIcon from './icons/IconDocumentation.vue'
import ToolingIcon from './icons/IconTooling.vue'
import EcosystemIcon from './icons/IconEcosystem.vue'
import CommunityIcon from './icons/IconCommunity.vue'
import SupportIcon from './icons/IconSupport.vue'
</script>
<template>
<WelcomeItem>
<template #icon>
<DocumentationIcon />
</template>
<template #heading>Documentation</template>
Vues
<a href="https://vuejs.org/" target="_blank" rel="noopener">official documentation</a>
provides you with all information you need to get started.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<ToolingIcon />
</template>
<template #heading>Tooling</template>
This project is served and bundled with
<a href="https://vitejs.dev/guide/features.html" target="_blank" rel="noopener">Vite</a>. The
recommended IDE setup is
<a href="https://code.visualstudio.com/" target="_blank" rel="noopener">VSCode</a> +
<a href="https://github.com/johnsoncodehk/volar" target="_blank" rel="noopener">Volar</a>. If
you need to test your components and web pages, check out
<a href="https://www.cypress.io/" target="_blank" rel="noopener">Cypress</a> and
<a href="https://on.cypress.io/component" target="_blank" rel="noopener"
>Cypress Component Testing</a
>.
<br />
More instructions are available in <code>README.md</code>.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<EcosystemIcon />
</template>
<template #heading>Ecosystem</template>
Get official tools and libraries for your project:
<a href="https://pinia.vuejs.org/" target="_blank" rel="noopener">Pinia</a>,
<a href="https://router.vuejs.org/" target="_blank" rel="noopener">Vue Router</a>,
<a href="https://test-utils.vuejs.org/" target="_blank" rel="noopener">Vue Test Utils</a>, and
<a href="https://github.com/vuejs/devtools" target="_blank" rel="noopener">Vue Dev Tools</a>. If
you need more resources, we suggest paying
<a href="https://github.com/vuejs/awesome-vue" target="_blank" rel="noopener">Awesome Vue</a>
a visit.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<CommunityIcon />
</template>
<template #heading>Community</template>
Got stuck? Ask your question on
<a href="https://chat.vuejs.org" target="_blank" rel="noopener">Vue Land</a>, our official
Discord server, or
<a href="https://stackoverflow.com/questions/tagged/vue.js" target="_blank" rel="noopener"
>StackOverflow</a
>. You should also subscribe to
<a href="https://news.vuejs.org" target="_blank" rel="noopener">our mailing list</a> and follow
the official
<a href="https://twitter.com/vuejs" target="_blank" rel="noopener">@vuejs</a>
twitter account for latest news in the Vue world.
</WelcomeItem>
<WelcomeItem>
<template #icon>
<SupportIcon />
</template>
<template #heading>Support Vue</template>
As an independent project, Vue relies on community backing for its sustainability. You can help
us by
<a href="https://vuejs.org/sponsor/" target="_blank" rel="noopener">becoming a sponsor</a>.
</WelcomeItem>
</template>

View File

@@ -0,0 +1,107 @@
<template>
<div class="task-new-wrapper">
<div class="task">
<input
v-model="task.title"
type="text"
class="title"
placeholder="What are you working on?"
/>
<a href="#">+ Project</a>
</div>
<div class="task">
<img src="/src/assets/svg/dollar.svg" alt="" />
<div class="f-row">
<p>{{ formattedElapsedTime }}</p>
<button @click="startStopTimer">{{ timerState }}</button>
<img src="/src/assets/svg/dots.svg" alt="" />
</div>
</div>
</div>
</template>
<script>
import AppStore from '@/stores/AppStore'
export default {
data() {
return {
timeNow: null,
timer: undefined,
timerState: 'Start',
task: {
timeStart: 0,
timeEnd: 0,
title: ''
},
restore: false
}
},
computed: {
formattedElapsedTime() {
const date = new Date(this.timeNow - this.task.timeStart)
const utc = date.toUTCString()
return utc.substr(utc.indexOf(':') - 2, 8)
}
},
methods: {
async startStopTimer() {
if (this.timerState == 'Start') {
this.timerState = 'Stop'
console.log('TADY', this.restore)
if (this.restore == false) {
console.log('TADY')
this.task.timeStart = Date.now()
}
this.timeNow = Date.now()
console.log('timer started')
this.timer = setInterval(() => {
this.timeNow = Date.now()
}, 1000)
if (!this.task._id) {
AppStore.data.newTask = {
title: this.task.title,
timeStart: this.task.timeStart
}
await AppStore.sendAdd(AppStore.data.newTask, '/task/add')
}
} else {
this.task.timeEnd = Date.now()
this.timerState = 'Start'
clearInterval(this.timer)
this.timer = undefined
this.timeNow = 0
AppStore.data.newTask = {
title: this.task.title,
timeStart: this.task.timeStart,
timeEnd: this.task.timeEnd
}
if (this.task._id) {
AppStore.data.newTask._id = this.task._id
await AppStore.sendAdd(AppStore.data.newTask, '/task/edit')
} else {
await AppStore.sendAdd(AppStore.data.newTask, '/task/add')
}
this.task = {
timeStart: 0,
timeEnd: 0,
title: ''
}
this.restore = false
this.$emit('get-tasks')
}
}
},
async mounted() {
await AppStore.fetchData()
const task = AppStore.data.fetchedTasks.filter((task) => task.timeEnd === null)
if (task.length > 0) {
this.task = task[0]
this.restore = true
this.startStopTimer()
}
}
}
</script>

View File

@@ -1,86 +0,0 @@
<template>
<div class="item">
<i>
<slot name="icon"></slot>
</i>
<div class="details">
<h3>
<slot name="heading"></slot>
</h3>
<slot></slot>
</div>
</div>
</template>
<style scoped>
.item {
margin-top: 2rem;
display: flex;
position: relative;
}
.details {
flex: 1;
margin-left: 1rem;
}
i {
display: flex;
place-items: center;
place-content: center;
width: 32px;
height: 32px;
color: var(--color-text);
}
h3 {
font-size: 1.2rem;
font-weight: 500;
margin-bottom: 0.4rem;
color: var(--color-heading);
}
@media (min-width: 1024px) {
.item {
margin-top: 0;
padding: 0.4rem 0 1rem calc(var(--section-gap) / 2);
}
i {
top: calc(50% - 25px);
left: -26px;
position: absolute;
border: 1px solid var(--color-border);
background: var(--color-background);
border-radius: 8px;
width: 50px;
height: 50px;
}
.item:before {
content: ' ';
border-left: 1px solid var(--color-border);
position: absolute;
left: 0;
bottom: calc(50% + 25px);
height: calc(50% - 25px);
}
.item:after {
content: ' ';
border-left: 1px solid var(--color-border);
position: absolute;
left: 0;
top: calc(50% + 25px);
height: calc(50% - 25px);
}
.item:first-of-type:before {
display: none;
}
.item:last-of-type:after {
display: none;
}
}
</style>

View File

@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
<path
d="M15 4a1 1 0 1 0 0 2V4zm0 11v-1a1 1 0 0 0-1 1h1zm0 4l-.707.707A1 1 0 0 0 16 19h-1zm-4-4l.707-.707A1 1 0 0 0 11 14v1zm-4.707-1.293a1 1 0 0 0-1.414 1.414l1.414-1.414zm-.707.707l-.707-.707.707.707zM9 11v-1a1 1 0 0 0-.707.293L9 11zm-4 0h1a1 1 0 0 0-1-1v1zm0 4H4a1 1 0 0 0 1.707.707L5 15zm10-9h2V4h-2v2zm2 0a1 1 0 0 1 1 1h2a3 3 0 0 0-3-3v2zm1 1v6h2V7h-2zm0 6a1 1 0 0 1-1 1v2a3 3 0 0 0 3-3h-2zm-1 1h-2v2h2v-2zm-3 1v4h2v-4h-2zm1.707 3.293l-4-4-1.414 1.414 4 4 1.414-1.414zM11 14H7v2h4v-2zm-4 0c-.276 0-.525-.111-.707-.293l-1.414 1.414C5.42 15.663 6.172 16 7 16v-2zm-.707 1.121l3.414-3.414-1.414-1.414-3.414 3.414 1.414 1.414zM9 12h4v-2H9v2zm4 0a3 3 0 0 0 3-3h-2a1 1 0 0 1-1 1v2zm3-3V3h-2v6h2zm0-6a3 3 0 0 0-3-3v2a1 1 0 0 1 1 1h2zm-3-3H3v2h10V0zM3 0a3 3 0 0 0-3 3h2a1 1 0 0 1 1-1V0zM0 3v6h2V3H0zm0 6a3 3 0 0 0 3 3v-2a1 1 0 0 1-1-1H0zm3 3h2v-2H3v2zm1-1v4h2v-4H4zm1.707 4.707l.586-.586-1.414-1.414-.586.586 1.414 1.414z"
/>
</svg>
</template>

View File

@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" fill="currentColor">
<path
d="M11 2.253a1 1 0 1 0-2 0h2zm-2 13a1 1 0 1 0 2 0H9zm.447-12.167a1 1 0 1 0 1.107-1.666L9.447 3.086zM1 2.253L.447 1.42A1 1 0 0 0 0 2.253h1zm0 13H0a1 1 0 0 0 1.553.833L1 15.253zm8.447.833a1 1 0 1 0 1.107-1.666l-1.107 1.666zm0-14.666a1 1 0 1 0 1.107 1.666L9.447 1.42zM19 2.253h1a1 1 0 0 0-.447-.833L19 2.253zm0 13l-.553.833A1 1 0 0 0 20 15.253h-1zm-9.553-.833a1 1 0 1 0 1.107 1.666L9.447 14.42zM9 2.253v13h2v-13H9zm1.553-.833C9.203.523 7.42 0 5.5 0v2c1.572 0 2.961.431 3.947 1.086l1.107-1.666zM5.5 0C3.58 0 1.797.523.447 1.42l1.107 1.666C2.539 2.431 3.928 2 5.5 2V0zM0 2.253v13h2v-13H0zm1.553 13.833C2.539 15.431 3.928 15 5.5 15v-2c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM5.5 15c1.572 0 2.961.431 3.947 1.086l1.107-1.666C9.203 13.523 7.42 13 5.5 13v2zm5.053-11.914C11.539 2.431 12.928 2 14.5 2V0c-1.92 0-3.703.523-5.053 1.42l1.107 1.666zM14.5 2c1.573 0 2.961.431 3.947 1.086l1.107-1.666C18.203.523 16.421 0 14.5 0v2zm3.5.253v13h2v-13h-2zm1.553 12.167C18.203 13.523 16.421 13 14.5 13v2c1.573 0 2.961.431 3.947 1.086l1.107-1.666zM14.5 13c-1.92 0-3.703.523-5.053 1.42l1.107 1.666C11.539 15.431 12.928 15 14.5 15v-2z"
/>
</svg>
</template>

View File

@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="20" fill="currentColor">
<path
d="M11.447 8.894a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm0 1.789a1 1 0 1 0 .894-1.789l-.894 1.789zM7.447 7.106a1 1 0 1 0-.894 1.789l.894-1.789zM10 9a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0H8zm9.447-5.606a1 1 0 1 0-.894-1.789l.894 1.789zm-2.894-.789a1 1 0 1 0 .894 1.789l-.894-1.789zm2 .789a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zM18 5a1 1 0 1 0-2 0h2zm-2 2.5a1 1 0 1 0 2 0h-2zm-5.447-4.606a1 1 0 1 0 .894-1.789l-.894 1.789zM9 1l.447-.894a1 1 0 0 0-.894 0L9 1zm-2.447.106a1 1 0 1 0 .894 1.789l-.894-1.789zm-6 3a1 1 0 1 0 .894 1.789L.553 4.106zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zm-2-.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 2.789a1 1 0 1 0 .894-1.789l-.894 1.789zM2 5a1 1 0 1 0-2 0h2zM0 7.5a1 1 0 1 0 2 0H0zm8.553 12.394a1 1 0 1 0 .894-1.789l-.894 1.789zm-1.106-2.789a1 1 0 1 0-.894 1.789l.894-1.789zm1.106 1a1 1 0 1 0 .894 1.789l-.894-1.789zm2.894.789a1 1 0 1 0-.894-1.789l.894 1.789zM8 19a1 1 0 1 0 2 0H8zm2-2.5a1 1 0 1 0-2 0h2zm-7.447.394a1 1 0 1 0 .894-1.789l-.894 1.789zM1 15H0a1 1 0 0 0 .553.894L1 15zm1-2.5a1 1 0 1 0-2 0h2zm12.553 2.606a1 1 0 1 0 .894 1.789l-.894-1.789zM17 15l.447.894A1 1 0 0 0 18 15h-1zm1-2.5a1 1 0 1 0-2 0h2zm-7.447-5.394l-2 1 .894 1.789 2-1-.894-1.789zm-1.106 1l-2-1-.894 1.789 2 1 .894-1.789zM8 9v2.5h2V9H8zm8.553-4.894l-2 1 .894 1.789 2-1-.894-1.789zm.894 0l-2-1-.894 1.789 2 1 .894-1.789zM16 5v2.5h2V5h-2zm-4.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zm-2.894-1l-2 1 .894 1.789 2-1L8.553.106zM1.447 5.894l2-1-.894-1.789-2 1 .894 1.789zm-.894 0l2 1 .894-1.789-2-1-.894 1.789zM0 5v2.5h2V5H0zm9.447 13.106l-2-1-.894 1.789 2 1 .894-1.789zm0 1.789l2-1-.894-1.789-2 1 .894 1.789zM10 19v-2.5H8V19h2zm-6.553-3.894l-2-1-.894 1.789 2 1 .894-1.789zM2 15v-2.5H0V15h2zm13.447 1.894l2-1-.894-1.789-2 1 .894 1.789zM18 15v-2.5h-2V15h2z"
/>
</svg>
</template>

View File

@@ -1,7 +0,0 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor">
<path
d="M10 3.22l-.61-.6a5.5 5.5 0 0 0-7.666.105 5.5 5.5 0 0 0-.114 7.665L10 18.78l8.39-8.4a5.5 5.5 0 0 0-.114-7.665 5.5 5.5 0 0 0-7.666-.105l-.61.61z"
/>
</svg>
</template>

View File

@@ -1,19 +0,0 @@
<!-- This icon is from <https://github.com/Templarian/MaterialDesign>, distributed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0) license-->
<template>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
aria-hidden="true"
role="img"
class="iconify iconify--mdi"
width="24"
height="24"
preserveAspectRatio="xMidYMid meet"
viewBox="0 0 24 24"
>
<path
d="M20 18v-4h-3v1h-2v-1H9v1H7v-1H4v4h16M6.33 8l-1.74 4H7v-1h2v1h6v-1h2v1h2.41l-1.74-4H6.33M9 5v1h6V5H9m12.84 7.61c.1.22.16.48.16.8V18c0 .53-.21 1-.6 1.41c-.4.4-.85.59-1.4.59H4c-.55 0-1-.19-1.4-.59C2.21 19 2 18.53 2 18v-4.59c0-.32.06-.58.16-.8L4.5 7.22C4.84 6.41 5.45 6 6.33 6H7V5c0-.55.18-1 .57-1.41C7.96 3.2 8.44 3 9 3h6c.56 0 1.04.2 1.43.59c.39.41.57.86.57 1.41v1h.67c.88 0 1.49.41 1.83 1.22l2.34 5.39z"
fill="currentColor"
></path>
</svg>
</template>

View File

@@ -1,4 +1,4 @@
import './assets/main.css'
import './assets/css/main.css'
import { createApp } from 'vue'
import App from './App.vue'

View File

@@ -1,5 +1,15 @@
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import TrackerView from '../views/TrackerView.vue'
import SignupView from '../views/SignupView.vue'
import LoginView from '../views/LoginView.vue'
import userAPIS from '../api/user'
const authGuard = async () => {
const data = await userAPIS.getUserStatus()
if (!data.data) {
throw router.push('/')
}
}
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
@@ -7,7 +17,27 @@ const router = createRouter({
{
path: '/',
name: 'home',
component: HomeView
//component: HomeView
redirect: '/tracker'
},
{
path: '/login',
name: 'login',
component: LoginView
},
{
path: '/signup',
name: 'signup',
component: SignupView
},
{
path: '/tracker',
name: 'tracker',
component: TrackerView,
alias: '/',
meta: {
requiresAuth: true
}
},
{
path: '/about',
@@ -20,4 +50,20 @@ const router = createRouter({
]
})
router.beforeEach(async (to, from, next) => {
const requiresAuth = to.matched.some((x) => x.meta.requiresAuth)
const requiresGuest = to.matched.some((x) => x.meta.requiresGuest)
if (requiresAuth) {
const userStatus = await userAPIS.getUserStatus()
if (!userStatus.data) {
router.replace('/login')
next()
return
}
}
next()
})
export default router

View File

@@ -0,0 +1,55 @@
export default {
api_url: 'http://localhost:6060/api/v1',
data: {
user: {
_id: '1234',
username: 'Example User',
email: 'test@example.com'
},
newTask: {},
fetchedTasks: [
//{
// _id: 1,
// title: 'Loading',
// project: 'Loading',
// client: 'Loading',
// timeStart: 1703960133061,
// timeEnd: 1703960141414
//}
]
},
async fetchData() {
try {
const response = await fetch(this.api_url + '/task/get', {
credentials: 'include'
})
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
const data = await response.json()
this.data.fetchedTasks = data
console.log('Received data:', data)
} catch (error) {
console.error('Error fetching data:', error)
}
},
async sendAdd(data, url) {
try {
const response = await fetch(this.api_url + url, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
} catch (error) {
console.error('Error sending data:', error)
}
}
}

View File

@@ -1,15 +1,19 @@
<template>
<div class="about">
<main class="about">
<h1>This is an about page</h1>
</div>
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nemo molestiae commodi ipsam cumque
voluptatem laboriosam modi ratione, ad porro repellendus deleniti quis nostrum fuga quaerat
voluptas facere minima explicabo! Voluptatem.
</p>
<p>
Source code available at:
<a href="https://git.filiprojek.cz/fr/tim" target="_blank"
>https://git.filiprojek.cz/fr/tim</a
>
</p>
<p>Created by <a href="https://filiprojek.cz" target="_blank">@filiprojek</a>, 2023</p>
</main>
</template>
<style>
@media (min-width: 1024px) {
.about {
min-height: 100vh;
display: flex;
align-items: center;
}
}
</style>
<style></style>

View File

@@ -1,7 +0,0 @@
<script setup>
</script>
<template>
<main>
</main>
</template>

View File

@@ -0,0 +1,33 @@
<script setup>
import router from '@/router'
</script>
<template>
<form>
<label for="email">Email:</label>
<input type="email" id="email" v-model="email" placeholder="Email" />
<label for="password">Password:</label>
<input type="password" id="password" v-model="password" placeholder="Password" />
<button @click.prevent="formAction">Log in</button>
</form>
</template>
<script>
import User from '@/api/user'
export default {
data() {
return {
email: '',
password: ''
}
},
methods: {
async formAction() {
const status = await User.loginUser({ email: this.email, password: this.password })
if (status.code == 200) {
throw router.push('/')
}
}
}
}
</script>

View File

@@ -0,0 +1,36 @@
<script setup>
import router from '@/router'
</script>
<template>
<form>
<label for="username">Username:</label>
<input type="text" id="username" v-model="username" placeholder="Username" />
<label for="email">Email:</label>
<input type="email" id="email" v-model="email" placeholder="Email" />
<label for="password">Password:</label>
<input type="password" id="password" v-model="password" placeholder="Password" />
<button @click.prevent="formAction">Sign up</button>
</form>
</template>
<script>
import User from '@/api/user'
export default {
data() {
return {
username: '',
email: '',
password: ''
}
},
methods: {
async formAction() {
const status = await User.registerUser({ username: this.username, email: this.email, password: this.password })
if (status.code == 201) {
throw router.push('/')
}
}
}
}
</script>

View File

@@ -0,0 +1,45 @@
<script setup>
import TrackerTimer from '@/components/TrackerTimer.vue'
import TaskHeader from '@/components/TaskHeader.vue'
import TaskRecord from '@/components/TaskRecord.vue'
</script>
<template>
<main>
<TrackerTimer @get-tasks="getTasks" />
<div class="task-day-wrapper">
<TaskHeader />
<div class="task-wrapper" v-for="task in sortedData" :key="task._id">
<TaskRecord :task="task" />
</div>
</div>
</main>
</template>
<script>
import AppStore from '@/stores/AppStore'
export default {
data() {
return {
tasks: AppStore.data.fetchedTasks
}
},
methods: {
async getTasks() {
await AppStore.fetchData()
this.tasks = AppStore.data.fetchedTasks
}
},
computed: {
sortedData() {
return this.tasks.slice().sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
}
},
async mounted() {
await AppStore.fetchData()
this.tasks = AppStore.data.fetchedTasks
}
}
</script>