error handler + login
This commit is contained in:
@ -2,26 +2,34 @@ import Server from './framework/express/server';
|
||||
import ip from 'ip';
|
||||
import UserModel from './framework/mongo/user';
|
||||
import { MongoClient } from 'mongodb';
|
||||
|
||||
const PORT = 8000;
|
||||
const MONGOURI = 'mongodb://localhost:27017';
|
||||
const DBNAME = 'dev';
|
||||
import { Config } from './config';
|
||||
import { exit, env } from 'process';
|
||||
|
||||
export type Services = {
|
||||
userModel: UserModel;
|
||||
};
|
||||
|
||||
const mongo = new MongoClient(MONGOURI);
|
||||
const db = mongo.db(DBNAME);
|
||||
const configFile = env.CONFIGFILE;
|
||||
if (configFile === undefined) {
|
||||
console.log('env var CONFIGFILE not set');
|
||||
exit(1);
|
||||
}
|
||||
|
||||
const config = new Config(configFile);
|
||||
|
||||
const mongo = new MongoClient(config.mongo.uri);
|
||||
const db = mongo.db(config.mongo.dbName);
|
||||
|
||||
const services: Services = {
|
||||
userModel: new UserModel(db),
|
||||
};
|
||||
|
||||
const server = new Server(services);
|
||||
const server = new Server(config.server, services);
|
||||
|
||||
server.start(PORT, () =>
|
||||
server.start(() =>
|
||||
console.log(
|
||||
`Running on http://127.0.0.1:${PORT} http://${ip.address()}:${PORT}`,
|
||||
`Running on http://127.0.0.1:${config.server.port} http://${ip.address()}:${
|
||||
config.server.port
|
||||
}`,
|
||||
),
|
||||
);
|
||||
|
21
api/src/config.ts
Normal file
21
api/src/config.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { readFileSync } from 'fs';
|
||||
|
||||
export type ServerConfig = {
|
||||
port: number;
|
||||
};
|
||||
|
||||
export type MongoConfig = {
|
||||
uri: string;
|
||||
dbName: string;
|
||||
};
|
||||
|
||||
export class Config {
|
||||
server: ServerConfig;
|
||||
mongo: MongoConfig;
|
||||
|
||||
constructor(configFile: string) {
|
||||
const config = JSON.parse(readFileSync(configFile).toString()) as Config;
|
||||
this.server = config.server;
|
||||
this.mongo = config.mongo;
|
||||
}
|
||||
}
|
@ -4,22 +4,22 @@ import {
|
||||
UserInfoWithPassword,
|
||||
UserWithPasswordCtor,
|
||||
} from '@core';
|
||||
import { createHash } from 'crypto';
|
||||
import { generateHash } from '../functions/password';
|
||||
import { Entity } from './entity';
|
||||
|
||||
export class User extends Entity implements UserInfo {
|
||||
name: string;
|
||||
username: string;
|
||||
|
||||
constructor(raw: UserCtor) {
|
||||
super(raw);
|
||||
|
||||
this.name = raw.name ? raw.name : '';
|
||||
this.username = raw.username ? raw.username : '';
|
||||
}
|
||||
|
||||
Info(): UserInfo {
|
||||
return {
|
||||
uuid: this.uuid,
|
||||
name: this.name,
|
||||
username: this.username,
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -30,15 +30,13 @@ export class UserWithPassword extends User implements UserInfoWithPassword {
|
||||
constructor(raw: UserWithPasswordCtor) {
|
||||
super(raw);
|
||||
|
||||
this.password = createHash('sha256')
|
||||
.update(`${this.uuid}+${raw.password}`)
|
||||
.digest('hex');
|
||||
this.password = generateHash(this.uuid, raw.password || '');
|
||||
}
|
||||
|
||||
Info(): UserInfoWithPassword {
|
||||
return {
|
||||
uuid: this.uuid,
|
||||
name: this.name,
|
||||
username: this.username,
|
||||
password: this.password,
|
||||
};
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
import { Request, RequestHandler } from 'express';
|
||||
import { ErrorRequestHandler, Request, RequestHandler } from 'express';
|
||||
import { randomUUID } from 'crypto';
|
||||
|
||||
export function getId(req: Request): string {
|
||||
@ -11,3 +11,11 @@ export function BeforeEach(): RequestHandler {
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
export function ErrorHandler(): ErrorRequestHandler {
|
||||
return (error, req, res, next) => {
|
||||
error.status
|
||||
? res.status(error.status).send(error)
|
||||
: res.status(500).send(error);
|
||||
};
|
||||
}
|
||||
|
@ -1,22 +1,27 @@
|
||||
import express, { Express } from 'express';
|
||||
import cors from 'cors';
|
||||
import * as router from './router';
|
||||
import { BeforeEach } from './middleware';
|
||||
import { BeforeEach, ErrorHandler } from './middleware';
|
||||
import { Services } from '../../app';
|
||||
import { ServerConfig } from '../../config';
|
||||
|
||||
class Server {
|
||||
private app: Express;
|
||||
private config: ServerConfig;
|
||||
|
||||
constructor(config: ServerConfig, services: Services) {
|
||||
this.config = config;
|
||||
|
||||
constructor(services: Services) {
|
||||
this.app = express();
|
||||
this.app.use(express.json());
|
||||
this.app.use(cors());
|
||||
this.app.use(BeforeEach());
|
||||
this.app.use(router.getRoutes(services));
|
||||
this.app.use(ErrorHandler());
|
||||
}
|
||||
|
||||
start(port: number, func: () => void): void {
|
||||
this.app.listen(port, func);
|
||||
start(func: () => void): void {
|
||||
this.app.listen(this.config.port, func);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,31 +1,36 @@
|
||||
import { RequestHandler, Router } from 'express';
|
||||
import { Services } from '../../app';
|
||||
import { Create, Read } from '../../functions/user';
|
||||
import { Create, Read, Login } from '../../functions/user';
|
||||
import { getId } from './middleware';
|
||||
|
||||
export function LoginHandler(services: Services): RequestHandler {
|
||||
return async (req, res) => {
|
||||
return res.send('Hey!\n');
|
||||
const login = Login(services);
|
||||
|
||||
return async (req, res, next) => {
|
||||
const user = await login(getId(req), req.body);
|
||||
user
|
||||
? res.status(200).send(user)
|
||||
: next({ status: 404, message: 'bad user or password' });
|
||||
};
|
||||
}
|
||||
|
||||
export function CreateHandler(services: Services): RequestHandler {
|
||||
const createUser = Create(services);
|
||||
|
||||
return async (req, res) => {
|
||||
return async (req, res, next) => {
|
||||
const user = await createUser(getId(req), req.body);
|
||||
|
||||
res.send(user);
|
||||
user ? res.status(201).send(user) : next();
|
||||
};
|
||||
}
|
||||
|
||||
export function ReadHandler(services: Services): RequestHandler {
|
||||
const readUser = Read(services);
|
||||
|
||||
return async (req, res) => {
|
||||
return async (req, res, next) => {
|
||||
const user = await readUser(getId(req), req.params.uuid);
|
||||
|
||||
res.send(user);
|
||||
user
|
||||
? res.status(200).send(user)
|
||||
: next({ status: 404, message: 'user not found' });
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -1,5 +1,8 @@
|
||||
import { Collection, Db } from 'mongodb';
|
||||
import { LoginUserBody } from '../../../../core/src/user';
|
||||
import { User, UserWithPassword } from '../../entities/user';
|
||||
import log from '../../functions/logger';
|
||||
import { generateHash } from '../../functions/password';
|
||||
|
||||
class UserModel {
|
||||
private collection: Collection<User>;
|
||||
@ -8,14 +11,42 @@ class UserModel {
|
||||
this.collection = db.collection<User>('users');
|
||||
}
|
||||
|
||||
public async login(tracker: string, data: LoginUserBody) {
|
||||
const checkUser = await this.collection.findOne({
|
||||
username: data.username,
|
||||
});
|
||||
if (checkUser === null) {
|
||||
log(tracker, 'User Not Found');
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = await this.collection.findOne({
|
||||
uuid: checkUser.uuid,
|
||||
password: generateHash(checkUser.uuid, data.password),
|
||||
});
|
||||
if (user === null) {
|
||||
log(tracker, 'Wrong Password');
|
||||
return null;
|
||||
}
|
||||
|
||||
log(tracker, 'LOG IN', user);
|
||||
return new User(user);
|
||||
}
|
||||
|
||||
public async create(tracker: string, user: UserWithPassword) {
|
||||
await this.collection.insertOne(user);
|
||||
log(tracker, 'CREATE USER', user);
|
||||
return this.read(tracker, user.uuid);
|
||||
}
|
||||
|
||||
public async read(tracker: string, uuid: string) {
|
||||
const user = await this.collection.findOne({ uuid });
|
||||
return new User(user || { name: 'not found' });
|
||||
if (user === null) {
|
||||
log(tracker, 'User Not Found');
|
||||
return null;
|
||||
}
|
||||
log(tracker, 'READ USER', user);
|
||||
return new User(user);
|
||||
}
|
||||
}
|
||||
|
||||
|
11
api/src/functions/logger.ts
Normal file
11
api/src/functions/logger.ts
Normal file
@ -0,0 +1,11 @@
|
||||
export function log(tracker: string, ...message: unknown[]) {
|
||||
message.forEach((obj, index) => {
|
||||
try {
|
||||
message[index] = JSON.stringify(obj);
|
||||
} catch {}
|
||||
});
|
||||
|
||||
tracker ? console.log(`[${tracker}]`, ...message) : console.log(...message);
|
||||
}
|
||||
|
||||
export default log;
|
5
api/src/functions/password.ts
Normal file
5
api/src/functions/password.ts
Normal file
@ -0,0 +1,5 @@
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
export function generateHash(...values: string[]) {
|
||||
return createHash('sha256').update(values.join('')).digest('hex');
|
||||
}
|
@ -1,25 +1,36 @@
|
||||
import { CreateUserBody, UserInfo } from '@core';
|
||||
import { CreateUserBody, LoginUserBody, UserInfo } from '@core';
|
||||
import { Services } from '../app';
|
||||
import { User, UserWithPassword } from '../entities/user';
|
||||
import { UserWithPassword } from '../entities/user';
|
||||
|
||||
export function Login(
|
||||
services: Services,
|
||||
): (tracker: string, raw: LoginUserBody) => Promise<UserInfo | null> {
|
||||
const { userModel } = services;
|
||||
|
||||
return async (tracker, raw) => {
|
||||
const user = await userModel.login(tracker, raw);
|
||||
return user ? user.Info() : null;
|
||||
};
|
||||
}
|
||||
|
||||
export function Create(
|
||||
services: Services,
|
||||
): (tracker: string, raw: CreateUserBody) => Promise<UserInfo> {
|
||||
): (tracker: string, raw: CreateUserBody) => Promise<UserInfo | null> {
|
||||
const { userModel } = services;
|
||||
|
||||
return async (tracker, raw) => {
|
||||
const user = await userModel.create(tracker, new UserWithPassword(raw));
|
||||
return user.Info();
|
||||
return user ? user.Info() : null;
|
||||
};
|
||||
}
|
||||
|
||||
export function Read(
|
||||
services: Services,
|
||||
): (tracker: string, uuid: string) => Promise<UserInfo> {
|
||||
): (tracker: string, uuid: string) => Promise<UserInfo | null> {
|
||||
const { userModel } = services;
|
||||
|
||||
return async (tracker, uuid) => {
|
||||
const user = await userModel.read(tracker, uuid);
|
||||
return user.Info();
|
||||
return user ? user.Info() : null;
|
||||
};
|
||||
}
|
||||
|
Reference in New Issue
Block a user