Skip to content

Commit

Permalink
Done more job
Browse files Browse the repository at this point in the history
Co-authored-by: Andrew <[email protected]>
Co-authored-by: Arkadiy Krava <[email protected]>
Co-authored-by: Yaroslav <[email protected]>
  • Loading branch information
Veetaha committed May 26, 2020
1 parent c3860ea commit 30f0802
Show file tree
Hide file tree
Showing 39 changed files with 3,667 additions and 188 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
database
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
For private use, all rights are reserved, distribution of copies is strictly prohibited!
2 changes: 1 addition & 1 deletion lab5/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ process.stdout.write = (...args: any) => {
logs += String(args[0]).replace(
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
''
) + '<br>';
) + '<br><br>'; // logs go brrr ахахахахахсука
return write.apply(process.stdout, args);
};

Expand Down
50 changes: 0 additions & 50 deletions lab5/initial_migration.sql

This file was deleted.

2 changes: 1 addition & 1 deletion lab5/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"private": true,
"scripts": {
"start": "ts-node ./app.ts",
"dev": "ts-node-dev --respawn --inspect=0.0.0.0:9229 -- app.ts",
"dev": "ts-node-dev --respawn -- app.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
Expand Down
56 changes: 54 additions & 2 deletions lab5/public/javascripts/db/db.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,62 @@ export class DbService {
}

async deletePubFormation(id: string): Promise<boolean> {
return await this.orm.delete(this.users, {id});
return await this.orm.delete(this.pubFormations, {id});
}

async deleteDocument(id: string): Promise<boolean> {
return await this.orm.delete(this.users, {id});
return await this.orm.delete(this.documents, {id});
}
}


// create table users (
// id uuid not null primary key, -- ідентифікатор користувача
// type text not null, -- роль користувача (реєстратор, адмінстратор, інший)
// name text not null, -- ім'я
// surname text not null, -- призвіще
// address text not null, -- адреса проживання
// password_hash text not null, -- хєш пароля користувача
// email text not null unique, -- поштова скринька
// passport_id text not null, -- номер паспорту
// taxes_card_id text not null -- номер картки платника податків
// );

// create table pub_formations (
// id uuid not null primary key, -- унікальний ідетифікатор формування
// registrator_id uuid not null references users(id), -- ідентифікатор реєстратора
// type text not null, -- тип формування (політична партія, благодійна організація, творча спілка і т.д...)
// registration_date timestamp not null default now(), -- дата реєстрації (легалізації)
// name text not null, -- повне найменування формування
// executives json, -- перелік та відомості про керівний склад
// residence_address text, -- адреса місця за який зареєстроване формування
// phone_number text, -- номер телефону
// activity_purpose text, -- мета діяльності
// is_disabled bool default false, -- анулювання реєстрації
// disabling_reason text, -- причина анулювання реєстрації
// status text, -- статус формування
// registration_certificate_id text, -- реєстраційний номер у відповідному
// structural_cell_type text, -- вид структурного осередку
// affected_teritory text, -- озплюєма територія
// members_amount integer, -- кількість учсаників формування
// arbitrages json -- відомості про третейських суддів
// );

// create table documents (
// id uuid not null primary key, -- унікальний ідентифікатор документа
// pf_id uuid not null references pub_formations(id), -- індентифікатор ГФ до якого відноситься цей документ
// type text not null, -- тип документу
// name text not null, -- назва документу
// uri text not null -- посилання на ресурс для завантаження документу
// );

// create table pf_transaction_log (
// id uuid not null primary key, -- унікальний ідентифікатор транзакції
// pf_id uuid not null references pub_formations(id), -- ідентифікатор ГФ до якого транзакція застосована
// initiator_id uuid not null references users(id), -- ідентифікатор реєстратора який ініціював транзакцію
// type text not null, -- тип транзакції (створення, видалення, редагування)
// date date not null, -- дата виконання транзакції
// old_value json, -- старе значення до транзакції
// new_value json, -- нове значення після транзакції
// col_name text -- назва колонки що була заторкнута
// );
19 changes: 6 additions & 13 deletions lab5/public/javascripts/db/entities/pub-formation.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,28 +65,21 @@ export class PubFormation {
@Column({ default: false })
disabled!: boolean; // анулювання реєстрації













@StringColumn({ nullable: true })
registration_athority?: null | string;

@StringColumn({ nullable: true })
disabling_reason?: null | string; // причина анулювання реєстрації

@StringColumn({ nullable: true })
status?: null | string; // статус формування

@StringColumn({ nullable: true })
@StringColumn({ nullable: true, default: () => ("" + Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)).padStart(10, "0") })
registration_certificate_id?: null | string; // реєстраційний номер у відповідному

@StringColumn({ nullable: true })
foundators?: null | string;

@StringColumn({ nullable: true })
structural_cell_type?: null | string; // вид структурного осередку

Expand Down
11 changes: 7 additions & 4 deletions lab5/public/stylesheets/authorise.css
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
body {
height: 100%;
}

body {
display: -ms-flexbox;
display: -webkit-box;
Expand All @@ -17,10 +17,13 @@ body {
padding-bottom: 40px;
background-color: #f5f5f5;
}

.form-signin {
width: 100%;
max-width: 330px;
max-width: 600px;
display: flex;
flex-direction: column;
align-items: flex-start;
padding: 15px;
margin: 0 auto;
}
Expand All @@ -46,4 +49,4 @@ body {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
}
8 changes: 6 additions & 2 deletions lab5/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import passport from "passport";
import Container from "typedi";
import { DbService } from "../public/javascripts/db/db.service";

// тут был Аркадий
// Аркаша это любовь!

export const serverSalt = "1'grechko postav ashku ili eshku";
const db = Container.get(DbService);

Expand All @@ -16,6 +19,7 @@ export function sha512(password: string, salt) {
return { salt, passwordHash: value };
};


export const router = Router()
.get('/logout', verify(), (req, res, next) => {
req.logout();
Expand Down Expand Up @@ -47,14 +51,14 @@ export const router = Router()
next();
}, passport.authenticate('local', {
successRedirect: '/formation',
failureRedirect: '/wrongdata'
failureRedirect: '/login'
}));



export function verify(roles?: UserRole[]) {
return (req, res, next) => {
console.log("Verifying", req.user);

if (!req.user) return res.redirect('/login');
if (req.user.disabled) return res.redirect('/login');
if (!roles) return next();
Expand Down
17 changes: 16 additions & 1 deletion lab5/routes/formations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const router = Router()

formations.forEach(formation => {
formation.type = types[formation.type];
formation.registration_date = formation.registration_date.toString().slice(0, 24) as any;
formation.registration_date = formation.registration_date.toString().slice(0, 24) as any ;
});
res.render('searchFormation', {
formations,
Expand All @@ -48,6 +48,8 @@ export const router = Router()
.post('/addFormation', verify(adminOrRegistrator), async (req, res, next) => {
let formation = new PubFormation();
Object.assign(formation, req.body);
console.log("adding formation ...");
console.table(formation);

const user = req.user as User;

Expand All @@ -60,12 +62,25 @@ export const router = Router()
.post('/editFormation/:id', async (req, res) => {
let formation = new PubFormation();
Object.assign(formation, req.body);
console.log("editing formation ...");
console.table(formation);

formation.id = req.params.id;

const updated = await db.updatePubFormation(formation);
console.log(updated);
res.redirect(`/formation`)
})
.get('/deleteFormation/:id', async (req, res) => {
await db.deletePubFormation(req.params.id);
res.redirect(`/formation`)
})
.get('/particularFormation/:id', async (req, res) => {
const formation = await db.getPubFormationById(req.params.id);
if (!formation) return res.render("/notfound");

res.render('particularFormation', { user: req.user, types, ...formation });
})
.get('/editFormation/:id', async (req, res) => {
const formation = await db.getPubFormationById(req.params.id);
if (!formation) return res.render("/notfound");
Expand Down
69 changes: 63 additions & 6 deletions lab5/routes/users.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import {Router} from "express"
import Container from "typedi";
import { DbService } from "../public/javascripts/db/db.service";
import { UserRole } from "../public/javascripts/db/entities/user.entity";
import { UserRole, User } from "../public/javascripts/db/entities/user.entity";
import { verify, sha512, serverSalt } from "./auth";
import { UpdateDateColumn } from "typeorm";

export const router = Router();
const db = Container.get(DbService);

router.get("/users", async (req, res, next) => {
router.get("/users", verify([UserRole.Admin]), async (req, res, next) => {
const users = await db.getAllUsers('');
users.forEach((user) => {
user.type = user.type === UserRole.Admin
Expand All @@ -24,11 +26,66 @@ router.get("/users", async (req, res, next) => {
user: req.user,
});
});
router.get("/users:id", async (req, res, next) => {
const user = await db.getUserById(req.params.id);
if (!user) {
// router.get("/users:id", verify([UserRole.Admin]), async (req, res, next) => {
// const user = await db.getUserById(req.params.id);
// if (!user) {
// return res.render("notfound");
// }

// res.render('user', user)
// });

router.get('/user/:id', verify([UserRole.Admin, UserRole.Registrator]), async (req, res, lol) => {
const registrator = await db.getUserById(req.params.id);
if (!registrator) {
return res.render("notfound");
}

res.render('user', user)
const user = req.user;
res.render('user', { user, registrator });
});

router.get('/registerRegistrator', verify([UserRole.Admin]), async (req, res, next) => {
res.render('registerRegistrator');
});

router.post('/editRegistrator/:id', verify([UserRole.Admin]), async (req, res, next) => {
console.log(req.body);
console.table(req.body);

const upd = {...req.body, id: req.params.id };

if (upd.disabled === "on") {
upd.disabled = true;
} else {
upd.disabled = false;
}

try {
await db.updateUser(upd);
res.redirect('/users');
} catch(err) {
console.error({ suka: err });
res.render('logintaken');
}
});

router.post('/registerRegistrator', verify([UserRole.Admin]), async (req, res, bext) => {
console.log(req.body);
console.table(req.body);

const password = req.body.password;
delete req.body.password;

const user: User = {...req.body};
user.password_hash = sha512(password, serverSalt).passwordHash;
user.type = UserRole.Registrator;

try {
await db.createUser(user);
res.redirect('/users');
} catch(err) {
console.error({ suka: err });
res.render('logintaken');
}
})
Loading

0 comments on commit 30f0802

Please sign in to comment.