feat(server): business owned by user data model

This commit is contained in:
eneller
2026-07-23 14:28:20 +02:00
parent c876a45ef8
commit 0f4474d29b
15 changed files with 69 additions and 37 deletions

View File

@@ -6,7 +6,7 @@
<i class="bi bi-person-circle fs-1 text-primary"></i> <i class="bi bi-person-circle fs-1 text-primary"></i>
</div> </div>
<h3 class="mb-1">{{ username }}</h3> <h3 class="mb-1">{{ username }}</h3>
<p class="text-muted mb-4">{{ userID }}</p> <p class="text-muted mb-4">{{ this.api.currentUser }}</p>
<div class="d-flex align-items-center justify-content-center gap-2 mb-1"> <div class="d-flex align-items-center justify-content-center gap-2 mb-1">
<i class="bi bi-wallet2 fs-4"></i> <i class="bi bi-wallet2 fs-4"></i>
<h3 class="mb-0">{{ balance | currency}}</h3> <h3 class="mb-0">{{ balance | currency}}</h3>
@@ -31,7 +31,7 @@
<i class="bi bi-person-fill fs-4 text-secondary"></i> <i class="bi bi-person-fill fs-4 text-secondary"></i>
</div> </div>
<div class="text-start"> <div class="text-start">
@if (transaction.receiverID == userID) { @if (transaction.receiverID == this.api.currentUser) {
<h6 class="mb-0">{{ transaction.senderID }}</h6> <h6 class="mb-0">{{ transaction.senderID }}</h6>
}@else { }@else {
<h6 class="mb-0">{{ transaction.receiverID }}</h6> <h6 class="mb-0">{{ transaction.receiverID }}</h6>
@@ -40,7 +40,7 @@
</div> </div>
</div> </div>
<div class="text-end"> <div class="text-end">
@if (transaction.receiverID == userID) { @if (transaction.receiverID == this.api.currentUser) {
<h6 class="mb-0 text-success"> <h6 class="mb-0 text-success">
{{ transaction.amount | currency }} {{ transaction.amount | currency }}
</h6> </h6>

View File

@@ -1,5 +1,5 @@
import { CommonModule, CurrencyPipe, DatePipe } from '@angular/common'; import { CommonModule, CurrencyPipe, DatePipe } from '@angular/common';
import { Component, OnInit } from '@angular/core'; import { Component, inject, OnInit } from '@angular/core';
import { APIService } from '../../services/api'; import { APIService } from '../../services/api';
import Transaction from '@model/transaction'; import Transaction from '@model/transaction';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
@@ -13,12 +13,11 @@ import { Router } from '@angular/router';
export class ScreenProfile implements OnInit{ export class ScreenProfile implements OnInit{
// TODO display real data // TODO display real data
username = 'John Doe'; username = 'John Doe';
userID = 'testuser';
balance = 200; balance = 200;
transactions!: Transaction[]; transactions!: Transaction[];
constructor( constructor(
private api: APIService, protected api: APIService,
private router: Router, private router: Router,
){} ){}

View File

@@ -40,7 +40,7 @@
<ng-template #content let-modal> <ng-template #content let-modal>
<div class="modal-header"> <div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Pay {{ amount}} to {{ user }}</h4> <h4 class="modal-title" id="modal-basic-title">Pay {{ amount}} to {{ this.api.currentUser }}</h4>
<button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss()"></button> <button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss()"></button>
</div> </div>
<div class="modal-body text-center"> <div class="modal-body text-center">

View File

@@ -2,6 +2,7 @@ import { Component, inject, TemplateRef } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { QrCodeComponent } from 'ng-qrcode'; import { QrCodeComponent } from 'ng-qrcode';
import { APIService } from '../../services/api';
@Component({ @Component({
selector: 'app-screen-receive', selector: 'app-screen-receive',
@@ -11,12 +12,12 @@ import { QrCodeComponent } from 'ng-qrcode';
}) })
export class ScreenReceive { export class ScreenReceive {
private modalService = inject(NgbModal); private modalService = inject(NgbModal);
api = inject(APIService);
user = 'DemoUser';
amount: number = 0; amount: number = 0;
get shareableLink(): string { get shareableLink(): string {
const currentDomain = window.location.origin; const currentDomain = window.location.origin;
return `${currentDomain}/send/${this.user}?amount=${this.amount}`; return `${currentDomain}/send/${this.api.currentUser}?amount=${this.amount}`;
} }
copyLink() { copyLink() {

View File

@@ -13,6 +13,9 @@ export class APIService {
private isAuthenticatedSubject = new BehaviorSubject<boolean>(false); private isAuthenticatedSubject = new BehaviorSubject<boolean>(false);
isAuthenticated$ = this.isAuthenticatedSubject.asObservable(); isAuthenticated$ = this.isAuthenticatedSubject.asObservable();
// TODO use real user here
currentUser = 'DemoUser';
constructor(private http: HttpClient){} constructor(private http: HttpClient){}
login(username: string, password: string): Observable<any>{ login(username: string, password: string): Observable<any>{

View File

@@ -16,7 +16,8 @@
"teardown": "docker compose down", "teardown": "docker compose down",
"keygen": "ts-node src/scripts/keygen.ts", "keygen": "ts-node src/scripts/keygen.ts",
"hash": "ts-node src/scripts/hash.ts", "hash": "ts-node src/scripts/hash.ts",
"verify": "ts-node src/scripts/verify.ts", "verify-hash": "ts-node src/scripts/verify-hash.ts",
"create-user": "ts-node src/scripts/create-user.ts",
"dev": "npm run setup && npm run node; npm run teardown" "dev": "npm run setup && npm run node; npm run teardown"
}, },
"dependencies": { "dependencies": {

View File

@@ -1,4 +1,4 @@
import User from "../model/user"; import Account from "../model/user";
export class UserRequest{ export class UserRequest{
constructor( constructor(
@@ -6,6 +6,6 @@ export class UserRequest{
} }
export class UserResponse{ export class UserResponse{
constructor( constructor(
public user: User public user: Account
){} ){}
} }

View File

@@ -1,5 +1,5 @@
import { Table, Column, Model, CreatedAt, ForeignKey, BelongsTo} from 'sequelize-typescript'; import { Table, Column, Model, CreatedAt, ForeignKey, BelongsTo} from 'sequelize-typescript';
import User from './user'; import Account from './user';
@Table @Table
export default class Transaction extends Model{ export default class Transaction extends Model{
@@ -10,18 +10,18 @@ export default class Transaction extends Model{
declare reference: string; declare reference: string;
@Column @Column
@ForeignKey(()=> User) @ForeignKey(()=> Account)
declare senderID: string; declare senderID: string;
@BelongsTo(() => User, 'senderID') @BelongsTo(() => Account, 'senderID')
declare sender: User; declare sender: Account;
@Column @Column
@ForeignKey(()=> User) @ForeignKey(()=> Account)
declare receiverID: string; declare receiverID: string;
@BelongsTo(() => User, 'receiverID') @BelongsTo(() => Account, 'receiverID')
declare receiver: User; declare receiver: Account;
@CreatedAt @CreatedAt
declare date: Date; declare date: Date;

View File

@@ -1,4 +1,4 @@
import { Table, Column, Model, CreatedAt, DataType, Scopes, DefaultScope} from 'sequelize-typescript'; import { Table, Column, Model, DataType, Scopes, DefaultScope, DeletedAt, BelongsToMany, ForeignKey} from 'sequelize-typescript';
@DefaultScope(() => ({ @DefaultScope(() => ({
attributes:{ exclude: ['password']} attributes:{ exclude: ['password']}
@@ -9,10 +9,13 @@ import { Table, Column, Model, CreatedAt, DataType, Scopes, DefaultScope} from '
} }
})) }))
@Table @Table
export default class User extends Model{ export default class Account extends Model{
@Column({primaryKey: true, unique: true, allowNull: false}) @Column({primaryKey: true, unique: true, allowNull: false})
declare userID: string; declare id: string;
@Column
declare isBusiness: boolean;
@Column @Column
declare displayName: string; declare displayName: string;
@@ -22,8 +25,21 @@ export default class User extends Model{
@Column @Column
declare password: string; declare password: string;
@DeletedAt
declare deletedAt: Date | null;
}
@Table
export class BusinessOwnership extends Model {
@ForeignKey(() => Account)
@Column
ownerAccountId!: number;
@CreatedAt @ForeignKey(() => Account)
declare creationDate: Date; @Column
ownedAccountId!: number;
@DeletedAt
declare deletedAt: Date | null;
} }

View File

@@ -1,7 +1,7 @@
import { compare } from 'bcrypt'; import { compare } from 'bcrypt';
import express from 'express'; import express from 'express';
import { logger } from '../util/logging'; import { logger } from '../util/logging';
import User from '../model/user'; import Account from '../model/user';
import { Scope } from '../util/db'; import { Scope } from '../util/db';
import { getJWT, requireAuth } from '../util/auth'; import { getJWT, requireAuth } from '../util/auth';
import { LoginRequest } from '../messages/Login'; import { LoginRequest } from '../messages/Login';
@@ -12,7 +12,7 @@ const router = express.Router();
router.post('/login', async (req, res) => { router.post('/login', async (req, res) => {
try { try {
const data : LoginRequest = req.body; const data : LoginRequest = req.body;
const user = await User.scope(Scope.withPassword).findOne({where: { userID: data.username}}); const user = await Account.scope(Scope.withPassword).findOne({where: { id: data.username}});
if (!user) return res.status(401).json(new Msg('Invalid credentials')); if (!user) return res.status(401).json(new Msg('Invalid credentials'));
const isMatch = await compare(data.password, user.password); const isMatch = await compare(data.password, user.password);
if (!isMatch) return res.status(401).json(new Msg('Invalid credentials')); if (!isMatch) return res.status(401).json(new Msg('Invalid credentials'));

View File

@@ -1,7 +1,7 @@
import express from 'express'; import express from 'express';
import { logger } from '../util/logging'; import { logger } from '../util/logging';
import { requireAuth } from '../util/auth'; import { requireAuth } from '../util/auth';
import User from '../model/user'; import Account from '../model/user';
import { db } from '../util/db'; import { db } from '../util/db';
import Transaction from '../model/transaction'; import Transaction from '../model/transaction';
import { SendRequest, SendResponse} from '../messages/Send'; import { SendRequest, SendResponse} from '../messages/Send';
@@ -12,9 +12,9 @@ const router = express.Router();
router.post('/', requireAuth, async (req, res) => { router.post('/', requireAuth, async (req, res) => {
try { try {
const sender = res.locals.user as User; const sender = res.locals.user as Account;
const data : SendRequest = req.body; const data : SendRequest = req.body;
const recipient = await User.findOne({where: {userID: data.recipientID}}) const recipient = await Account.findOne({where: {id: data.recipientID}})
if ( Number(data.amount) <= 0) { if ( Number(data.amount) <= 0) {
return res.status(400).json(new Err('Invalid transfer amount')); return res.status(400).json(new Err('Invalid transfer amount'));
} }
@@ -31,8 +31,8 @@ router.post('/', requireAuth, async (req, res) => {
await recipient.increment({balance: data.amount}); await recipient.increment({balance: data.amount});
await Transaction.create({ await Transaction.create({
amount: data.amount, amount: data.amount,
senderID: sender.userID, senderID: sender.id,
receiverID: recipient.userID, receiverID: recipient.id,
reference: data.reference reference: data.reference
}); });
}) })

View File

@@ -0,0 +1,12 @@
import { db, testConnection } from "../util/db";
import { hash } from "bcrypt";
import Account from '../model/user';
(async () =>{
await testConnection();
await Account.create({
id: process.argv[2],
displayName: process.argv[3],
balance: process.argv[4],
password: await hash(process.argv[5], 10),
})
})();

View File

@@ -1,5 +1,5 @@
import { NextFunction, Request, Response } from "express"; import { NextFunction, Request, Response } from "express";
import User from "../model/user" import Account from "../model/user"
import { importJWK, SignJWT, jwtVerify } from "jose"; import { importJWK, SignJWT, jwtVerify } from "jose";
@@ -9,9 +9,9 @@ async function setKeyFromEnv() {
key = await importJWK(JSON.parse(process.env.FM_PRIVATE_KEY)); key = await importJWK(JSON.parse(process.env.FM_PRIVATE_KEY));
} }
async function getJWT(user: User){ async function getJWT(user: Account){
let jwt = await new SignJWT() let jwt = await new SignJWT()
.setSubject(user.userID) .setSubject(user.id)
.setProtectedHeader({ alg: 'HS256' }) .setProtectedHeader({ alg: 'HS256' })
.setIssuedAt() .setIssuedAt()
.sign(key); .sign(key);
@@ -26,7 +26,7 @@ async function requireAuth(req: Request, res: Response, next: NextFunction) {
return res.status(401).json({ error: 'Unauthorized: No token provided' }); return res.status(401).json({ error: 'Unauthorized: No token provided' });
} }
const jwt= await jwtVerify(token, key); const jwt= await jwtVerify(token, key);
const user = await User.findOne({where: { userID: jwt.payload.sub}}); const user = await Account.findOne({where: { id: jwt.payload.sub}});
if (!user) { if (!user) {
return res.status(401).json({ error: 'Unauthorized: User not found' }); return res.status(401).json({ error: 'Unauthorized: User not found' });
} }

View File

@@ -1,6 +1,6 @@
import { Sequelize } from 'sequelize-typescript'; import { Sequelize } from 'sequelize-typescript';
import { logger } from './logging'; import { logger } from './logging';
import User from '../model/user'; import Account, { BusinessOwnership } from '../model/user';
import Transaction from '../model/transaction'; import Transaction from '../model/transaction';
enum Scope{ enum Scope{
@@ -19,7 +19,7 @@ const db = new Sequelize({
logging: logger.debug.bind(logger), logging: logger.debug.bind(logger),
}); });
db.addModels([User, Transaction ]) db.addModels([Account, BusinessOwnership, Transaction ])
// Test the connection // Test the connection
async function testConnection() { async function testConnection() {